Merge the development branch: stream negotiation, best first then fall back
No conflicts. From the development branch: stream connections step down when they connect but carry no media or never decode (another codec, H.264 profiles, SRTP fallback), mDNS host candidates, larger stream sockets, and the smoke test waiting for clients instead of pausing. Nothing in the UI crate changed; this wave's screens are as they were. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
55440a202d
28 files changed
+2454
-299
No files matched your search
@@ -244,6 +244,13 @@ pub enum Command {
|
||||
session: SessionId,
|
||||
stream_id: String,
|
||||
},
|
||||
/// The video of a watched stream arrives, but none of it decodes: watch
|
||||
/// it in another codec the streamer offered, if there is one (a new
|
||||
/// connection without this one). [`media::Viewer`] sends it.
|
||||
StreamUndecodable {
|
||||
session: SessionId,
|
||||
stream_id: String,
|
||||
},
|
||||
/// Watch simulcast layer `layer` of a stream (`None`: as the bandwidth
|
||||
/// allows). Only for a stream whose [`Event::WatchLayers`] listed
|
||||
/// layers; otherwise an [`Event::Error`].
|
||||
@@ -962,6 +969,7 @@ fn command_session(command: &Command) -> SessionId {
|
||||
| Command::WatchStream { session, .. }
|
||||
| Command::LeaveStream { session, .. }
|
||||
| Command::RequestStreamKeyframe { session, .. }
|
||||
| Command::StreamUndecodable { session, .. }
|
||||
| Command::SetWatchLayer { session, .. }
|
||||
| Command::SetStreamVolume { session, .. }
|
||||
| Command::SetClientVolume { session, .. }
|
||||
|
||||
+298
-76
@@ -59,13 +59,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::{DecoderBackend, DecoderPreference, 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};
|
||||
@@ -95,6 +95,13 @@ const FRAMES_WITHOUT_PICTURE: u32 = 10;
|
||||
const PICTURE_POOL: usize = 4;
|
||||
/// The decoding rates of [`DecodeStats`] cover at least this long.
|
||||
const RATE_WINDOW: Duration = Duration::from_millis(500);
|
||||
/// A watched stream's video of one codec counts as undecodable here once it
|
||||
/// came this long, and at least [`UNDECODABLE_FRAMES`] frames of it, without
|
||||
/// a single picture: time for the pipeline to try every decoder of the
|
||||
/// codec's ladder ([`DECODER_FAILURES`] failures of up to
|
||||
/// [`FRAMES_WITHOUT_PICTURE`] frames each).
|
||||
const UNDECODABLE_AFTER: Duration = Duration::from_secs(10);
|
||||
const UNDECODABLE_FRAMES: u64 = 60;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum MediaError {
|
||||
@@ -128,6 +135,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 {
|
||||
@@ -279,16 +297,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;
|
||||
}
|
||||
}
|
||||
@@ -298,16 +316,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 {
|
||||
@@ -1934,6 +1948,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>>,
|
||||
@@ -1946,8 +1962,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
|
||||
@@ -2008,7 +2032,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);
|
||||
@@ -2030,20 +2054,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
|
||||
}
|
||||
}
|
||||
@@ -2054,13 +2085,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;
|
||||
@@ -2080,7 +2112,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);
|
||||
@@ -2093,29 +2125,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;
|
||||
@@ -2125,7 +2169,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.
|
||||
@@ -2560,6 +2608,51 @@ impl FrameInput {
|
||||
pub fn lost(&self) {
|
||||
lock(&self.queue.state).lost = true;
|
||||
}
|
||||
|
||||
/// Pictures decoded so far (without touching the rates of
|
||||
/// [`VideoPipeline::stats`]).
|
||||
fn decoded(&self) -> u64 {
|
||||
lock(&self.queue.stats).decoded
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the video of a watched stream decodes at all: video of one codec
|
||||
/// that keeps coming ([`UNDECODABLE_AFTER`], [`UNDECODABLE_FRAMES`]) without a
|
||||
/// single picture is reported once, so the stream can be watched in another
|
||||
/// codec ([`Command::StreamUndecodable`]). A codec that decoded once is
|
||||
/// fine (losses later are the pipeline's to repair); another codec starts
|
||||
/// over.
|
||||
struct DecodeWatch {
|
||||
after: Duration,
|
||||
frames: u64,
|
||||
/// The codec, when its first frame came, pictures decoded by then, its
|
||||
/// frames so far, and whether it is settled (decoded, or reported).
|
||||
current: Option<(MediaCodec, Instant, u64, u64, bool)>,
|
||||
}
|
||||
|
||||
type MediaCodec = voelin_stream::Codec;
|
||||
|
||||
impl DecodeWatch {
|
||||
fn new(after: Duration, frames: u64) -> Self {
|
||||
Self { after, frames, current: None }
|
||||
}
|
||||
|
||||
/// A video frame of `codec` arrived at `now`, with `decoded` pictures so
|
||||
/// far; `true` when the codec turned out undecodable.
|
||||
fn frame(&mut self, codec: MediaCodec, decoded: u64, now: Instant) -> bool {
|
||||
let current = match &mut self.current {
|
||||
Some(current) if current.0 == codec => current,
|
||||
_ => self.current.insert((codec, now, decoded, 0, false)),
|
||||
};
|
||||
let (_, since, start, frames, settled) = current;
|
||||
*frames += 1;
|
||||
if *settled || decoded > *start {
|
||||
*settled = true;
|
||||
return false;
|
||||
}
|
||||
*settled = *frames >= self.frames && now.saturating_duration_since(*since) >= self.after;
|
||||
*settled
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes the video frames of one stream on its own thread. See the
|
||||
@@ -2887,11 +2980,25 @@ impl Viewer {
|
||||
let input = pipeline.input();
|
||||
let mut frames = engine.subscribe_frames();
|
||||
let stream_id = stream_id.to_owned();
|
||||
let forward = engine.runtime().spawn(async move {
|
||||
let runtime = engine.runtime().clone();
|
||||
let engine = engine.clone();
|
||||
let forward = runtime.spawn(async move {
|
||||
use tokio::sync::broadcast::error::RecvError;
|
||||
let mut watch = DecodeWatch::new(UNDECODABLE_AFTER, UNDECODABLE_FRAMES);
|
||||
loop {
|
||||
match frames.recv().await {
|
||||
Ok(f) if f.session == session && f.stream_id == stream_id => {
|
||||
if f.frame.kind == MediaKind::Video
|
||||
&& watch.frame(f.frame.codec, input.decoded(), Instant::now())
|
||||
{
|
||||
warn!(
|
||||
stream = stream_id,
|
||||
codec = ?f.frame.codec,
|
||||
"the stream's video does not decode here; asking for another codec"
|
||||
);
|
||||
let stream_id = stream_id.clone();
|
||||
engine.send(Command::StreamUndecodable { session, stream_id });
|
||||
}
|
||||
input.push(f.frame)
|
||||
}
|
||||
Ok(_) => {}
|
||||
@@ -3048,6 +3155,71 @@ pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Reported once, only after both the time and the frames, never for a
|
||||
/// codec that decoded; another codec starts over.
|
||||
#[test]
|
||||
fn decode_watch_reports_a_codec_that_never_decodes() {
|
||||
let (t0, second) = (Instant::now(), Duration::from_secs(1));
|
||||
let mut watch = DecodeWatch::new(2 * second, 3);
|
||||
let vp9 = MediaCodec::Vp9;
|
||||
assert!(!watch.frame(vp9, 5, t0));
|
||||
assert!(!watch.frame(vp9, 5, t0 + 3 * second), "two frames are not enough");
|
||||
assert!(watch.frame(vp9, 5, t0 + 3 * second), "three frames, three seconds, no picture");
|
||||
assert!(!watch.frame(vp9, 5, t0 + 9 * second), "once");
|
||||
// Another codec starts over, and once it decodes it is fine.
|
||||
let vp8 = MediaCodec::Vp8;
|
||||
assert!(!watch.frame(vp8, 5, t0 + 10 * second));
|
||||
assert!(!watch.frame(vp8, 6, t0 + 11 * second));
|
||||
for _ in 0..10 {
|
||||
assert!(!watch.frame(vp8, 6, t0 + 20 * second));
|
||||
}
|
||||
// Many frames quickly are not enough without the time.
|
||||
let av1 = MediaCodec::Av1;
|
||||
for _ in 0..100 {
|
||||
assert!(!watch.frame(av1, 6, t0 + 20 * second));
|
||||
}
|
||||
assert!(watch.frame(av1, 6, t0 + 22 * second));
|
||||
}
|
||||
|
||||
/// Frames that no decoder of the codec takes (VP9 that is not VP9)
|
||||
/// through a real pipeline: no picture comes, and the watch reports it;
|
||||
/// real VP8 keyframes decode and are never reported.
|
||||
#[tokio::test]
|
||||
async fn undecodable_video_is_noticed_through_the_pipeline() {
|
||||
let codecs = Arc::new(Codecs::builtin());
|
||||
let run = |codec: MediaCodec, data: Vec<u8>| {
|
||||
let codecs = codecs.clone();
|
||||
async move {
|
||||
let pipeline = VideoPipeline::new(codecs, |_| {}, || {});
|
||||
let input = pipeline.input();
|
||||
let mut watch = DecodeWatch::new(Duration::from_millis(400), 10);
|
||||
let start = Instant::now();
|
||||
let data: Arc<[u8]> = data.into();
|
||||
for n in 0..40u64 {
|
||||
let frame = MediaFrame {
|
||||
kind: MediaKind::Video,
|
||||
codec,
|
||||
time: MediaTime::from_90khz(n * 3000),
|
||||
network_time: Instant::now(),
|
||||
contiguous: true,
|
||||
data: data.clone(),
|
||||
};
|
||||
if watch.frame(codec, input.decoded(), Instant::now()) {
|
||||
return Some(start.elapsed());
|
||||
}
|
||||
input.push(frame);
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
None
|
||||
}
|
||||
};
|
||||
let junk = vec![0x82, 0x49, 0x83, 0x42, 0x00, 0x13, 0xf0, 0x0e, 0xf6, 0x00, 1, 2, 3];
|
||||
let reported = run(MediaCodec::Vp9, junk).await;
|
||||
assert!(reported.is_some_and(|after| after >= Duration::from_millis(400)), "{reported:?}");
|
||||
let vp8 = voelin_stream::SyntheticSource::video_frame(0, 64);
|
||||
assert_eq!(run(MediaCodec::Vp8, vp8).await, None, "VP8 decodes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyframe_detection() {
|
||||
// VP8: the 1x1 keyframe of voelin-stream's synthetic source.
|
||||
@@ -3126,11 +3298,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,
|
||||
}
|
||||
|
||||
@@ -3139,8 +3311,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
|
||||
}
|
||||
|
||||
@@ -3148,11 +3320,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.
|
||||
@@ -3169,29 +3360,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");
|
||||
@@ -3201,12 +3378,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.
|
||||
@@ -3215,8 +3391,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
|
||||
|
||||
@@ -484,6 +484,9 @@ impl Session {
|
||||
Command::RequestStreamKeyframe { stream_id, .. } => {
|
||||
self.stream_input(StreamInput::RequestKeyframe { stream_id });
|
||||
}
|
||||
Command::StreamUndecodable { stream_id, .. } => {
|
||||
self.stream_input(StreamInput::Undecodable { stream_id });
|
||||
}
|
||||
Command::SetWatchLayer { stream_id, layer, .. } => {
|
||||
self.stream_input(StreamInput::WatchLayer { stream_id, layer });
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -163,6 +163,10 @@ pub(crate) enum StreamInput {
|
||||
RequestKeyframe {
|
||||
stream_id: String,
|
||||
},
|
||||
/// The stream's video arrives but does not decode.
|
||||
Undecodable {
|
||||
stream_id: String,
|
||||
},
|
||||
WatchLayer {
|
||||
stream_id: String,
|
||||
layer: Option<LayerId>,
|
||||
@@ -172,8 +176,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`.
|
||||
@@ -376,6 +380,7 @@ impl StreamTask {
|
||||
self.streams.request_keyframe(&stream_id);
|
||||
Ok(())
|
||||
}
|
||||
StreamInput::Undecodable { stream_id } => self.streams.video_undecodable(&stream_id),
|
||||
StreamInput::WatchLayer { stream_id, layer } => self
|
||||
.streams
|
||||
.set_watch_layer(&stream_id, layer)
|
||||
@@ -397,8 +402,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) => {
|
||||
|
||||
Reference in new issue
Block a user