forge
Explore
Log in

Don't you dare go Hollow

ec-mp4: faststart (moov before mdat) via set_faststart + finish_faststart

Browse files at this commit

8e0480a7a588babd54051b8d8a8e91a2d6e34348Ahmet Kaan GümüşParent: 032b561
crates/ec-mp4/src/mux.rsmodified+181 -33
@@ -1,7 +1,7 @@
11 //! The writer: `ftyp`, then one `mdat` the samples stream into, then the `moov`
22 //! built from what was written.
33
4-use std::io::{Seek, SeekFrom, Write};
4+use std::io::{Read, Seek, SeekFrom, Write};
55
66 use ec_core::{
77 CodecId, ContentLight, Error, Muxer, Packet, Result, Rounding, StreamInfo, TimeBase,
@@ -14,6 +14,9 @@ use crate::esds::{Esds, object_type};
1414 /// every sample time is in its own track's timescale.
1515 const MOVIE_TIMESCALE: u32 = 1_000;
1616
17+/// How much of the `mdat` is copied at a time when a faststart file is laid out.
18+const COPY_CHUNK: u64 = 8 << 20;
19+
1720 /// One written sample, as the sample tables will state it.
1821 struct Sample {
1922 size: u32,
@@ -61,8 +64,8 @@ struct Track {
6164 /// arrive, so muxing costs one pass and no temporary file, and the sample tables
6265 /// — which cannot be written before the sizes they state are known — go at the
6366 /// end. The cost is that a player streaming the file over HTTP has to reach the
64-/// end before it can start; a faststart (`moov` in front) writer would have to
65-/// copy the whole `mdat` a second time, and is not implemented here.
67+/// end before it can start; [`Mp4Muxer::set_faststart`] moves the `moov` in
68+/// front instead, at the price of copying the `mdat` once more.
6669 ///
6770 /// Interleaving is the caller's: packets are written in the order they are
6871 /// handed over, and the chunk table follows that order exactly.
@@ -83,6 +86,8 @@ pub struct Mp4Muxer<W> {
8386 /// Chapter marks as `(start in ns, title)`, sorted by start. Written as a
8487 /// Nero `chpl` in `moov/udta` and as a QuickTime text track.
8588 chapters: Vec<(u64, String)>,
89+ /// Lay the `moov` in front of the `mdat`; see [`Mp4Muxer::set_faststart`].
90+ faststart: bool,
8691 }
8792
8893 /// The chapter text track as it is laid out in the file: its samples sit in the
@@ -124,6 +129,7 @@ impl<W: Write + Seek> Mp4Muxer<W> {
124129 title: None,
125130 brands,
126131 chapters: Vec::new(),
132+ faststart: false,
127133 })
128134 }
129135
@@ -271,6 +277,13 @@ impl<W: Write + Seek> Mp4Muxer<W> {
271277 Ok(())
272278 }
273279
280+ /// Lay the file out `ftyp`, `moov`, `mdat` instead of `ftyp`, `mdat`, `moov`,
281+ /// so a player can start before the end. Such a file is finished with
282+ /// [`Mp4Muxer::finish_faststart`], which reads the `mdat` back to move it.
283+ pub fn set_faststart(&mut self, on: bool) {
284+ self.faststart = on;
285+ }
286+
274287 /// Take the writer back once the file is finished.
275288 pub fn into_inner(self) -> W {
276289 self.w
@@ -401,7 +414,30 @@ impl<W: Write + Seek> Mp4Muxer<W> {
401414 })
402415 }
403416
404- fn write_moov(&mut self, chapters: Option<&ChapterText>) -> Result<()> {
417+ /// Everything `finish` writes before the `moov`: the chapter text, the
418+ /// durations, and the `mdat`'s real size. Returns the chapter text, if any.
419+ fn seal_mdat(&mut self) -> Result<Option<ChapterText>> {
420+ self.start()?;
421+ for track in &mut self.tracks {
422+ Mp4Muxer::<W>::resolve_durations(track);
423+ }
424+ // The chapter text samples are media, so they go in the mdat before its
425+ // size is known.
426+ let chapters = match self.chapters.is_empty() {
427+ true => None,
428+ false => Some(self.write_chapter_text()?),
429+ };
430+ // The mdat's real size, into the 64-bit field left for it.
431+ let mdat_len = self.pos - self.mdat_at;
432+ self.w.seek(SeekFrom::Start(self.mdat_at + 8))?;
433+ self.w.write_all(&mdat_len.to_be_bytes())?;
434+ self.w.seek(SeekFrom::Start(self.pos))?;
435+ Ok(chapters)
436+ }
437+
438+ /// The `moov` as bytes, its chunk offsets moved `shift` bytes further into
439+ /// the file: 0 when it follows the `mdat`, its own length when it leads.
440+ fn moov_bytes(&self, chapters: Option<&ChapterText>, shift: u64) -> Result<Vec<u8>> {
405441 let mut moov = Vec::with_capacity(4096);
406442 let at = open(&mut moov, b"moov");
407443 let duration = self.movie_duration().max(chapters.map_or(0, |c| c.end_ms));
@@ -428,10 +464,10 @@ impl<W: Write + Seek> Mp4Muxer<W> {
428464 true => chapter_id,
429465 false => None,
430466 };
431- self.write_trak(&mut moov, i, duration, chapter_ref)?;
467+ self.write_trak(&mut moov, i, duration, chapter_ref, shift)?;
432468 }
433469 if let (Some(text), Some(id)) = (chapters, chapter_id) {
434- write_chapter_trak(&mut moov, id, text);
470+ write_chapter_trak(&mut moov, id, text, shift);
435471 }
436472 let chpl = (1..=255).contains(&self.chapters.len());
437473 if self.title.is_some() || chpl {
@@ -445,6 +481,11 @@ impl<W: Write + Seek> Mp4Muxer<W> {
445481 close(&mut moov, udta);
446482 }
447483 close(&mut moov, at);
484+ Ok(moov)
485+ }
486+
487+ fn write_moov(&mut self, chapters: Option<&ChapterText>) -> Result<()> {
488+ let moov = self.moov_bytes(chapters, 0)?;
448489 self.w.write_all(&moov)?;
449490 self.pos += moov.len() as u64;
450491 Ok(())
@@ -458,6 +499,7 @@ impl<W: Write + Seek> Mp4Muxer<W> {
458499 i: usize,
459500 movie_duration: i64,
460501 chapter_ref: Option<u32>,
502+ shift: u64,
461503 ) -> Result<()> {
462504 let track = &self.tracks[i];
463505 let codec = track.info.params.codec;
@@ -600,7 +642,7 @@ impl<W: Write + Seek> Mp4Muxer<W> {
600642 out.extend_from_slice(&1u32.to_be_bytes());
601643 sample_entry(out, &track.info, track.field_order, track.chan)?;
602644 close(out, stsd);
603- sample_tables(out, track);
645+ sample_tables(out, track, shift);
604646 close(out, stbl);
605647 close(out, minf);
606648 close(out, mdia);
@@ -697,33 +739,80 @@ impl<W: Write + Seek + Send> Muxer for Mp4Muxer<W> {
697739 if self.finished {
698740 return Ok(());
699741 }
700- self.finished = true;
701- self.start()?;
702- for track in &mut self.tracks {
703- Mp4Muxer::<W>::resolve_durations(track);
742+ if self.faststart {
743+ return Err(Error::unsupported(
744+ "mp4 faststart",
745+ "finish it with finish_faststart, which reads the mdat back",
746+ ));
704747 }
705- // The chapter text samples are media, so they go in the mdat before its
706- // size is known.
707- let chapters = match self.chapters.is_empty() {
708- true => None,
709- false => Some(self.write_chapter_text()?),
710- };
711- // The mdat's real size, into the 64-bit field left for it.
712- let mdat_len = self.pos - self.mdat_at;
713- self.w.seek(SeekFrom::Start(self.mdat_at + 8))?;
714- self.w.write_all(&mdat_len.to_be_bytes())?;
715- self.w.seek(SeekFrom::Start(self.pos))?;
748+ self.finished = true;
749+ let chapters = self.seal_mdat()?;
716750 self.write_moov(chapters.as_ref())?;
717751 self.w.flush()?;
718752 Ok(())
719753 }
720754 }
721755
756+impl<W: Read + Write + Seek + Send> Mp4Muxer<W> {
757+ /// Finish a faststart file: `ftyp`, `moov`, `mdat`. The `mdat` is copied
758+ /// `moov`-length bytes further on, from the end backwards, then the `moov`
759+ /// goes where the `mdat` was.
760+ pub fn finish_faststart(mut self) -> Result<W> {
761+ if self.finished {
762+ return Ok(self.w);
763+ }
764+ self.finished = true;
765+ let chapters = self.seal_mdat()?;
766+ let moov = self.faststart_moov(chapters.as_ref())?;
767+ let shift = moov.len() as u64;
768+ self.move_mdat(shift)?;
769+ self.w.seek(SeekFrom::Start(self.mdat_at))?;
770+ self.w.write_all(&moov)?;
771+ self.w.flush()?;
772+ Ok(self.w)
773+ }
774+
775+ /// The `moov` whose offsets are shifted by its own length. The length can
776+ /// change with the shift (a `stco` becoming a `co64`), so this repeats until
777+ /// it is stable; the length only grows, so it does.
778+ fn faststart_moov(&self, chapters: Option<&ChapterText>) -> Result<Vec<u8>> {
779+ let mut moov = self.moov_bytes(chapters, 0)?;
780+ loop {
781+ let shift = moov.len() as u64;
782+ let next = self.moov_bytes(chapters, shift)?;
783+ if next.len() as u64 == shift {
784+ return Ok(next);
785+ }
786+ moov = next;
787+ }
788+ }
789+
790+ /// Move the `mdat` (from its header to the end of the file) `shift` bytes on.
791+ /// Destination is above source, so chunks are copied from the end down: a
792+ /// chunk's destination only reaches bytes already read or already moved.
793+ fn move_mdat(&mut self, shift: u64) -> Result<()> {
794+ let start = self.mdat_at;
795+ let end = self.pos;
796+ let mut buf = vec![0u8; (end - start).min(COPY_CHUNK) as usize];
797+ let mut hi = end;
798+ while hi > start {
799+ let lo = hi.saturating_sub(COPY_CHUNK).max(start);
800+ let len = (hi - lo) as usize;
801+ self.w.seek(SeekFrom::Start(lo))?;
802+ self.w.read_exact(&mut buf[..len])?;
803+ self.w.seek(SeekFrom::Start(lo + shift))?;
804+ self.w.write_all(&buf[..len])?;
805+ hi = lo;
806+ }
807+ Ok(())
808+ }
809+}
810+
722811 /// The QuickTime chapter text track: one `text` sample per chapter, in the movie
723812 /// clock (milliseconds), with a `co64` offset so it stays right past 4 GB. It is
724813 /// disabled, as a chapter track is in a QuickTime file, and its `edts` puts the
725814 /// first chapter at its own start when that is not zero.
726-fn write_chapter_trak(out: &mut Vec<u8>, id: u32, chap: &ChapterText) {
815+fn write_chapter_trak(out: &mut Vec<u8>, id: u32, chap: &ChapterText, shift: u64) {
727816 let at = open(out, b"trak");
728817
729818 let tkhd = open(out, b"tkhd");
@@ -841,7 +930,7 @@ fn write_chapter_trak(out: &mut Vec<u8>, id: u32, chap: &ChapterText) {
841930 let co64 = open(out, b"co64");
842931 full_head(out, 0, 0);
843932 out.extend_from_slice(&1u32.to_be_bytes());
844- out.extend_from_slice(&chap.offset.to_be_bytes());
933+ out.extend_from_slice(&(chap.offset + shift).to_be_bytes());
845934 close(out, co64);
846935 close(out, stbl);
847936 close(out, minf);
@@ -954,7 +1043,7 @@ fn opus_pre_skip(track: &Track) -> i64 {
9541043 /// The tables of a QuickTime PCM track the way QuickTime and ffmpeg lay them
9551044 /// out: a *sample* is one frame (`frame_bytes`, one `stts` tick), and a chunk
9561045 /// holds as many samples as the packets written into it had frames.
957-fn pcm_tables(out: &mut Vec<u8>, track: &Track, frame_bytes: u32) {
1046+fn pcm_tables(out: &mut Vec<u8>, track: &Track, frame_bytes: u32, shift: u64) {
9581047 let frame_bytes = frame_bytes.max(1);
9591048 let total: u64 = track
9601049 .samples
@@ -1009,26 +1098,34 @@ fn pcm_tables(out: &mut Vec<u8>, track: &Track, frame_bytes: u32) {
10091098 out.extend_from_slice(&(total as u32).to_be_bytes());
10101099 close(out, stsz);
10111100
1012- let big = track.chunks.iter().any(|&(at, _)| at > u64::from(u32::MAX));
1101+ let big = track
1102+ .chunks
1103+ .iter()
1104+ .any(|&(at, _)| at + shift > u64::from(u32::MAX));
10131105 let kind = if big { b"co64" } else { b"stco" };
10141106 let chunks = open(out, kind);
10151107 full_head(out, 0, 0);
10161108 out.extend_from_slice(&(track.chunks.len() as u32).to_be_bytes());
10171109 for &(at, _) in &track.chunks {
10181110 match big {
1019- true => out.extend_from_slice(&at.to_be_bytes()),
1020- false => out.extend_from_slice(&(at as u32).to_be_bytes()),
1111+ true => out.extend_from_slice(&(at + shift).to_be_bytes()),
1112+ false => out.extend_from_slice(&((at + shift) as u32).to_be_bytes()),
10211113 }
10221114 }
10231115 close(out, chunks);
10241116 }
10251117
10261118 /// The `stts`/`ctts`/`stss`/`stsc`/`stsz` and chunk-offset tables of one track.
1027-fn sample_tables(out: &mut Vec<u8>, track: &Track) {
1119+fn sample_tables(out: &mut Vec<u8>, track: &Track, shift: u64) {
10281120 if let (Some((bytes, _)), Some(audio)) =
10291121 (qt_pcm(track.info.params.codec), track.info.params.audio())
10301122 {
1031- pcm_tables(out, track, bytes * audio.layout.channel_count() as u32);
1123+ pcm_tables(
1124+ out,
1125+ track,
1126+ bytes * audio.layout.channel_count() as u32,
1127+ shift,
1128+ );
10321129 return;
10331130 }
10341131 // stts: runs of equal durations, which for constant-rate video is one entry
@@ -1139,15 +1236,18 @@ fn sample_tables(out: &mut Vec<u8>, track: &Track) {
11391236 close(out, stsz);
11401237
11411238 // co64 where the file is big enough to need it, stco where it is not.
1142- let big = track.chunks.iter().any(|&(at, _)| at > u64::from(u32::MAX));
1239+ let big = track
1240+ .chunks
1241+ .iter()
1242+ .any(|&(at, _)| at + shift > u64::from(u32::MAX));
11431243 let kind = if big { b"co64" } else { b"stco" };
11441244 let chunks = open(out, kind);
11451245 full_head(out, 0, 0);
11461246 out.extend_from_slice(&(track.chunks.len() as u32).to_be_bytes());
11471247 for &(at, _) in &track.chunks {
11481248 match big {
1149- true => out.extend_from_slice(&at.to_be_bytes()),
1150- false => out.extend_from_slice(&(at as u32).to_be_bytes()),
1249+ true => out.extend_from_slice(&(at + shift).to_be_bytes()),
1250+ false => out.extend_from_slice(&((at + shift) as u32).to_be_bytes()),
11511251 }
11521252 }
11531253 close(out, chunks);
@@ -1628,6 +1728,54 @@ mod tests {
16281728 assert_eq!(back[3], vec![0xAA, 3, 0x55]);
16291729 }
16301730
1731+ #[test]
1732+ fn faststart_puts_the_moov_before_the_mdat_and_the_samples_still_read_back() {
1733+ let mut params = CodecParameters::new(CodecId::Aac);
1734+ params.extradata = Some(Buf::from(vec![0x12, 0x10]));
1735+ params.media = MediaParameters::Audio(AudioParameters {
1736+ sample_rate: 44_100,
1737+ layout: ChannelLayout::from_count(2),
1738+ ..Default::default()
1739+ });
1740+ let mut muxer = Mp4Muxer::new(Cursor::new(Vec::new())).unwrap();
1741+ muxer.set_faststart(true);
1742+ let stream = muxer
1743+ .add_stream(StreamInfo::new(0, TimeBase::from_rate(44_100), params))
1744+ .unwrap();
1745+ for i in 0..10u8 {
1746+ let mut packet = Packet::new(stream, TimeBase::from_rate(44_100), vec![0xAA, i, 0x55]);
1747+ packet.dts = Some(i64::from(i) * 1024);
1748+ packet.duration = Some(1024);
1749+ packet.flags.keyframe = true;
1750+ muxer.write_packet(&packet).unwrap();
1751+ }
1752+ let bytes = muxer.finish_faststart().unwrap().into_inner();
1753+
1754+ let mut order = Vec::new();
1755+ let mut at = 0usize;
1756+ while at + 8 <= bytes.len() {
1757+ let size = u32::from_be_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]);
1758+ order.push(String::from_utf8_lossy(&bytes[at + 4..at + 8]).into_owned());
1759+ at += match size {
1760+ 1 => u64::from_be_bytes(bytes[at + 8..at + 16].try_into().unwrap()) as usize,
1761+ _ => size as usize,
1762+ };
1763+ }
1764+ assert_eq!(order, ["ftyp", "moov", "mdat"]);
1765+
1766+ let mut demuxer = Mp4Demuxer::new(Cursor::new(bytes)).unwrap();
1767+ let mut back = Vec::new();
1768+ loop {
1769+ match demuxer.next_packet() {
1770+ Ok(packet) => back.push(packet.data.to_vec()),
1771+ Err(Error::Eof) => break,
1772+ Err(e) => panic!("{e}"),
1773+ }
1774+ }
1775+ let written: Vec<Vec<u8>> = (0..10u8).map(|i| vec![0xAA, i, 0x55]).collect();
1776+ assert_eq!(back, written);
1777+ }
1778+
16311779 #[test]
16321780 fn language_packing_is_the_demuxers_inverse() {
16331781 for tag in ["tur", "eng", "und"] {