diff --git a/crates/ec-mp4/src/mux.rs b/crates/ec-mp4/src/mux.rs index 4cca6834..08759326 100644 --- a/crates/ec-mp4/src/mux.rs +++ b/crates/ec-mp4/src/mux.rs @@ -1,7 +1,7 @@ //! The writer: `ftyp`, then one `mdat` the samples stream into, then the `moov` //! built from what was written. -use std::io::{Seek, SeekFrom, Write}; +use std::io::{Read, Seek, SeekFrom, Write}; use ec_core::{ CodecId, ContentLight, Error, Muxer, Packet, Result, Rounding, StreamInfo, TimeBase, @@ -14,6 +14,9 @@ use crate::esds::{Esds, object_type}; /// every sample time is in its own track's timescale. const MOVIE_TIMESCALE: u32 = 1_000; +/// How much of the `mdat` is copied at a time when a faststart file is laid out. +const COPY_CHUNK: u64 = 8 << 20; + /// One written sample, as the sample tables will state it. struct Sample { size: u32, @@ -61,8 +64,8 @@ struct Track { /// arrive, so muxing costs one pass and no temporary file, and the sample tables /// — which cannot be written before the sizes they state are known — go at the /// end. The cost is that a player streaming the file over HTTP has to reach the -/// end before it can start; a faststart (`moov` in front) writer would have to -/// copy the whole `mdat` a second time, and is not implemented here. +/// end before it can start; [`Mp4Muxer::set_faststart`] moves the `moov` in +/// front instead, at the price of copying the `mdat` once more. /// /// Interleaving is the caller's: packets are written in the order they are /// handed over, and the chunk table follows that order exactly. @@ -83,6 +86,8 @@ pub struct Mp4Muxer { /// Chapter marks as `(start in ns, title)`, sorted by start. Written as a /// Nero `chpl` in `moov/udta` and as a QuickTime text track. chapters: Vec<(u64, String)>, + /// Lay the `moov` in front of the `mdat`; see [`Mp4Muxer::set_faststart`]. + faststart: bool, } /// The chapter text track as it is laid out in the file: its samples sit in the @@ -124,6 +129,7 @@ impl Mp4Muxer { title: None, brands, chapters: Vec::new(), + faststart: false, }) } @@ -271,6 +277,13 @@ impl Mp4Muxer { Ok(()) } + /// Lay the file out `ftyp`, `moov`, `mdat` instead of `ftyp`, `mdat`, `moov`, + /// so a player can start before the end. Such a file is finished with + /// [`Mp4Muxer::finish_faststart`], which reads the `mdat` back to move it. + pub fn set_faststart(&mut self, on: bool) { + self.faststart = on; + } + /// Take the writer back once the file is finished. pub fn into_inner(self) -> W { self.w @@ -401,7 +414,30 @@ impl Mp4Muxer { }) } - fn write_moov(&mut self, chapters: Option<&ChapterText>) -> Result<()> { + /// Everything `finish` writes before the `moov`: the chapter text, the + /// durations, and the `mdat`'s real size. Returns the chapter text, if any. + fn seal_mdat(&mut self) -> Result> { + self.start()?; + for track in &mut self.tracks { + Mp4Muxer::::resolve_durations(track); + } + // The chapter text samples are media, so they go in the mdat before its + // size is known. + let chapters = match self.chapters.is_empty() { + true => None, + false => Some(self.write_chapter_text()?), + }; + // The mdat's real size, into the 64-bit field left for it. + let mdat_len = self.pos - self.mdat_at; + self.w.seek(SeekFrom::Start(self.mdat_at + 8))?; + self.w.write_all(&mdat_len.to_be_bytes())?; + self.w.seek(SeekFrom::Start(self.pos))?; + Ok(chapters) + } + + /// The `moov` as bytes, its chunk offsets moved `shift` bytes further into + /// the file: 0 when it follows the `mdat`, its own length when it leads. + fn moov_bytes(&self, chapters: Option<&ChapterText>, shift: u64) -> Result> { let mut moov = Vec::with_capacity(4096); let at = open(&mut moov, b"moov"); let duration = self.movie_duration().max(chapters.map_or(0, |c| c.end_ms)); @@ -428,10 +464,10 @@ impl Mp4Muxer { true => chapter_id, false => None, }; - self.write_trak(&mut moov, i, duration, chapter_ref)?; + self.write_trak(&mut moov, i, duration, chapter_ref, shift)?; } if let (Some(text), Some(id)) = (chapters, chapter_id) { - write_chapter_trak(&mut moov, id, text); + write_chapter_trak(&mut moov, id, text, shift); } let chpl = (1..=255).contains(&self.chapters.len()); if self.title.is_some() || chpl { @@ -445,6 +481,11 @@ impl Mp4Muxer { close(&mut moov, udta); } close(&mut moov, at); + Ok(moov) + } + + fn write_moov(&mut self, chapters: Option<&ChapterText>) -> Result<()> { + let moov = self.moov_bytes(chapters, 0)?; self.w.write_all(&moov)?; self.pos += moov.len() as u64; Ok(()) @@ -458,6 +499,7 @@ impl Mp4Muxer { i: usize, movie_duration: i64, chapter_ref: Option, + shift: u64, ) -> Result<()> { let track = &self.tracks[i]; let codec = track.info.params.codec; @@ -600,7 +642,7 @@ impl Mp4Muxer { out.extend_from_slice(&1u32.to_be_bytes()); sample_entry(out, &track.info, track.field_order, track.chan)?; close(out, stsd); - sample_tables(out, track); + sample_tables(out, track, shift); close(out, stbl); close(out, minf); close(out, mdia); @@ -697,33 +739,80 @@ impl Muxer for Mp4Muxer { if self.finished { return Ok(()); } - self.finished = true; - self.start()?; - for track in &mut self.tracks { - Mp4Muxer::::resolve_durations(track); + if self.faststart { + return Err(Error::unsupported( + "mp4 faststart", + "finish it with finish_faststart, which reads the mdat back", + )); } - // The chapter text samples are media, so they go in the mdat before its - // size is known. - let chapters = match self.chapters.is_empty() { - true => None, - false => Some(self.write_chapter_text()?), - }; - // The mdat's real size, into the 64-bit field left for it. - let mdat_len = self.pos - self.mdat_at; - self.w.seek(SeekFrom::Start(self.mdat_at + 8))?; - self.w.write_all(&mdat_len.to_be_bytes())?; - self.w.seek(SeekFrom::Start(self.pos))?; + self.finished = true; + let chapters = self.seal_mdat()?; self.write_moov(chapters.as_ref())?; self.w.flush()?; Ok(()) } } +impl Mp4Muxer { + /// Finish a faststart file: `ftyp`, `moov`, `mdat`. The `mdat` is copied + /// `moov`-length bytes further on, from the end backwards, then the `moov` + /// goes where the `mdat` was. + pub fn finish_faststart(mut self) -> Result { + if self.finished { + return Ok(self.w); + } + self.finished = true; + let chapters = self.seal_mdat()?; + let moov = self.faststart_moov(chapters.as_ref())?; + let shift = moov.len() as u64; + self.move_mdat(shift)?; + self.w.seek(SeekFrom::Start(self.mdat_at))?; + self.w.write_all(&moov)?; + self.w.flush()?; + Ok(self.w) + } + + /// The `moov` whose offsets are shifted by its own length. The length can + /// change with the shift (a `stco` becoming a `co64`), so this repeats until + /// it is stable; the length only grows, so it does. + fn faststart_moov(&self, chapters: Option<&ChapterText>) -> Result> { + let mut moov = self.moov_bytes(chapters, 0)?; + loop { + let shift = moov.len() as u64; + let next = self.moov_bytes(chapters, shift)?; + if next.len() as u64 == shift { + return Ok(next); + } + moov = next; + } + } + + /// Move the `mdat` (from its header to the end of the file) `shift` bytes on. + /// Destination is above source, so chunks are copied from the end down: a + /// chunk's destination only reaches bytes already read or already moved. + fn move_mdat(&mut self, shift: u64) -> Result<()> { + let start = self.mdat_at; + let end = self.pos; + let mut buf = vec![0u8; (end - start).min(COPY_CHUNK) as usize]; + let mut hi = end; + while hi > start { + let lo = hi.saturating_sub(COPY_CHUNK).max(start); + let len = (hi - lo) as usize; + self.w.seek(SeekFrom::Start(lo))?; + self.w.read_exact(&mut buf[..len])?; + self.w.seek(SeekFrom::Start(lo + shift))?; + self.w.write_all(&buf[..len])?; + hi = lo; + } + Ok(()) + } +} + /// The QuickTime chapter text track: one `text` sample per chapter, in the movie /// clock (milliseconds), with a `co64` offset so it stays right past 4 GB. It is /// disabled, as a chapter track is in a QuickTime file, and its `edts` puts the /// first chapter at its own start when that is not zero. -fn write_chapter_trak(out: &mut Vec, id: u32, chap: &ChapterText) { +fn write_chapter_trak(out: &mut Vec, id: u32, chap: &ChapterText, shift: u64) { let at = open(out, b"trak"); let tkhd = open(out, b"tkhd"); @@ -841,7 +930,7 @@ fn write_chapter_trak(out: &mut Vec, id: u32, chap: &ChapterText) { let co64 = open(out, b"co64"); full_head(out, 0, 0); out.extend_from_slice(&1u32.to_be_bytes()); - out.extend_from_slice(&chap.offset.to_be_bytes()); + out.extend_from_slice(&(chap.offset + shift).to_be_bytes()); close(out, co64); close(out, stbl); close(out, minf); @@ -954,7 +1043,7 @@ fn opus_pre_skip(track: &Track) -> i64 { /// The tables of a QuickTime PCM track the way QuickTime and ffmpeg lay them /// out: a *sample* is one frame (`frame_bytes`, one `stts` tick), and a chunk /// holds as many samples as the packets written into it had frames. -fn pcm_tables(out: &mut Vec, track: &Track, frame_bytes: u32) { +fn pcm_tables(out: &mut Vec, track: &Track, frame_bytes: u32, shift: u64) { let frame_bytes = frame_bytes.max(1); let total: u64 = track .samples @@ -1009,26 +1098,34 @@ fn pcm_tables(out: &mut Vec, track: &Track, frame_bytes: u32) { out.extend_from_slice(&(total as u32).to_be_bytes()); close(out, stsz); - let big = track.chunks.iter().any(|&(at, _)| at > u64::from(u32::MAX)); + let big = track + .chunks + .iter() + .any(|&(at, _)| at + shift > u64::from(u32::MAX)); let kind = if big { b"co64" } else { b"stco" }; let chunks = open(out, kind); full_head(out, 0, 0); out.extend_from_slice(&(track.chunks.len() as u32).to_be_bytes()); for &(at, _) in &track.chunks { match big { - true => out.extend_from_slice(&at.to_be_bytes()), - false => out.extend_from_slice(&(at as u32).to_be_bytes()), + true => out.extend_from_slice(&(at + shift).to_be_bytes()), + false => out.extend_from_slice(&((at + shift) as u32).to_be_bytes()), } } close(out, chunks); } /// The `stts`/`ctts`/`stss`/`stsc`/`stsz` and chunk-offset tables of one track. -fn sample_tables(out: &mut Vec, track: &Track) { +fn sample_tables(out: &mut Vec, track: &Track, shift: u64) { if let (Some((bytes, _)), Some(audio)) = (qt_pcm(track.info.params.codec), track.info.params.audio()) { - pcm_tables(out, track, bytes * audio.layout.channel_count() as u32); + pcm_tables( + out, + track, + bytes * audio.layout.channel_count() as u32, + shift, + ); return; } // stts: runs of equal durations, which for constant-rate video is one entry @@ -1139,15 +1236,18 @@ fn sample_tables(out: &mut Vec, track: &Track) { close(out, stsz); // co64 where the file is big enough to need it, stco where it is not. - let big = track.chunks.iter().any(|&(at, _)| at > u64::from(u32::MAX)); + let big = track + .chunks + .iter() + .any(|&(at, _)| at + shift > u64::from(u32::MAX)); let kind = if big { b"co64" } else { b"stco" }; let chunks = open(out, kind); full_head(out, 0, 0); out.extend_from_slice(&(track.chunks.len() as u32).to_be_bytes()); for &(at, _) in &track.chunks { match big { - true => out.extend_from_slice(&at.to_be_bytes()), - false => out.extend_from_slice(&(at as u32).to_be_bytes()), + true => out.extend_from_slice(&(at + shift).to_be_bytes()), + false => out.extend_from_slice(&((at + shift) as u32).to_be_bytes()), } } close(out, chunks); @@ -1628,6 +1728,54 @@ mod tests { assert_eq!(back[3], vec![0xAA, 3, 0x55]); } + #[test] + fn faststart_puts_the_moov_before_the_mdat_and_the_samples_still_read_back() { + let mut params = CodecParameters::new(CodecId::Aac); + params.extradata = Some(Buf::from(vec![0x12, 0x10])); + params.media = MediaParameters::Audio(AudioParameters { + sample_rate: 44_100, + layout: ChannelLayout::from_count(2), + ..Default::default() + }); + let mut muxer = Mp4Muxer::new(Cursor::new(Vec::new())).unwrap(); + muxer.set_faststart(true); + let stream = muxer + .add_stream(StreamInfo::new(0, TimeBase::from_rate(44_100), params)) + .unwrap(); + for i in 0..10u8 { + let mut packet = Packet::new(stream, TimeBase::from_rate(44_100), vec![0xAA, i, 0x55]); + packet.dts = Some(i64::from(i) * 1024); + packet.duration = Some(1024); + packet.flags.keyframe = true; + muxer.write_packet(&packet).unwrap(); + } + let bytes = muxer.finish_faststart().unwrap().into_inner(); + + let mut order = Vec::new(); + let mut at = 0usize; + while at + 8 <= bytes.len() { + let size = u32::from_be_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]); + order.push(String::from_utf8_lossy(&bytes[at + 4..at + 8]).into_owned()); + at += match size { + 1 => u64::from_be_bytes(bytes[at + 8..at + 16].try_into().unwrap()) as usize, + _ => size as usize, + }; + } + assert_eq!(order, ["ftyp", "moov", "mdat"]); + + let mut demuxer = Mp4Demuxer::new(Cursor::new(bytes)).unwrap(); + let mut back = Vec::new(); + loop { + match demuxer.next_packet() { + Ok(packet) => back.push(packet.data.to_vec()), + Err(Error::Eof) => break, + Err(e) => panic!("{e}"), + } + } + let written: Vec> = (0..10u8).map(|i| vec![0xAA, i, 0x55]).collect(); + assert_eq!(back, written); + } + #[test] fn language_packing_is_the_demuxers_inverse() { for tag in ["tur", "eng", "und"] {