Skip to content

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

MEM1: desktop reads media files in place

justjohn12345ac8279d293b6
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index a5f34e61d..3cb02a834 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -163,6 +163,11 @@ impl Services for FsServices {
fn file_loader(&self) -> Option<filmcraft_media::sequence::FrameLoader> {
Some(std::sync::Arc::new(|p: &str| std::fs::read(p)))
}
+ /// Media are read in place from the open file: a clip costs its index, not its size.
+ #[cfg(any(unix, windows))]
+ fn reader(&self, path: &str) -> Option<std::io::Result<filmcraft_media::SharedReader>> {
+ Some(filmcraft_media::reader::FileReader::open(std::path::Path::new(path)).map(|r| std::sync::Arc::new(r) as filmcraft_media::SharedReader))
+ }
fn list_entries(&self, dir: &str) -> Option<std::io::Result<Vec<media_browser::DirEntry>>> {
Some(media_browser::std_list_entries(dir))
}
diff --git a/crates/engine/src/media_pool.rs b/crates/engine/src/media_pool.rs
index b8e7bc729..6a323ffe5 100644
--- a/crates/engine/src/media_pool.rs
+++ b/crates/engine/src/media_pool.rs
@@ -382,3 +382,47 @@ impl MediaSource for ProxySource {
self.proxy.audio(start, frames, sample_rate)
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A host whose whole-file read fails: opening must go through the reader.
+ struct ReaderOnly(Arc<[u8]>);
+ impl Services for ReaderOnly {
+ fn read_file(&self, path: &str) -> std::io::Result<Vec<u8>> {
+ Err(std::io::Error::other(format!("{path}: read whole")))
+ }
+ fn write_file(&self, _path: &str, _data: &[u8]) -> std::io::Result<()> {
+ Ok(())
+ }
+ fn reader(&self, _path: &str) -> Option<std::io::Result<filmcraft_media::SharedReader>> {
+ Some(Ok(Arc::new(filmcraft_media::reader::MemReader(self.0.clone()))))
+ }
+ }
+
+ #[test]
+ fn open_file_prefers_the_hosts_reader() {
+ let wav = filmcraft_media::wav::write_wav16(&[0.0, 0.5, -0.5, 0.25], 2, 48_000);
+ let s = MediaPool::default().open_file("a.wav", &ReaderOnly(wav.into())).unwrap();
+ assert!(s.info().has_audio());
+ }
+
+ /// The desktop host reads media in place instead of loading every clip into memory.
+ #[cfg(any(unix, windows))]
+ #[test]
+ fn fs_services_open_media_through_a_file_reader() {
+ let dir = std::env::temp_dir().join(format!("filmcraft-pool-reader-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("a.wav");
+ let wav = filmcraft_media::wav::write_wav16(&[0.0, 0.5, -0.5, 0.25], 2, 48_000);
+ std::fs::write(&path, &wav).unwrap();
+ let p = path.to_string_lossy().to_string();
+ let r = crate::FsServices.reader(&p).expect("a reader").unwrap();
+ assert_eq!(r.len(), wav.len() as u64);
+ assert!(MediaPool::default().open_file(&p, &crate::FsServices).unwrap().info().has_audio());
+ let missing = dir.join("missing.wav").to_string_lossy().to_string();
+ assert!(matches!(MediaPool::default().open_file(&missing, &crate::FsServices), Err(MediaError::Offline(_))));
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/crates/media/src/reader.rs b/crates/media/src/reader.rs
index 1fbbac76f..3a84fa221 100644
--- a/crates/media/src/reader.rs
+++ b/crates/media/src/reader.rs
@@ -43,6 +43,57 @@ impl ByteReader for MemReader {
}
}
+/// A file on disk, read in place: the file stays open and only the requested ranges are read, so
+/// opening a clip costs its index rather than its size.
+#[cfg(any(unix, windows))]
+#[derive(Debug)]
+pub struct FileReader {
+ file: std::fs::File,
+ len: u64,
+}
+
+#[cfg(any(unix, windows))]
+impl FileReader {
+ pub fn open(path: &std::path::Path) -> io::Result<Self> {
+ let file = std::fs::File::open(path)?;
+ let m = file.metadata()?;
+ if !m.is_file() {
+ return Err(io::Error::new(io::ErrorKind::NotFound, format!("{} is not a file", path.display())));
+ }
+ Ok(Self { file, len: m.len() })
+ }
+}
+
+#[cfg(any(unix, windows))]
+impl ByteReader for FileReader {
+ fn len(&self) -> u64 {
+ self.len
+ }
+ /// Positional reads: threads decoding different parts of the file do not share a cursor.
+ fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
+ #[cfg(unix)]
+ {
+ std::os::unix::fs::FileExt::read_exact_at(&self.file, buf, offset)
+ }
+ #[cfg(windows)]
+ {
+ let (mut done, mut at) = (0usize, offset);
+ while let Some(rest) = buf.get_mut(done..).filter(|r| !r.is_empty()) {
+ match std::os::windows::fs::FileExt::seek_read(&self.file, rest, at) {
+ Ok(0) => return Err(eof()),
+ Ok(n) => {
+ done = done.saturating_add(n);
+ at = at.saturating_add(n as u64);
+ }
+ Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
+ Err(e) => return Err(e),
+ }
+ }
+ Ok(())
+ }
+ }
+}
+
/// Read `len` bytes at `offset` (fewer at the end of the reader).
pub fn read_range(r: &dyn ByteReader, offset: u64, len: usize) -> io::Result<Vec<u8>> {
let n = (r.len().saturating_sub(offset)).min(len as u64) as usize;
@@ -85,6 +136,28 @@ mod tests {
assert_eq!(read_range(&r, 8, 100).unwrap(), b"89");
}
+ #[cfg(any(unix, windows))]
+ #[test]
+ fn file_reader_reads_ranges_in_place() {
+ let dir = std::env::temp_dir().join(format!("filmcraft-file-reader-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("bytes.bin");
+ std::fs::write(&path, b"0123456789").unwrap();
+ let r = FileReader::open(&path).unwrap();
+ assert_eq!(r.len(), 10);
+ let mut b = [0u8; 3];
+ r.read_at(4, &mut b).unwrap();
+ assert_eq!(&b, b"456");
+ // reads are positional: an earlier offset after a later one
+ r.read_at(0, &mut b).unwrap();
+ assert_eq!(&b, b"012");
+ assert_eq!(r.read_at(8, &mut b).unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
+ assert_eq!(read_range(&r, 8, 100).unwrap(), b"89");
+ assert!(FileReader::open(&dir).is_err(), "a directory is not a media file");
+ assert_eq!(FileReader::open(&dir.join("missing")).unwrap_err().kind(), io::ErrorKind::NotFound);
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
#[test]
fn falls_back_to_byte_openers() {
// a WAV is opened through the whole-file path
diff --git a/docs/performance.md b/docs/performance.md
index adf11c1b3..1b09b5ac2 100644
--- a/docs/performance.md
+++ b/docs/performance.md
@@ -13,6 +13,20 @@ the before/after comparison relies on. Each milestone below alternated base / af
each); the most load-independent figure is the decoder's own cycle count (`proc_pid_rusage`
instructions and cycles of a process, all threads summed).
+## Memory of clips on a timeline (MEM1–MEM3)
+
+Measured on the desktop release build with `footprint`, `heap` and `malloc_history`
+(`MallocStackLogging=lite`), 2026-10-05: twelve H.264 clips dropped on a timeline took the process
+to a 12 GB footprint, 10.8 GB of it live heap in three piles.
+
+1. **Media files read whole (2.9 GB), MEM1.** The desktop host had no `Services::reader`, so
+ `MediaPool::open_file` fell back to `read_file` and every clip's bytes stayed in memory for as
+ long as its source was open. `FsServices::reader` now returns a
+ `filmcraft_media::reader::FileReader`: the file stays open and containers read their index and
+ then single samples with positional reads, as the web host already did through `BlobReader`
+ ([web.md](web.md)). Formats decoded in one go (stills, WAV, MPEG elementary streams) are still
+ read whole through the reader.
+
## Results (GPU2: standard effects on the GPU compositor, #30, before → after)
Before = this change with clips that carry standard effects sent back to the CPU layer path in