The index, random access and late-declared streams a host needs
Browse files at this commitd7dca0c1cbf2a5bfc49d727ac8f8561e37039149Parent: b5f5ec8- feat
- the index, random access and late-declared streams a host needs
3 changed files +171 -26
- crates/ec-mp4/src/demux.rs +141 -20
- crates/ec-mp4/src/lib.rs +1 -1
- crates/ec-mp4/src/mux.rs +29 -5
crates/ec-mp4/src/demux.rsmodified+141 -20
| @@ -23,17 +23,25 @@ const MOOF_LIMIT: u64 = 64 << 20; | ||
| 23 | 23 | const SAMPLE_LIMIT: u64 = 256 << 20; |
| 24 | 24 | |
| 25 | 25 | /// 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, | |
| 31 | 38 | /// Decode time in track ticks, edit list applied. |
| 32 | - dts: i64, | |
| 39 | + pub dts: i64, | |
| 33 | 40 | /// Composition (presentation) time in track ticks, `ctts` and edit list |
| 34 | 41 | /// applied. |
| 35 | - cts: i64, | |
| 36 | - sync: bool, | |
| 42 | + pub cts: i64, | |
| 43 | + /// Whether a decoder may be started on it. | |
| 44 | + pub sync: bool, | |
| 37 | 45 | } |
| 38 | 46 | |
| 39 | 47 | /// One `trak`, as far as the packet loop cares about it. |
| @@ -49,6 +57,35 @@ struct Trak { | ||
| 49 | 57 | title: Option<String>, |
| 50 | 58 | } |
| 51 | 59 | |
| 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 | + | |
| 52 | 89 | /// `trex` defaults: what a fragment leaves unsaid. |
| 53 | 90 | #[derive(Debug, Clone, Copy, Default)] |
| 54 | 91 | struct Trex { |
| @@ -69,8 +106,14 @@ pub struct Mp4Demuxer<R> { | ||
| 69 | 106 | src: Src<R>, |
| 70 | 107 | streams: Vec<StreamInfo>, |
| 71 | 108 | 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>, | |
| 72 | 112 | title: Option<String>, |
| 73 | 113 | 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), | |
| 74 | 117 | } |
| 75 | 118 | |
| 76 | 119 | impl<R: Read + Seek> Mp4Demuxer<R> { |
| @@ -106,8 +149,10 @@ impl<R: Read + Seek> Mp4Demuxer<R> { | ||
| 106 | 149 | src, |
| 107 | 150 | streams: Vec::new(), |
| 108 | 151 | traks: Vec::new(), |
| 152 | + tracks: Vec::new(), | |
| 109 | 153 | title: None, |
| 110 | 154 | fragments: moofs.len(), |
| 155 | + movie: (0, 0), | |
| 111 | 156 | }; |
| 112 | 157 | let trex = me.read_moov(&data)?; |
| 113 | 158 | for (moof_at, body, stop) in moofs { |
| @@ -161,16 +206,59 @@ impl<R: Read + Seek> Mp4Demuxer<R> { | ||
| 161 | 206 | self.fragments |
| 162 | 207 | } |
| 163 | 208 | |
| 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 | + | |
| 164 | 250 | fn read_moov(&mut self, data: &[u8]) -> Result<Vec<Trex>> { |
| 165 | 251 | let mut movie_timescale = 1_000u32; |
| 166 | 252 | for child in Boxes::new(data) { |
| 167 | 253 | let (kind, payload) = child?; |
| 168 | 254 | if &kind == b"mvhd" { |
| 169 | 255 | 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)?), | |
| 173 | 259 | }; |
| 260 | + movie_timescale = timescale; | |
| 261 | + self.movie = (duration, timescale); | |
| 174 | 262 | } |
| 175 | 263 | } |
| 176 | 264 | let mut trex = Vec::new(); |
| @@ -281,6 +369,11 @@ impl<R: Read + Seek> Mp4Demuxer<R> { | ||
| 281 | 369 | // the first ctts delay, and reading that as a trim throws away real |
| 282 | 370 | // pictures). |
| 283 | 371 | let mut shift = 0i64; |
| 372 | + let media_time = edit | |
| 373 | + .iter() | |
| 374 | + .flatten() | |
| 375 | + .map(|&(_, media_time, _)| media_time) | |
| 376 | + .find(|&t| t >= 0); | |
| 284 | 377 | if let Some(edits) = edit { |
| 285 | 378 | let mut empty = 0i64; |
| 286 | 379 | for (segment, media_time, _) in edits { |
| @@ -297,6 +390,7 @@ impl<R: Read + Seek> Mp4Demuxer<R> { | ||
| 297 | 390 | |
| 298 | 391 | let table = SampleTable::read(stbl, self.src.len)?; |
| 299 | 392 | let samples = table.build(shift)?; |
| 393 | + let track_language = language.clone(); | |
| 300 | 394 | let stream = match table.entry { |
| 301 | 395 | Some(entry) => { |
| 302 | 396 | let media = match entry.codec.media_type() { |
| @@ -329,6 +423,19 @@ impl<R: Read + Seek> Mp4Demuxer<R> { | ||
| 329 | 423 | } |
| 330 | 424 | None => None, |
| 331 | 425 | }; |
| 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 | + }); | |
| 332 | 439 | self.traks.push(Trak { |
| 333 | 440 | track_id, |
| 334 | 441 | stream, |
| @@ -500,15 +607,7 @@ impl<R: Read + Seek + Send> Demuxer for Mp4Demuxer<R> { | ||
| 500 | 607 | let data = self |
| 501 | 608 | .src |
| 502 | 609 | .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)) | |
| 512 | 611 | } |
| 513 | 612 | |
| 514 | 613 | fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> { |
| @@ -558,10 +657,26 @@ impl<R: Read + Seek + Send> Demuxer for Mp4Demuxer<R> { | ||
| 558 | 657 | } |
| 559 | 658 | } |
| 560 | 659 | |
| 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 | + | |
| 561 | 673 | /// The five tables that turn a sample number into a byte range and an instant, |
| 562 | 674 | /// plus the one sample entry describing what those bytes are. |
| 563 | 675 | struct SampleTable<'a> { |
| 564 | 676 | 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, | |
| 565 | 680 | stts: Vec<(u32, u32)>, |
| 566 | 681 | ctts: Vec<(u32, i32)>, |
| 567 | 682 | stss: Vec<u32>, |
| @@ -576,6 +691,7 @@ impl<'a> SampleTable<'a> { | ||
| 576 | 691 | fn read(stbl: &'a [u8], file_len: u64) -> Result<SampleTable<'a>> { |
| 577 | 692 | let mut me = SampleTable { |
| 578 | 693 | entry: None, |
| 694 | + entry_kind: [0; 4], | |
| 579 | 695 | stts: Vec::new(), |
| 580 | 696 | ctts: Vec::new(), |
| 581 | 697 | stss: Vec::new(), |
| @@ -594,6 +710,7 @@ impl<'a> SampleTable<'a> { | ||
| 594 | 710 | // thing any muxer writes. |
| 595 | 711 | if let Some(child) = Boxes::new(rest.get(4..).unwrap_or(&[])).next() { |
| 596 | 712 | let (kind, payload) = child?; |
| 713 | + me.entry_kind = kind; | |
| 597 | 714 | me.entry = sample_entry(&kind, payload)?; |
| 598 | 715 | } |
| 599 | 716 | } |
| @@ -871,6 +988,10 @@ fn sample_entry(kind: &FourCc, payload: &[u8]) -> Result<Option<Entry>> { | ||
| 871 | 988 | b".mp3" | b"ms\x00\x55" => (CodecId::Mp3, None), |
| 872 | 989 | b"ac-3" => (CodecId::Ac3, config_bytes(config, b"dac3")), |
| 873 | 990 | 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), | |
| 874 | 995 | b"alac" => ( |
| 875 | 996 | CodecId::Alac, |
| 876 | 997 | // 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; | ||
| 47 | 47 | mod esds; |
| 48 | 48 | mod mux; |
| 49 | 49 | |
| 50 | -pub use demux::Mp4Demuxer; | |
| 50 | +pub use demux::{Mp4Demuxer, Sample, TrackInfo}; | |
| 51 | 51 | pub use esds::{Esds, object_type}; |
| 52 | 52 | pub use mux::Mp4Muxer; |
| 53 | 53 |
crates/ec-mp4/src/mux.rsmodified+29 -5
| @@ -95,6 +95,28 @@ impl<W: Write + Seek> Mp4Muxer<W> { | ||
| 95 | 95 | Ok(()) |
| 96 | 96 | } |
| 97 | 97 | |
| 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 | + | |
| 98 | 120 | /// Take the writer back once the file is finished. |
| 99 | 121 | pub fn into_inner(self) -> W { |
| 100 | 122 | self.w |
| @@ -320,12 +342,14 @@ impl<W: Write + Seek> Mp4Muxer<W> { | ||
| 320 | 342 | } |
| 321 | 343 | |
| 322 | 344 | 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. | |
| 323 | 352 | 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 | - } | |
| 329 | 353 | let timescale = u32::try_from(info.time_base.den()).map_err(|_| { |
| 330 | 354 | Error::corrupt(format!( |
| 331 | 355 | "mp4: a time base of 1/{} does not fit a 32-bit timescale", |