Offer H.264 in Constrained High, then Constrained Baseline
A streamer offered H.264 only in Constrained High, which peers whose decoders list no High profile (headless Chromium's libwebrtc, many other WebRTC stacks) cannot answer, so an H.264 stream had no way to reach them. The offer now lists both profiles, best first (PT 112 Constrained High, PT 108 Constrained Baseline, at the level the stream needs). The answer's payload type tells the streamer which one the viewer took (PeerEvent::VideoCodec now carries a VideoFormat: the codec, and H.264 with its profile). The streamer already ran one encoder per codec viewers chose; it now runs one per format, so a Baseline viewer gets frames from an encoder in Constrained Baseline, and frames go only to viewers of their format (LayerFeedback has a bit for it). voelinctl's FrameSource path offers Constrained High alone, as it cannot encode per viewer. The browser test now offers the ladder and checks the SPS profile of what it sent against what the browser chose. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3bd230767c
commit
9b20da22d8
9 files changed
+533
-214
No files matched your search
+166
-75
@@ -56,13 +56,13 @@ use voelin_media::scale::Pyramid;
|
||||
use voelin_media::studio::Studio;
|
||||
use voelin_media::studio::output::{Packet, Track};
|
||||
use voelin_media::{
|
||||
Codec, Codecs, ContentHint, EncodedChunk, EncoderConfig, FrameRef, GpuFrame, VideoEncoder,
|
||||
VideoFrame,
|
||||
Codec, Codecs, ContentHint, EncodedChunk, EncoderConfig, FrameRef, GpuFrame, H264Profile,
|
||||
VideoEncoder, VideoFrame,
|
||||
};
|
||||
pub use voelin_media::{EncoderBackend, EncoderPreference};
|
||||
use voelin_stream::{
|
||||
EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind,
|
||||
MediaTime, PeerConfig, VideoCodec,
|
||||
MediaTime, PeerConfig, VideoCodec, VideoFormat,
|
||||
};
|
||||
|
||||
use crate::settings::{AudioSourceKindSetting, AudioSourceSetting};
|
||||
@@ -114,6 +114,17 @@ pub fn media_codec(codec: VideoCodec) -> Codec {
|
||||
}
|
||||
}
|
||||
|
||||
/// The H.264 profile an encoder of `format` makes (Constrained High for
|
||||
/// every other codec, where it means nothing).
|
||||
fn h264_profile(format: VideoFormat) -> H264Profile {
|
||||
match format {
|
||||
VideoFormat::H264(voelin_stream::H264Profile::ConstrainedBaseline) => {
|
||||
H264Profile::ConstrainedBaseline
|
||||
}
|
||||
_ => H264Profile::ConstrainedHigh,
|
||||
}
|
||||
}
|
||||
|
||||
/// The negotiable video codec of a `voelin_media` codec.
|
||||
pub fn video_codec(codec: Codec) -> VideoCodec {
|
||||
match codec {
|
||||
@@ -255,16 +266,16 @@ pub trait MediaSink: Send + Sync {
|
||||
None
|
||||
}
|
||||
|
||||
/// Send one video frame encoded in `codec`: it goes to the viewers whose
|
||||
/// answer chose `codec`.
|
||||
fn send_video(&self, frame: EncodedFrame, codec: Codec) -> bool {
|
||||
let _ = codec;
|
||||
/// Send one video frame encoded in `format`: it goes to the viewers
|
||||
/// whose answer chose that codec (and H.264 profile).
|
||||
fn send_video(&self, frame: EncodedFrame, format: VideoFormat) -> bool {
|
||||
let _ = format;
|
||||
self.send(frame)
|
||||
}
|
||||
|
||||
/// Adds to `out` the video codecs the viewers chose; none (the default)
|
||||
/// means only the stream codec is sent.
|
||||
fn video_codecs(&self, out: &mut Vec<Codec>) {
|
||||
/// Adds to `out` the video codecs (with the H.264 profile) the viewers
|
||||
/// chose; none (the default) means only the stream codec is sent.
|
||||
fn video_codecs(&self, out: &mut Vec<VideoFormat>) {
|
||||
let _ = out;
|
||||
}
|
||||
}
|
||||
@@ -274,16 +285,12 @@ impl MediaSink for StreamSink {
|
||||
StreamSink::send(self, frame)
|
||||
}
|
||||
|
||||
fn send_video(&self, frame: EncodedFrame, codec: Codec) -> bool {
|
||||
StreamSink::send_video(self, frame, video_codec(codec))
|
||||
fn send_video(&self, frame: EncodedFrame, format: VideoFormat) -> bool {
|
||||
StreamSink::send_video(self, frame, format)
|
||||
}
|
||||
|
||||
fn video_codecs(&self, out: &mut Vec<Codec>) {
|
||||
for codec in VideoCodec::ALL {
|
||||
if self.has_video_codec(codec) {
|
||||
out.push(media_codec(codec));
|
||||
}
|
||||
}
|
||||
fn video_codecs(&self, out: &mut Vec<VideoFormat>) {
|
||||
out.extend(VideoFormat::ALL.into_iter().filter(|f| self.has_video_codec(*f)));
|
||||
}
|
||||
|
||||
fn take_keyframe_request(&self) -> bool {
|
||||
@@ -1867,6 +1874,8 @@ enum ToStudio<'a> {
|
||||
|
||||
/// One encoder of a layer: its keyframe and bitrate state.
|
||||
struct LayerEncoder {
|
||||
/// What viewers get from it: the codec, and H.264 in one profile.
|
||||
format: VideoFormat,
|
||||
codec: Codec,
|
||||
/// `None`: creating it failed (not retried until it is needed anew).
|
||||
encoder: Option<Box<dyn VideoEncoder>>,
|
||||
@@ -1879,8 +1888,16 @@ struct LayerEncoder {
|
||||
}
|
||||
|
||||
impl LayerEncoder {
|
||||
fn new(encoder: Box<dyn VideoEncoder>, fps: u32) -> Self {
|
||||
Self { codec: encoder.codec(), encoder: Some(encoder), keyframe_due: true, bitrate: 0, fps }
|
||||
fn new(encoder: Box<dyn VideoEncoder>, format: VideoFormat, fps: u32) -> Self {
|
||||
let codec = encoder.codec();
|
||||
Self { format, codec, encoder: Some(encoder), keyframe_due: true, bitrate: 0, fps }
|
||||
}
|
||||
|
||||
/// The stream codec's encoder: H.264 in Constrained High, as
|
||||
/// [`new_encoder`] makes it.
|
||||
fn primary(encoder: Box<dyn VideoEncoder>, fps: u32) -> Self {
|
||||
let format = video_codec(encoder.codec()).into();
|
||||
Self::new(encoder, format, fps)
|
||||
}
|
||||
|
||||
/// Encode `picture` and hand the frames to `sink` (and `studio`'s
|
||||
@@ -1941,7 +1958,7 @@ impl LayerEncoder {
|
||||
layer: layer.id,
|
||||
keyframe: chunk.keyframe,
|
||||
};
|
||||
if sink.send_video(encoded, codec) {
|
||||
if sink.send_video(encoded, self.format) {
|
||||
layer.frames.fetch_add(1, Ordering::Relaxed);
|
||||
layer.keyframes.fetch_add(u64::from(chunk.keyframe), Ordering::Relaxed);
|
||||
layer.bytes.fetch_add(chunk.data.len() as u64, Ordering::Relaxed);
|
||||
@@ -1963,20 +1980,27 @@ impl LayerEncoder {
|
||||
}
|
||||
}
|
||||
|
||||
/// An encoder of `codec` for `layer` (a codec a viewer chose), with the
|
||||
/// streamer's current codecs and preference.
|
||||
fn extra_encoder(shared: &Shared, layer: &Layer, codec: Codec) -> Option<Box<dyn VideoEncoder>> {
|
||||
/// An encoder of `format` for `layer` (a codec and H.264 profile a viewer
|
||||
/// chose), with the streamer's current codecs and preference.
|
||||
fn extra_encoder(
|
||||
shared: &Shared,
|
||||
layer: &Layer,
|
||||
format: VideoFormat,
|
||||
) -> Option<Box<dyn VideoEncoder>> {
|
||||
let guard = lock(&shared.encoders);
|
||||
let (codecs, preference) = guard.as_ref()?;
|
||||
let spec = lock(&layer.spec).clone();
|
||||
let config = encoder_config(&spec, layer.fps.load(Ordering::Relaxed), layer.threads);
|
||||
match codecs.new_encoder_preferring(codec, config, preference) {
|
||||
let config = EncoderConfig {
|
||||
h264_profile: h264_profile(format),
|
||||
..encoder_config(&spec, layer.fps.load(Ordering::Relaxed), layer.threads)
|
||||
};
|
||||
match codecs.new_encoder_preferring(media_codec(format.codec()), config, preference) {
|
||||
Ok(encoder) => {
|
||||
debug!(layer = layer.id, %codec, backend = %encoder.backend(), "encoder for viewers");
|
||||
debug!(layer = layer.id, %format, backend = %encoder.backend(), "encoder for viewers");
|
||||
Some(encoder)
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(layer = layer.id, %codec, "no encoder for viewers of this codec: {e}");
|
||||
warn!(layer = layer.id, %format, "no encoder for viewers of this codec: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -1987,13 +2011,14 @@ fn extra_encoder(shared: &Shared, layer: &Layer, codec: Codec) -> Option<Box<dyn
|
||||
/// dropped when none does).
|
||||
fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box<dyn VideoEncoder>) {
|
||||
let fps = layer.fps.load(Ordering::Relaxed);
|
||||
let mut primary = LayerEncoder::new(encoder, fps);
|
||||
let mut primary = LayerEncoder::primary(encoder, fps);
|
||||
// The first frame is a keyframe anyway; no need to insist.
|
||||
primary.keyframe_due = false;
|
||||
primary.bitrate = layer.bitrate.load(Ordering::Relaxed);
|
||||
*lock(&layer.backend) = primary.encoder.as_ref().map(|e| e.backend());
|
||||
let mut extra: Vec<LayerEncoder> = Vec::new();
|
||||
let mut wanted: Vec<Codec> = Vec::new();
|
||||
let mut wanted: Vec<VideoFormat> = Vec::new();
|
||||
let mut studio_codecs: Vec<Codec> = Vec::new();
|
||||
let mut generation = shared.encoders_generation.load(Ordering::Relaxed);
|
||||
// Whether the stream codec was encoded for the last frame.
|
||||
let mut primary_on = true;
|
||||
@@ -2013,7 +2038,7 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box<dyn VideoEncoder>) {
|
||||
if let Some(next) = lock(&layer.next_encoder).take() {
|
||||
// Another codec: its first frame is a keyframe anyway.
|
||||
*lock(&layer.backend) = Some(next.backend());
|
||||
primary = LayerEncoder::new(next, primary.fps);
|
||||
primary = LayerEncoder::primary(next, primary.fps);
|
||||
}
|
||||
let Some(sink) = shared.sink() else { continue };
|
||||
shared.poll_keyframes(&*sink);
|
||||
@@ -2026,29 +2051,41 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box<dyn VideoEncoder>) {
|
||||
// With a studio, the stream codec for its recordings and replay
|
||||
// buffer, and the codecs its outputs of this layer need (RTMP: H.264).
|
||||
if let Some(studio) = &shared.studio {
|
||||
if !wanted.contains(&primary.codec) {
|
||||
wanted.insert(0, primary.codec);
|
||||
if !wanted.contains(&primary.format) {
|
||||
wanted.insert(0, primary.format);
|
||||
}
|
||||
studio_codecs.clear();
|
||||
studio.output_codecs(u32::from(layer.id), &mut studio_codecs);
|
||||
for &codec in &studio_codecs {
|
||||
let format = video_codec(codec).into();
|
||||
if !wanted.contains(&format) {
|
||||
wanted.push(format);
|
||||
}
|
||||
}
|
||||
studio.output_codecs(u32::from(layer.id), &mut wanted);
|
||||
}
|
||||
let now = shared.encoders_generation.load(Ordering::Relaxed);
|
||||
if now != generation {
|
||||
generation = now;
|
||||
extra.clear();
|
||||
}
|
||||
extra.retain(|e| wanted.contains(&e.codec));
|
||||
for &codec in &wanted {
|
||||
if codec != primary.codec && !extra.iter().any(|e| e.codec == codec) {
|
||||
extra.retain(|e| wanted.contains(&e.format));
|
||||
for &format in &wanted {
|
||||
if format != primary.format && !extra.iter().any(|e| e.format == format) {
|
||||
let fps = layer.fps.load(Ordering::Relaxed);
|
||||
extra.push(match extra_encoder(shared, layer, codec) {
|
||||
Some(encoder) => LayerEncoder::new(encoder, fps),
|
||||
None => {
|
||||
LayerEncoder { codec, encoder: None, keyframe_due: false, bitrate: 0, fps }
|
||||
}
|
||||
extra.push(match extra_encoder(shared, layer, format) {
|
||||
Some(encoder) => LayerEncoder::new(encoder, format, fps),
|
||||
None => LayerEncoder {
|
||||
format,
|
||||
codec: media_codec(format.codec()),
|
||||
encoder: None,
|
||||
keyframe_due: false,
|
||||
bitrate: 0,
|
||||
fps,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
let primary_wanted = wanted.is_empty() || wanted.contains(&primary.codec);
|
||||
let primary_wanted = wanted.is_empty() || wanted.contains(&primary.format);
|
||||
if primary_wanted && !primary_on {
|
||||
// Frames were skipped: the next one must stand alone.
|
||||
primary.keyframe_due = true;
|
||||
@@ -2058,7 +2095,11 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box<dyn VideoEncoder>) {
|
||||
let mut codecs = lock(&layer.codecs);
|
||||
codecs.clear();
|
||||
codecs.extend(primary_on.then_some(primary.codec));
|
||||
codecs.extend(extra.iter().filter(|e| e.encoder.is_some()).map(|e| e.codec));
|
||||
for e in extra.iter().filter(|e| e.encoder.is_some()) {
|
||||
if !codecs.contains(&e.codec) {
|
||||
codecs.push(e.codec);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The stream codec's encoder counts even while nobody takes it, so
|
||||
// the capture does not switch paths as viewers come and go.
|
||||
@@ -2911,11 +2952,11 @@ mod tests {
|
||||
}
|
||||
|
||||
/// A sink whose viewers chose `codecs`; keeps every video frame with its
|
||||
/// codec.
|
||||
/// format.
|
||||
#[derive(Default)]
|
||||
struct CodecSink {
|
||||
codecs: Mutex<Vec<Codec>>,
|
||||
frames: Mutex<Vec<(Codec, EncodedFrame)>>,
|
||||
codecs: Mutex<Vec<VideoFormat>>,
|
||||
frames: Mutex<Vec<(VideoFormat, EncodedFrame)>>,
|
||||
keyframe: AtomicBool,
|
||||
}
|
||||
|
||||
@@ -2924,8 +2965,8 @@ mod tests {
|
||||
true
|
||||
}
|
||||
|
||||
fn send_video(&self, frame: EncodedFrame, codec: Codec) -> bool {
|
||||
lock(&self.frames).push((codec, frame));
|
||||
fn send_video(&self, frame: EncodedFrame, format: VideoFormat) -> bool {
|
||||
lock(&self.frames).push((format, frame));
|
||||
true
|
||||
}
|
||||
|
||||
@@ -2933,11 +2974,30 @@ mod tests {
|
||||
self.keyframe.swap(false, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn video_codecs(&self, out: &mut Vec<Codec>) {
|
||||
fn video_codecs(&self, out: &mut Vec<VideoFormat>) {
|
||||
out.extend(lock(&self.codecs).iter());
|
||||
}
|
||||
}
|
||||
|
||||
impl CodecSink {
|
||||
/// Wait until `count` frames of `format` arrived.
|
||||
async fn wait_for(&self, format: VideoFormat, count: usize) {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
let n = lock(&self.frames).iter().filter(|(f, _)| *f == format).count();
|
||||
if n >= count {
|
||||
return;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "no {format} frames");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn count(&self, format: VideoFormat) -> usize {
|
||||
lock(&self.frames).iter().filter(|(f, _)| *f == format).count()
|
||||
}
|
||||
}
|
||||
|
||||
/// Viewers that chose another codec get their own encoder per layer,
|
||||
/// made when they come and dropped when they go; the stream codec is
|
||||
/// skipped while nobody takes it.
|
||||
@@ -2954,29 +3014,15 @@ mod tests {
|
||||
let streamer = Streamer::start(&codecs, config).await.unwrap();
|
||||
let sink = Arc::new(CodecSink::default());
|
||||
streamer.attach(sink.clone());
|
||||
let wait_for = |codec: Codec, count: usize| {
|
||||
let sink = sink.clone();
|
||||
async move {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
let n = lock(&sink.frames).iter().filter(|(c, _)| *c == codec).count();
|
||||
if n >= count {
|
||||
return;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "no {codec} frames");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
};
|
||||
// Nobody chose yet: the stream codec.
|
||||
wait_for(Codec::Vp8, 3).await;
|
||||
sink.wait_for(VideoFormat::Vp8, 3).await;
|
||||
// A VP9 viewer as well.
|
||||
*lock(&sink.codecs) = vec![Codec::Vp8, Codec::Vp9];
|
||||
wait_for(Codec::Vp9, 5).await;
|
||||
*lock(&sink.codecs) = vec![VideoFormat::Vp8, VideoFormat::Vp9];
|
||||
sink.wait_for(VideoFormat::Vp9, 5).await;
|
||||
assert_eq!(streamer.stats().layers[0].codecs, [Codec::Vp8, Codec::Vp9]);
|
||||
let vp9: Vec<EncodedFrame> = lock(&sink.frames)
|
||||
.iter()
|
||||
.filter(|(c, _)| *c == Codec::Vp9)
|
||||
.filter(|(f, _)| *f == VideoFormat::Vp9)
|
||||
.map(|(_, f)| f.clone())
|
||||
.collect();
|
||||
assert!(is_keyframe(Codec::Vp9, &vp9[0].data), "the first VP9 frame is a keyframe");
|
||||
@@ -2986,12 +3032,11 @@ mod tests {
|
||||
assert_eq!((picture.width, picture.height), (160, 120));
|
||||
}
|
||||
// Only VP9 viewers left: VP8 stops.
|
||||
*lock(&sink.codecs) = vec![Codec::Vp9];
|
||||
*lock(&sink.codecs) = vec![VideoFormat::Vp9];
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
let before = lock(&sink.frames).iter().filter(|(c, _)| *c == Codec::Vp8).count();
|
||||
wait_for(Codec::Vp9, vp9.len() + 10).await;
|
||||
let after = lock(&sink.frames).iter().filter(|(c, _)| *c == Codec::Vp8).count();
|
||||
assert_eq!(before, after, "VP8 is not encoded for nobody");
|
||||
let before = sink.count(VideoFormat::Vp8);
|
||||
sink.wait_for(VideoFormat::Vp9, vp9.len() + 10).await;
|
||||
assert_eq!(before, sink.count(VideoFormat::Vp8), "VP8 is not encoded for nobody");
|
||||
assert_eq!(streamer.stats().layers[0].codecs, [Codec::Vp9]);
|
||||
assert_eq!(streamer.stats().layers[0].backend, Some(EncoderBackend::Libvpx));
|
||||
// Another encoder preference: new encoders, the stream goes on.
|
||||
@@ -3000,8 +3045,54 @@ mod tests {
|
||||
..StreamerConfigUpdate::default()
|
||||
};
|
||||
streamer.reconfigure(&codecs, update).unwrap();
|
||||
let count = lock(&sink.frames).iter().filter(|(c, _)| *c == Codec::Vp9).count();
|
||||
wait_for(Codec::Vp9, count + 5).await;
|
||||
sink.wait_for(VideoFormat::Vp9, sink.count(VideoFormat::Vp9) + 5).await;
|
||||
}
|
||||
|
||||
/// `profile_idc` of the first SPS in an H.264 access unit (Annex B).
|
||||
fn sps_profile(data: &[u8]) -> Option<u8> {
|
||||
let at = data.windows(4).position(|w| w[..3] == [0, 0, 1] && w[3] & 0x1f == 7)?;
|
||||
data.get(at + 4).copied()
|
||||
}
|
||||
|
||||
/// H.264 viewers of both profiles of our offer's ladder: each gets an
|
||||
/// encoder of its own, in its profile (High 100, Baseline 66 in the SPS).
|
||||
#[cfg(feature = "media-desktop")]
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_encoder_per_h264_profile_viewers_chose() {
|
||||
use voelin_stream::H264Profile::{ConstrainedBaseline, ConstrainedHigh};
|
||||
let codecs = Codecs::new();
|
||||
if !codecs.encoder_codecs().contains(&Codec::H264) {
|
||||
eprintln!("skipped: no H.264 encoder on this machine");
|
||||
return;
|
||||
}
|
||||
let config = StreamerConfig {
|
||||
source: SourceId::Synthetic,
|
||||
synthetic_size: (320, 240),
|
||||
codec: Codec::H264,
|
||||
audio: false,
|
||||
..StreamerConfig::default()
|
||||
};
|
||||
let streamer = Streamer::start(&codecs, config).await.unwrap();
|
||||
let sink = Arc::new(CodecSink::default());
|
||||
let (high, baseline) =
|
||||
(VideoFormat::H264(ConstrainedHigh), VideoFormat::H264(ConstrainedBaseline));
|
||||
*lock(&sink.codecs) = vec![high, baseline];
|
||||
streamer.attach(sink.clone());
|
||||
sink.wait_for(high, 3).await;
|
||||
sink.wait_for(baseline, 3).await;
|
||||
let first = |format| {
|
||||
let frames = lock(&sink.frames);
|
||||
frames.iter().find(|(f, _)| *f == format).map(|(_, frame)| frame.data.clone()).unwrap()
|
||||
};
|
||||
assert_eq!(sps_profile(&first(high)), Some(100));
|
||||
assert_eq!(sps_profile(&first(baseline)), Some(66));
|
||||
assert_eq!(streamer.stats().layers[0].codecs, [Codec::H264], "one codec, two profiles");
|
||||
// The Baseline viewers alone: High is no longer encoded.
|
||||
*lock(&sink.codecs) = vec![baseline];
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
let before = sink.count(high);
|
||||
sink.wait_for(baseline, sink.count(baseline) + 10).await;
|
||||
assert_eq!(before, sink.count(high), "High is not encoded for nobody");
|
||||
}
|
||||
|
||||
/// The test pattern through VP8 and back, without a network: pictures
|
||||
|
||||
@@ -30,7 +30,7 @@ use voelin_stream::{
|
||||
pub use voelin_stream::{
|
||||
Codec, EncodedFrame, EndReason, FrameSource, Frequency, LayerId, LayerSet, LayerSpec,
|
||||
LeaveReason, MediaFrame, MediaKind, MediaTime, PeerConfig, SrtpProfile, StreamInfo, StreamKind,
|
||||
StreamSetup, SyntheticSource, VideoCodec, ViewerInfo, ViewerState,
|
||||
StreamSetup, SyntheticSource, VideoCodec, VideoFormat, ViewerInfo, ViewerState,
|
||||
};
|
||||
|
||||
use crate::audio::{AudioHandle, AudioIn};
|
||||
@@ -92,16 +92,16 @@ impl StreamSink {
|
||||
self.live.load(Ordering::Relaxed) && self.tx.send(StreamInput::Frame(frame)).is_ok()
|
||||
}
|
||||
|
||||
/// Send one video frame encoded in `codec`: only viewers whose answer
|
||||
/// chose `codec` get it.
|
||||
pub fn send_video(&self, frame: EncodedFrame, codec: VideoCodec) -> bool {
|
||||
/// Send one video frame encoded in `format`: only viewers whose answer
|
||||
/// chose that codec (and H.264 profile) get it.
|
||||
pub fn send_video(&self, frame: EncodedFrame, format: VideoFormat) -> bool {
|
||||
self.live.load(Ordering::Relaxed)
|
||||
&& self.tx.send(StreamInput::VideoFrame(frame, codec)).is_ok()
|
||||
&& self.tx.send(StreamInput::VideoFrame(frame, format)).is_ok()
|
||||
}
|
||||
|
||||
/// Whether a viewer's answer chose `codec`.
|
||||
pub fn has_video_codec(&self, codec: VideoCodec) -> bool {
|
||||
self.feedback.has_codec(codec)
|
||||
/// Whether a viewer's answer chose `format`.
|
||||
pub fn has_video_codec(&self, format: VideoFormat) -> bool {
|
||||
self.feedback.has_codec(format)
|
||||
}
|
||||
|
||||
/// Whether a viewer asked for a keyframe of any layer since the last
|
||||
@@ -172,8 +172,8 @@ pub(crate) enum StreamInput {
|
||||
/// SRTP profile order of new connections.
|
||||
SrtpProfiles(Vec<SrtpProfile>),
|
||||
Frame(EncodedFrame),
|
||||
/// A video frame for the viewers that chose its codec.
|
||||
VideoFrame(EncodedFrame, VideoCodec),
|
||||
/// A video frame for the viewers that chose its codec and H.264 profile.
|
||||
VideoFrame(EncodedFrame, VideoFormat),
|
||||
Notification(StreamNotification),
|
||||
RequestFailed(Request, String),
|
||||
/// Clients on the server: channel and `client_is_streaming`.
|
||||
@@ -397,8 +397,8 @@ impl StreamTask {
|
||||
self.streams.write_frame(&frame);
|
||||
Ok(())
|
||||
}
|
||||
StreamInput::VideoFrame(frame, codec) => {
|
||||
self.streams.write_frame_in(&frame, Some(codec));
|
||||
StreamInput::VideoFrame(frame, format) => {
|
||||
self.streams.write_frame_in(&frame, Some(format));
|
||||
Ok(())
|
||||
}
|
||||
StreamInput::Notification(n) => {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! The stream's real encoders against a browser's WebRTC stack: the test
|
||||
//! pattern, encoded by each encoder this machine has as a share encodes the
|
||||
//! screen, sent by our streamer peer offering just that codec, must decode
|
||||
//! at its size in headless Chromium (libwebrtc, the stack the official
|
||||
//! TeamSpeak 6 client is built on).
|
||||
//! screen, sent by our streamer peer offering just that codec (H.264 in both
|
||||
//! profiles of the ladder, encoded in the one the browser chose), must
|
||||
//! decode at its size in headless Chromium (libwebrtc, the stack the
|
||||
//! official TeamSpeak 6 client is built on).
|
||||
//!
|
||||
//! Runs only with `VOELIN_INTEROP=1` (see `tests/interop/README.md`). Codecs
|
||||
//! the browser does not decode (H.264 in Playwright's Chromium, HEVC) are
|
||||
@@ -11,6 +12,8 @@
|
||||
|
||||
#![cfg(feature = "media-desktop")]
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, mpsc};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -18,11 +21,11 @@ use tokio::time::timeout;
|
||||
use voelin_core::media::voelin_media::capture::SourceId;
|
||||
use voelin_core::media::voelin_media::{Codec, Codecs};
|
||||
use voelin_core::media::{
|
||||
EncodedSource, EncoderPreference, Streamer, StreamerConfig, decoded_everywhere, media_codec,
|
||||
EncoderPreference, MediaSink, Streamer, StreamerConfig, decoded_everywhere, media_codec,
|
||||
peer_config, preferred_codec, video_codec,
|
||||
};
|
||||
use voelin_core::stream::{FrameSource, PeerConfig, VideoCodec};
|
||||
use voelin_stream::{Peer, PeerEvent};
|
||||
use voelin_core::stream::{EncodedFrame, PeerConfig, VideoFormat};
|
||||
use voelin_stream::{H264Profile, Peer, PeerEvent};
|
||||
|
||||
#[path = "../../../tests/interop/browser.rs"]
|
||||
mod browser;
|
||||
@@ -30,10 +33,45 @@ use browser::{Browser, enabled};
|
||||
|
||||
const SIZE: (u32, u32) = (1280, 720);
|
||||
|
||||
/// A viewer as the stream task serves it: the frames of the format its
|
||||
/// answer chose (the streamer makes an encoder of that format), keyframe
|
||||
/// requests back.
|
||||
struct ViewerSink {
|
||||
format: VideoFormat,
|
||||
frames: mpsc::Sender<EncodedFrame>,
|
||||
keyframe: AtomicBool,
|
||||
}
|
||||
|
||||
impl MediaSink for ViewerSink {
|
||||
fn send(&self, _: EncodedFrame) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn send_video(&self, frame: EncodedFrame, format: VideoFormat) -> bool {
|
||||
format != self.format || self.frames.send(frame).is_ok()
|
||||
}
|
||||
|
||||
fn video_codecs(&self, out: &mut Vec<VideoFormat>) {
|
||||
out.push(self.format);
|
||||
}
|
||||
|
||||
fn take_keyframe_request(&self) -> bool {
|
||||
self.keyframe.swap(false, Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
/// The streamer, its viewer and the viewer's frames.
|
||||
type Source = (Streamer, Arc<ViewerSink>, mpsc::Receiver<EncodedFrame>);
|
||||
|
||||
/// The test pattern encoded with `codec` by the encoders `preference` picks
|
||||
/// (from DMA-BUFs with `dmabuf`, as the ScreenCast portal hands over the
|
||||
/// screen).
|
||||
async fn test_pattern(preference: EncoderPreference, codec: Codec, dmabuf: bool) -> EncodedSource {
|
||||
/// screen), for a viewer of `format`.
|
||||
async fn test_pattern(
|
||||
preference: EncoderPreference,
|
||||
codec: Codec,
|
||||
dmabuf: bool,
|
||||
format: VideoFormat,
|
||||
) -> Source {
|
||||
let codecs = Codecs::new().with_preference(preference.clone());
|
||||
let config = StreamerConfig {
|
||||
source: SourceId::Synthetic,
|
||||
@@ -46,12 +84,22 @@ async fn test_pattern(preference: EncoderPreference, codec: Codec, dmabuf: bool)
|
||||
encoder: preference,
|
||||
..StreamerConfig::default()
|
||||
};
|
||||
EncodedSource::new(Streamer::start(&codecs, config).await.unwrap())
|
||||
let streamer = Streamer::start(&codecs, config).await.unwrap();
|
||||
let (tx, frames) = mpsc::channel();
|
||||
let sink = Arc::new(ViewerSink { format, frames: tx, keyframe: AtomicBool::new(true) });
|
||||
streamer.attach(sink.clone());
|
||||
(streamer, sink, frames)
|
||||
}
|
||||
|
||||
/// `profile_idc` of the first SPS in an H.264 access unit (Annex B).
|
||||
fn sps_profile(data: &[u8]) -> Option<u8> {
|
||||
let at = data.windows(4).position(|w| w[..3] == [0, 0, 1] && w[3] & 0x1f == 7)?;
|
||||
data.get(at + 4).copied()
|
||||
}
|
||||
|
||||
/// Our streamer peer with `config`'s offer, answered by the browser and
|
||||
/// connected; the codec the answer chose, `None` if it took no video.
|
||||
async fn connect(browser: &mut Browser, config: &PeerConfig) -> Option<(Peer, VideoCodec)> {
|
||||
/// connected; the format the answer chose, `None` if it took no video.
|
||||
async fn connect(browser: &mut Browser, config: &PeerConfig) -> Option<(Peer, VideoFormat)> {
|
||||
let (mut peer, offer) = Peer::offer(config, "interop").await.unwrap();
|
||||
let answer = browser.call(json!({ "op": "answer", "sdp": offer })).await;
|
||||
peer.accept_answer(answer["sdp"].as_str().unwrap()).await.ok()?;
|
||||
@@ -71,27 +119,30 @@ async fn connect(browser: &mut Browser, config: &PeerConfig) -> Option<(Peer, Vi
|
||||
Some((peer, chosen?))
|
||||
}
|
||||
|
||||
/// Three seconds of `source` to `peer`; the browser's `inbound-rtp` video
|
||||
/// stats.
|
||||
async fn send(browser: &mut Browser, peer: &mut Peer, source: &mut EncodedSource) -> Value {
|
||||
source.request_keyframe();
|
||||
let mut frames = Vec::new();
|
||||
/// Three seconds of the streamer's frames for its viewer to `peer`; the
|
||||
/// browser's `inbound-rtp` video stats, and the first frame sent.
|
||||
async fn send(
|
||||
browser: &mut Browser,
|
||||
peer: &mut Peer,
|
||||
(_streamer, sink, frames): Source,
|
||||
) -> (Value, Option<EncodedFrame>) {
|
||||
let mut first = None;
|
||||
let end = Instant::now() + Duration::from_secs(3);
|
||||
while Instant::now() < end {
|
||||
source.poll_frames(Instant::now(), &mut frames);
|
||||
for f in frames.drain(..) {
|
||||
peer.write(f.kind, f.time, f.data);
|
||||
while let Ok(f) = frames.try_recv() {
|
||||
peer.write(f.kind, f.time, f.data.clone());
|
||||
first.get_or_insert(f);
|
||||
}
|
||||
while let Some(event) = peer.try_next_event() {
|
||||
if matches!(event, PeerEvent::KeyframeRequest) {
|
||||
source.request_keyframe();
|
||||
sink.keyframe.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
let stats = browser.call(json!({ "op": "stats" })).await;
|
||||
peer.close();
|
||||
stats["inbound"]["video"].clone()
|
||||
(stats["inbound"]["video"].clone(), first)
|
||||
}
|
||||
|
||||
/// Whether the browser decoded most of three seconds at the stream's size.
|
||||
@@ -107,7 +158,9 @@ fn decoded(video: &Value) -> Result<(), String> {
|
||||
|
||||
/// Every encoder of this machine (hardware ones from memory and from
|
||||
/// DMA-BUFs) decodes in the browser: most frames decoded, at the stream's
|
||||
/// size.
|
||||
/// size. H.264 is offered in both profiles of the ladder; the browser takes
|
||||
/// the one it lists (headless Chromium: Constrained Baseline only) and gets
|
||||
/// it from an encoder of that profile.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn real_encoders_decode_in_browser() {
|
||||
if !enabled() {
|
||||
@@ -126,25 +179,30 @@ async fn real_encoders_decode_in_browser() {
|
||||
let config = PeerConfig {
|
||||
video_codecs: vec![video_codec(codec)],
|
||||
audio: false,
|
||||
// Headless Chromium lists only the H.264 profiles of
|
||||
// libwebrtc's software decoder (Baseline, Constrained
|
||||
// Baseline, Main), not the Constrained High we offer; its
|
||||
// FFmpeg decoder takes our High profile streams all the same.
|
||||
h264_profile_level_id: 0x42e01f,
|
||||
..PeerConfig::loopback()
|
||||
};
|
||||
let Some((mut peer, _)) = connect(&mut browser, &config).await else {
|
||||
let Some((mut peer, format)) = connect(&mut browser, &config).await else {
|
||||
eprintln!("{what}: the browser does not decode it, skipped");
|
||||
continue;
|
||||
};
|
||||
let preference =
|
||||
EncoderPreference { hardware: true, backend: backend.name().parse().unwrap() };
|
||||
let mut source = test_pattern(preference, codec, dmabuf).await;
|
||||
let video = send(&mut browser, &mut peer, &mut source).await;
|
||||
eprintln!("{what}: {video}");
|
||||
let source = test_pattern(preference, codec, dmabuf, format).await;
|
||||
let (video, first) = send(&mut browser, &mut peer, source).await;
|
||||
eprintln!("{what}, the browser chose {format}: {video}");
|
||||
if let Err(e) = decoded(&video) {
|
||||
failed.push(format!("{what}: {e}"));
|
||||
}
|
||||
// H.264 in the profile the answer chose.
|
||||
let expected = match format {
|
||||
VideoFormat::H264(H264Profile::ConstrainedHigh) => Some(100),
|
||||
VideoFormat::H264(H264Profile::ConstrainedBaseline) => Some(66),
|
||||
_ => None,
|
||||
};
|
||||
let sps = first.as_ref().and_then(|f| sps_profile(&f.data));
|
||||
if expected.is_some() && sps != expected {
|
||||
failed.push(format!("{what}: SPS profile {sps:?}, {format} answered"));
|
||||
}
|
||||
}
|
||||
}
|
||||
browser.quit().await;
|
||||
@@ -172,15 +230,15 @@ async fn share_offer_picks_a_codec_every_client_decodes() {
|
||||
};
|
||||
let config = peer_config(&codecs, config);
|
||||
eprintln!("offer: {:?}", config.video_codecs);
|
||||
let (mut peer, chosen) = connect(&mut browser, &config).await.expect("video answered");
|
||||
let chosen = media_codec(chosen);
|
||||
let (mut peer, format) = connect(&mut browser, &config).await.expect("video answered");
|
||||
let chosen = media_codec(format.codec());
|
||||
assert!(
|
||||
decoded_everywhere(chosen),
|
||||
"the browser chose {chosen} from {:?}",
|
||||
config.video_codecs
|
||||
);
|
||||
let mut source = test_pattern(codecs.preference().clone(), chosen, false).await;
|
||||
let video = send(&mut browser, &mut peer, &mut source).await;
|
||||
let source = test_pattern(codecs.preference().clone(), chosen, false, format).await;
|
||||
let (video, _) = send(&mut browser, &mut peer, source).await;
|
||||
eprintln!("{chosen}: {video}");
|
||||
browser.quit().await;
|
||||
decoded(&video).unwrap();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Feedback from the stream sessions to the encoders of our stream's layers:
|
||||
//! keyframe requests and bitrate targets per [`LayerId`], and the video
|
||||
//! codecs the viewers negotiated.
|
||||
//! formats (codec and H.264 profile) the viewers negotiated.
|
||||
//!
|
||||
//! [`LayerFeedback`] is shared between the stream session (which writes) and
|
||||
//! encoder threads (which read every frame). Both sides only use atomics;
|
||||
@@ -13,7 +13,7 @@ use std::sync::OnceLock;
|
||||
use std::sync::atomic::{AtomicU8, AtomicU16, AtomicU64, Ordering};
|
||||
|
||||
use crate::layer::{LayerId, LayerSet};
|
||||
use crate::peer::VideoCodec;
|
||||
use crate::peer::VideoFormat;
|
||||
|
||||
/// Words of the keyframe bitmap: one bit per layer id.
|
||||
const WORDS: usize = (LayerId::MAX as usize + 1) / 64;
|
||||
@@ -32,7 +32,7 @@ pub struct LayerFeedback {
|
||||
top: AtomicU16,
|
||||
/// Bitrate targets (bit/s, 0: none) in chunks of [`CHUNK`] layer ids.
|
||||
bitrates: Box<[OnceLock<Box<[AtomicU64]>>]>,
|
||||
/// [`VideoCodec::bit`]s of the codecs connected viewers negotiated.
|
||||
/// [`VideoFormat::bit`]s of the formats connected viewers negotiated.
|
||||
codecs: AtomicU8,
|
||||
}
|
||||
|
||||
@@ -128,15 +128,15 @@ impl LayerFeedback {
|
||||
(bitrate != 0).then_some(bitrate)
|
||||
}
|
||||
|
||||
/// The video codecs the viewers negotiated.
|
||||
pub fn set_codecs(&self, codecs: impl IntoIterator<Item = VideoCodec>) {
|
||||
let bits = codecs.into_iter().fold(0, |bits, c| bits | c.bit());
|
||||
/// The video formats the viewers negotiated.
|
||||
pub fn set_codecs(&self, formats: impl IntoIterator<Item = VideoFormat>) {
|
||||
let bits = formats.into_iter().fold(0, |bits, f| bits | f.bit());
|
||||
self.codecs.store(bits, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Whether a viewer negotiated `codec`.
|
||||
pub fn has_codec(&self, codec: VideoCodec) -> bool {
|
||||
self.codecs.load(Ordering::Relaxed) & codec.bit() != 0
|
||||
/// Whether a viewer negotiated `format`.
|
||||
pub fn has_codec(&self, format: VideoFormat) -> bool {
|
||||
self.codecs.load(Ordering::Relaxed) & format.bit() != 0
|
||||
}
|
||||
|
||||
/// Whether any viewer negotiated a codec yet.
|
||||
@@ -184,11 +184,16 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn codecs() {
|
||||
use crate::h264::H264Profile::{ConstrainedBaseline, ConstrainedHigh};
|
||||
let f = LayerFeedback::new();
|
||||
assert!(!f.has_codecs());
|
||||
f.set_codecs([VideoCodec::Vp8, VideoCodec::H265, VideoCodec::Vp8]);
|
||||
assert!(f.has_codec(VideoCodec::Vp8) && f.has_codec(VideoCodec::H265));
|
||||
assert!(!f.has_codec(VideoCodec::H264));
|
||||
f.set_codecs([VideoFormat::Vp8, VideoFormat::H265, VideoFormat::Vp8]);
|
||||
assert!(f.has_codec(VideoFormat::Vp8) && f.has_codec(VideoFormat::H265));
|
||||
assert!(!f.has_codec(VideoFormat::H264(ConstrainedHigh)));
|
||||
// H.264 in each profile is a format of its own.
|
||||
f.set_codecs([VideoFormat::H264(ConstrainedBaseline)]);
|
||||
assert!(f.has_codec(VideoFormat::H264(ConstrainedBaseline)));
|
||||
assert!(!f.has_codec(VideoFormat::H264(ConstrainedHigh)));
|
||||
f.set_codecs([]);
|
||||
assert!(!f.has_codecs());
|
||||
}
|
||||
|
||||
@@ -3,16 +3,32 @@
|
||||
//! H.264 Table A-1), instead of a fixed level.
|
||||
|
||||
/// Profile of our H.264 streams.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum H264Profile {
|
||||
/// Constrained High (`profile_idc` 100, `constraint_set4` and `5`): what
|
||||
/// TeamSpeak clients decode.
|
||||
#[default]
|
||||
ConstrainedHigh,
|
||||
/// Constrained Baseline (`profile_idc` 66, `constraint_set0` and `1`).
|
||||
/// Constrained Baseline (`profile_idc` 66, `constraint_set0` and `1`):
|
||||
/// what every H.264 decoder takes; libwebrtc's software decoder lists
|
||||
/// no High profile.
|
||||
ConstrainedBaseline,
|
||||
}
|
||||
|
||||
impl H264Profile {
|
||||
/// The order an offer lists them in: Constrained High (better pictures
|
||||
/// for the bitrate), then Constrained Baseline for peers that take only
|
||||
/// that. The streamer encodes each viewer in the one its answer chose.
|
||||
pub const LADDER: [Self; 2] = [Self::ConstrainedHigh, Self::ConstrainedBaseline];
|
||||
|
||||
/// The profile of a `profile-level-id` (`profile_idc` and `profile-iop`
|
||||
/// as [`profile_level_id`] writes them; any level); `None` for other
|
||||
/// profiles.
|
||||
pub fn from_profile_level_id(id: u32) -> Option<Self> {
|
||||
Self::LADDER.into_iter().find(|p| profile_level_id(*p, 0) == id & !0xff)
|
||||
}
|
||||
}
|
||||
|
||||
/// Level limits: `level_idc`, macroblocks per second, macroblocks per frame,
|
||||
/// bitrate in kbit/s (Baseline; High allows 1.25 times that).
|
||||
const LEVELS: [(u8, u64, u64, u64); 19] = [
|
||||
@@ -127,5 +143,14 @@ mod tests {
|
||||
assert_eq!(profile_level_id(H264Profile::ConstrainedBaseline, 31), 0x42e01f);
|
||||
assert_eq!(offer_profile_level_id(HIGH, 320, 240, 15, 200_000), 0x640c1f);
|
||||
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));
|
||||
assert_eq!(
|
||||
H264Profile::from_profile_level_id(0x42e01f),
|
||||
Some(H264Profile::ConstrainedBaseline)
|
||||
);
|
||||
for other in [0x42001f, 0x4d001f, 0x64001f] {
|
||||
assert_eq!(H264Profile::from_profile_level_id(other), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,9 @@ pub use dtls::SrtpProfile;
|
||||
pub use feedback::LayerFeedback;
|
||||
pub use h264::H264Profile;
|
||||
pub use layer::{LayerId, LayerSet, LayerSpec};
|
||||
pub use peer::{MediaFrame, OfferOptions, Peer, PeerConfig, PeerError, PeerEvent, VideoCodec};
|
||||
pub use peer::{
|
||||
MediaFrame, OfferOptions, Peer, PeerConfig, PeerError, PeerEvent, VideoCodec, VideoFormat,
|
||||
};
|
||||
pub use proto::{LeaveReason, StreamInfo, StreamKind, StreamNotification, StreamSetup};
|
||||
pub use session::{
|
||||
EndReason, Output, Request, SessionError, StreamDirectory, StreamEvent, StreamerEvent,
|
||||
|
||||
@@ -92,6 +92,73 @@ impl std::fmt::Display for VideoCodec {
|
||||
}
|
||||
}
|
||||
|
||||
/// A video codec as an answer chose it, with the H.264 profile: the
|
||||
/// streamer encodes each format with an encoder of its own and sends a
|
||||
/// viewer only frames of its format.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum VideoFormat {
|
||||
Vp8,
|
||||
Vp9,
|
||||
H264(H264Profile),
|
||||
Av1,
|
||||
H265,
|
||||
}
|
||||
|
||||
impl VideoFormat {
|
||||
pub const ALL: [Self; 6] = [
|
||||
Self::Vp8,
|
||||
Self::Vp9,
|
||||
Self::H264(H264Profile::ConstrainedHigh),
|
||||
Self::H264(H264Profile::ConstrainedBaseline),
|
||||
Self::Av1,
|
||||
Self::H265,
|
||||
];
|
||||
|
||||
pub fn codec(self) -> VideoCodec {
|
||||
match self {
|
||||
Self::Vp8 => VideoCodec::Vp8,
|
||||
Self::Vp9 => VideoCodec::Vp9,
|
||||
Self::H264(_) => VideoCodec::H264,
|
||||
Self::Av1 => VideoCodec::Av1,
|
||||
Self::H265 => VideoCodec::H265,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bit of this format in a set of formats ([`crate::LayerFeedback`]):
|
||||
/// the codec's, and one more for H.264 Constrained Baseline.
|
||||
pub fn bit(self) -> u8 {
|
||||
match self {
|
||||
Self::H264(H264Profile::ConstrainedBaseline) => 1 << VideoCodec::ALL.len(),
|
||||
other => other.codec().bit(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// H.264 in Constrained High, what our encoders make unless told otherwise.
|
||||
impl From<VideoCodec> for VideoFormat {
|
||||
fn from(codec: VideoCodec) -> Self {
|
||||
match codec {
|
||||
VideoCodec::Vp8 => Self::Vp8,
|
||||
VideoCodec::Vp9 => Self::Vp9,
|
||||
VideoCodec::H264 => Self::H264(H264Profile::ConstrainedHigh),
|
||||
VideoCodec::Av1 => Self::Av1,
|
||||
VideoCodec::H265 => Self::H265,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for VideoFormat {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::H264(H264Profile::ConstrainedHigh) => f.write_str("H264 Constrained High"),
|
||||
Self::H264(H264Profile::ConstrainedBaseline) => {
|
||||
f.write_str("H264 Constrained Baseline")
|
||||
}
|
||||
other => other.codec().fmt(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PeerConfig {
|
||||
/// Local addresses for host candidates. Empty: the primary IPv4 address.
|
||||
@@ -123,10 +190,13 @@ pub struct PeerConfig {
|
||||
/// simulcast leaves the peer unable to send video. Official TeamSpeak
|
||||
/// viewers get a plain offer and one layer at a time.
|
||||
pub simulcast: bool,
|
||||
/// H.264 `profile-level-id` of the offer: Constrained High at the level
|
||||
/// the stream needs ([`set_h264_format`](Self::set_h264_format)); level
|
||||
/// 3.1 by default.
|
||||
pub h264_profile_level_id: u32,
|
||||
/// H.264 `profile-level-id`s of the offer, best first: Constrained High,
|
||||
/// then Constrained Baseline for peers that take only that (headless
|
||||
/// Chromium and other libwebrtc builds without a High decoder), each at
|
||||
/// the level the stream needs ([`set_h264_format`](Self::set_h264_format));
|
||||
/// level 3.1 by default. A viewer gets frames of the profile its answer
|
||||
/// chose ([`PeerEvent::VideoCodec`]). At most two are offered.
|
||||
pub h264_profile_level_ids: Vec<u32>,
|
||||
}
|
||||
|
||||
impl Default for PeerConfig {
|
||||
@@ -141,7 +211,10 @@ impl Default for PeerConfig {
|
||||
srtp_profiles: SrtpProfile::DEFAULT_ORDER.to_vec(),
|
||||
bandwidth_estimation: true,
|
||||
simulcast: false,
|
||||
h264_profile_level_id: H264_CONSTRAINED_HIGH,
|
||||
h264_profile_level_ids: H264Profile::LADDER
|
||||
.iter()
|
||||
.map(|p| h264::profile_level_id(*p, h264::MIN_OFFER_LEVEL))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -156,19 +229,14 @@ impl PeerConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Offer H.264 in `profile` at the level a `width` x `height` stream at
|
||||
/// `fps` and `bitrate` bit/s needs (at least 3.1, see
|
||||
/// [`crate::h264::offer_profile_level_id`]).
|
||||
pub fn set_h264_format(
|
||||
&mut self,
|
||||
profile: H264Profile,
|
||||
width: u32,
|
||||
height: u32,
|
||||
fps: u32,
|
||||
bitrate: u64,
|
||||
) {
|
||||
self.h264_profile_level_id =
|
||||
h264::offer_profile_level_id(profile, width, height, fps, bitrate);
|
||||
/// Offer H.264 in both profiles ([`H264Profile::LADDER`]) at the levels
|
||||
/// a `width` x `height` stream at `fps` and `bitrate` bit/s needs (at
|
||||
/// least 3.1, see [`crate::h264::offer_profile_level_id`]).
|
||||
pub fn set_h264_format(&mut self, width: u32, height: u32, fps: u32, bitrate: u64) {
|
||||
self.h264_profile_level_ids = H264Profile::LADDER
|
||||
.iter()
|
||||
.map(|p| h264::offer_profile_level_id(*p, width, height, fps, bitrate))
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,9 +299,10 @@ pub enum PeerEvent {
|
||||
/// The answer accepted RID simulcast: video goes out per layer with
|
||||
/// these RIDs ([`Peer::write_rid`]).
|
||||
Simulcast(Vec<Rid>),
|
||||
/// The video codec the answer chose (streamer side): the viewer's first
|
||||
/// one. Video written to this peer must be in it.
|
||||
VideoCodec(VideoCodec),
|
||||
/// The video codec the answer chose (streamer side), with the H.264
|
||||
/// profile: the first of our offer the viewer took. Video written to
|
||||
/// this peer must be in it.
|
||||
VideoCodec(VideoFormat),
|
||||
/// The connection is gone.
|
||||
Closed,
|
||||
}
|
||||
@@ -440,9 +509,11 @@ impl Drop for Peer {
|
||||
}
|
||||
}
|
||||
|
||||
/// H.264 Constrained High, level 3.1: reportedly the only H.264 profile the
|
||||
/// TeamSpeak client decodes; str0m's defaults lack it.
|
||||
const H264_CONSTRAINED_HIGH: u32 = 0x640c1f;
|
||||
/// Payload types (and their RTX) of the H.264 profiles an offer lists, in
|
||||
/// the order of [`PeerConfig::h264_profile_level_ids`]: 112 as before for
|
||||
/// Constrained High, which str0m's defaults lack, and 108, str0m's own for
|
||||
/// Constrained Baseline.
|
||||
const H264_PTS: [(u8, u8); 2] = [(112, 113), (108, 109)];
|
||||
|
||||
/// The send simulcast of an offer: the layers with a RID, if at least two.
|
||||
fn simulcast_offer(layers: &[LayerSpec]) -> Option<Simulcast> {
|
||||
@@ -474,10 +545,11 @@ fn simulcast_offer(layers: &[LayerSpec]) -> Option<Simulcast> {
|
||||
|
||||
/// An RTC with Opus and `video` codecs, in this order of preference, our
|
||||
/// DTLS, and bandwidth estimation starting at `bwe` bit/s if given. An
|
||||
/// offer lists H.264 only as our encoders produce it (`profile-level-id`
|
||||
/// [`PeerConfig::h264_profile_level_id`], packetization mode 1): with
|
||||
/// str0m's other variants offered too, a viewer may answer a profile we
|
||||
/// never send. An answer takes every variant the offer has.
|
||||
/// offer lists H.264 only as our encoders produce it (the
|
||||
/// [`PeerConfig::h264_profile_level_ids`], packetization mode 1, best
|
||||
/// first): with str0m's other variants offered too, a viewer may answer a
|
||||
/// profile we never send. An answer takes str0m's variants and Constrained
|
||||
/// High, which they lack.
|
||||
fn build_rtc(
|
||||
config: &PeerConfig,
|
||||
video: &[VideoCodec],
|
||||
@@ -492,12 +564,14 @@ fn build_rtc(
|
||||
VideoCodec::Vp9 => rtc_config.enable_vp9(true),
|
||||
VideoCodec::H264 => {
|
||||
let mut c = if offer { rtc_config } else { rtc_config.enable_h264(true) };
|
||||
c.codec_config().add_h264(
|
||||
112.into(),
|
||||
Some(113.into()),
|
||||
true,
|
||||
config.h264_profile_level_id,
|
||||
);
|
||||
let ids = config.h264_profile_level_ids.iter().copied().filter(|id| {
|
||||
offer
|
||||
|| H264Profile::from_profile_level_id(*id)
|
||||
== Some(H264Profile::ConstrainedHigh)
|
||||
});
|
||||
for (id, (pt, rtx)) in ids.zip(H264_PTS) {
|
||||
c.codec_config().add_h264(pt.into(), Some(rtx.into()), true, id);
|
||||
}
|
||||
c
|
||||
}
|
||||
VideoCodec::Av1 => rtc_config.enable_av1(true),
|
||||
@@ -917,13 +991,21 @@ impl Task {
|
||||
// The codec video is written in (see `find_writer`).
|
||||
if let Some((mid, pt)) = self.find_writer(MediaKind::Video) {
|
||||
self.writers.insert(MediaKind::Video, (mid, pt));
|
||||
let codec = self.rtc.writer(mid).and_then(|w| {
|
||||
let params = w.payload_params().find(|p| p.pt() == pt)?;
|
||||
VideoCodec::from_codec(params.spec().codec)
|
||||
let format = self.rtc.writer(mid).and_then(|w| {
|
||||
let spec = w.payload_params().find(|p| p.pt() == pt)?.spec();
|
||||
Some(match VideoCodec::from_codec(spec.codec)? {
|
||||
VideoCodec::H264 => VideoFormat::H264(
|
||||
spec.format
|
||||
.profile_level_id
|
||||
.and_then(H264Profile::from_profile_level_id)
|
||||
.unwrap_or_default(),
|
||||
),
|
||||
codec => codec.into(),
|
||||
})
|
||||
});
|
||||
if let Some(codec) = codec {
|
||||
debug!(%codec, "the answer chose");
|
||||
let _ = self.events.send(PeerEvent::VideoCodec(codec));
|
||||
if let Some(format) = format {
|
||||
debug!(%format, "the answer chose");
|
||||
let _ = self.events.send(PeerEvent::VideoCodec(format));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -991,10 +1073,24 @@ mod tests {
|
||||
..PeerConfig::loopback()
|
||||
};
|
||||
let (_peer, offer) = Peer::offer(&streamer, "s").await.unwrap();
|
||||
assert!(offer.contains("profile-level-id=640c1f"), "{offer}");
|
||||
// Only the profile we encode: a viewer must not answer another.
|
||||
let h264 = offer.lines().filter(|l| l.contains(" H264/90000")).count();
|
||||
assert_eq!(h264, 1, "{offer}");
|
||||
// Only the profiles we encode, best first: a viewer must not answer
|
||||
// another.
|
||||
let h264: Vec<&str> = offer
|
||||
.lines()
|
||||
.filter(|l| l.starts_with("a=fmtp:") && l.contains("profile-level-id"))
|
||||
.collect();
|
||||
assert_eq!(h264.len(), 2, "{offer}");
|
||||
assert!(h264[0].contains("profile-level-id=640c1f"), "{offer}");
|
||||
assert!(h264[1].contains("profile-level-id=42e01f"), "{offer}");
|
||||
let pts: Vec<&str> = offer
|
||||
.lines()
|
||||
.find_map(|l| l.strip_prefix("m=video "))
|
||||
.unwrap()
|
||||
.split(' ')
|
||||
.skip(2)
|
||||
.collect();
|
||||
let at = |pt: &str| pts.iter().position(|p| *p == pt).unwrap();
|
||||
assert!(at("112") < at("108") && at("108") < at("96"), "{pts:?}");
|
||||
let (_peer, answer) = Peer::answer(&PeerConfig::loopback(), &offer).await.unwrap();
|
||||
assert_eq!(offered_video_codecs(&answer)[0], VideoCodec::H264, "{answer}");
|
||||
let vp8_only =
|
||||
@@ -1067,41 +1163,81 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// The format the answer chose, as the streamer's peer reports it.
|
||||
async fn answered_format(peer: &mut Peer) -> VideoFormat {
|
||||
loop {
|
||||
match peer.next_event().await.unwrap() {
|
||||
PeerEvent::VideoCodec(format) => return format,
|
||||
PeerEvent::Closed => panic!("closed"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Several codecs offered: the streamer learns which one each viewer's
|
||||
/// answer chose; H.264 carries the level the stream needs.
|
||||
/// answer chose; H.264 carries the level the stream needs, in both
|
||||
/// profiles.
|
||||
#[tokio::test]
|
||||
async fn streamer_learns_the_answered_codec() {
|
||||
let mut streamer = PeerConfig {
|
||||
video_codecs: vec![VideoCodec::Vp8, VideoCodec::H264, VideoCodec::H265],
|
||||
..PeerConfig::loopback()
|
||||
};
|
||||
streamer.set_h264_format(H264Profile::ConstrainedHigh, 1920, 1080, 60, 8_000_000);
|
||||
streamer.set_h264_format(1920, 1080, 60, 8_000_000);
|
||||
let (mut peer, offer) = Peer::offer(&streamer, "s").await.unwrap();
|
||||
assert!(offer.contains("profile-level-id=640c2a"), "{offer}");
|
||||
assert!(offer.contains("profile-level-id=42e02a"), "{offer}");
|
||||
assert!(offer.contains("H265/90000"), "{offer}");
|
||||
let high = VideoFormat::H264(H264Profile::ConstrainedHigh);
|
||||
let viewers = [
|
||||
(vec![VideoCodec::Vp8, VideoCodec::H264], VideoCodec::Vp8),
|
||||
(vec![VideoCodec::H264], VideoCodec::H264),
|
||||
(vec![VideoCodec::H265], VideoCodec::H265),
|
||||
(vec![VideoCodec::Vp8, VideoCodec::H264], VideoFormat::Vp8),
|
||||
// Our viewers take both H.264 profiles: the better one.
|
||||
(vec![VideoCodec::H264], high),
|
||||
(vec![VideoCodec::H265], VideoFormat::H265),
|
||||
];
|
||||
for (accept, expected) in viewers {
|
||||
let (mut streamer_peer, offer) = Peer::offer(&streamer, "s").await.unwrap();
|
||||
let config = PeerConfig { accept_video_codecs: accept, ..PeerConfig::loopback() };
|
||||
let (_viewer, answer) = Peer::answer(&config, &offer).await.unwrap();
|
||||
streamer_peer.accept_answer(&answer).await.unwrap();
|
||||
let codec = loop {
|
||||
match streamer_peer.next_event().await.unwrap() {
|
||||
PeerEvent::VideoCodec(codec) => break codec,
|
||||
PeerEvent::Closed => panic!("closed"),
|
||||
_ => {}
|
||||
}
|
||||
};
|
||||
assert_eq!(codec, expected);
|
||||
assert_eq!(answered_format(&mut streamer_peer).await, expected);
|
||||
}
|
||||
peer.close();
|
||||
while peer.next_event().await.is_some() {}
|
||||
}
|
||||
|
||||
/// A viewer whose H.264 is Constrained Baseline only (headless
|
||||
/// Chromium's libwebrtc lists no High profile) answers the fallback
|
||||
/// payload type of our H.264 ladder, and the streamer learns the profile.
|
||||
#[tokio::test]
|
||||
async fn a_baseline_only_viewer_gets_the_fallback_profile() {
|
||||
let streamer =
|
||||
PeerConfig { video_codecs: vec![VideoCodec::H264], ..PeerConfig::loopback() };
|
||||
let (mut streamer_peer, offer) = Peer::offer(&streamer, "s").await.unwrap();
|
||||
let mut viewer = RtcConfig::new().clear_codecs().enable_opus(true);
|
||||
viewer.codec_config().add_h264(102.into(), Some(103.into()), true, 0x42e01f);
|
||||
let mut viewer = viewer.build(Instant::now());
|
||||
let offer = SdpOffer::from_sdp_string(&offer).unwrap();
|
||||
let answer = viewer.sdp_api().accept_offer(offer).unwrap().to_sdp_string();
|
||||
assert!(answer.contains("profile-level-id=42e01f"), "{answer}");
|
||||
assert!(!answer.contains("profile-level-id=640c"), "{answer}");
|
||||
streamer_peer.accept_answer(&answer).await.unwrap();
|
||||
assert_eq!(
|
||||
answered_format(&mut streamer_peer).await,
|
||||
VideoFormat::H264(H264Profile::ConstrainedBaseline)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_bits_are_distinct() {
|
||||
let bits = VideoFormat::ALL.iter().fold(0u8, |bits, f| {
|
||||
assert_eq!(bits & f.bit(), 0, "{f}");
|
||||
bits | f.bit()
|
||||
});
|
||||
assert_eq!(bits.count_ones(), 6);
|
||||
assert_eq!(VideoFormat::from(VideoCodec::H264).bit(), VideoCodec::H264.bit());
|
||||
}
|
||||
|
||||
/// The SDP lines that make up the media description (not the random ids,
|
||||
/// ports, credentials and fingerprints).
|
||||
fn media_lines(sdp: &str) -> Vec<&str> {
|
||||
|
||||
@@ -40,7 +40,7 @@ use crate::discovery::{ClientState, Discovery, StreamLookup};
|
||||
use crate::dtls::SrtpProfile;
|
||||
use crate::feedback::LayerFeedback;
|
||||
use crate::layer::{self, LayerId, LayerSet, LayerSpec};
|
||||
use crate::peer::{MediaFrame, OfferOptions, Peer, PeerConfig, PeerEvent, VideoCodec};
|
||||
use crate::peer::{MediaFrame, OfferOptions, Peer, PeerConfig, PeerEvent, VideoCodec, VideoFormat};
|
||||
use crate::proto::{self, LeaveReason, StreamInfo, StreamNotification, StreamSetup};
|
||||
use crate::signal::Signal;
|
||||
use crate::source::EncodedFrame;
|
||||
@@ -567,8 +567,8 @@ struct ViewerSlot {
|
||||
/// The latest bandwidth estimate of the connection (bit/s).
|
||||
estimate: Option<u64>,
|
||||
srtp_profile: Option<SrtpProfile>,
|
||||
/// The video codec its answer chose.
|
||||
codec: Option<VideoCodec>,
|
||||
/// The video codec (and H.264 profile) its answer chose.
|
||||
codec: Option<VideoFormat>,
|
||||
/// The layer the viewer asked for ([`Signal::Layer`]); `None`: its
|
||||
/// estimate decides.
|
||||
pinned: Option<LayerId>,
|
||||
@@ -680,7 +680,7 @@ impl StreamerSession {
|
||||
layer: (v.peer.is_some() && v.rids.is_none()).then_some(v.choice.layer),
|
||||
estimate: v.estimate,
|
||||
srtp_profile: v.srtp_profile,
|
||||
codec: v.codec,
|
||||
codec: v.codec.map(VideoFormat::codec),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1001,13 +1001,13 @@ impl StreamerSession {
|
||||
self.write_frame_in(frame, None, out);
|
||||
}
|
||||
|
||||
/// [`write_frame`](Self::write_frame) for video encoded in `codec`
|
||||
/// [`write_frame`](Self::write_frame) for video encoded in `format`
|
||||
/// (`None`: whatever the viewers negotiated): only viewers whose answer
|
||||
/// chose that codec get it.
|
||||
/// chose that codec and H.264 profile get it.
|
||||
pub fn write_frame_in(
|
||||
&mut self,
|
||||
frame: &EncodedFrame,
|
||||
codec: Option<VideoCodec>,
|
||||
format: Option<VideoFormat>,
|
||||
out: &mut Outbox,
|
||||
) {
|
||||
let (kind, time, layer) = (frame.kind, frame.time, frame.layer);
|
||||
@@ -1024,8 +1024,8 @@ impl StreamerSession {
|
||||
peer.write(kind, time, frame.data.clone());
|
||||
continue;
|
||||
}
|
||||
if let (Some(codec), Some(negotiated)) = (codec, slot.codec)
|
||||
&& codec != negotiated
|
||||
if let (Some(format), Some(negotiated)) = (format, slot.codec)
|
||||
&& format != negotiated
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -1147,9 +1147,9 @@ impl StreamerSession {
|
||||
slot.rids = Some(rids);
|
||||
}
|
||||
}
|
||||
PeerEvent::VideoCodec(codec) => {
|
||||
debug!(viewer = viewer.0, %codec, "viewer's video codec");
|
||||
slot.codec = Some(codec);
|
||||
PeerEvent::VideoCodec(format) => {
|
||||
debug!(viewer = viewer.0, %format, "viewer's video codec");
|
||||
slot.codec = Some(format);
|
||||
self.emit_viewers(out);
|
||||
}
|
||||
PeerEvent::Media(_) | PeerEvent::LayerMedia { .. } => {}
|
||||
@@ -1683,12 +1683,12 @@ impl Streams {
|
||||
self.write_frame_in(frame, None);
|
||||
}
|
||||
|
||||
/// [`write_frame`](Self::write_frame) of video encoded in `codec`: to
|
||||
/// [`write_frame`](Self::write_frame) of video encoded in `format`: to
|
||||
/// the viewers that negotiated it (see
|
||||
/// [`StreamerSession::write_frame_in`]).
|
||||
pub fn write_frame_in(&mut self, frame: &EncodedFrame, codec: Option<VideoCodec>) {
|
||||
pub fn write_frame_in(&mut self, frame: &EncodedFrame, format: Option<VideoFormat>) {
|
||||
if let Some(s) = self.streamer.as_mut().filter(|s| !s.is_ended()) {
|
||||
s.write_frame_in(frame, codec, &mut self.out);
|
||||
s.write_frame_in(frame, format, &mut self.out);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,9 +21,9 @@ use voelin_core::media::{
|
||||
};
|
||||
use voelin_model::ServerFlavor;
|
||||
use voelin_stream::{
|
||||
ClientState, EndReason, FrameSource, H264Profile, LayerId, LayerSpec, MediaKind, Output,
|
||||
PeerConfig, Request, SrtpProfile, StreamEvent, StreamInfo, StreamNotification, StreamSetup,
|
||||
StreamerEvent, StreamerOptions, Streams, SyntheticSource, VideoCodec, ViewerInfo, WatchEvent,
|
||||
ClientState, EndReason, FrameSource, LayerId, LayerSpec, MediaKind, Output, PeerConfig,
|
||||
Request, SrtpProfile, StreamEvent, StreamInfo, StreamNotification, StreamSetup, StreamerEvent,
|
||||
StreamerOptions, Streams, SyntheticSource, VideoCodec, ViewerInfo, WatchEvent,
|
||||
};
|
||||
|
||||
#[derive(Args, Debug, Clone)]
|
||||
@@ -192,7 +192,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;
|
||||
config.set_h264_format(H264Profile::ConstrainedHigh, w, h, *fps, bitrate);
|
||||
config.set_h264_format(w, h, *fps, bitrate);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -204,8 +204,10 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> {
|
||||
};
|
||||
if matches!(args.command, StreamCommand::Start { .. }) {
|
||||
// Frames go out through a `FrameSource`, which does not tell codecs
|
||||
// apart: offer the stream codec alone.
|
||||
// apart: offer the stream codec alone, H.264 in the profile it is
|
||||
// encoded in (Constrained High).
|
||||
config.video_codecs.truncate(1);
|
||||
config.h264_profile_level_ids.truncate(1);
|
||||
}
|
||||
let codec = stream_codec(&codecs, &config);
|
||||
let mut driver = Driver { streams: Streams::new(own, config), pending: HashMap::new() };
|
||||
|
||||
Reference in new issue
Block a user