Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,17 @@ impl<T> BoundedQueue<T> {
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<T> {
self.state
.lock()
Expand Down Expand Up @@ -201,7 +212,6 @@ impl<T> BoundedQueue<T> {
self.ready.notify_all();
}

#[cfg(test)]
pub fn len(&self) -> usize {
self.state
.lock()
Expand All @@ -215,6 +225,18 @@ impl<T> BoundedQueue<T> {
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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ pub enum BackendEvent {
NeedKeyframe,
QueueOverflow {
media: &'static str,
count: usize,
},
DeviceLost {
subsystem: Subsystem,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<Instant> = 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 })) {
Expand Down Expand Up @@ -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;
Expand All @@ -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() {
Expand All @@ -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 {
Comment on lines +807 to +809

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reset the backlog timer when decoder recovery starts

If reference-loss recovery or reconfiguration occurs while backlog_since is set, that timestamp survives the decoder restart and any wait for a new keyframe. After a recovery lasting at least 250 ms, a fresh keyframe with 12 newly queued access units behind it immediately satisfies this comparison, discarding the new prediction chain and closing the keyframe gate again even though the new backlog has existed only briefly. This produces an unnecessary second freeze and keyframe request immediately after successful recovery. Clear the timer at decoder recovery and generation boundaries before measuring the new backlog.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed. Fixed in f7cdbe2: every recovery ends with need_keyframe set, so the worker clears backlog_since for as long as that wait lasts. A new backlog is measured from the keyframe that ends it.

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();
Expand Down Expand Up @@ -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<VideoCommand>, 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;

Expand Down Expand Up @@ -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!(),
Expand Down Expand Up @@ -1504,6 +1594,7 @@ fn enqueue_frames(
events,
BackendEvent::QueueOverflow {
media: "decoded-video",
count: 1,
},
);
}
Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<Vec<DecodedVideoFrame>> {
match self.decoder.send_eof() {
Ok(()) | Err(ffmpeg::Error::Eof) => self.drain(true),
Expand All @@ -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<std::result::Result<(), String>> = OnceLock::new();
INITIALIZED
Expand Down Expand Up @@ -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] {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,11 @@ pub(crate) trait VideoDecoder {
fn poll(&mut self) -> Result<Vec<DecodedVideoFrame>> {
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<Vec<DecodedVideoFrame>>;
fn take_format_change(&mut self) -> Option<StreamFormat>;
}
Expand Down
Loading