diff --git a/native/opennow-streamer/crates/opennow-streamer-platform-linux/src/queue.rs b/native/opennow-streamer/crates/opennow-streamer-platform-linux/src/queue.rs index 67586361f..ee6870f52 100644 --- a/native/opennow-streamer/crates/opennow-streamer-platform-linux/src/queue.rs +++ b/native/opennow-streamer/crates/opennow-streamer-platform-linux/src/queue.rs @@ -120,6 +120,17 @@ impl BoundedQueue { outcome } + /// Remove every queued item matching `should_remove`; returns how many. + pub fn remove_where(&self, mut should_remove: impl FnMut(&T) -> bool) -> usize { + let mut state = self + .state + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + let original_len = state.items.len(); + state.items.retain(|queued| !should_remove(queued)); + original_len - state.items.len() + } + pub fn try_pop(&self) -> Option { self.state .lock() @@ -201,7 +212,6 @@ impl BoundedQueue { self.ready.notify_all(); } - #[cfg(test)] pub fn len(&self) -> usize { self.state .lock() @@ -215,6 +225,18 @@ impl BoundedQueue { mod tests { use super::*; + #[test] + fn remove_where_keeps_the_other_items_in_order() { + let queue = BoundedQueue::new(4); + for value in [1, 2, 3, 4] { + assert_eq!(queue.push(value), QueuePush::Added); + } + assert_eq!(queue.remove_where(|value| value % 2 == 0), 2); + assert_eq!(queue.len(), 2); + assert_eq!(queue.try_pop(), Some(1)); + assert_eq!(queue.try_pop(), Some(3)); + } + #[test] fn latest_pop_discards_stale_frames_and_counts_them() { let queue = BoundedQueue::new(3); diff --git a/native/opennow-streamer/crates/opennow-streamer-platform-linux/src/session.rs b/native/opennow-streamer/crates/opennow-streamer-platform-linux/src/session.rs index 6529b9153..d306acaad 100644 --- a/native/opennow-streamer/crates/opennow-streamer-platform-linux/src/session.rs +++ b/native/opennow-streamer/crates/opennow-streamer-platform-linux/src/session.rs @@ -176,6 +176,7 @@ pub enum BackendEvent { NeedKeyframe, QueueOverflow { media: &'static str, + count: usize, }, DeviceLost { subsystem: Subsystem, @@ -543,7 +544,13 @@ fn queue_video_command( }) { QueuePush::Added => Ok(PushOutcome::Queued), QueuePush::Full => { - emit(events, BackendEvent::QueueOverflow { media: "video" }); + emit( + events, + BackendEvent::QueueOverflow { + media: "video", + count: 1, + }, + ); needs_keyframe.store(true, Ordering::Release); // A keyframe that happens to arrive at the overflow boundary can @@ -641,7 +648,13 @@ fn run_video_worker( let mut active_format = config.stream_format; let mut active_generation = 0; + let mut backlog_since: Option = None; loop { + // Every recovery ends in a wait for a keyframe; a backlog is measured + // from that keyframe, not from before the recovery. + if need_keyframe { + backlog_since = None; + } let poll_output = decoder_needs_poll(backend, config.codec); let command = match commands.wait_pop(Duration::from_millis(if poll_output { 5 } else { 100 })) { @@ -713,31 +726,38 @@ fn run_video_worker( { decoded.clear(); decode_timings.clear(); - if backend == DecoderBackend::MediaCodec { - if let Err(error) = close_decoder(&mut decoder) { - report_video_close_error(error, &close_error, &state, &events); - return; - } - drop(decoder); - } - match open_preferred_decoder(&config, active_format) { - Ok((new_backend, new_decoder)) => { - if new_backend != backend { - emit( - &events, - BackendEvent::DecoderChanged { - from: backend, - to: new_backend, - reason: "encoded queue discontinuity".to_owned(), - }, - ); + // Reopening a hardware decoder takes long enough (V4L2 + // stream off/on, buffer allocation) for the encoded queue + // to overflow again, so one overflow turned into seconds of + // back-to-back recoveries. Decoders that can drop their + // state in place (FFmpeg: avcodec_flush_buffers) do that. + if !decoder.reset_in_place() { + if backend == DecoderBackend::MediaCodec { + if let Err(error) = close_decoder(&mut decoder) { + report_video_close_error(error, &close_error, &state, &events); + return; } - backend = new_backend; - decoder = new_decoder; + drop(decoder); } - Err(error) => { - report_worker_error(&state, &events, error); - return; + match open_preferred_decoder(&config, active_format) { + Ok((new_backend, new_decoder)) => { + if new_backend != backend { + emit( + &events, + BackendEvent::DecoderChanged { + from: backend, + to: new_backend, + reason: "encoded queue discontinuity".to_owned(), + }, + ); + } + backend = new_backend; + decoder = new_decoder; + } + Err(error) => { + report_worker_error(&state, &events, error); + return; + } } } need_keyframe = true; @@ -762,7 +782,11 @@ fn run_video_worker( let call_duration = call_started.elapsed(); match result { Ok(frames) => { - if frame.is_some() || !frames.is_empty() { + // Only a submitted frame ends the wait for a keyframe: the gate + // already let it through. Polled output can be left over from + // before a stale backlog was dropped, and says nothing about + // the deltas that follow. + if frame.is_some() { need_keyframe = false; } if !frames.is_empty() { @@ -775,6 +799,31 @@ fn run_video_worker( record_decoded_outputs(&decode_timings, &frames); decode_timings.record_call(call_duration, !frames.is_empty()); enqueue_frames(&decoded, &events, frames); + // A short stall leaves a backlog that a decoder running just + // under the frame interval drains only slowly, keeping the + // picture late for seconds. Drop it instead and restart from + // a keyframe, as a queue overflow would. + if frame.is_some() && commands.len() >= BACKLOG_FRAMES { + let now = Instant::now(); + let since = *backlog_since.get_or_insert(now); + if now.duration_since(since) >= STALE_BACKLOG { + backlog_since = None; + let backlog = drop_stale_backlog(&commands, active_generation); + emit( + &events, + BackendEvent::QueueOverflow { + media: "video", + count: backlog.dropped, + }, + ); + if !backlog.recovery_queued { + need_keyframe = true; + emit(&events, BackendEvent::NeedKeyframe); + } + } + } else { + backlog_since = None; + } } Err(error @ Error::ReferenceLost { .. }) => { decoded.clear(); @@ -885,6 +934,41 @@ fn decoder_needs_poll(backend: DecoderBackend, codec: VideoCodec) -> bool { || (backend == DecoderBackend::V4l2 && codec == VideoCodec::H264) } +/// Encoded frames still queued after a decode. A backlog this deep that does +/// not drain (the decoder keeps pace but no longer catches up) only adds +/// latency; past `STALE_BACKLOG` it is dropped and a keyframe requested. +const BACKLOG_FRAMES: usize = 12; +const STALE_BACKLOG: Duration = Duration::from_millis(250); + +struct StaleBacklog { + dropped: usize, + /// A newer generation's keyframe is queued, so the recovery it starts is + /// already on its way and no other keyframe has to be requested. + recovery_queued: bool, +} + +/// Drops the frames of the generation being decoded. A queue overflow can have +/// put a newer generation behind them, and that one is the recovery itself. +fn drop_stale_backlog(commands: &BoundedQueue, generation: u64) -> StaleBacklog { + let mut recovery_queued = false; + let dropped = commands.remove_where(|queued| match queued { + VideoCommand::Decode { + frame, + generation: queued, + .. + } if *queued > generation => { + recovery_queued |= frame.keyframe; + false + } + VideoCommand::Decode { .. } => true, + VideoCommand::Reconfigure { .. } => false, + }); + StaleBacklog { + dropped, + recovery_queued, + } +} + const AUDIO_DECODE_STRIKES_BEFORE_RESET: u32 = 8; const AUDIO_DECODER_RESET_LIMIT: u32 = 2; @@ -956,7 +1040,13 @@ fn submit_audio_packet( match queue.push_latest(packet) { QueuePush::Added => Ok(PushOutcome::Queued), QueuePush::DroppedOldest => { - emit(events, BackendEvent::QueueOverflow { media: "audio" }); + emit( + events, + BackendEvent::QueueOverflow { + media: "audio", + count: 1, + }, + ); Ok(PushOutcome::DroppedOldest) } QueuePush::Full => unreachable!(), @@ -1504,6 +1594,7 @@ fn enqueue_frames( events, BackendEvent::QueueOverflow { media: "decoded-video", + count: 1, }, ); } @@ -2009,6 +2100,45 @@ mod tests { assert!(session.stop().is_ok()); } + #[test] + fn stale_backlog_drop_keeps_a_newer_generation_recovery() { + let decode = |generation, keyframe| super::VideoCommand::Decode { + frame: super::EncodedVideoFrame::new(vec![0, 0, 0, 1, 0x65], 42, keyframe).unwrap(), + generation, + reset: keyframe, + }; + let commands = super::BoundedQueue::new(8); + for command in [ + decode(1, false), + decode(1, false), + decode(2, true), + decode(2, false), + ] { + assert!(matches!(commands.push(command), super::QueuePush::Added)); + } + let backlog = super::drop_stale_backlog(&commands, 1); + assert_eq!(backlog.dropped, 2); + assert!(backlog.recovery_queued); + assert_eq!(commands.len(), 2); + assert!(matches!( + commands.try_pop(), + Some(super::VideoCommand::Decode { + generation: 2, + reset: true, + .. + }) + )); + + let commands = super::BoundedQueue::new(8); + assert!(matches!( + commands.push(decode(1, false)), + super::QueuePush::Added + )); + let backlog = super::drop_stale_backlog(&commands, 1); + assert_eq!(backlog.dropped, 1); + assert!(!backlog.recovery_queued); + } + #[test] fn overflow_preserves_recovery_keyframe_and_rejects_inter_frames_until_it_arrives() { let commands = BoundedQueue::new(2); diff --git a/native/opennow-streamer/crates/opennow-streamer-platform-linux/src/video/ffmpeg.rs b/native/opennow-streamer/crates/opennow-streamer-platform-linux/src/video/ffmpeg.rs index 1c9a72bee..a2ded1612 100644 --- a/native/opennow-streamer/crates/opennow-streamer-platform-linux/src/video/ffmpeg.rs +++ b/native/opennow-streamer/crates/opennow-streamer-platform-linux/src/video/ffmpeg.rs @@ -470,6 +470,15 @@ impl FfmpegDecoder { subsystem: Subsystem::V4l2, reason, } + } else if self.mode == FfmpegMode::Vaapi && vaapi_picture_error(error) { + // A picture the hardware failed to decode (VA_STATUS_ERROR_ + // DECODING_ERROR becomes EIO in FFmpeg): the stream is still + // decodable from the next keyframe, so recover rather than switch + // to a fallback backend. + Error::ReferenceLost { + subsystem: Subsystem::VaApi, + reason, + } } else { Error::backend(Subsystem::Ffmpeg, reason) } @@ -1118,6 +1127,18 @@ fn map_hardware_frame_to_dmabuf( ) }; if map_result < 0 { + // Mapping syncs the surface, so a picture the hardware failed to + // decode surfaces here: recoverable from the next keyframe. + if mode == FfmpegMode::Vaapi && vaapi_picture_error(ffmpeg::Error::from(map_result)) { + return Err(Error::ReferenceLost { + subsystem: Subsystem::VaApi, + reason: format!( + "{} frame DMA-BUF export failed: {}", + mode.label(), + ffmpeg::Error::from(map_result) + ), + }); + } return Err(ffmpeg_error( format!("{} frame DMA-BUF export failed", mode.label()), map_result, @@ -1306,6 +1327,17 @@ impl VideoDecoder for FfmpegDecoder { self.drain(false) } + fn reset_in_place(&mut self) -> bool { + // Hardware decoders only: the VA context and its surfaces stay, the + // next keyframe (AV1 refresh-all, H.264 IDR) restarts the references. + // Decode errors go through ReferenceLost and a full reopen instead. + if self.mode != FfmpegMode::Vaapi { + return false; + } + self.decoder.flush(); + true + } + fn flush(&mut self) -> Result> { match self.decoder.send_eof() { Ok(()) | Err(ffmpeg::Error::Eof) => self.drain(true), @@ -1321,6 +1353,13 @@ impl VideoDecoder for FfmpegDecoder { } } +/// FFmpeg's VA-API hwaccel turns a failed vaEndPicture/vaSyncSurface into +/// EIO, and a picture it could not set up into InvalidData. +fn vaapi_picture_error(error: ffmpeg::Error) -> bool { + matches!(error, ffmpeg::Error::InvalidData) + || matches!(error, ffmpeg::Error::Other { errno } if errno == libc::EIO) +} + fn initialize_ffmpeg() -> Result<()> { static INITIALIZED: OnceLock> = OnceLock::new(); INITIALIZED @@ -1691,6 +1730,19 @@ mod tests { } } + #[test] + fn vaapi_picture_errors_are_recoverable_and_others_are_not() { + use super::vaapi_picture_error; + assert!(vaapi_picture_error(ffmpeg_next::Error::InvalidData)); + assert!(vaapi_picture_error(ffmpeg_next::Error::Other { + errno: libc::EIO + })); + assert!(!vaapi_picture_error(ffmpeg_next::Error::Other { + errno: libc::ENOMEM + })); + assert!(!vaapi_picture_error(ffmpeg_next::Error::Eof)); + } + #[test] fn hardware_only_policy_rejects_every_software_codec_and_probe() { for codec in [VideoCodec::H264, VideoCodec::H265, VideoCodec::Av1] { diff --git a/native/opennow-streamer/crates/opennow-streamer-platform-linux/src/video/mod.rs b/native/opennow-streamer/crates/opennow-streamer-platform-linux/src/video/mod.rs index ac5f59b15..04785098b 100644 --- a/native/opennow-streamer/crates/opennow-streamer-platform-linux/src/video/mod.rs +++ b/native/opennow-streamer/crates/opennow-streamer-platform-linux/src/video/mod.rs @@ -105,6 +105,11 @@ pub(crate) trait VideoDecoder { fn poll(&mut self) -> Result> { Ok(Vec::new()) } + /// Drop all decoder state so the next keyframe starts clean, without + /// reopening the device. Returns false when only a reopen will do. + fn reset_in_place(&mut self) -> bool { + false + } fn flush(&mut self) -> Result>; fn take_format_change(&mut self) -> Option; } diff --git a/native/opennow-streamer/crates/opennow-streamer-platform/src/media.rs b/native/opennow-streamer/crates/opennow-streamer-platform/src/media.rs index 15a45bdcf..3800819c0 100644 --- a/native/opennow-streamer/crates/opennow-streamer-platform/src/media.rs +++ b/native/opennow-streamer/crates/opennow-streamer-platform/src/media.rs @@ -1423,6 +1423,10 @@ impl MediaSession { }; config.decoder_preference = decoder_preference; config.embedded_presentation = true; + // 200 ms at 120 fps: rides out a brief decoder or network stall; a + // backlog that does not drain is dropped by the session (STALE_BACKLOG) + // rather than kept as latency. + config.encoded_queue_depth = 24; config.stream_format.pixel_format = stream.color_quality.linux_pixel_format(); if stream.hdr { config.stream_format.color_transfer = @@ -3619,10 +3623,10 @@ fn run_embedded_linux_monitor( opennow_streamer_platform_linux::BackendEvent::NeedKeyframe => { request_linux_keyframe(&shared, "Linux decoder requires a fresh keyframe"); } - opennow_streamer_platform_linux::BackendEvent::QueueOverflow { media } => { + opennow_streamer_platform_linux::BackendEvent::QueueOverflow { media, count } => { let _ = shared .feedback - .send(MediaFeedback::QueueDropped { media, count: 1 }); + .send(MediaFeedback::QueueDropped { media, count }); } opennow_streamer_platform_linux::BackendEvent::DeviceLost { subsystem, reason } => { let _ = shared.feedback.send(MediaFeedback::DeviceLost { @@ -3752,10 +3756,10 @@ fn run_linux_monitor(shared: Arc, host_commands: Sender { request_linux_keyframe(&shared, "Linux decoder requires a fresh keyframe"); } - opennow_streamer_platform_linux::BackendEvent::QueueOverflow { media } => { + opennow_streamer_platform_linux::BackendEvent::QueueOverflow { media, count } => { let _ = shared .feedback - .send(MediaFeedback::QueueDropped { media, count: 1 }); + .send(MediaFeedback::QueueDropped { media, count }); } opennow_streamer_platform_linux::BackendEvent::DeviceLost { subsystem, reason } => { let _ = shared.feedback.send(MediaFeedback::DeviceLost {