forge
Explore
Log in

Don't you dare go Hollow

The index, random access and late-declared streams a host needs

Browse files at this commit

d7dca0c1cbf2a5bfc49d727ac8f8561e37039149Ahmet Kaan GümüşParent: b5f5ec8
  • feat
    • the index, random access and late-declared streams a host needs
Show full message
feat(mp4): the index, random access and late-declared streams a host needs

The replica's engine reads and writes mp4 through this crate now, and five
things it needs were not reachable through the two traits alone:

- `Sample` is public, and `samples(stream)` hands the whole resolved table
  over. That table *is* the index an mp4 carries of itself -- a caller that
  counts frames, builds a display-order seek table or asks what a track spends
  reads it here instead of walking the file again.
- `read_sample(stream, index)` reads one sample of one stream without moving
  the packet cursor: random access beside the sequential `next_packet`, for a
  caller holding an index of its own.
- `tracks()` lists every track the container declares, in file order, with its
  `tkhd` id, its handler, its sample entry fourcc, its language and its edit
  list's `media_time`. Two things ride on it: a track whose codec this build
  has no id for is still listed (a picker greys such a row out rather than
  pretending the file has fewer tracks than it has), and `avc3` can be told
  from `avc1` by a host that re-injects parameter sets out of the `avcC`.
- `duration_secs()` is the `mvhd`'s own length, which is what a file's byte
  rate is measured over -- not any one track's.
- The muxer takes `add_stream` at any point before `finish`, and `set_color`
  after the stream is declared. Samples are written where they arrive and the
  sample entries are built at the end, so a track declared after the picture
  is already in the `mdat` costs nothing -- which is what lets an export mix
  and encode its sound while it writes the picture, and add its subtitles once
  the film's length is known.

