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 @@
1 //! The writer: `ftyp`, then one `mdat` the samples stream into, then the `moov`1 //! The writer: `ftyp`, then one `mdat` the samples stream into, then the `moov`
2 //! built from what was written.2 //! built from what was written.
3 3
4-use std::io::{Seek, SeekFrom, Write};4+use std::io::{Read, Seek, SeekFrom, Write};
5 5
6 use ec_core::{6 use ec_core::{
7 CodecId, ContentLight, Error, Muxer, Packet, Result, Rounding, StreamInfo, TimeBase,7 CodecId, ContentLight, Error, Muxer, Packet, Result, Rounding, StreamInfo, TimeBase,
@@ -14,6 +14,9 @@ use crate::esds::{Esds, object_type};
14 /// every sample time is in its own track's timescale.14 /// every sample time is in its own track's timescale.
15 const MOVIE_TIMESCALE: u32 = 1_000;15 const MOVIE_TIMESCALE: u32 = 1_000;
16 16
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+
17 /// One written sample, as the sample tables will state it.20 /// One written sample, as the sample tables will state it.
18 struct Sample {21 struct Sample {
19 size: u32,22 size: u32,
@@ -61,8 +64,8 @@ struct Track {
61 /// arrive, so muxing costs one pass and no temporary file, and the sample tables64 /// arrive, so muxing costs one pass and no temporary file, and the sample tables
62 /// — which cannot be written before the sizes they state are known — go at the65 /// — which cannot be written before the sizes they state are known — go at the
63 /// end. The cost is that a player streaming the file over HTTP has to reach the66 /// 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 to67+/// end before it can start; [`Mp4Muxer::set_faststart`] moves the `moov` in
65-/// copy the whole `mdat` a second time, and is not implemented here.68+/// front instead, at the price of copying the `mdat` once more.
66 ///69 ///
67 /// Interleaving is the caller's: packets are written in the order they are70 /// Interleaving is the caller's: packets are written in the order they are
68 /// handed over, and the chunk table follows that order exactly.71 /// handed over, and the chunk table follows that order exactly.
@@ -83,6 +86,8 @@ pub struct Mp4Muxer<W> {
83 /// Chapter marks as `(start in ns, title)`, sorted by start. Written as a86 /// Chapter marks as `(start in ns, title)`, sorted by start. Written as a
84 /// Nero `chpl` in `moov/udta` and as a QuickTime text track.87 /// Nero `chpl` in `moov/udta` and as a QuickTime text track.
85 chapters: Vec<(u64, String)>,88 chapters: Vec<(u64, String)>,
89+ /// Lay the `moov` in front of the `mdat`; see [`Mp4Muxer::set_faststart`].
90+ faststart: bool,
86 }91 }
87 92
88 /// The chapter text track as it is laid out in the file: its samples sit in the93 /// 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> {
124 title: None,129 title: None,
125 brands,130 brands,
126 chapters: Vec::new(),131 chapters: Vec::new(),
132+ faststart: false,
127 })133 })
128 }134 }
129 135
@@ -271,6 +277,13 @@ impl<W: Write + Seek> Mp4Muxer<W> {
271 Ok(())277 Ok(())
272 }278 }
273 279
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+
274 /// Take the writer back once the file is finished.287 /// Take the writer back once the file is finished.
275 pub fn into_inner(self) -> W {288 pub fn into_inner(self) -> W {
276 self.w289 self.w
@@ -401,7 +414,30 @@ impl<W: Write + Seek> Mp4Muxer<W> {
401 })414 })
402 }415 }
403 416
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>> {
405 let mut moov = Vec::with_capacity(4096);441 let mut moov = Vec::with_capacity(4096);
406 let at = open(&mut moov, b"moov");442 let at = open(&mut moov, b"moov");
407 let duration = self.movie_duration().max(chapters.map_or(0, |c| c.end_ms));443 let duration = self.movie_duration().max(chapters.map_or(0, |c| c.end_ms));
@@ -428,10 +464,10 @@ impl<W: Write + Seek> Mp4Muxer<W> {
428 true => chapter_id,464 true => chapter_id,
429 false => None,465 false => None,
430 };466 };
431- self.write_trak(&mut moov, i, duration, chapter_ref)?;467+ self.write_trak(&mut moov, i, duration, chapter_ref, shift)?;
432 }468 }
433 if let (Some(text), Some(id)) = (chapters, chapter_id) {469 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);
435 }471 }
436 let chpl = (1..=255).contains(&self.chapters.len());472 let chpl = (1..=255).contains(&self.chapters.len());
437 if self.title.is_some() || chpl {473 if self.title.is_some() || chpl {
@@ -445,6 +481,11 @@ impl<W: Write + Seek> Mp4Muxer<W> {
445 close(&mut moov, udta);481 close(&mut moov, udta);
446 }482 }
447 close(&mut moov, at);483 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)?;
448 self.w.write_all(&moov)?;489 self.w.write_all(&moov)?;
449 self.pos += moov.len() as u64;490 self.pos += moov.len() as u64;
450 Ok(())491 Ok(())
@@ -458,6 +499,7 @@ impl<W: Write + Seek> Mp4Muxer<W> {
458 i: usize,499 i: usize,
459 movie_duration: i64,500 movie_duration: i64,
460 chapter_ref: Option<u32>,501 chapter_ref: Option<u32>,
502+ shift: u64,
461 ) -> Result<()> {503 ) -> Result<()> {
462 let track = &self.tracks[i];504 let track = &self.tracks[i];
463 let codec = track.info.params.codec;505 let codec = track.info.params.codec;
@@ -600,7 +642,7 @@ impl<W: Write + Seek> Mp4Muxer<W> {
600 out.extend_from_slice(&1u32.to_be_bytes());642 out.extend_from_slice(&1u32.to_be_bytes());
601 sample_entry(out, &track.info, track.field_order, track.chan)?;643 sample_entry(out, &track.info, track.field_order, track.chan)?;
602 close(out, stsd);644 close(out, stsd);
603- sample_tables(out, track);645+ sample_tables(out, track, shift);
604 close(out, stbl);646 close(out, stbl);
605 close(out, minf);647 close(out, minf);
606 close(out, mdia);648 close(out, mdia);
@@ -697,33 +739,80 @@ impl<W: Write + Seek + Send> Muxer for Mp4Muxer<W> {
697 if self.finished {739 if self.finished {
698 return Ok(());740 return Ok(());
699 }741 }
700- self.finished = true;742+ if self.faststart {
701- self.start()?;743+ return Err(Error::unsupported(
702- for track in &mut self.tracks {744+ "mp4 faststart",
703- Mp4Muxer::<W>::resolve_durations(track);745+ "finish it with finish_faststart, which reads the mdat back",
746+ ));
704 }747 }
705- // The chapter text samples are media, so they go in the mdat before its748+ self.finished = true;
706- // size is known.749+ let chapters = self.seal_mdat()?;
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))?;
716 self.write_moov(chapters.as_ref())?;750 self.write_moov(chapters.as_ref())?;
717 self.w.flush()?;751 self.w.flush()?;
718 Ok(())752 Ok(())
719 }753 }
720 }754 }
721 755
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+
722 /// The QuickTime chapter text track: one `text` sample per chapter, in the movie811 /// The QuickTime chapter text track: one `text` sample per chapter, in the movie
723 /// clock (milliseconds), with a `co64` offset so it stays right past 4 GB. It is812 /// clock (milliseconds), with a `co64` offset so it stays right past 4 GB. It is
724 /// disabled, as a chapter track is in a QuickTime file, and its `edts` puts the813 /// disabled, as a chapter track is in a QuickTime file, and its `edts` puts the
725 /// first chapter at its own start when that is not zero.814 /// 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) {
727 let at = open(out, b"trak");816 let at = open(out, b"trak");
728 817
729 let tkhd = open(out, b"tkhd");818 let tkhd = open(out, b"tkhd");
@@ -841,7 +930,7 @@ fn write_chapter_trak(out: &mut Vec<u8>, id: u32, chap: &ChapterText) {
841 let co64 = open(out, b"co64");930 let co64 = open(out, b"co64");
842 full_head(out, 0, 0);931 full_head(out, 0, 0);
843 out.extend_from_slice(&1u32.to_be_bytes());932 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());
845 close(out, co64);934 close(out, co64);
846 close(out, stbl);935 close(out, stbl);
847 close(out, minf);936 close(out, minf);
@@ -954,7 +1043,7 @@ fn opus_pre_skip(track: &Track) -> i64 {
954 /// The tables of a QuickTime PCM track the way QuickTime and ffmpeg lay them1043 /// The tables of a QuickTime PCM track the way QuickTime and ffmpeg lay them
955 /// out: a *sample* is one frame (`frame_bytes`, one `stts` tick), and a chunk1044 /// out: a *sample* is one frame (`frame_bytes`, one `stts` tick), and a chunk
956 /// holds as many samples as the packets written into it had frames.1045 /// 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) {
958 let frame_bytes = frame_bytes.max(1);1047 let frame_bytes = frame_bytes.max(1);
959 let total: u64 = track1048 let total: u64 = track
960 .samples1049 .samples
@@ -1009,26 +1098,34 @@ fn pcm_tables(out: &mut Vec<u8>, track: &Track, frame_bytes: u32) {
1009 out.extend_from_slice(&(total as u32).to_be_bytes());1098 out.extend_from_slice(&(total as u32).to_be_bytes());
1010 close(out, stsz);1099 close(out, stsz);
1011 1100
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));
1013 let kind = if big { b"co64" } else { b"stco" };1105 let kind = if big { b"co64" } else { b"stco" };
1014 let chunks = open(out, kind);1106 let chunks = open(out, kind);
1015 full_head(out, 0, 0);1107 full_head(out, 0, 0);
1016 out.extend_from_slice(&(track.chunks.len() as u32).to_be_bytes());1108 out.extend_from_slice(&(track.chunks.len() as u32).to_be_bytes());
1017 for &(at, _) in &track.chunks {1109 for &(at, _) in &track.chunks {
1018 match big {1110 match big {
1019- true => out.extend_from_slice(&at.to_be_bytes()),1111+ true => out.extend_from_slice(&(at + shift).to_be_bytes()),
1020- false => out.extend_from_slice(&(at as u32).to_be_bytes()),1112+ false => out.extend_from_slice(&((at + shift) as u32).to_be_bytes()),
1021 }1113 }
1022 }1114 }
1023 close(out, chunks);1115 close(out, chunks);
1024 }1116 }
1025 1117
1026 /// The `stts`/`ctts`/`stss`/`stsc`/`stsz` and chunk-offset tables of one track.1118 /// 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) {
1028 if let (Some((bytes, _)), Some(audio)) =1120 if let (Some((bytes, _)), Some(audio)) =
1029 (qt_pcm(track.info.params.codec), track.info.params.audio())1121 (qt_pcm(track.info.params.codec), track.info.params.audio())
1030 {1122 {
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+ );
1032 return;1129 return;
1033 }1130 }
1034 // stts: runs of equal durations, which for constant-rate video is one entry1131 // 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) {
1139 close(out, stsz);1236 close(out, stsz);
1140 1237
1141 // co64 where the file is big enough to need it, stco where it is not.1238 // 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));
1143 let kind = if big { b"co64" } else { b"stco" };1243 let kind = if big { b"co64" } else { b"stco" };
1144 let chunks = open(out, kind);1244 let chunks = open(out, kind);
1145 full_head(out, 0, 0);1245 full_head(out, 0, 0);
1146 out.extend_from_slice(&(track.chunks.len() as u32).to_be_bytes());1246 out.extend_from_slice(&(track.chunks.len() as u32).to_be_bytes());
1147 for &(at, _) in &track.chunks {1247 for &(at, _) in &track.chunks {
1148 match big {1248 match big {
1149- true => out.extend_from_slice(&at.to_be_bytes()),1249+ true => out.extend_from_slice(&(at + shift).to_be_bytes()),
1150- false => out.extend_from_slice(&(at as u32).to_be_bytes()),1250+ false => out.extend_from_slice(&((at + shift) as u32).to_be_bytes()),
1151 }1251 }
1152 }1252 }
1153 close(out, chunks);1253 close(out, chunks);
@@ -1628,6 +1728,54 @@ mod tests {
1628 assert_eq!(back[3], vec![0xAA, 3, 0x55]);1728 assert_eq!(back[3], vec![0xAA, 3, 0x55]);
1629 }1729 }
1630 1730
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+
1631 #[test]1779 #[test]
1632 fn language_packing_is_the_demuxers_inverse() {1780 fn language_packing_is_the_demuxers_inverse() {
1633 for tag in ["tur", "eng", "und"] {1781 for tag in ["tur", "eng", "und"] {