FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
#279: WAV opens in place and reads only the samples asked for
vangel76878000df077c
diff --git a/crates/media/src/reader.rs b/crates/media/src/reader.rsindex 2aeb47bfe..6ec25fae3 100644--- a/crates/media/src/reader.rs+++ b/crates/media/src/reader.rs@@ -2,8 +2,9 @@//!//! A [`ByteReader`] serves reads at any offset (a native file, a web `Blob` read in chunks, an//! in-memory buffer). Container openers that only need the index and then single samples (MP4/MOV,-//! Matroska) open from a reader ([`ReaderOpener`]); formats decoded in one go (stills, WAV,-//! standalone compressed audio) fall back to reading the whole file through it.+//! Matroska) open from a reader ([`ReaderOpener`]), as does WAV (header now, sample ranges on+//! demand); formats decoded in one go (stills, standalone compressed audio) fall back to reading+//! the whole file through it.use std::io;use std::sync::Arc;@@ -109,15 +110,15 @@ pub type ReaderOpener = fn(name: &str, head: &[u8], reader: &SharedReader) -> Op/// Bytes sniffed by [`open_reader`].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).+/// Open media from a reader: reader openers first, then WAV (read in place); otherwise read the+/// whole file and use the byte openers (`extra`, then stills).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+/// Media Browser's properties and thumbnails, #157): reading a multi-gigabyte AVI 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}")))?;@@ -126,6 +127,9 @@ pub fn open_reader_within(name: &str, reader: SharedReader, reader_openers: &[Rereturn r;}}+ if crate::wav::sniff(&head) {+ return Ok(Arc::new(crate::wav::WavSource::open(name, reader)?));+ }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")));}@@ -181,35 +185,58 @@ mod tests {}}- /// #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.+ /// #157: looking at a file no streaming reader takes (an AVI) read all of it. Within a limit+ /// it reads the head only and refuses.#[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().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();+ let mut avi = vec![0u8; 4 * HEAD_LEN];+ avi[..4].copy_from_slice(b"RIFF");+ avi[8..12].copy_from_slice(b"AVI ");+ let r = Arc::new(Counting(MemReader(Arc::from(avi)), Default::default()));+ let e = open_reader_within("a.avi", r.clone(), &[], &[], HEAD_LEN as u64).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 ");+ }++ /// #279: a WAV is read in place, never whole: opening it reads the sniffing head and its chunk+ /// headers, and audio reads only the requested samples, however large the file (and over the+ /// Media Browser's whole-file limit too).+ #[test]+ fn wav_opens_in_place_and_reads_only_requested_samples() {+ let rate = 48_000usize;+ let samples: Vec<f32> = (0..rate * 2 * 20).map(|i| ((i / 2) % 100) as f32 / 200.0).collect();+ let wav = crate::wav::write_wav16(&samples, 2, rate as u32);+ let size = wav.len() as u64;+ assert!(size > 3 * HEAD_LEN as u64);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);+ let read = || r.1.load(std::sync::atomic::Ordering::SeqCst);+ let src = open_reader_within("a.wav", r.clone(), &[], &[], HEAD_LEN as u64).unwrap();+ assert_eq!(src.info().audio().unwrap().channels, 2);+ assert_eq!(src.info().duration, filmcraft_time::Tick::from_units(20, 1));+ assert_eq!(src.info().file_size, Some(size));+ let after_open = read();+ assert!(after_open <= HEAD_LEN as u64 + 64, "{after_open}");+ // 10 ms from the middle: about that much is read, and the samples are right+ let a = src.audio(rate as i64 * 10 + 7, 480, rate as u32).unwrap();+ assert!(read() - after_open <= 481 * 4, "{}", read() - after_open);+ let frame = rate * 10 + 7 + 3;+ assert!((a.channels[0][3] - samples[frame * 2]).abs() < 1e-4);+ assert!((a.channels[1][3] - samples[frame * 2 + 1]).abs() < 1e-4);+ // past the end: silence, nothing read+ let before = read();+ let a = src.audio(rate as i64 * 30, 16, rate as u32).unwrap();+ assert!(a.channels[0].iter().all(|&s| s == 0.0));+ assert_eq!(read(), before);}#[test]fn falls_back_to_byte_openers() {- // a WAV is opened through the whole-file path- let wav = crate::wav::write_wav16(&[0.0, 0.5, -0.5, 0.25], 2, 48_000);- let r: SharedReader = Arc::new(MemReader(wav.into()));- let s = open_reader("a.wav", r, &[], &[]).unwrap();- assert!(s.info().has_audio());+ // a format without a reader opener is read whole and handed to the byte openers+ fn whole(_: &str, bytes: Arc<[u8]>) -> Option<Result<SharedSource>> {+ Some(Err(MediaError::Unsupported(format!("got {} bytes", bytes.len()))))+ }+ let r: SharedReader = Arc::new(MemReader(Arc::from(&b"bytes"[..])));+ let e = open_reader("a.xyz", r, &[], &[whole]).err().unwrap();+ assert!(matches!(&e, MediaError::Unsupported(m) if m == "got 5 bytes"), "{e:?}");}}diff --git a/crates/media/src/wav.rs b/crates/media/src/wav.rsindex 6b63bf4ae..4a0df3d2b 100644--- a/crates/media/src/wav.rs+++ b/crates/media/src/wav.rs@@ -7,17 +7,32 @@ use std::sync::Arc;use filmcraft_frame::{AudioBuffer, VideoFrame};use filmcraft_time::Tick;+use crate::reader::{MemReader, SharedReader, read_range};use crate::{AudioStreamInfo, FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, Result};pub fn sniff(b: &[u8]) -> bool {b.len() >= 12 && (&b[0..4] == b"RIFF" || &b[0..4] == b"RF64") && &b[8..12] == b"WAVE"}+/// Chunks walked looking for `fmt `/`data`/`bext`/`iXML` (real files have a handful).+const MAX_CHUNKS: usize = 1 << 16;+/// Bytes of an iXML chunk searched for the time reference.+const IXML_MAX: u64 = 1 << 20;+/// Output frames converted per read of the data chunk.+const BLOCK_FRAMES: usize = 4096;+/// Largest single read of the data chunk; a wider span (an extreme resampling ratio) reads the+/// two frames each output frame needs instead.+const MAX_SPAN_BYTES: u64 = 4 << 20;++/// A WAV file read in place: opening it reads its chunk headers (not its samples), and+/// [`MediaSource::audio`] reads only the sample range it is asked for, so a 90-minute recording+/// costs its header rather than its size (#279).pub struct WavSource {info: MediaInfo,- bytes: Arc<[u8]>,- data_off: usize,- data_len: usize,+ reader: SharedReader,+ data_off: u64,+ /// Whole frames only.+ frames: u64,channels: usize,bits: u16,float: bool,@@ -26,63 +41,80 @@ pub struct WavSource {}fn le16(b: &[u8], o: usize) -> u16 {- u16::from_le_bytes([b[o], b[o + 1]])+ b.get(o..o.saturating_add(2)).and_then(|s| s.try_into().ok()).map_or(0, u16::from_le_bytes)}fn le32(b: &[u8], o: usize) -> u32 {- u32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]])+ b.get(o..o.saturating_add(4)).and_then(|s| s.try_into().ok()).map_or(0, u32::from_le_bytes)}impl WavSource {+ /// Parse a WAV file held in memory.pub fn parse(name: &str, bytes: Arc<[u8]>) -> Result<Self> {- let b = &bytes[..];- let mut pos = 12;+ Self::open(name, Arc::new(MemReader(bytes)))+ }++ /// Open a WAV file through a random-access reader.+ pub fn open(name: &str, reader: SharedReader) -> Result<Self> {+ let io = |e: std::io::Error| MediaError::Io(format!("{name}: {e}"));+ let len = reader.len();+ let mut pos: u64 = 12;let mut fmt = None;let mut data = None;let mut bext_tr = None;let mut ixml_tr = None;- while pos + 8 <= b.len() {- let id = &b[pos..pos + 4];- let mut len = le32(b, pos + 4) as usize;- let body = pos + 8;- if id == b"data" && (len == 0xFFFF_FFFF || body + len > b.len()) {- len = b.len() - body;+ for _ in 0..MAX_CHUNKS {+ let Some(body) = pos.checked_add(8).filter(|&b| b <= len) else { break };+ let mut hdr = [0u8; 8];+ reader.read_at(pos, &mut hdr).map_err(io)?;+ let id = &hdr[0..4];+ let mut clen = u64::from(le32(&hdr, 4));+ let rest = len - body;+ if id == b"data" && (clen == 0xFFFF_FFFF || clen > rest) {+ clen = rest;}- if body + len > b.len() {+ if clen > rest {break;}match id {- b"fmt " if len >= 16 => {- let mut tag = le16(b, body);- let ch = le16(b, body + 2);- let rate = le32(b, body + 4);- let bits = le16(b, body + 14);- if tag == 0xFFFE && len >= 40 {- tag = le16(b, body + 24);+ b"fmt " if clen >= 16 => {+ let b = read_range(&*reader, body, clen.min(40) as usize).map_err(io)?;+ let mut tag = le16(&b, 0);+ let ch = le16(&b, 2);+ let rate = le32(&b, 4);+ let bits = le16(&b, 14);+ if tag == 0xFFFE && clen >= 40 {+ tag = le16(&b, 24);}fmt = Some((tag, ch, rate, bits));}- b"data" => data = Some((body, len)),+ b"data" => data = Some((body, clen)),// bext: Description 256, Originator 32, OriginatorReference 32, OriginationDate 10,// OriginationTime 8, then TimeReference (low u32, high u32)- b"bext" if len >= 346 => bext_tr = Some(le32(b, body + 338) as u64 | (le32(b, body + 342) as u64) << 32),- b"iXML" => ixml_tr = ixml_time_reference(&b[body..body + len]),+ b"bext" if clen >= 346 => {+ let b = read_range(&*reader, body + 338, 8).map_err(io)?;+ bext_tr = Some(u64::from(le32(&b, 0)) | u64::from(le32(&b, 4)) << 32);+ }+ b"iXML" => {+ let b = read_range(&*reader, body, clen.min(IXML_MAX) as usize).map_err(io)?;+ ixml_tr = ixml_time_reference(&b);+ }_ => {}}- pos = body + len + (len & 1);+ pos = body + clen + (clen & 1);}let (tag, ch, rate, bits) = fmt.ok_or_else(|| MediaError::Decode(format!("{name}: missing fmt chunk")))?;- let (off, len) = data.ok_or_else(|| MediaError::Decode(format!("{name}: missing data chunk")))?;+ let (off, dlen) = data.ok_or_else(|| MediaError::Decode(format!("{name}: missing data chunk")))?;let float = tag == 3;if !(tag == 1 || float) || ch == 0 || !matches!(bits, 8 | 16 | 24 | 32 | 64) {return Err(MediaError::Unsupported(format!("{name}: WAV format tag {tag}, {bits} bits")));}- let frame_bytes = ch as usize * bits as usize / 8;- let frames = len / frame_bytes;+ let frame_bytes = u64::from(ch) * u64::from(bits / 8);+ let frames = dlen / frame_bytes;let time_reference = bext_tr.or(ixml_tr);let mut info = MediaInfo {name: name.into(),kind: MediaKind::AudioOnly,- duration: Tick::from_units(frames as i64, rate as i64),+ duration: Tick::from_units(i64::try_from(frames).unwrap_or(i64::MAX), rate as i64),video: None,audio_streams: vec![AudioStreamInfo {sample_rate: rate,@@ -92,16 +124,16 @@ impl WavSource {}],container: if time_reference.is_some() { "Broadcast WAV".into() } else { "WAV".into() },start_timecode: None,- file_size: Some(b.len() as u64),+ file_size: Some(len),};// start timecode: frames at the media's frame rate (the default rate for audio-only media)if let Some(tr) = time_reference.filter(|_| rate > 0) {let r = info.frame_rate();let n = tr as i128 * r.num as i128;let d = rate as i128 * r.den as i128;- info.start_timecode = Some(((n + d / 2) / d) as i64);+ info.start_timecode = (n + d / 2).checked_div(d).and_then(|t| i64::try_from(t).ok());}- Ok(Self { info, data_off: off, data_len: frames * frame_bytes, channels: ch as usize, bits, float, rate, bytes, time_reference })+ Ok(Self { info, reader, data_off: off, frames, channels: ch as usize, bits, float, rate, time_reference })}/// Broadcast Wave start time: samples since midnight.@@ -109,17 +141,32 @@ impl WavSource {self.time_reference}- fn sample(&self, frame: usize, ch: usize) -> f32 {+ fn frame_bytes(&self) -> usize {+ self.channels * (self.bits as usize / 8)+ }++ /// Read whole frames `first..=last` of the data chunk.+ fn read_frames(&self, first: u64, last: u64) -> Result<Vec<u8>> {+ let fb = self.frame_bytes() as u64;+ let n = last.saturating_sub(first).saturating_add(1).saturating_mul(fb);+ let off = self.data_off.saturating_add(first.saturating_mul(fb));+ let mut buf = vec![0u8; usize::try_from(n).map_err(|_| MediaError::Decode(format!("{}: audio read too large", self.info.name)))?];+ self.reader.read_at(off, &mut buf).map_err(|e| MediaError::Io(format!("{}: {e}", self.info.name)))?;+ Ok(buf)+ }++ /// Sample `ch` of frame `frame` of `block`, a run of whole frames.+ fn sample(&self, block: &[u8], frame: usize, ch: usize) -> f32 {let bps = self.bits as usize / 8;- let o = self.data_off + (frame * self.channels + ch) * bps;- let b = &self.bytes;- match (self.bits, self.float) {- (8, _) => (b[o] as f32 - 128.0) / 128.0,- (16, _) => i16::from_le_bytes([b[o], b[o + 1]]) as f32 / 32768.0,- (24, _) => ((i32::from_le_bytes([0, b[o], b[o + 1], b[o + 2]]) >> 8) as f32) / 8_388_608.0,- (32, false) => i32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]]) as f32 / 2_147_483_648.0,- (32, true) => f32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]]),- (64, true) => f64::from_le_bytes(b[o..o + 8].try_into().unwrap_or([0; 8])) as f32,+ let o = (frame * self.channels + ch) * bps;+ let Some(b) = block.get(o..o.saturating_add(bps)) else { return 0.0 };+ match (self.bits, self.float, b) {+ (8, _, &[a]) => (a as f32 - 128.0) / 128.0,+ (16, _, &[a, b]) => i16::from_le_bytes([a, b]) as f32 / 32768.0,+ (24, _, &[a, b, c]) => ((i32::from_le_bytes([0, a, b, c]) >> 8) as f32) / 8_388_608.0,+ (32, false, &[a, b, c, d]) => i32::from_le_bytes([a, b, c, d]) as f32 / 2_147_483_648.0,+ (32, true, &[a, b, c, d]) => f32::from_le_bytes([a, b, c, d]),+ (64, true, b) => f64::from_le_bytes(b.try_into().unwrap_or([0; 8])) as f32,_ => 0.0,}}@@ -133,25 +180,54 @@ impl MediaSource for WavSource {Err(MediaError::NoStream("video"))}fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result<AudioBuffer> {- let total = self.data_len / (self.channels * self.bits as usize / 8);+ let total = self.frames;let mut out = AudioBuffer::silence(sample_rate, self.channels, frames);+ if total == 0 || sample_rate == 0 {+ return Ok(out);+ }// Linear-interpolating resample when rates differ (the audio crate provides sinc resampling).let ratio = self.rate as f64 / sample_rate as f64;- for i in 0..frames {- let src = (start + i as i64) as f64 * ratio;- if src < 0.0 {+ let src_of = |i: usize| start.saturating_add(i as i64) as f64 * ratio;+ let mut i = 0;+ while i < frames {+ let end = frames.min(i + BLOCK_FRAMES);+ let (lo, hi) = (src_of(i), src_of(end - 1));+ if hi < 0.0 {+ i = end;continue;}- let i0 = src.floor() as usize;- if i0 >= total {+ let first = lo.max(0.0).floor() as u64;+ if first >= total {break;}- let fr = (src - i0 as f64) as f32;- for c in 0..self.channels {- let a = self.sample(i0, c);- let b = if i0 + 1 < total { self.sample(i0 + 1, c) } else { a };- out.channels[c][i] = a + (b - a) * fr;+ let last = (hi.floor() as u64).saturating_add(1).min(total - 1);+ let span = last.saturating_sub(first).saturating_add(1).saturating_mul(self.frame_bytes() as u64);+ let block = if span <= MAX_SPAN_BYTES { Some(self.read_frames(first, last)?) } else { None };+ for slot in i..end {+ let src = src_of(slot);+ if src < 0.0 {+ continue;+ }+ let i0 = src.floor() as u64;+ if i0 >= total {+ break;+ }+ let i1 = (i0 + 1).min(total - 1);+ let fr = (src - i0 as f64) as f32;+ let (buf, base) = match &block {+ Some(b) => (std::borrow::Cow::Borrowed(b.as_slice()), first),+ None => (std::borrow::Cow::Owned(self.read_frames(i0, i1)?), i0),+ };+ let (k0, k1) = ((i0 - base) as usize, (i1 - base) as usize);+ for c in 0..self.channels {+ let a = self.sample(&buf, k0, c);+ let b = self.sample(&buf, k1, c);+ if let Some(s) = out.channels.get_mut(c).and_then(|ch| ch.get_mut(slot)) {+ *s = a + (b - a) * fr;+ }+ }}+ i = end;}Ok(out)}