diff --git a/crates/voelin-core/src/lib.rs b/crates/voelin-core/src/lib.rs index 705179f..fafd6cd 100644 --- a/crates/voelin-core/src/lib.rs +++ b/crates/voelin-core/src/lib.rs @@ -243,6 +243,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`]. @@ -961,6 +968,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, .. } diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index a26d593..ad03601 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -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 { @@ -2601,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 @@ -2928,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(_) => {} @@ -3089,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| { + 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. diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index 1a4634d..4f0a5fb 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -463,6 +463,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 }); } diff --git a/crates/voelin-core/src/stream.rs b/crates/voelin-core/src/stream.rs index 2ea979b..d3542eb 100644 --- a/crates/voelin-core/src/stream.rs +++ b/crates/voelin-core/src/stream.rs @@ -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, @@ -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) diff --git a/crates/voelin-stream/src/session.rs b/crates/voelin-stream/src/session.rs index 073a942..694624d 100644 --- a/crates/voelin-stream/src/session.rs +++ b/crates/voelin-stream/src/session.rs @@ -1597,15 +1597,15 @@ impl ViewerSession { Ok(()) } - /// Connected, but no video came ([`PeerEvent::NoVideo`]): ask for a new - /// connection with the next lower set ([`Fallback`]), without the SRTP - /// profile this one negotiated when nothing came at all, without its - /// video codec when audio did (or no other profile is left). - fn fall_back(&mut self, audio: bool, out: &mut Outbox) { + /// The media of this connection does not get through (`why`): ask for a + /// new connection with the next lower set ([`Fallback`]): without the + /// SRTP profile this one negotiated when `srtp` (nothing came at all), + /// else (or when no other profile is left) without its video codec. + fn fall_back(&mut self, srtp: bool, why: &str, out: &mut Outbox) { let config = self.fallback.apply(&self.config); let profile = self.peer.as_ref().and_then(Peer::srtp_profile); let mut step = None; - if !audio && let Some(profile) = profile { + if srtp && let Some(profile) = profile { step = self .fallback .without_srtp(&config, profile) @@ -1625,18 +1625,24 @@ impl ViewerSession { .map(|left| format!("without {codec} (left: {})", list(&left))); } let Some(step) = step else { - warn!(stream = self.id, audio, "connected, but no video; nothing left to fall back to"); + warn!(stream = self.id, "{why}; nothing left to fall back to"); return; }; - warn!( - stream = self.id, - audio, "connected, but no video; asking for a new connection {step}" - ); + warn!(stream = self.id, "{why}; asking for a new connection {step}"); self.peer = None; self.state = WatchState::Connecting; self.signal(Signal::Reconnect, out); } + /// Video arrives, but none of it decodes here (the app's decoders told + /// [`Streams::video_undecodable`]): a new connection without its codec, + /// if the streamer offered another we take. + pub fn video_undecodable(&mut self, out: &mut Outbox) { + if self.state == WatchState::Connected { + self.fall_back(false, "video arrives, but none of it decodes", out); + } + } + /// Drop the connection and ask the streamer for a new offer (`reconnect`). pub fn reconnect(&mut self, out: &mut Outbox) { if matches!(self.state, WatchState::Connecting | WatchState::Connected) { @@ -1716,7 +1722,12 @@ impl ViewerSession { self.event(WatchEvent::Frame(frame), out); } } - PeerEvent::NoVideo { audio } => self.fall_back(audio, out), + PeerEvent::NoVideo { audio: false } => { + self.fall_back(true, "connected, but nothing arrives", out); + } + PeerEvent::NoVideo { audio: true } => { + self.fall_back(false, "connected, but no video arrives (audio does)", out); + } PeerEvent::KeyframeRequest | PeerEvent::LayerKeyframeRequest(_) | PeerEvent::BitrateEstimate(_) @@ -1944,6 +1955,16 @@ impl Streams { viewer.set_layer(layer, &mut self.out) } + /// The video of a watched stream arrives, but none of it decodes: watch + /// it in another codec the streamer offered, if there is one (see + /// [`ViewerSession::video_undecodable`]). + pub fn video_undecodable(&mut self, id: &str) -> Result<(), SessionError> { + let viewer = + self.viewers.get_mut(id).ok_or_else(|| SessionError::NotWatching(id.into()))?; + viewer.video_undecodable(&mut self.out); + Ok(()) + } + /// Reconnect to a watched stream: the streamer sends a new offer. pub fn reconnect(&mut self, id: &str) -> Result<(), SessionError> { let viewer = diff --git a/crates/voelin-stream/tests/sessions.rs b/crates/voelin-stream/tests/sessions.rs index ae52869..22f5e1a 100644 --- a/crates/voelin-stream/tests/sessions.rs +++ b/crates/voelin-stream/tests/sessions.rs @@ -610,6 +610,40 @@ async fn viewer_falls_back_to_another_codec() { assert_eq!(net.viewer().codec, Some(VideoCodec::Vp8)); } +/// Video arrives in the codec our answer took, but our decoders make +/// nothing of it (the app's pipeline says so: `video_undecodable`): the +/// viewer asks for a new connection without that codec and gets the next +/// one the streamer offered. With no other codec left it stays. +#[tokio::test(flavor = "multi_thread")] +async fn undecodable_video_falls_back_to_another_codec() { + let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init(); + let streamer = PeerConfig { + video_codecs: vec![VideoCodec::Vp9, VideoCodec::Vp8], + ..config(&SrtpProfile::DEFAULT_ORDER, Duration::MAX) + }; + let mut net = Net::with(streamer, config(&SrtpProfile::DEFAULT_ORDER, Duration::MAX), None); + net.source = Some(SyntheticSource::new(30, 4000, true)); + let id = net.watching().await; + net.frames(10).await; + assert_eq!(net.viewer().codec, Some(VideoCodec::Vp9)); + net.clients[VIEWER].video_undecodable(&id).unwrap(); + net.until("connected again", |i, e| { + i == VIEWER && watch_event(e, |e| matches!(e, WatchEvent::Connected)) + }) + .await; + net.frames(10).await; + assert_eq!(net.sent(VIEWER, |s| *s == Signal::Reconnect), 1); + assert_eq!(net.viewer().codec, Some(VideoCodec::Vp8)); + // VP8 does not decode either: nothing is left, the viewer stays. + net.clients[VIEWER].video_undecodable(&id).unwrap(); + net.frames(10).await; + assert_eq!(net.sent(VIEWER, |s| *s == Signal::Reconnect), 1); + assert_eq!( + net.clients[VIEWER].video_undecodable("nope"), + Err(SessionError::NotWatching("nope".into())) + ); +} + /// Nothing left to fall back to: SRTP fails with every profile both sides /// have. The viewer says so and stays; nothing loops. #[tokio::test(flavor = "multi_thread")]