//! Movie and audio files read in place: the container's index now, single samples on demand. //! //! Reading a file whole before opening it made a clip cost its full size in memory (twice while //! probing: the file's bytes plus the demuxer's copy), so a 45-minute movie took gigabytes just to //! import. Reader openers (MP4/MOV, Matroska/WebM, MXF, Ogg, MPEG-PS/TS) open from a random-access //! byte reader; [`FileReader`] serves them positional reads from the open file. //! Formats decoded in one go (stills, WAV, FLAC, MP3…) still read the whole file, as before. //! Builds without a native file system (wasm32) keep using in-memory bytes. use std::path::Path; use std::sync::Arc; use effectcraft_render::reads::FileStamp; use effectcraft_time::Tick; use crate::{MediaError, Result}; /// A decoded video frame from either `craft-media-source` or `filmcraft-media`. pub(crate) enum DecodedFrame { Craft(Arc), Film(Arc), } impl DecodedFrame { pub(crate) fn width(&self) -> u32 { match self { DecodedFrame::Craft(f) => f.width, DecodedFrame::Film(f) => f.width, } } pub(crate) fn height(&self) -> u32 { match self { DecodedFrame::Craft(f) => f.height, DecodedFrame::Film(f) => f.height, } } } /// An opened movie/audio source, routed through `craft-media-source` for migrated formats /// (the route matrix in `craft_source`) and `filmcraft-media` for remaining formats. #[derive(Clone)] pub(crate) enum MediaSource { Craft(craft_media_source::SharedSource), Film(filmcraft_media::SharedSource), } impl MediaSource { pub(crate) fn video_frame(&self, time: Tick, scale: f32) -> Result { match self { MediaSource::Craft(s) => { s.video_frame(craft_media_source::FrameRequest { time: craft_time::Tick(time.0), scale }).map(DecodedFrame::Craft).map_err(MediaError::from) } MediaSource::Film(s) => { s.video_frame(filmcraft_media::FrameRequest { time: filmcraft_time::Tick(time.0), scale }).map(DecodedFrame::Film).map_err(MediaError::from) } } } pub(crate) fn audio(&self, start: i64, frames: usize, rate: u32) -> std::result::Result>, String> { match self { MediaSource::Craft(s) => s.audio(start, frames, rate).map(|b| b.channels).map_err(|e| e.to_string()), MediaSource::Film(s) => s.audio(start, frames, rate).map(|b| b.channels).map_err(|e| e.to_string()), } } pub(crate) fn primary_audio(&self) -> Option<(u32, u32, String)> { match self { MediaSource::Craft(s) => s.info().audio().map(|a| (a.sample_rate, a.channels, a.codec.clone())), MediaSource::Film(s) => s.info().audio().map(|a| (a.sample_rate, a.channels, a.codec.clone())), } } } /// Open an in-memory movie/audio source, trying migrated `craft-media-source` routes first. pub(crate) fn open_bytes(name: &str, bytes: Arc<[u8]>) -> Result { if let Some(res) = crate::craft_source::open_bytes(name, bytes.clone()) { return res.map(MediaSource::Craft).map_err(MediaError::from); } filmcraft_codecs::open_bytes(name, bytes).map(MediaSource::Film).map_err(MediaError::from) } /// A file on disk read in place: it stays open and only the requested ranges are read. #[cfg(any(unix, windows))] #[derive(Debug)] pub(crate) struct FileReader { file: std::fs::File, len: u64, /// The file's identity when it was opened. stamp: FileStamp, } #[cfg(any(unix, windows))] impl FileReader { /// Opens `path` for reading and records its length and modification time. pub(crate) fn open(path: &Path) -> std::io::Result { #[cfg(test)] crate::count_open(path); let file = std::fs::File::open(path)?; let m = file.metadata()?; if !m.is_file() { return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{} is not a file", path.display()))); } Ok(Self { file, len: m.len(), stamp: FileStamp::of_metadata(&m) }) } } #[cfg(any(unix, windows))] impl FileReader { fn len_bytes(&self) -> u64 { self.len } /// Positional reads: threads decoding different parts of the file share no cursor. fn read_exact_at(&self, offset: u64, buf: &mut [u8]) -> std::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(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "read past end of file")), Ok(n) => { done = done.saturating_add(n); at = at.saturating_add(n as u64); } Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} Err(e) => return Err(e), } } Ok(()) } } } #[cfg(any(unix, windows))] impl filmcraft_media::ByteReader for FileReader { fn len(&self) -> u64 { self.len_bytes() } fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { self.read_exact_at(offset, buf) } } #[cfg(any(unix, windows))] impl craft_media::ByteSource for FileReader { fn len(&self) -> u64 { self.len_bytes() } fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { self.read_exact_at(offset, buf) } } #[cfg(any(unix, windows))] fn name_of(path: &Path) -> String { path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default() } /// Open a movie/audio file for the media pool, reading only what its container needs; files the /// reader openers don't handle are read whole and opened from memory, exactly as before. `None` /// when the file can't be opened in place (the caller reads it whole, which reports the error). /// With the file's identity as opened. #[cfg(any(unix, windows))] pub(crate) fn open_source(path: &Path) -> Option<(Result, FileStamp)> { let reader = Arc::new(FileReader::open(path).ok()?); let stamp = reader.stamp; let name = name_of(path); let craft_reader: craft_media_source::SharedBytes = reader.clone(); if let Ok(head) = craft_media_source::read_range(&*craft_reader, 0, crate::craft_source::NATIVE_SNIFF_HEAD_LEN) && let Some(res) = crate::craft_source::open_reader(&name, &head, &craft_reader) { return Some((res.map(MediaSource::Craft).map_err(MediaError::from), stamp)); } let fc_reader: filmcraft_media::SharedReader = reader; let opened = filmcraft_media::reader::open_reader(&name, fc_reader, &filmcraft_codecs::reader_openers(), &filmcraft_codecs::openers()); Some((opened.map(MediaSource::Film).map_err(MediaError::from), stamp)) } /// Without a native file system there is no in-place source: always `None`. #[cfg(not(any(unix, windows)))] pub(crate) fn open_source(_path: &Path) -> Option<(Result, FileStamp)> { None } /// `path` read in place (`None` when it can't be opened, or without a native file system). #[cfg(any(unix, windows))] pub(crate) fn file_reader(path: &Path) -> Option> { Some(Box::new(FileReader::open(path).ok()?)) } #[cfg(not(any(unix, windows)))] pub(crate) fn file_reader(_path: &Path) -> Option> { None } /// The leading `ftyp` and the `moov` box of an ISO-BMFF movie on disk (all a track's display /// matrix needs), without reading the samples: top-level box headers are walked with positional /// reads. `None` when the file isn't ISO-BMFF or its `moov` is missing or implausibly large. #[cfg(any(unix, windows))] pub(crate) fn movie_header(path: &Path) -> Option> { use std::io::{Read, Seek, SeekFrom}; const MAX_MOOV: u64 = 64 << 20; let mut f = std::fs::File::open(path).ok()?; let len = f.metadata().ok()?.len(); let mut out = Vec::new(); let mut pos = 0u64; for _ in 0..4096 { if pos.checked_add(8)? > len { return None; } f.seek(SeekFrom::Start(pos)).ok()?; let mut h = [0u8; 16]; f.read_exact(&mut h[..8]).ok()?; let kind = [h[4], h[5], h[6], h[7]]; let mut size = u64::from(u32::from_be_bytes([h[0], h[1], h[2], h[3]])); if size == 1 { f.read_exact(&mut h[8..16]).ok()?; size = u64::from_be_bytes([h[8], h[9], h[10], h[11], h[12], h[13], h[14], h[15]]); } else if size == 0 { size = len - pos; } if size < 8 || pos.checked_add(size)? > len { return None; } if kind == *b"ftyp" || kind == *b"moov" { if size > MAX_MOOV { return None; } f.seek(SeekFrom::Start(pos)).ok()?; let mut b = vec![0u8; usize::try_from(size).ok()?]; f.read_exact(&mut b).ok()?; out.extend_from_slice(&b); if kind == *b"moov" { return Some(out); } } pos += size; } None } #[cfg(not(any(unix, windows)))] pub(crate) fn movie_header(_path: &Path) -> Option> { None } /// Probing in place: the opened container when `path` is a movie/audio container a reader opener /// handles and nothing probed before containers (stills, layered and vector documents, 3D models) /// claims it. `None`: probe the whole file's bytes as before. #[cfg(any(unix, windows))] pub(crate) fn probe_source(path: &Path) -> Option> { let ext = crate::ext_of(path); if crate::STILL_EXTENSIONS.contains(&ext.as_str()) || crate::MODEL_EXTENSIONS.contains(&ext.as_str()) { return None; } let reader = Arc::new(FileReader::open(path).ok()?); let head = filmcraft_media::reader::read_range(&*reader, 0, crate::craft_source::NATIVE_SNIFF_HEAD_LEN).ok()?; let legacy_head = &head[..head.len().min(filmcraft_media::reader::HEAD_LEN)]; let name = path.to_string_lossy(); if crate::layered::sniff(&name, legacy_head) || image::guess_format(legacy_head).is_ok() { return None; } let name = name_of(path); let craft_reader: craft_media_source::SharedBytes = reader.clone(); if let Some(res) = crate::craft_source::open_reader(&name, &head, &craft_reader) { return Some(res.map(MediaSource::Craft).map_err(MediaError::from)); } let fc_reader: filmcraft_media::SharedReader = reader; filmcraft_codecs::reader_openers().into_iter().find_map(|open| open(&name, legacy_head, &fc_reader)).map(|r| r.map(MediaSource::Film).map_err(Into::into)) } #[cfg(not(any(unix, windows)))] pub(crate) fn probe_source(_path: &Path) -> Option> { None } #[cfg(all(test, any(unix, windows)))] mod tests { use super::*; use craft_media::isobmff::{self, Brand, CodecConfig, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions}; use filmcraft_frame::PixelData; use image::ExtendedColorType; use image::codecs::jpeg::JpegEncoder; type TestResult = std::result::Result>; const WIDTH: u16 = 16; const HEIGHT: u16 = 16; fn generated_mjpeg_mov() -> TestResult> { // Original synthetic fixture: encode two authored solid RGB tiles, not external media. let mut writer = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mov))?; let video = writer.add_track(TrackConfig::new(SampleEntry::jpeg(WIDTH, HEIGHT), 1_000))?; for rgb in [[220, 32, 24], [19, 36, 224]] { let rgb = rgb.repeat(usize::from(WIDTH) * usize::from(HEIGHT)); let mut jpeg = Vec::new(); JpegEncoder::new_with_quality(&mut jpeg, 90).encode(&rgb, u32::from(WIDTH), u32::from(HEIGHT), ExtendedColorType::Rgb8)?; writer.write_sample(video, WriteSample { data: &jpeg, duration: 40, composition_offset: 0, is_sync: true })?; } Ok(writer.finish()?.into_inner().into()) } fn legacy_mjpeg_pixels(source: &MediaSource, time: Tick) -> TestResult>> { let frame = match source.video_frame(time, 1.0)? { DecodedFrame::Film(frame) => Some(frame), DecodedFrame::Craft(_) => None, } .ok_or("the MJPEG baseline must use FilmCraft")?; assert_eq!((frame.width, frame.height), (u32::from(WIDTH), u32::from(HEIGHT))); let rgba = match &frame.data { PixelData::Rgba8(rgba) => Some(rgba), _ => None, } .ok_or("legacy MJPEG decodes to RGBA8")?; assert_eq!(rgba.len(), usize::from(WIDTH) * usize::from(HEIGHT) * 4); Ok(rgba.clone()) } #[test] fn generated_mjpeg_mov_preserves_legacy_probe_and_seek() -> TestResult<()> { let bytes = generated_mjpeg_mov()?; let mov = isobmff::open(bytes.as_ref())?; assert!(mov.is_quicktime); assert_eq!(mov.tracks.len(), 1); let track = &mov.tracks[0]; assert!(matches!(track.codec(), Some(CodecConfig::Jpeg { .. }))); assert_eq!(track.timescale, 1_000); assert_eq!(track.samples.len(), 2); assert_eq!((track.samples[0].pts, track.samples[1].pts), (0, 40)); let dir = tempfile::tempdir()?; let name = "generated-mjpeg.mov"; let path = dir.path().join(name); std::fs::write(&path, bytes.as_ref())?; let native_probe = crate::probe(&path)?; let memory_probe = crate::probe_bytes(name, bytes.clone())?; let direct = filmcraft_codecs::open_bytes(name, bytes.clone())?; let legacy_probe = crate::probe::footage_from_info(name, direct.info()); let step = Tick::from_units(1, 25); for probe in [native_probe, memory_probe] { assert!(probe.has_video && !probe.has_audio); assert_eq!((probe.width, probe.height), (u32::from(WIDTH), u32::from(HEIGHT))); assert_eq!((probe.frame_rate.num, probe.frame_rate.den), (25, 1)); assert_eq!(probe.duration, Tick::from_units(2, 25)); assert_eq!(probe.codec, legacy_probe.codec); assert_eq!(probe.color_profile, legacy_probe.color_profile); } let native = open_source(&path).ok_or("native source")?.0?; let memory = open_bytes(name, bytes)?; assert!(matches!(&native, MediaSource::Film(_))); assert!(matches!(&memory, MediaSource::Film(_))); let legacy = MediaSource::Film(direct); for (time, dominant) in [(Tick::ZERO, 0), (step, 2), (Tick::ZERO, 0)] { let expected = legacy_mjpeg_pixels(&legacy, time)?; // Independent colour check: a repeated first frame or blank decode cannot pass parity. assert!(expected.as_chunks::<4>().0.iter().all(|p| p[dominant] > 180 && p[2 - dominant] < 80 && p[3] == 255)); assert_eq!(legacy_mjpeg_pixels(&native, time)?, expected); assert_eq!(legacy_mjpeg_pixels(&memory, time)?, expected); } Ok(()) } }