Compare commits

...
2 changed files with 47 additions and 11 deletions
+30 -2
View File
@@ -146,6 +146,9 @@ pub struct Movie {
thumbs: Lru<(usize, u32)>,
/// Decoded frames since open (statistics for tests and the UI).
pub decoded: u64,
/// Unit tests can shrink the workload without bypassing the request guard.
#[cfg(test)]
pub(crate) request_bytes_override: Option<usize>,
}
impl std::fmt::Debug for Movie {
@@ -270,7 +273,22 @@ impl Movie {
has_audio,
quicktime: mp4.is_quicktime,
};
Ok(Movie { src, mp4, track, info, codec, order, rank, times, h264: None, cache: Lru::new(12), thumbs: Lru::new(256), decoded: 0 })
Ok(Movie {
src,
mp4,
track,
info,
codec,
order,
rank,
times,
h264: None,
cache: Lru::new(12),
thumbs: Lru::new(256),
decoded: 0,
#[cfg(test)]
request_bytes_override: None,
})
}
pub fn info(&self) -> &MovieInfo {
@@ -470,6 +488,15 @@ impl Movie {
/// at most 16, so a stream that produces nothing for this long will produce nothing.
const MAX_SAMPLES_WITHOUT_PICTURE: usize = 256;
/// The request budget: [`Self::MAX_REQUEST_BYTES`], or a smaller one a unit test sets.
pub(crate) fn max_request_bytes(&self) -> usize {
#[cfg(test)]
if let Some(bytes) = self.request_bytes_override {
return bytes;
}
Self::MAX_REQUEST_BYTES
}
fn decode_h264(&mut self, index: usize) -> Result<Arc<Frame>> {
let Codec::H264 { avcc } = &self.codec else { return Err(VideoError::Unsupported("not H.264".into())) };
let target = self.order.get(index).copied().ok_or(VideoError::OutOfRange)?;
@@ -485,6 +512,7 @@ impl Movie {
}
let total = self.order.len();
let mut last_err: Option<String> = None;
let max_request_bytes = self.max_request_bytes();
let (mut fed, mut without_picture) = (0usize, 0usize);
// Bounded: each iteration feeds one sample, or flushes once at the end.
for _ in 0..=total.saturating_add(1) {
@@ -502,7 +530,7 @@ impl Movie {
let pts = self.rank.get(s).copied().unwrap_or(0) as i64;
// The declared size is checked before the read allocates it. An error leaves no decoder
// behind that has stepped past this sample: the next request starts from its keyframe.
if fed.saturating_add(self.declared_size(s)) > Self::MAX_REQUEST_BYTES {
if fed.saturating_add(self.declared_size(s)) > max_request_bytes {
self.h264 = None;
return Err(VideoError::Decode(format!("frame {index} needs more than {} MiB of samples", Self::MAX_REQUEST_BYTES >> 20)));
}
+17 -9
View File
@@ -120,12 +120,13 @@ fn prores_frame_size_is_checked_before_decoding() {
assert!(matches!(m.frame(0), Err(VideoError::Decode(e)) if e.contains("56x48 frame in a 64x48 track")));
}
/// In-memory movie bytes, zero-padded up to `len` without storing the padding. Records the
/// largest read asked of it and refuses reads over 32 MiB (the test movies are much smaller).
/// In-memory movie bytes, zero-padded up to `len` without storing the padding. Counts
/// reads, records their largest size, and refuses reads over 32 MiB.
struct PaddedSource {
bytes: Vec<u8>,
len: u64,
largest: AtomicUsize,
reads: AtomicUsize,
}
impl ByteSource for PaddedSource {
@@ -134,6 +135,7 @@ impl ByteSource for PaddedSource {
}
fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {
self.largest.fetch_max(buf.len(), Ordering::Relaxed);
self.reads.fetch_add(1, Ordering::Relaxed);
if buf.len() > 32 << 20 {
return Err(std::io::Error::other("read too large for the test source"));
}
@@ -153,7 +155,7 @@ fn h264_sample_reads_are_capped() {
// After the type: version and flags, the constant size (0: one size per sample), the count.
let field = if bytes[at + 8..at + 12] == [0; 4] { at + 16 } else { at + 8 };
bytes[field..field + 4].copy_from_slice(&(300u32 << 20).to_be_bytes());
let src = Arc::new(PaddedSource { bytes, len: 1 << 30, largest: AtomicUsize::new(0) });
let src = Arc::new(PaddedSource { bytes, len: 1 << 30, largest: AtomicUsize::new(0), reads: AtomicUsize::new(0) });
let mut m = Movie::open_source(src.clone()).unwrap();
let r = m.frame(0);
assert!(matches!(&r, Err(VideoError::Decode(e)) if e.contains("sample larger than 256 MiB")), "{r:?}");
@@ -163,27 +165,33 @@ fn h264_sample_reads_are_capped() {
#[test]
fn one_frame_request_reads_a_bounded_amount_of_samples() {
// 65 frames whose `stsz` entries each claim 32 MiB: under the per-sample cap, but together
// past the 2 GiB one request may feed the decoder.
// Keep the 65-sample GOP, but scale the declared sample size and the per-request budget
// together: exactly 64 samples fit, and the 65th must be refused before it is read.
const SAMPLE_BYTES: u32 = 16 << 10;
let mut bytes = h264_mp4(65, 65).unwrap();
let at = bytes.windows(4).position(|w| w == b"stsz").unwrap();
if bytes[at + 8..at + 12] == [0; 4] {
// one size per sample
for i in 0..65 {
let field = at + 16 + 4 * i;
bytes[field..field + 4].copy_from_slice(&(32u32 << 20).to_be_bytes());
bytes[field..field + 4].copy_from_slice(&SAMPLE_BYTES.to_be_bytes());
}
} else {
// the writer stored one size for all the (equally large) samples
bytes[at + 8..at + 12].copy_from_slice(&(32u32 << 20).to_be_bytes());
bytes[at + 8..at + 12].copy_from_slice(&SAMPLE_BYTES.to_be_bytes());
}
let src = Arc::new(PaddedSource { bytes, len: 3 << 30, largest: AtomicUsize::new(0) });
let mut m = Movie::open_source(src).unwrap();
let src = Arc::new(PaddedSource { bytes, len: 3 << 30, largest: AtomicUsize::new(0), reads: AtomicUsize::new(0) });
let mut m = Movie::open_source(src.clone()).unwrap();
assert_eq!(m.max_request_bytes(), 2 << 30);
m.request_bytes_override = Some(64 * SAMPLE_BYTES as usize);
src.reads.store(0, Ordering::Relaxed); // Don't count reads made when opening the movie.
let r = m.frame(64);
assert!(matches!(&r, Err(VideoError::Decode(e)) if e.contains("needs more than 2048 MiB of samples")), "{r:?}");
assert_eq!(src.reads.swap(0, Ordering::Relaxed), 64, "the first request must stop before reading the refused sample");
// the sample that was refused is not skipped: asking again fails the same way instead of decoding past it
let again = m.frame(64);
assert!(matches!(&again, Err(VideoError::Decode(e)) if e.contains("needs more than 2048 MiB of samples")), "{again:?}");
assert_eq!(src.reads.load(Ordering::Relaxed), 64, "the retry must start from the keyframe and stop before the refused sample");
}
/// A source that, once `failing` is set, cannot be read at all.