Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

media browser: probing a file doesn't read it whole (#157)

carlitosteso3dd404568aee9
diff --git a/crates/engine/src/media_browser.rs b/crates/engine/src/media_browser.rs
index 09bd5cd8c..60cc6c244 100644
--- a/crates/engine/src/media_browser.rs
+++ b/crates/engine/src/media_browser.rs
@@ -476,13 +476,17 @@ fn open_in_source(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"item": item.0}))
}
-/// Media properties of a file (cached per path).
+/// Media properties of a file (cached per path). Only the container's index is read; a format
+/// without a streaming reader is read whole only when small (see [`MediaPool::probe_file`]), so
+/// browsing a folder of large AVI or WAV files doesn't read all of them (#157).
+///
+/// [`MediaPool::probe_file`]: crate::media_pool::MediaPool::probe_file
pub fn probe(s: &mut Session, path: &str) -> Option<MediaInfo> {
if let Some(v) = s.browser.probes.get(path) {
return v.clone();
}
let info = if kind_of(path).is_some_and(|k| matches!(k, "video" | "audio" | "image")) {
- s.media.open_file(path, &*s.services).ok().map(|src| src.info().clone())
+ s.media.probe_file(path, &*s.services).ok().map(|src| src.info().clone())
} else {
None
};
diff --git a/crates/engine/src/media_browser_tests.rs b/crates/engine/src/media_browser_tests.rs
index 83d914b5f..df956ea00 100644
--- a/crates/engine/src/media_browser_tests.rs
+++ b/crates/engine/src/media_browser_tests.rs
@@ -248,3 +248,31 @@ fn path_helpers() {
assert_eq!(media_browser::parent("C:\\Media"), Some("C:\\".into()));
assert_eq!(media_browser::base_name("/home/me/Movies/"), "Movies");
}
+
+/// #157: browsing a folder read every file no streaming reader takes (an AVI, a WAV) whole into
+/// memory, just to show its properties or to find out it isn't supported. Large ones are now
+/// refused after the head; small ones still show their properties; MP4 is read through its index.
+#[cfg(any(unix, windows))]
+#[test]
+fn probing_large_unstreamable_files_does_not_read_them_whole() {
+ let dir = crate::media_test_util::tmp_dir("browser-probe-large");
+ // a 100 MB "AVI" (sparse: nothing is written past the header)
+ let avi = dir.join("camera.avi");
+ let mut head = vec![0u8; 64];
+ head[..4].copy_from_slice(b"RIFF");
+ head[8..12].copy_from_slice(b"AVI ");
+ std::fs::write(&avi, &head).unwrap();
+ std::fs::OpenOptions::new().write(true).open(&avi).unwrap().set_len(crate::media_pool::PROBE_WHOLE_FILE_MAX + 36 * 1024 * 1024).unwrap();
+ let wav = dir.join("voice.wav");
+ std::fs::write(&wav, filmcraft_media::wav::write_wav16(&[0.1; 9_600], 2, 48_000)).unwrap();
+ let mov = dir.join("clip.mov");
+ crate::media_test_util::make_movie(&mov, filmcraft_media::DemoScene::OceanSunset, 64, 36, 24);
+ let mut s = Session::default();
+ assert!(media_browser::probe(&mut s, &avi.to_string_lossy()).is_none());
+ assert_eq!(media_browser::probe(&mut s, &wav.to_string_lossy()).unwrap().audio.unwrap().channels, 2);
+ assert!(media_browser::probe(&mut s, &mov.to_string_lossy()).unwrap().video.is_some());
+ // importing is unchanged: it still opens files through the full path
+ let r = s.execute("file.import", json!({"paths": [wav.to_string_lossy()]})).unwrap();
+ assert_eq!(r["items"].as_array().unwrap().len(), 1);
+ let _ = std::fs::remove_dir_all(&dir);
+}
diff --git a/crates/engine/src/media_pool.rs b/crates/engine/src/media_pool.rs
index 6a323ffe5..d2f296111 100644
--- a/crates/engine/src/media_pool.rs
+++ b/crates/engine/src/media_pool.rs
@@ -53,6 +53,10 @@ impl Default for MediaPool {
}
}
+/// Largest file [`MediaPool::probe_file`] reads whole when no streaming reader takes it (WAV,
+/// MP3 and other byte-opened formats, or an unsupported container such as AVI).
+pub const PROBE_WHOLE_FILE_MAX: u64 = 64 * 1024 * 1024;
+
/// Cache key of a media clip's full-resolution reference ("" matches anything: generators and
/// sources inserted without a key).
pub fn media_key(m: &MediaClip) -> String {
@@ -186,6 +190,16 @@ impl MediaPool {
self.open_bytes(&file_name(path), bytes.into())
}
+ /// Open a file to look at it (Media Browser properties and thumbnails), not to import it: a
+ /// format without a streaming reader is read whole only up to [`PROBE_WHOLE_FILE_MAX`] bytes
+ /// (#157). Hosts without random-access readers open the file as [`Self::open_file`] does.
+ pub fn probe_file(&self, path: &str, services: &dyn Services) -> Result<SharedSource, MediaError> {
+ let Some(r) = services.reader(path) else { return self.open_file(path, services) };
+ let r = r.map_err(|e| if e.kind() == std::io::ErrorKind::NotFound { MediaError::Offline(e.to_string()) } else { MediaError::Io(e.to_string()) })?;
+ let openers = self.openers.read().unwrap_or_else(|e| e.into_inner()).clone();
+ filmcraft_media::reader::open_reader_within(&file_name(path), r, &filmcraft_codecs::reader_openers(), &openers, PROBE_WHOLE_FILE_MAX)
+ }
+
/// Resolve (and cache) the source for a project item, using proxies when they are enabled.
pub fn source_for(&self, p: &Project, item: ItemId, services: &dyn Services) -> Option<SharedSource> {
self.resolve(p, item, services, self.use_proxies())
diff --git a/crates/media/src/reader.rs b/crates/media/src/reader.rs
index 3a84fa221..d4f87ab8f 100644
--- a/crates/media/src/reader.rs
+++ b/crates/media/src/reader.rs
@@ -112,12 +112,23 @@ pub const HEAD_LEN: usize = 64 * 1024;
/// Open media from a reader: reader openers first; otherwise read the whole file and use the
/// byte openers (`extra`, then stills / WAV).
pub fn open_reader(name: &str, reader: SharedReader, reader_openers: &[ReaderOpener], extra: &[Opener]) -> Result<SharedSource> {
+ open_reader_within(name, reader, reader_openers, extra, u64::MAX)
+}
+
+/// Like [`open_reader`], but a file no reader opener takes is read whole only up to `max_whole`
+/// bytes; a larger one is refused instead. For looking at files rather than importing them (the
+/// Media Browser's properties and thumbnails, #157): reading a multi-gigabyte AVI or WAV into
+/// memory to show its duration, or to find out it isn't supported, thrashes the disk.
+pub fn open_reader_within(name: &str, reader: SharedReader, reader_openers: &[ReaderOpener], extra: &[Opener], max_whole: u64) -> Result<SharedSource> {
let head = read_range(&*reader, 0, HEAD_LEN).map_err(|e| MediaError::Io(format!("{name}: {e}")))?;
for o in reader_openers {
if let Some(r) = o(name, &head, &reader) {
return r;
}
}
+ if reader.len() > max_whole {
+ return Err(MediaError::Unsupported(format!("{name}: no streaming reader for this format, and it is too large to read whole here")));
+ }
let all = read_range(&*reader, 0, usize::try_from(reader.len()).unwrap_or(usize::MAX)).map_err(|e| MediaError::Io(format!("{name}: {e}")))?;
crate::open_bytes(name, all.into(), extra)
}
@@ -158,6 +169,41 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}
+ /// A reader that counts the bytes read from it.
+ struct Counting(MemReader, std::sync::atomic::AtomicU64);
+ impl ByteReader for Counting {
+ fn len(&self) -> u64 {
+ self.0.len()
+ }
+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
+ self.1.fetch_add(buf.len() as u64, std::sync::atomic::Ordering::SeqCst);
+ self.0.read_at(offset, buf)
+ }
+ }
+
+ /// #157: looking at a file no streaming reader takes (an AVI, a large WAV) read all of it.
+ /// Within a limit it reads the head only and refuses; a small file still opens.
+ #[test]
+ fn open_within_reads_only_the_head_of_large_unstreamable_files() {
+ let mut wav = crate::wav::write_wav16(&vec![0.25; 48_000 * 2], 2, 48_000);
+ let small = wav.len() as u64;
+ let r = Arc::new(Counting(MemReader(Arc::from(wav.clone())), Default::default()));
+ let src = open_reader_within("a.wav", r.clone(), &[], &[], small).unwrap();
+ assert_eq!(src.info().audio.as_ref().unwrap().channels, 2);
+ // the same file over the limit: refused after reading the sniffing head only
+ let r = Arc::new(Counting(MemReader(Arc::from(wav.clone())), Default::default()));
+ let e = open_reader_within("a.wav", r.clone(), &[], &[], small - 1).err().unwrap();
+ assert!(matches!(e, MediaError::Unsupported(_)), "{e:?}");
+ assert!(r.1.load(std::sync::atomic::Ordering::SeqCst) <= HEAD_LEN as u64);
+ // an unsupported format is refused without being read whole either
+ wav.resize(4 * HEAD_LEN, 0);
+ wav[..4].copy_from_slice(b"RIFF");
+ wav[8..12].copy_from_slice(b"AVI ");
+ let r = Arc::new(Counting(MemReader(Arc::from(wav)), Default::default()));
+ assert!(open_reader_within("a.avi", r.clone(), &[], &[], HEAD_LEN as u64).is_err());
+ assert!(r.1.load(std::sync::atomic::Ordering::SeqCst) <= HEAD_LEN as u64);
+ }
+
#[test]
fn falls_back_to_byte_openers() {
// a WAV is opened through the whole-file path