codecs: bound the search for a random-access sample and honour cancellation in it (#4229)

* codecs: bound the search for a random-access sample and honour cancellation in it

* address review: poll cancellation before the sample-zero exit of the random-access search

* address review: refuse an oversized random-access candidate before reading it

* Merge origin/main; address review: check an unknown-size candidate after its read, report the Matroska size with its prefix, and keep sample_size to the containers with a test

* Raise the random-access probe limit to 65 536 so a long unkeyed GOP still seeks
This commit is contained in:
Dylan M. Taylor authored and GitHub committed 2026-11-11 14:01:00 -05:00
1 parent 3285bbf75a
commit 4bec22bd03
4 files changed
+152 -18

No files matched your search

+51 -18
View File
@@ -120,6 +120,12 @@ pub trait VideoSamples: Sync {
/// The sample presented at `t` (track units), if any.
fn sample_at(&self, t: i64) -> Option<usize>;
fn read(&self, i: usize) -> crate::Result<Vec<u8>>;
/// Bytes sample `i` holds, from the index and without reading it. Implementations that know
/// it should say so: the random-access search checks a candidate against its byte budget
/// before [`read`](VideoSamples::read) allocates it. `None`: not known (read, then count).
fn sample_size(&self, _i: usize) -> Option<u64> {
None
}
fn make_decoder(&self) -> crate::Result<Box<dyn VideoDecoder>>;
}
@@ -582,6 +588,49 @@ fn isolated<T: Send>(f: impl FnOnce() -> crate::Result<T> + Send) -> crate::Resu
job()
}
/// Most sync candidates, and bytes read from them, one search for a random-access sample may try.
// 65 536 probes is 18 minutes of an unkeyed 60 fps stream: far past any real GOP, yet each hostile probe stays bounded by the byte budget
const MAX_RANDOM_ACCESS_PROBES: usize = 65_536;
const MAX_RANDOM_ACCESS_PROBE_BYTES: usize = 512 << 20;
/// The container's sync flags may be wrong for the codec (an MP4 without `stss` marks every
/// sample): step back from sync sample `key` to one the decoder can start from (`is_ra` says, with
/// None meaning "cannot tell", which is taken as yes). A file whose index aliases many claimed
/// keyframes onto one large non-random-access sample would otherwise read it once per claim, so
/// the search is bounded in probes and bytes, and stops when the request is cancelled.
fn random_access_at_or_before(s: &dyn VideoSamples, mut key: usize, mut is_ra: impl FnMut(&[u8]) -> Option<bool>) -> crate::Result<usize> {
let (mut probes, mut bytes) = (0usize, 0usize);
// polled before the sample-zero exit too: a cancelled request must not go on to decode from there
if filmcraft_media::cancel::cancelled() {
return Err(CodecError::Cancelled);
}
while key > 0 {
if filmcraft_media::cancel::cancelled() {
return Err(CodecError::Cancelled);
}
// refused before the read: a claimed keyframe that is one huge sample must not be loaded
if s.sample_size(key).is_some_and(|n| n > (MAX_RANDOM_ACCESS_PROBE_BYTES - bytes) as u64) {
return Err(CodecError::Decode("no random-access picture found before the requested frame".into()));
}
let data = s.read(key)?;
// a container that cannot say a sample's size (see `sample_size`) is checked after the read:
// the initial read of an unknown size is allowed, but one sample past the budget ends the search
if data.len() > MAX_RANDOM_ACCESS_PROBE_BYTES - bytes {
return Err(CodecError::Decode("no random-access picture found before the requested frame".into()));
}
if is_ra(&data) != Some(false) {
break;
}
probes += 1;
bytes = bytes.saturating_add(data.len());
if probes >= MAX_RANDOM_ACCESS_PROBES || bytes > MAX_RANDOM_ACCESS_PROBE_BYTES {
return Err(CodecError::Decode("no random-access picture found before the requested frame".into()));
}
key = s.sync_before(key - 1);
}
Ok(key)
}
impl GopCache {
pub fn new(explicit_color: Option<ColorInfo>) -> Self {
// unit tests count decoder restarts: each of their caches gets a pool of its own
@@ -860,15 +909,7 @@ impl GopCache {
let continuing = running && (st.next > key || near) && (i >= st.next || (st.start <= i && want_pts > st.out_max));
if !continuing {
SEEKS.fetch_add(1, Ordering::Relaxed);
// The container's sync flags may be wrong for the codec (an MP4 without `stss` marks
// every sample): step back to a sample the decoder can start from.
while key > 0 {
let data = s.read(key)?;
if st.decoder.as_ref().and_then(|d| d.is_random_access(&data)) != Some(false) {
break;
}
key = s.sync_before(key - 1);
}
key = random_access_at_or_before(s, key, |data| st.decoder.as_ref().and_then(|d| d.is_random_access(data)))?;
if let Some(d) = st.decoder.as_mut() {
d.reset();
}
@@ -942,15 +983,7 @@ impl GopCache {
// Continue the running decoder when the wanted sample is ahead within this GOP run.
let continuing = *next != usize::MAX && *next > key && *next <= i + 16 && *next <= n;
if !continuing {
// The container's sync flags may be wrong for the codec (an MP4 without `stss` marks
// every sample): step back to a sample the decoder can start from.
while key > 0 {
let data = s.read(key)?;
if d.is_random_access(&data) != Some(false) {
break;
}
key = s.sync_before(key - 1);
}
key = random_access_at_or_before(s, key, |data| d.is_random_access(data))?;
d.reset();
*next = key;
}
+94
View File
@@ -1041,3 +1041,97 @@ fn release_idle_empties_idle_caches_and_leaves_one_in_use_alone() {
assert_eq!(pool.bytes.load(Ordering::Relaxed), 0);
assert_eq!(pool.decoders.load(Ordering::Relaxed), 0);
}
/// Every sample claims to be a keyframe but none can start a decode: the search for a random-access
/// sample gives up after a bounded number of probes instead of reading them all.
#[test]
fn random_access_search_is_bounded_when_every_claimed_keyframe_is_not_one() {
struct Aliased {
reads: std::sync::atomic::AtomicUsize,
}
impl VideoSamples for Aliased {
fn count(&self) -> usize {
1 << 20
}
fn pts(&self, i: usize) -> i64 {
i as i64
}
fn sync_before(&self, i: usize) -> usize {
i
}
fn sample_at(&self, t: i64) -> Option<usize> {
usize::try_from(t).ok()
}
fn read(&self, _: usize) -> crate::Result<Vec<u8>> {
self.reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
Ok(vec![0; 16])
}
fn make_decoder(&self) -> crate::Result<Box<dyn VideoDecoder>> {
Err(crate::CodecError::Unsupported("test".into()))
}
}
let s = Aliased { reads: Default::default() };
struct Huge(Aliased);
impl VideoSamples for Huge {
fn count(&self) -> usize {
self.0.count()
}
fn pts(&self, i: usize) -> i64 {
self.0.pts(i)
}
fn sync_before(&self, i: usize) -> usize {
i
}
fn sample_at(&self, t: i64) -> Option<usize> {
self.0.sample_at(t)
}
fn read(&self, i: usize) -> crate::Result<Vec<u8>> {
self.0.read(i)
}
fn sample_size(&self, _: usize) -> Option<u64> {
Some(MAX_RANDOM_ACCESS_PROBE_BYTES as u64 + 1)
}
fn make_decoder(&self) -> crate::Result<Box<dyn VideoDecoder>> {
self.0.make_decoder()
}
}
// a candidate declared larger than the byte budget is refused without being read
let h = Huge(Aliased { reads: Default::default() });
assert!(random_access_at_or_before(&h, 100, |_| Some(true)).is_err());
assert_eq!(h.0.reads.load(std::sync::atomic::Ordering::Relaxed), 0);
assert!(random_access_at_or_before(&s, 1 << 19, |_| Some(false)).is_err());
assert!(s.reads.load(std::sync::atomic::Ordering::Relaxed) <= MAX_RANDOM_ACCESS_PROBES);
// a sample that can start a decode ends the search at once
assert_eq!(random_access_at_or_before(&s, 100, |_| Some(true)).unwrap(), 100);
assert_eq!(random_access_at_or_before(&s, 0, |_| Some(false)).unwrap(), 0);
// a container that cannot say a sample's size: the oversized candidate is refused after its one read
struct Unsized(Aliased);
impl VideoSamples for Unsized {
fn count(&self) -> usize {
self.0.count()
}
fn pts(&self, i: usize) -> i64 {
self.0.pts(i)
}
fn sync_before(&self, i: usize) -> usize {
i
}
fn sample_at(&self, t: i64) -> Option<usize> {
self.0.sample_at(t)
}
fn read(&self, _: usize) -> crate::Result<Vec<u8>> {
self.0.reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
Ok(vec![0; MAX_RANDOM_ACCESS_PROBE_BYTES + 1])
}
fn make_decoder(&self) -> crate::Result<Box<dyn VideoDecoder>> {
self.0.make_decoder()
}
}
let u = Unsized(Aliased { reads: Default::default() });
assert!(random_access_at_or_before(&u, 100, |_| Some(true)).is_err());
assert_eq!(u.0.reads.load(std::sync::atomic::Ordering::Relaxed), 1);
// a cancelled request is refused even when the search starts at sample zero
let flag = Arc::new(std::sync::atomic::AtomicBool::new(true));
let r = filmcraft_media::cancel::with_cancel(&flag, || random_access_at_or_before(&s, 0, |_| Some(true)));
assert!(matches!(r, Err(CodecError::Cancelled)));
}
+4
View File
@@ -617,6 +617,10 @@ impl VideoSamples for MkvVideo<'_> {
fn read(&self, i: usize) -> crate::Result<Vec<u8>> {
self.src.read(self.track, i)
}
fn sample_size(&self, i: usize) -> Option<u64> {
// the size `read` returns: the stored size plus the header-stripping or ProRes prefix
self.src.file.tracks.get(self.track)?.sample_size(i)
}
fn make_decoder(&self) -> crate::Result<Box<dyn VideoDecoder>> {
let Some(e) = &self.src.ventry else {
return Err(CodecError::Unsupported(format!("no decoder for {} video", codec_label(&self.src.file.tracks[self.track].codec))));
+3
View File
@@ -490,6 +490,9 @@ impl VideoSamples for Mp4Video<'_> {
fn read(&self, i: usize) -> crate::Result<Vec<u8>> {
self.src.read(self.track, i)
}
fn sample_size(&self, i: usize) -> Option<u64> {
Some(u64::from(self.src.file.tracks.get(self.track)?.samples.get(i)?.size))
}
fn make_decoder(&self) -> crate::Result<Box<dyn VideoDecoder>> {
make_video_decoder(&self.src.file.tracks[self.track].entries[0])
}