cargo test -p ec-mp4: 10 passed.
crates/ec-mp4/src/demux.rsmodified+141 -20
@@ -23,17 +23,25 @@ const MOOF_LIMIT: u64 = 64 << 20;
2323 const SAMPLE_LIMIT: u64 = 256 << 20;
2424
2525 /// One sample of one track, resolved: everything a packet needs but its bytes.
26-#[derive(Debug, Clone, Copy)]
27-struct Sample {
28- offset: u64,
29- size: u32,
30- duration: u32,
26+///
27+/// This *is* the index an mp4 carries of itself, so it is public: a caller that
28+/// counts frames, builds a seek table or asks how many bytes a track spends
29+/// reads it here rather than walking the file a second time.
30+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31+pub struct Sample {
32+ /// Byte offset in the file.
33+ pub offset: u64,
34+ /// Size in bytes.
35+ pub size: u32,
36+ /// How long it lasts, in track ticks.
37+ pub duration: u32,
3138 /// Decode time in track ticks, edit list applied.
32- dts: i64,
39+ pub dts: i64,
3340 /// Composition (presentation) time in track ticks, `ctts` and edit list
3441 /// applied.
35- cts: i64,
36- sync: bool,
42+ pub cts: i64,
43+ /// Whether a decoder may be started on it.
44+ pub sync: bool,
3745 }
3846
3947 /// One `trak`, as far as the packet loop cares about it.
@@ -49,6 +57,35 @@ struct Trak {
4957 title: Option<String>,
5058 }
5159
60+/// What the container says about one track, whether or not this build has a
61+/// [`CodecId`] for what is in it.
62+///
63+/// A track whose sample entry is unknown here has `stream: None` — its samples
64+/// are never handed out as some other codec's — but it is still *listed*, with
65+/// the four-character code that named it, so a caller can say what it is leaving
66+/// out instead of pretending the file has fewer tracks than it has.
67+#[derive(Debug, Clone, PartialEq, Eq)]
68+pub struct TrackInfo {
69+ /// `tkhd` track id, which is what the file itself names the track by.
70+ pub track_id: u32,
71+ /// What the `hdlr` says the track carries, [`None`] for a handler this does
72+ /// not map (a chapter or a hint track).
73+ pub media: Option<MediaType>,
74+ /// Four-character code of the first `stsd` entry: `avc1`, `hvc1`, `mp4a`,
75+ /// `ac-3`, `tx3g`, ... Zero where the track has no sample entry at all.
76+ pub sample_entry: [u8; 4],
77+ /// Index in [`Mp4Demuxer::streams`], or [`None`] for a track walked past.
78+ pub stream: Option<u32>,
79+ /// ISO 639-2 language from the `mdhd`, [`None`] for the `und` a muxer
80+ /// writes when it was never told.
81+ pub language: Option<String>,
82+ /// `media_time` of the edit list's first real entry, in track ticks: where
83+ /// the presentation starts inside the media, which for a sound track is its
84+ /// encoder delay. [`None`] where the track carries no edit list, which is
85+ /// not the same claim as an edit list stating zero.
86+ pub media_time: Option<i64>,
87+}
88+
5289 /// `trex` defaults: what a fragment leaves unsaid.
5390 #[derive(Debug, Clone, Copy, Default)]
5491 struct Trex {
@@ -69,8 +106,14 @@ pub struct Mp4Demuxer<R> {
69106 src: Src<R>,
70107 streams: Vec<StreamInfo>,
71108 traks: Vec<Trak>,
109+ /// One per [`Mp4Demuxer::traks`], same order: what the container said about
110+ /// the track, including the ones no stream was made for.
111+ tracks: Vec<TrackInfo>,
72112 title: Option<String>,
73113 fragments: usize,
114+ /// `mvhd` duration and timescale: how long the *movie* plays, which on a
115+ /// file whose sound outlasts its picture is neither track's own length.
116+ movie: (u64, u32),
74117 }
75118
76119 impl<R: Read + Seek> Mp4Demuxer<R> {
@@ -106,8 +149,10 @@ impl<R: Read + Seek> Mp4Demuxer<R> {
106149 src,
107150 streams: Vec::new(),
108151 traks: Vec::new(),
152+ tracks: Vec::new(),
109153 title: None,
110154 fragments: moofs.len(),
155+ movie: (0, 0),
111156 };
112157 let trex = me.read_moov(&data)?;
113158 for (moof_at, body, stop) in moofs {
@@ -161,16 +206,59 @@ impl<R: Read + Seek> Mp4Demuxer<R> {
161206 self.fragments
162207 }
163208
209+ /// Every track the file declares, in file order — the order the `moov`
210+ /// wrote them in, which is the order a caller may number them by and get
211+ /// the same answer twice.
212+ pub fn tracks(&self) -> &[TrackInfo] {
213+ &self.tracks
214+ }
215+
216+ /// How long the *movie* plays, out of the `mvhd`: one length spanning every
217+ /// track, which is what a file's byte rate is measured over. [`None`] where
218+ /// the header states none.
219+ pub fn duration_secs(&self) -> Option<f64> {
220+ let (duration, timescale) = self.movie;
221+ (duration > 0 && timescale > 0).then(|| duration as f64 / f64::from(timescale))
222+ }
223+
224+ /// Every sample of `stream`, in decode order: the index the file carries of
225+ /// itself. Empty for a stream that does not exist.
226+ pub fn samples(&self, stream: u32) -> &[Sample] {
227+ self.traks
228+ .iter()
229+ .find(|t| t.stream == Some(stream))
230+ .map_or(&[], |t| &t.samples[..])
231+ }
232+
233+ /// One sample of one stream by its index in [`Mp4Demuxer::samples`], read
234+ /// **without moving the packet cursor**: random access for a caller holding
235+ /// an index of its own, beside the sequential [`Demuxer::next_packet`].
236+ pub fn read_sample(&mut self, stream: u32, index: usize) -> Result<Packet> {
237+ let Some(trak) = self.traks.iter().find(|t| t.stream == Some(stream)) else {
238+ return Err(Error::corrupt(format!("mp4: no stream {stream} to read")));
239+ };
240+ let Some(sample) = trak.samples.get(index).copied() else {
241+ return Err(Error::Eof);
242+ };
243+ let time_base = trak.time_base;
244+ let data = self
245+ .src
246+ .read_vec(sample.offset, u64::from(sample.size), SAMPLE_LIMIT)?;
247+ Ok(packet_of(stream, time_base, &sample, data))
248+ }
249+
164250 fn read_moov(&mut self, data: &[u8]) -> Result<Vec<Trex>> {
165251 let mut movie_timescale = 1_000u32;
166252 for child in Boxes::new(data) {
167253 let (kind, payload) = child?;
168254 if &kind == b"mvhd" {
169255 let (version, _, rest) = full(payload)?;
170- movie_timescale = match version {
171- 0 => be32(rest, 8)?,
172- _ => be32(rest, 16)?,
256+ let (timescale, duration) = match version {
257+ 0 => (be32(rest, 8)?, u64::from(be32(rest, 12)?)),
258+ _ => (be32(rest, 16)?, be64(rest, 20)?),
173259 };
260+ movie_timescale = timescale;
261+ self.movie = (duration, timescale);
174262 }
175263 }
176264 let mut trex = Vec::new();
@@ -281,6 +369,11 @@ impl<R: Read + Seek> Mp4Demuxer<R> {
281369 // the first ctts delay, and reading that as a trim throws away real
282370 // pictures).
283371 let mut shift = 0i64;
372+ let media_time = edit
373+ .iter()
374+ .flatten()
375+ .map(|&(_, media_time, _)| media_time)
376+ .find(|&t| t >= 0);
284377 if let Some(edits) = edit {
285378 let mut empty = 0i64;
286379 for (segment, media_time, _) in edits {
@@ -297,6 +390,7 @@ impl<R: Read + Seek> Mp4Demuxer<R> {
297390
298391 let table = SampleTable::read(stbl, self.src.len)?;
299392 let samples = table.build(shift)?;
393+ let track_language = language.clone();
300394 let stream = match table.entry {
301395 Some(entry) => {
302396 let media = match entry.codec.media_type() {
@@ -329,6 +423,19 @@ impl<R: Read + Seek> Mp4Demuxer<R> {
329423 }
330424 None => None,
331425 };
426+ self.tracks.push(TrackInfo {
427+ track_id,
428+ media: match &handler {
429+ b"vide" => Some(MediaType::Video),
430+ b"soun" => Some(MediaType::Audio),
431+ b"sbtl" | b"subt" | b"text" => Some(MediaType::Subtitle),
432+ _ => None,
433+ },
434+ sample_entry: table.entry_kind,
435+ stream,
436+ language: track_language,
437+ media_time,
438+ });
332439 self.traks.push(Trak {
333440 track_id,
334441 stream,
@@ -500,15 +607,7 @@ impl<R: Read + Seek + Send> Demuxer for Mp4Demuxer<R> {
500607 let data = self
501608 .src
502609 .read_vec(sample.offset, u64::from(sample.size), SAMPLE_LIMIT)?;
503- let mut packet = Packet::new(stream, time_base, data);
504- packet.pts = Some(sample.cts);
505- packet.dts = Some(sample.dts);
506- packet.duration = Some(i64::from(sample.duration));
507- packet.flags = PacketFlags {
508- keyframe: sample.sync,
509- ..PacketFlags::default()
510- };
511- Ok(packet)
610+ Ok(packet_of(stream, time_base, &sample, data))
512611 }
513612
514613 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
@@ -558,10 +657,26 @@ impl<R: Read + Seek + Send> Demuxer for Mp4Demuxer<R> {
558657 }
559658 }
560659
660+/// One resolved sample and its bytes as the packet a caller is handed.
661+fn packet_of(stream: u32, time_base: TimeBase, sample: &Sample, data: Vec<u8>) -> Packet {
662+ let mut packet = Packet::new(stream, time_base, data);
663+ packet.pts = Some(sample.cts);
664+ packet.dts = Some(sample.dts);
665+ packet.duration = Some(i64::from(sample.duration));
666+ packet.flags = PacketFlags {
667+ keyframe: sample.sync,
668+ ..PacketFlags::default()
669+ };
670+ packet
671+}
672+
561673 /// The five tables that turn a sample number into a byte range and an instant,
562674 /// plus the one sample entry describing what those bytes are.
563675 struct SampleTable<'a> {
564676 entry: Option<Entry>,
677+ /// The first `stsd` entry's four-character code, kept whether or not this
678+ /// build knows the codec behind it.
679+ entry_kind: FourCc,
565680 stts: Vec<(u32, u32)>,
566681 ctts: Vec<(u32, i32)>,
567682 stss: Vec<u32>,
@@ -576,6 +691,7 @@ impl<'a> SampleTable<'a> {
576691 fn read(stbl: &'a [u8], file_len: u64) -> Result<SampleTable<'a>> {
577692 let mut me = SampleTable {
578693 entry: None,
694+ entry_kind: [0; 4],
579695 stts: Vec::new(),
580696 ctts: Vec::new(),
581697 stss: Vec::new(),
@@ -594,6 +710,7 @@ impl<'a> SampleTable<'a> {
594710 // thing any muxer writes.
595711 if let Some(child) = Boxes::new(rest.get(4..).unwrap_or(&[])).next() {
596712 let (kind, payload) = child?;
713+ me.entry_kind = kind;
597714 me.entry = sample_entry(&kind, payload)?;
598715 }
599716 }
@@ -871,6 +988,10 @@ fn sample_entry(kind: &FourCc, payload: &[u8]) -> Result<Option<Entry>> {
871988 b".mp3" | b"ms\x00\x55" => (CodecId::Mp3, None),
872989 b"ac-3" => (CodecId::Ac3, config_bytes(config, b"dac3")),
873990 b"ec-3" => (CodecId::EAc3, config_bytes(config, b"dec3")),
991+ // Named rather than dropped: see `codec_of` in ec-matroska. A track
992+ // listed as unsupported beats a track that vanished.
993+ b"mlpa" => (CodecId::TrueHd, None),
994+ b"dtsc" | b"dtse" | b"dtsh" | b"dtsl" => (CodecId::Dts, None),
874995 b"alac" => (
875996 CodecId::Alac,
876997 // ALAC's magic cookie is taken with its box header, which is the
crates/ec-mp4/src/lib.rsmodified+1 -1
@@ -47,7 +47,7 @@ mod demux;
4747 mod esds;
4848 mod mux;
4949
50-pub use demux::Mp4Demuxer;
50+pub use demux::{Mp4Demuxer, Sample, TrackInfo};
5151 pub use esds::{Esds, object_type};
5252 pub use mux::Mp4Muxer;
5353
crates/ec-mp4/src/mux.rsmodified+29 -5
@@ -95,6 +95,28 @@ impl<W: Write + Seek> Mp4Muxer<W> {
9595 Ok(())
9696 }
9797
98+ /// Say what a video stream's samples mean after the stream was declared.
99+ ///
100+ /// The `colr` box is part of the sample entry and the sample entry is
101+ /// written at [`Muxer::finish`], so this may be said any time before then —
102+ /// which is what a caller that learns the source's colour space after it has
103+ /// opened the file needs.
104+ pub fn set_color(&mut self, stream: u32, color: ec_core::ColorInfo) -> Result<()> {
105+ let track = self
106+ .tracks
107+ .get_mut(stream as usize)
108+ .ok_or_else(|| Error::corrupt(format!("mp4: no stream {stream} to colour")))?;
109+ match &mut track.info.params.media {
110+ ec_core::MediaParameters::Video(video) => video.color = color,
111+ _ => {
112+ return Err(Error::corrupt(format!(
113+ "mp4: stream {stream} is not a video track"
114+ )));
115+ }
116+ }
117+ Ok(())
118+ }
119+
98120 /// Take the writer back once the file is finished.
99121 pub fn into_inner(self) -> W {
100122 self.w
@@ -320,12 +342,14 @@ impl<W: Write + Seek> Mp4Muxer<W> {
320342 }
321343
322344 impl<W: Write + Seek + Send> Muxer for Mp4Muxer<W> {
345+ /// Declare a stream — **at any point before [`Muxer::finish`]**, which is
346+ /// more than the trait promises. Samples are written where they arrive and
347+ /// the chunk table follows, so a track declared after the picture is
348+ /// already in the `mdat` costs nothing: its `trak` is built at the end with
349+ /// every other. That is what lets an export mix and encode its sound *while*
350+ /// it writes the picture, and add its subtitles once the film's length is
351+ /// known.
323352 fn add_stream(&mut self, info: StreamInfo) -> Result<u32> {
324- if self.started {
325- return Err(Error::corrupt(
326- "mp4: a stream added after the first packet was written",
327- ));
328- }
329353 let timescale = u32::try_from(info.time_base.den()).map_err(|_| {
330354 Error::corrupt(format!(
331355 "mp4: a time base of 1/{} does not fit a 32-bit timescale",