FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
#447: HybridDecoder fallback replay goes on past samples the software decoder rejects
MrCloudy2c724bc5566c8
diff --git a/crates/platform/src/hybrid.rs b/crates/platform/src/hybrid.rsindex 073549182..c010e79e0 100644--- a/crates/platform/src/hybrid.rs+++ b/crates/platform/src/hybrid.rs@@ -129,7 +129,10 @@ impl HybridDecoder {}/// Switch to the software decoder after `err`, replaying the log (which ends with the sample- /// that failed).+ /// that failed). The replay goes on past samples the software decoder rejects, as decoding in+ /// software from the restart point would: one that the hardware had already decoded is logged+ /// (its call returned long ago), and if the failed sample itself is rejected its error is this+ /// call's, while the pictures replayed before it are kept for the next output.fn fall_back(&mut self, err: CodecError) -> Result<Vec<DecodedFrame>> {let Some(mut hw) = self.hw.take() else { return Err(err) };log::warn!("{} failed ({err}); continuing with the software decoder", hw.name());@@ -149,12 +152,28 @@ impl HybridDecoder {return Err(CodecError::Decode(format!("{err} (continuing in software after the next seek)")));};let mut frames = Vec::new();- for (s, p) in &log {+ let mut rejected = None;+ let last = log.len().saturating_sub(1);+ for (i, (s, p)) in log.iter().enumerate() {let Some(sw) = self.sw.as_mut() else { break };- frames.extend(sw.decode(s, *p)?);+ match sw.decode(s, *p) {+ Ok(out) => frames.extend(out),+ Err(e) if i == last => rejected = Some(e),+ Err(e) => log::warn!("software replay after the hardware decoder failed: {e}"),+ }}self.log = Some(log);- Ok(self.merge(frames))+ match rejected {+ None => Ok(self.merge(frames)),+ Some(e) => {+ for f in frames {+ if !self.emitted.contains(&f.pts) {+ self.carry.insert(f.pts, f);+ }+ }+ Err(e)+ }+ }}}diff --git a/crates/platform/tests/fallback.rs b/crates/platform/tests/fallback.rsindex f6005c14c..95d8e4304 100644--- a/crates/platform/tests/fallback.rs+++ b/crates/platform/tests/fallback.rs@@ -1,7 +1,9 @@//! [`HybridDecoder`] fallback on every platform, with a stand-in "hardware" decoder (our software//! decoder that starts failing after N samples, as a lost hardware session does): the output must//! be exactly the software decoder's, whatever sample the failure hits. Also: in-band parameter-//! sets that differ from the sample entry's switch to software; identical ones do not.+//! sets that differ from the sample entry's switch to software; identical ones do not; and a+//! damaged sample that the hardware decoded but the software decoder rejects, inside the replayed+//! run, loses no picture.mod common;@@ -105,3 +107,107 @@ fn changed_in_band_parameter_sets_switch_to_software() {assert!(!d.is_hardware(), "changed SPS: software");assert_same("changed SPS", &out, &decode_all(filmcraft_codecs::software_video_decoder(&s.entry).unwrap().as_mut(), &changed));}++/// Like [`Failing`], but tolerant of one damaged sample the way a GPU can be: at `damaged_at` it+/// decodes the intact sample instead of the one it is given (which the software decoder rejects).+struct Tolerant {+ inner: Box<dyn VideoDecoder>,+ intact: Vec<u8>,+ damaged_at: usize,+ fail_after: usize,+ fed: usize,+}++impl VideoDecoder for Tolerant {+ fn decode(&mut self, sample: &[u8], pts: i64) -> Result<Vec<DecodedFrame>> {+ let i = self.fed;+ self.fed += 1;+ if self.fed > self.fail_after {+ return Err(filmcraft_codecs::CodecError::Decode("session invalidated (test)".into()));+ }+ self.inner.decode(if i == self.damaged_at { &self.intact } else { sample }, pts)+ }+ fn flush(&mut self) -> Vec<DecodedFrame> {+ self.inner.flush()+ }+ fn reset(&mut self) {+ self.inner.reset();+ }+ fn name(&self) -> &str {+ "stand-in hardware"+ }+}++/// Feed `samples` then flush, carrying on past samples the decoder rejects (as playback does);+/// returns the pictures and the indices of the rejected samples.+fn decode_lenient(d: &mut dyn VideoDecoder, samples: &[(Vec<u8>, i64)]) -> (Vec<DecodedFrame>, Vec<usize>) {+ let (mut out, mut rejected) = (Vec::new(), Vec::new());+ for (i, (s, p)) in samples.iter().enumerate() {+ match d.decode(s, *p) {+ Ok(f) => out.extend(f),+ Err(_) => rejected.push(i),+ }+ }+ out.extend(d.flush());+ (out, rejected)+}++/// The sample's NAL unit with its header kept and its payload overwritten: the slice header no+/// longer parses, so the software decoder rejects the sample.+fn damaged(sample: &[u8], nal_header: usize) -> Vec<u8> {+ let mut v = sample.to_vec();+ let start = (4 + nal_header).min(v.len());+ v[start..].fill(0xff);+ v+}++/// A replay (after the hardware fails) that meets a sample the software decoder rejects must go+/// on to the end of the replayed run, like decoding in software does, and must not lose the+/// pictures it decoded before that sample: every picture the software decoder outputs for the+/// stream is output, once and in order, and from the next restart point on the pictures are the+/// software decoder's.+#[test]+fn a_sample_software_rejects_during_the_replay_loses_no_pictures() {+ let ff = filmcraft_testkit::require_ffmpeg!();+ let mut checked = 0;+ for (name, _) in FIXTURES {+ let Some(path) = named(&ff, name) else { continue };+ let s = read_stream(&path);+ let info = NalStreamInfo::from_entry(&s.entry).unwrap().unwrap();+ let header = if name.starts_with("hevc") { 2 } else { 1 };+ // the second restart point, and a disposable picture before it that is not the first sample+ let Some(next) = (1..s.samples.len()).find(|&i| s.sync[i]) else { continue };+ let Some(d) = (2..next.saturating_sub(2)).find(|&i| info.is_disposable(&s.samples[i].0)) else { continue };+ let mut stream = s.samples.clone();+ stream[d].0 = damaged(&s.samples[d].0, header);+ let (reference, rejected) = decode_lenient(filmcraft_codecs::software_video_decoder(&s.entry).unwrap().as_mut(), &stream);+ assert_eq!(rejected, [d], "{name}: the software decoder rejects the damaged sample (and only it)");+ let restart = stream[next..].iter().map(|x| x.1).min().unwrap();+ // failing at the damaged sample itself (the software decoder rejects the failed sample+ // too), and after the hardware had decoded it+ for fail_after in [d, d + 1, d + 2, next - 1] {+ let tolerant = Tolerant {+ inner: filmcraft_codecs::software_video_decoder(&s.entry).unwrap(),+ intact: s.samples[d].0.clone(),+ damaged_at: d,+ fail_after,+ fed: 0,+ };+ let mut h = HybridDecoder::new(Box::new(tolerant), s.entry.clone(), info.clone());+ let (out, errors) = decode_lenient(&mut h, &stream);+ let what = format!("{name}: sample {d} damaged, hardware failing after {fail_after}");+ assert!(!h.is_hardware(), "{what}: fell back");+ // the damaged sample is reported as the software decoder reports it, unless the+ // hardware had already decoded it+ assert_eq!(errors, if fail_after == d { vec![d] } else { vec![] }, "{what}: rejected samples");+ let pts: Vec<i64> = out.iter().map(|f| f.pts).collect();+ assert!(pts.windows(2).all(|w| w[0] < w[1]), "{what}: pictures once and in order: {pts:?}");+ let lost: Vec<i64> = reference.iter().map(|f| f.pts).filter(|p| !pts.contains(p)).collect();+ assert!(lost.is_empty(), "{what}: lost pictures at pts {lost:?}");+ let from = |v: &[DecodedFrame]| v.iter().position(|f| f.pts >= restart).unwrap_or(v.len());+ assert_same(&format!("{what}, from the next restart point"), &out[from(&out)..], &reference[from(&reference)..]);+ }+ checked += 1;+ }+ assert_eq!(checked, FIXTURES.len(), "every fixture has a damaged-sample case");+}