forge
Explore
Log in

Don't you dare go Hollow

The writer, with the boxes edith wrote by hand in-crate

Browse files at this commit

73369033038844251438200bc02e0544eff399cdAhmet Kaan GümüşParent: 49be010
  • feat
    • the writer, with the boxes edith wrote by hand in-crate
Show full message
feat(mp4): the writer, with the boxes edith wrote by hand in-crate

One pass: ftyp, then an mdat the samples stream into, then the moov built
from what was written (a faststart layout would have to copy the whole
mdat a second time). Sample tables are generated from the packets --
run-length stts, ctts only where something is reordered, stss only where
some sample is not a sync one, co64 where the file is big enough to need
it -- and an elst is written where the first picture is not the first
decoded one, so a reordered track does not start late.

The four boxes edith patched into the incumbent's output are written here
instead: av01+av1C, hvc1+hvcC, colr nclx (with mdcv/clli beside it, so an
HDR grade survives a remux) and udta/name for the movie and each track,
plus a tx3g entry with its style and font table.
crates/ec-mp4/src/lib.rsmodified+2 -0
@@ -45,9 +45,11 @@
45 mod boxes;45 mod boxes;
46 mod demux;46 mod demux;
47 mod esds;47 mod esds;
48+mod mux;
48 49
49 pub use demux::Mp4Demuxer;50 pub use demux::Mp4Demuxer;
50 pub use esds::{Esds, object_type};51 pub use esds::{Esds, object_type};
52+pub use mux::Mp4Muxer;
51 53
52 /// True when `head` looks like an ISOBMFF file: the second word of its first box54 /// True when `head` looks like an ISOBMFF file: the second word of its first box
53 /// is one of the types an mp4 or a `.mov` starts with.55 /// is one of the types an mp4 or a `.mov` starts with.
crates/ec-mp4/src/mux.rsadded+864 -0
@@ -0,0 +1,864 @@
1+//! The writer: `ftyp`, then one `mdat` the samples stream into, then the `moov`
2+//! built from what was written.
3+
4+use std::io::{Seek, SeekFrom, Write};
5+
6+use ec_core::{
7+ CodecId, ContentLight, Error, Muxer, Packet, Result, Rounding, StreamInfo, TimeBase,
8+};
9+
10+use crate::boxes::{close, full_head, leaf, open};
11+use crate::esds::{Esds, object_type};
12+
13+/// The clock the movie header counts in. Only `mvhd`/`tkhd` durations are in it;
14+/// every sample time is in its own track's timescale.
15+const MOVIE_TIMESCALE: u32 = 1_000;
16+
17+/// One written sample, as the sample tables will state it.
18+struct Sample {
19+ size: u32,
20+ dts: i64,
21+ cts: i64,
22+ duration: u32,
23+ sync: bool,
24+}
25+
26+/// One declared stream and everything written on it.
27+struct Track {
28+ info: StreamInfo,
29+ /// Ticks a second on this track: `time_base.den()`, so a `1001/24000` base
30+ /// becomes a 24000 clock counting 1001 a frame — exact, never rounded.
31+ timescale: u32,
32+ time_base: TimeBase,
33+ samples: Vec<Sample>,
34+ /// `(file offset, sample count)` per chunk: a run of this track's samples
35+ /// written back to back, which is what an interleaved file is made of.
36+ chunks: Vec<(u64, u32)>,
37+ /// Where the last sample of this track ended, to tell "same chunk" from "a
38+ /// new one".
39+ chunk_end: u64,
40+ title: Option<String>,
41+}
42+
43+/// An MP4 writer over anything seekable.
44+///
45+/// **Layout: `mdat` first, `moov` last.** Samples are written the instant they
46+/// arrive, so muxing costs one pass and no temporary file, and the sample tables
47+/// — which cannot be written before the sizes they state are known — go at the
48+/// end. The cost is that a player streaming the file over HTTP has to reach the
49+/// end before it can start; a faststart (`moov` in front) writer would have to
50+/// copy the whole `mdat` a second time, and is not implemented here.
51+///
52+/// Interleaving is the caller's: packets are written in the order they are
53+/// handed over, and the chunk table follows that order exactly.
54+pub struct Mp4Muxer<W> {
55+ w: W,
56+ tracks: Vec<Track>,
57+ /// Current write offset.
58+ pos: u64,
59+ /// Offset of the `mdat` box header, patched with its real size at
60+ /// [`Mp4Muxer::finish`].
61+ mdat_at: u64,
62+ started: bool,
63+ finished: bool,
64+ title: Option<String>,
65+}
66+
67+impl<W: Write + Seek> Mp4Muxer<W> {
68+ /// A writer over `w`, which is positioned at its start.
69+ pub fn new(mut w: W) -> Result<Mp4Muxer<W>> {
70+ let pos = w.seek(SeekFrom::Start(0))?;
71+ Ok(Mp4Muxer {
72+ w,
73+ tracks: Vec::new(),
74+ pos,
75+ mdat_at: 0,
76+ started: false,
77+ finished: false,
78+ title: None,
79+ })
80+ }
81+
82+ /// Name the movie: a `moov/udta/name` box.
83+ pub fn set_title(&mut self, title: impl Into<String>) {
84+ self.title = Some(title.into());
85+ }
86+
87+ /// Name one track: a `trak/udta/name` box, which is what an mp4 calls a
88+ /// subtitle track in a player's menu.
89+ pub fn set_track_title(&mut self, stream: u32, title: impl Into<String>) -> Result<()> {
90+ let track = self
91+ .tracks
92+ .get_mut(stream as usize)
93+ .ok_or_else(|| Error::corrupt(format!("mp4: no stream {stream} to name")))?;
94+ track.title = Some(title.into());
95+ Ok(())
96+ }
97+
98+ /// Take the writer back once the file is finished.
99+ pub fn into_inner(self) -> W {
100+ self.w
101+ }
102+
103+ fn start(&mut self) -> Result<()> {
104+ if self.started {
105+ return Ok(());
106+ }
107+ self.started = true;
108+ let mut head = Vec::with_capacity(64);
109+ let at = open(&mut head, b"ftyp");
110+ head.extend_from_slice(b"isom");
111+ head.extend_from_slice(&512u32.to_be_bytes());
112+ head.extend_from_slice(b"isom");
113+ head.extend_from_slice(b"iso2");
114+ for track in &self.tracks {
115+ if let Some(brand) = video_entry(track.info.params.codec) {
116+ head.extend_from_slice(brand);
117+ }
118+ }
119+ head.extend_from_slice(b"mp41");
120+ close(&mut head, at);
121+ self.mdat_at = head.len() as u64;
122+ // The 64-bit form of an `mdat` header, always: a two-hour 4K export goes
123+ // past 4 GB and the placeholder cannot grow later without moving every
124+ // sample in the file.
125+ head.extend_from_slice(&1u32.to_be_bytes());
126+ head.extend_from_slice(b"mdat");
127+ head.extend_from_slice(&0u64.to_be_bytes());
128+ self.w.write_all(&head)?;
129+ self.pos = head.len() as u64;
130+ Ok(())
131+ }
132+
133+ /// Sample durations, resolved: a packet that stated one keeps it, and one
134+ /// that did not gets the step to the next sample — which is what the last
135+ /// sample has no next for, so it repeats the step before it.
136+ fn resolve_durations(track: &mut Track) {
137+ for i in 0..track.samples.len() {
138+ if track.samples[i].duration != 0 {
139+ continue;
140+ }
141+ let step = match track.samples.get(i + 1) {
142+ Some(next) => next.dts - track.samples[i].dts,
143+ None => i
144+ .checked_sub(1)
145+ .map_or(0, |prev| i64::from(track.samples[prev].duration)),
146+ };
147+ track.samples[i].duration = u32::try_from(step.max(0)).unwrap_or(0);
148+ }
149+ }
150+
151+ fn write_moov(&mut self) -> Result<()> {
152+ let mut moov = Vec::with_capacity(4096);
153+ let at = open(&mut moov, b"moov");
154+ let movie_base = TimeBase::from_rate(MOVIE_TIMESCALE);
155+ let duration = self
156+ .tracks
157+ .iter()
158+ .map(|t| {
159+ t.time_base
160+ .rescale(track_ticks(t), movie_base, Rounding::Up)
161+ })
162+ .max()
163+ .unwrap_or(0);
164+
165+ let mvhd = open(&mut moov, b"mvhd");
166+ full_head(&mut moov, 0, 0);
167+ moov.extend_from_slice(&0u32.to_be_bytes()); // creation
168+ moov.extend_from_slice(&0u32.to_be_bytes()); // modification
169+ moov.extend_from_slice(&MOVIE_TIMESCALE.to_be_bytes());
170+ moov.extend_from_slice(&(duration.max(0) as u32).to_be_bytes());
171+ moov.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // rate 1.0
172+ moov.extend_from_slice(&0x0100u16.to_be_bytes()); // volume 1.0
173+ moov.extend_from_slice(&[0; 2 + 8]);
174+ moov.extend_from_slice(&UNITY_MATRIX);
175+ moov.extend_from_slice(&[0; 24]); // pre_defined
176+ moov.extend_from_slice(&(self.tracks.len() as u32 + 1).to_be_bytes());
177+ close(&mut moov, mvhd);
178+
179+ for i in 0..self.tracks.len() {
180+ self.write_trak(&mut moov, i, duration)?;
181+ }
182+ if let Some(title) = &self.title {
183+ let udta = open(&mut moov, b"udta");
184+ leaf(&mut moov, b"name", title.as_bytes());
185+ close(&mut moov, udta);
186+ }
187+ close(&mut moov, at);
188+ self.w.write_all(&moov)?;
189+ self.pos += moov.len() as u64;
190+ Ok(())
191+ }
192+
193+ fn write_trak(&self, out: &mut Vec<u8>, i: usize, movie_duration: i64) -> Result<()> {
194+ let track = &self.tracks[i];
195+ let codec = track.info.params.codec;
196+ let at = open(out, b"trak");
197+
198+ let tkhd = open(out, b"tkhd");
199+ full_head(out, 0, 0x7); // enabled, in movie, in preview
200+ out.extend_from_slice(&0u32.to_be_bytes());
201+ out.extend_from_slice(&0u32.to_be_bytes());
202+ out.extend_from_slice(&(i as u32 + 1).to_be_bytes()); // track_ID
203+ out.extend_from_slice(&0u32.to_be_bytes());
204+ out.extend_from_slice(&(movie_duration.max(0) as u32).to_be_bytes());
205+ out.extend_from_slice(&[0; 8]);
206+ out.extend_from_slice(&0u16.to_be_bytes()); // layer
207+ out.extend_from_slice(&0u16.to_be_bytes()); // alternate group
208+ let volume: u16 = match codec.media_type() {
209+ ec_core::MediaType::Audio => 0x0100,
210+ _ => 0,
211+ };
212+ out.extend_from_slice(&volume.to_be_bytes());
213+ out.extend_from_slice(&0u16.to_be_bytes());
214+ out.extend_from_slice(&UNITY_MATRIX);
215+ let (width, height) = match track.info.params.video() {
216+ Some(v) => (v.width, v.height),
217+ None => (0, 0),
218+ };
219+ out.extend_from_slice(&(width << 16).to_be_bytes());
220+ out.extend_from_slice(&(height << 16).to_be_bytes());
221+ close(out, tkhd);
222+
223+ // An `elst`, where the first picture is not the first *decoded* one: a
224+ // reordered stream's earliest composition time is the reorder delay, and
225+ // without an edit saying so every player starts the track that much
226+ // late. This is where a demuxer's `media_time` comes from, and it is a
227+ // shift, never a trim.
228+ let priming = presentation_start(track);
229+ if priming > 0 {
230+ let edts = open(out, b"edts");
231+ let elst = open(out, b"elst");
232+ full_head(out, 0, 0);
233+ out.extend_from_slice(&1u32.to_be_bytes());
234+ let movie_base = TimeBase::from_rate(MOVIE_TIMESCALE);
235+ let segment =
236+ track
237+ .time_base
238+ .rescale(track_ticks(track) - priming, movie_base, Rounding::Up);
239+ out.extend_from_slice(&(segment.max(0) as u32).to_be_bytes());
240+ out.extend_from_slice(&(priming as u32).to_be_bytes());
241+ out.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // media rate 1.0
242+ close(out, elst);
243+ close(out, edts);
244+ }
245+
246+ let mdia = open(out, b"mdia");
247+ let mdhd = open(out, b"mdhd");
248+ full_head(out, 0, 0);
249+ out.extend_from_slice(&0u32.to_be_bytes());
250+ out.extend_from_slice(&0u32.to_be_bytes());
251+ out.extend_from_slice(&track.timescale.to_be_bytes());
252+ out.extend_from_slice(&(track_ticks(track).max(0) as u32).to_be_bytes());
253+ out.extend_from_slice(&pack_language(track.info.language.as_deref()).to_be_bytes());
254+ out.extend_from_slice(&0u16.to_be_bytes()); // pre_defined
255+ close(out, mdhd);
256+
257+ let (handler, handler_name) = match codec.media_type() {
258+ ec_core::MediaType::Video => (b"vide", "VideoHandler"),
259+ ec_core::MediaType::Audio => (b"soun", "SoundHandler"),
260+ ec_core::MediaType::Subtitle => (b"sbtl", "SubtitleHandler"),
261+ };
262+ let hdlr = open(out, b"hdlr");
263+ full_head(out, 0, 0);
264+ out.extend_from_slice(&0u32.to_be_bytes()); // pre_defined
265+ out.extend_from_slice(handler);
266+ out.extend_from_slice(&[0; 12]); // reserved
267+ out.extend_from_slice(handler_name.as_bytes());
268+ out.push(0);
269+ close(out, hdlr);
270+
271+ let minf = open(out, b"minf");
272+ match codec.media_type() {
273+ ec_core::MediaType::Video => {
274+ let vmhd = open(out, b"vmhd");
275+ full_head(out, 0, 1);
276+ out.extend_from_slice(&[0; 8]); // graphicsmode + opcolor
277+ close(out, vmhd);
278+ }
279+ ec_core::MediaType::Audio => {
280+ let smhd = open(out, b"smhd");
281+ full_head(out, 0, 0);
282+ out.extend_from_slice(&[0; 4]); // balance + reserved
283+ close(out, smhd);
284+ }
285+ ec_core::MediaType::Subtitle => {
286+ let nmhd = open(out, b"nmhd");
287+ full_head(out, 0, 0);
288+ close(out, nmhd);
289+ }
290+ }
291+ let dinf = open(out, b"dinf");
292+ let dref = open(out, b"dref");
293+ full_head(out, 0, 0);
294+ out.extend_from_slice(&1u32.to_be_bytes());
295+ let url = open(out, b"url ");
296+ full_head(out, 0, 1); // flag 1: the media is in this very file
297+ close(out, url);
298+ close(out, dref);
299+ close(out, dinf);
300+
301+ let stbl = open(out, b"stbl");
302+ let stsd = open(out, b"stsd");
303+ full_head(out, 0, 0);
304+ out.extend_from_slice(&1u32.to_be_bytes());
305+ sample_entry(out, &track.info)?;
306+ close(out, stsd);
307+ sample_tables(out, track);
308+ close(out, stbl);
309+ close(out, minf);
310+ close(out, mdia);
311+
312+ if let Some(title) = &track.title {
313+ let udta = open(out, b"udta");
314+ leaf(out, b"name", title.as_bytes());
315+ close(out, udta);
316+ }
317+ close(out, at);
318+ Ok(())
319+ }
320+}
321+
322+impl<W: Write + Seek + Send> Muxer for Mp4Muxer<W> {
323+ 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+ let timescale = u32::try_from(info.time_base.den()).map_err(|_| {
330+ Error::corrupt(format!(
331+ "mp4: a time base of 1/{} does not fit a 32-bit timescale",
332+ info.time_base.den()
333+ ))
334+ })?;
335+ if timescale == 0 {
336+ return Err(Error::corrupt("mp4: a stream with a zero timescale"));
337+ }
338+ let index = self.tracks.len() as u32;
339+ self.tracks.push(Track {
340+ info,
341+ timescale,
342+ time_base: TimeBase::from_rate(timescale),
343+ samples: Vec::new(),
344+ chunks: Vec::new(),
345+ chunk_end: u64::MAX,
346+ title: None,
347+ });
348+ Ok(index)
349+ }
350+
351+ fn write_packet(&mut self, packet: &Packet) -> Result<()> {
352+ self.start()?;
353+ let pos = self.pos;
354+ let track = self
355+ .tracks
356+ .get_mut(packet.stream as usize)
357+ .ok_or_else(|| Error::corrupt(format!("mp4: no stream {}", packet.stream)))?;
358+ let to = track.time_base;
359+ let at = |ticks: i64| packet.time_base.rescale(ticks, to, Rounding::Nearest);
360+ let dts = match (packet.dts, packet.pts) {
361+ (Some(dts), _) => at(dts),
362+ (None, Some(pts)) => at(pts),
363+ // A stream that states no time at all is laid end to end, which is
364+ // what a constant-rate audio track is anyway.
365+ (None, None) => track
366+ .samples
367+ .last()
368+ .map_or(0, |s| s.dts + i64::from(s.duration)),
369+ };
370+ let cts = packet.pts.map_or(dts, at);
371+ let size = u32::try_from(packet.data.len())
372+ .map_err(|_| Error::corrupt("mp4: a sample over 4 GB"))?;
373+ track.samples.push(Sample {
374+ size,
375+ dts,
376+ cts,
377+ duration: packet.duration.map_or(0, |d| at(d).max(0) as u32),
378+ sync: packet.flags.keyframe,
379+ });
380+ match track.chunk_end == pos {
381+ true => {
382+ if let Some(chunk) = track.chunks.last_mut() {
383+ chunk.1 += 1;
384+ }
385+ }
386+ false => track.chunks.push((pos, 1)),
387+ }
388+ track.chunk_end = pos + u64::from(size);
389+ self.w.write_all(&packet.data)?;
390+ self.pos = pos + u64::from(size);
391+ Ok(())
392+ }
393+
394+ fn finish(&mut self) -> Result<()> {
395+ if self.finished {
396+ return Ok(());
397+ }
398+ self.finished = true;
399+ self.start()?;
400+ // The mdat's real size, into the 64-bit field left for it.
401+ let mdat_len = self.pos - self.mdat_at;
402+ self.w.seek(SeekFrom::Start(self.mdat_at + 8))?;
403+ self.w.write_all(&mdat_len.to_be_bytes())?;
404+ self.w.seek(SeekFrom::Start(self.pos))?;
405+ for track in &mut self.tracks {
406+ Mp4Muxer::<W>::resolve_durations(track);
407+ }
408+ self.write_moov()?;
409+ self.w.flush()?;
410+ Ok(())
411+ }
412+}
413+
414+/// Total media ticks of a track: from the first sample's decode time to the end
415+/// of the last one. A span rather than an endpoint, because a track handed over
416+/// with an edit list already applied starts at a negative decode time and its
417+/// duration is still the whole of it.
418+fn track_ticks(track: &Track) -> i64 {
419+ let first = track.samples.first().map_or(0, |s| s.dts);
420+ track
421+ .samples
422+ .last()
423+ .map_or(0, |s| s.dts + i64::from(s.duration) - first)
424+}
425+
426+/// Where the first *picture* is on the written timeline: decode times start at
427+/// zero in the file (`stts` states durations, not instants), so this is the
428+/// smallest composition offset — the reorder delay of a stream with B-frames and
429+/// zero for everything else.
430+fn presentation_start(track: &Track) -> i64 {
431+ let first = track.samples.first().map_or(0, |s| s.dts);
432+ track
433+ .samples
434+ .iter()
435+ .map(|s| s.cts - first)
436+ .min()
437+ .unwrap_or(0)
438+}
439+
440+/// The `stts`/`ctts`/`stss`/`stsc`/`stsz` and chunk-offset tables of one track.
441+fn sample_tables(out: &mut Vec<u8>, track: &Track) {
442+ // stts: runs of equal durations, which for constant-rate video is one entry
443+ // for the whole film.
444+ let stts = open(out, b"stts");
445+ full_head(out, 0, 0);
446+ let count_at = out.len();
447+ out.extend_from_slice(&0u32.to_be_bytes());
448+ let mut runs = 0u32;
449+ let mut i = 0;
450+ while i < track.samples.len() {
451+ let delta = track.samples[i].duration;
452+ let mut run = 0u32;
453+ while i < track.samples.len() && track.samples[i].duration == delta {
454+ run += 1;
455+ i += 1;
456+ }
457+ out.extend_from_slice(&run.to_be_bytes());
458+ out.extend_from_slice(&delta.to_be_bytes());
459+ runs += 1;
460+ }
461+ out[count_at..count_at + 4].copy_from_slice(&runs.to_be_bytes());
462+ close(out, stts);
463+
464+ // ctts, only where something is actually reordered.
465+ let offsets: Vec<i64> = track.samples.iter().map(|s| s.cts - s.dts).collect();
466+ if offsets.iter().any(|&o| o != 0) {
467+ let negative = offsets.iter().any(|&o| o < 0);
468+ let ctts = open(out, b"ctts");
469+ // Version 1 states the offset as signed, which is the only way to say
470+ // that a picture is shown *before* it is decoded.
471+ full_head(out, u8::from(negative), 0);
472+ let count_at = out.len();
473+ out.extend_from_slice(&0u32.to_be_bytes());
474+ let mut runs = 0u32;
475+ let mut i = 0;
476+ while i < offsets.len() {
477+ let offset = offsets[i];
478+ let mut run = 0u32;
479+ while i < offsets.len() && offsets[i] == offset {
480+ run += 1;
481+ i += 1;
482+ }
483+ out.extend_from_slice(&run.to_be_bytes());
484+ out.extend_from_slice(&(offset as i32).to_be_bytes());
485+ runs += 1;
486+ }
487+ out[count_at..count_at + 4].copy_from_slice(&runs.to_be_bytes());
488+ close(out, ctts);
489+ }
490+
491+ // stss, only where some samples are not sync ones: no box at all means
492+ // every sample is a random access point, which is the truth for audio.
493+ if track.samples.iter().any(|s| !s.sync) {
494+ let stss = open(out, b"stss");
495+ full_head(out, 0, 0);
496+ let syncs: Vec<u32> = track
497+ .samples
498+ .iter()
499+ .enumerate()
500+ .filter(|(_, s)| s.sync)
501+ .map(|(i, _)| i as u32 + 1)
502+ .collect();
503+ out.extend_from_slice(&(syncs.len() as u32).to_be_bytes());
504+ for n in syncs {
505+ out.extend_from_slice(&n.to_be_bytes());
506+ }
507+ close(out, stss);
508+ }
509+
510+ // stsc: runs of chunks holding the same number of samples.
511+ let stsc = open(out, b"stsc");
512+ full_head(out, 0, 0);
513+ let count_at = out.len();
514+ out.extend_from_slice(&0u32.to_be_bytes());
515+ let mut runs = 0u32;
516+ let mut first = 0usize;
517+ while first < track.chunks.len() {
518+ let per = track.chunks[first].1;
519+ out.extend_from_slice(&(first as u32 + 1).to_be_bytes());
520+ out.extend_from_slice(&per.to_be_bytes());
521+ out.extend_from_slice(&1u32.to_be_bytes()); // sample_description_index
522+ runs += 1;
523+ first += 1;
524+ while first < track.chunks.len() && track.chunks[first].1 == per {
525+ first += 1;
526+ }
527+ }
528+ out[count_at..count_at + 4].copy_from_slice(&runs.to_be_bytes());
529+ close(out, stsc);
530+
531+ // stsz: one size for all, where they really are all one size.
532+ let stsz = open(out, b"stsz");
533+ full_head(out, 0, 0);
534+ let uniform = track
535+ .samples
536+ .first()
537+ .map(|f| f.size)
538+ .filter(|&size| track.samples.iter().all(|s| s.size == size))
539+ .unwrap_or(0);
540+ out.extend_from_slice(&uniform.to_be_bytes());
541+ out.extend_from_slice(&(track.samples.len() as u32).to_be_bytes());
542+ if uniform == 0 {
543+ for sample in &track.samples {
544+ out.extend_from_slice(&sample.size.to_be_bytes());
545+ }
546+ }
547+ close(out, stsz);
548+
549+ // co64 where the file is big enough to need it, stco where it is not.
550+ let big = track.chunks.iter().any(|&(at, _)| at > u64::from(u32::MAX));
551+ let kind = if big { b"co64" } else { b"stco" };
552+ let chunks = open(out, kind);
553+ full_head(out, 0, 0);
554+ out.extend_from_slice(&(track.chunks.len() as u32).to_be_bytes());
555+ for &(at, _) in &track.chunks {
556+ match big {
557+ true => out.extend_from_slice(&at.to_be_bytes()),
558+ false => out.extend_from_slice(&(at as u32).to_be_bytes()),
559+ }
560+ }
561+ close(out, chunks);
562+}
563+
564+/// The sample entry name and configuration box of a video codec.
565+fn video_entry(codec: CodecId) -> Option<&'static [u8; 4]> {
566+ Some(match codec {
567+ CodecId::H264 => b"avc1",
568+ // `hvc1` and not `hev1`: the parameter sets are in the `hvcC`, which is
569+ // exactly what the `hvc1` name promises a reader.
570+ CodecId::H265 => b"hvc1",
571+ CodecId::Av1 => b"av01",
572+ CodecId::Vp9 => b"vp09",
573+ CodecId::Vp8 => b"vp08",
574+ _ => return None,
575+ })
576+}
577+
578+fn config_box(codec: CodecId) -> &'static [u8; 4] {
579+ match codec {
580+ CodecId::H264 => b"avcC",
581+ CodecId::H265 => b"hvcC",
582+ CodecId::Av1 => b"av1C",
583+ _ => b"vpcC",
584+ }
585+}
586+
587+/// One `stsd` entry for `info`.
588+fn sample_entry(out: &mut Vec<u8>, info: &StreamInfo) -> Result<()> {
589+ let codec = info.params.codec;
590+ let extradata = info.params.extradata.as_deref();
591+ if let Some(name) = video_entry(codec) {
592+ let video = info.params.video().ok_or_else(|| {
593+ Error::corrupt("mp4: a video codec declared without video parameters")
594+ })?;
595+ let config = extradata.ok_or_else(|| {
596+ Error::unsupported(
597+ format!("mp4: a {} track with no codec configuration", codec.name()),
598+ "an ISOBMFF video sample entry has to carry its avcC/hvcC/av1C/vpcC record",
599+ )
600+ })?;
601+ let at = open(out, name);
602+ out.extend_from_slice(&[0; 6]); // reserved
603+ out.extend_from_slice(&1u16.to_be_bytes()); // data_reference_index
604+ out.extend_from_slice(&[0; 16]); // pre_defined + reserved
605+ out.extend_from_slice(&(video.width as u16).to_be_bytes());
606+ out.extend_from_slice(&(video.height as u16).to_be_bytes());
607+ out.extend_from_slice(&0x0048_0000u32.to_be_bytes()); // 72 dpi
608+ out.extend_from_slice(&0x0048_0000u32.to_be_bytes());
609+ out.extend_from_slice(&0u32.to_be_bytes()); // reserved
610+ out.extend_from_slice(&1u16.to_be_bytes()); // frame_count
611+ out.extend_from_slice(&[0; 32]); // compressorname
612+ out.extend_from_slice(&0x0018u16.to_be_bytes()); // depth: colour, no alpha
613+ out.extend_from_slice(&(-1i16).to_be_bytes()); // pre_defined
614+ leaf(out, config_box(codec), config);
615+ colour_boxes(out, video.color, video.light);
616+ if let Some(sar) = video.sample_aspect_ratio {
617+ let pasp = open(out, b"pasp");
618+ out.extend_from_slice(&(sar.num() as u32).to_be_bytes());
619+ out.extend_from_slice(&(sar.den() as u32).to_be_bytes());
620+ close(out, pasp);
621+ }
622+ close(out, at);
623+ return Ok(());
624+ }
625+ if codec == CodecId::Tx3g {
626+ let at = open(out, b"tx3g");
627+ out.extend_from_slice(&[0; 6]);
628+ out.extend_from_slice(&1u16.to_be_bytes());
629+ match extradata {
630+ // Round-tripped from another mp4: the style it already stated.
631+ Some(style) if style.len() >= 30 => out.extend_from_slice(style),
632+ _ => {
633+ out.extend_from_slice(&0u32.to_be_bytes()); // displayFlags
634+ out.push(1); // horizontal justification: centred
635+ out.push(0xFF); // vertical: bottom
636+ out.extend_from_slice(&[0, 0, 0, 0]); // background: transparent
637+ out.extend_from_slice(&[0; 8]); // text box: the whole picture
638+ out.extend_from_slice(&0u16.to_be_bytes()); // startChar
639+ out.extend_from_slice(&0u16.to_be_bytes()); // endChar
640+ out.extend_from_slice(&1u16.to_be_bytes()); // font-ID
641+ out.push(0); // face-style-flags
642+ out.push(18); // font-size
643+ out.extend_from_slice(&[0xFF; 4]); // text colour: opaque white
644+ let ftab = open(out, b"ftab");
645+ out.extend_from_slice(&1u16.to_be_bytes());
646+ out.extend_from_slice(&1u16.to_be_bytes());
647+ out.push(5);
648+ out.extend_from_slice(b"Serif");
649+ close(out, ftab);
650+ }
651+ }
652+ close(out, at);
653+ return Ok(());
654+ }
655+
656+ let (name, audio) = match info.params.audio() {
657+ Some(audio) => (audio_entry(codec)?, audio),
658+ None => {
659+ return Err(Error::unsupported(
660+ format!("mp4: a {} track", codec.name()),
661+ "this writer has a sample entry for video, AAC-family audio and tx3g text only; \
662+ Matroska carries the rest",
663+ ));
664+ }
665+ };
666+ let at = open(out, name);
667+ out.extend_from_slice(&[0; 6]);
668+ out.extend_from_slice(&1u16.to_be_bytes()); // data_reference_index
669+ out.extend_from_slice(&[0; 8]); // version, revision, vendor
670+ out.extend_from_slice(&(audio.layout.channel_count() as u16).to_be_bytes());
671+ out.extend_from_slice(&(audio.bits_per_sample.unwrap_or(16) as u16).to_be_bytes());
672+ out.extend_from_slice(&0u16.to_be_bytes()); // pre_defined
673+ out.extend_from_slice(&0u16.to_be_bytes()); // reserved
674+ // 16.16, so a rate over 65535 is stated as its low half — which is what
675+ // every writer does and what the `mdhd` timescale says exactly anyway.
676+ out.extend_from_slice(&((audio.sample_rate as u16 as u32) << 16).to_be_bytes());
677+ match codec {
678+ CodecId::Aac => {
679+ let asc = extradata.ok_or_else(|| {
680+ Error::unsupported(
681+ "mp4: an AAC track with no AudioSpecificConfig",
682+ "an esds descriptor is the only place an mp4 states an AAC track's setup",
683+ )
684+ })?;
685+ let esds = open(out, b"esds");
686+ out.extend_from_slice(&Esds::aac(asc).write());
687+ close(out, esds);
688+ }
689+ CodecId::Mp3 => {
690+ let mut mp3 = Esds::aac(&[][..]);
691+ mp3.object_type = object_type::MPEG1_AUDIO;
692+ mp3.decoder_specific = None;
693+ let esds = open(out, b"esds");
694+ out.extend_from_slice(&mp3.write());
695+ close(out, esds);
696+ }
697+ CodecId::Ac3 | CodecId::EAc3 | CodecId::Flac | CodecId::Opus | CodecId::Alac => {
698+ let config = extradata.ok_or_else(|| {
699+ Error::unsupported(
700+ format!("mp4: a {} track with no codec configuration", codec.name()),
701+ "its sample entry has to carry the codec's own configuration box",
702+ )
703+ })?;
704+ match codec {
705+ // ALAC's cookie is carried with its box header, so it is written
706+ // back exactly as it was read.
707+ CodecId::Alac if config.len() > 8 && &config[4..8] == b"alac" => {
708+ out.extend_from_slice(config)
709+ }
710+ CodecId::Opus => leaf(out, b"dOps", &dops(config)),
711+ _ => leaf(out, audio_config_box(codec), config),
712+ }
713+ }
714+ _ => {}
715+ }
716+ close(out, at);
717+ Ok(())
718+}
719+
720+/// `colr`, and the two HDR boxes where the grade stated them — metadata a remux
721+/// must not quietly drop, because nothing downstream can reconstruct it.
722+fn colour_boxes(out: &mut Vec<u8>, color: ec_core::ColorInfo, light: ContentLight) {
723+ if color != ec_core::ColorInfo::default() {
724+ let colr = open(out, b"colr");
725+ out.extend_from_slice(b"nclx");
726+ out.extend_from_slice(&u16::from(color.primaries).to_be_bytes());
727+ out.extend_from_slice(&u16::from(color.transfer).to_be_bytes());
728+ out.extend_from_slice(&u16::from(color.matrix).to_be_bytes());
729+ out.push(u8::from(color.full_range) << 7);
730+ close(out, colr);
731+ }
732+ if light.mastering_max.is_some() || light.mastering_min.is_some() {
733+ let mdcv = open(out, b"mdcv");
734+ // Display primaries and white point: not carried by [`ContentLight`],
735+ // which holds the luminances a tone map needs. BT.2020 is what an HDR
736+ // grade is mastered on and what every writer states here.
737+ for xy in BT2020_PRIMARIES {
738+ out.extend_from_slice(&xy.to_be_bytes());
739+ }
740+ let nits = |v: Option<f32>| ((v.unwrap_or(0.0) * 10_000.0) as u32).to_be_bytes();
741+ out.extend_from_slice(&nits(light.mastering_max));
742+ out.extend_from_slice(&nits(light.mastering_min));
743+ close(out, mdcv);
744+ }
745+ if light.max_cll.is_some() || light.max_fall.is_some() {
746+ let clli = open(out, b"clli");
747+ out.extend_from_slice(&(light.max_cll.unwrap_or(0.0) as u16).to_be_bytes());
748+ out.extend_from_slice(&(light.max_fall.unwrap_or(0.0) as u16).to_be_bytes());
749+ close(out, clli);
750+ }
751+}
752+
753+/// BT.2020 green, blue, red and D65, in the 0.00002 units an `mdcv` states them.
754+const BT2020_PRIMARIES: [u16; 8] = [8500, 39850, 6550, 2300, 35400, 14600, 15635, 16450];
755+
756+const UNITY_MATRIX: [u8; 36] = {
757+ let mut m = [0u8; 36];
758+ m[0] = 0x00;
759+ m[1] = 0x01;
760+ m[16] = 0x00;
761+ m[17] = 0x01;
762+ m[32] = 0x40;
763+ m
764+};
765+
766+fn audio_entry(codec: CodecId) -> Result<&'static [u8; 4]> {
767+ Ok(match codec {
768+ CodecId::Aac | CodecId::Mp3 => b"mp4a",
769+ CodecId::Ac3 => b"ac-3",
770+ CodecId::EAc3 => b"ec-3",
771+ CodecId::Alac => b"alac",
772+ CodecId::Flac => b"fLaC",
773+ CodecId::Opus => b"Opus",
774+ CodecId::PcmS16Le => b"sowt",
775+ CodecId::PcmS16Be => b"twos",
776+ CodecId::PcmU8 => b"raw ",
777+ _ => {
778+ return Err(Error::unsupported(
779+ format!("mp4: a {} audio track", codec.name()),
780+ "no ISOBMFF sample entry is defined for it",
781+ ));
782+ }
783+ })
784+}
785+
786+fn audio_config_box(codec: CodecId) -> &'static [u8; 4] {
787+ match codec {
788+ CodecId::Ac3 => b"dac3",
789+ CodecId::EAc3 => b"dec3",
790+ CodecId::Flac => b"dfLa",
791+ _ => b"dOps",
792+ }
793+}
794+
795+/// The `dOps` payload from an `OpusHead`: same fields, opposite byte order, and
796+/// without the magic — the inverse of what the demuxer does on the way in.
797+fn dops(head: &[u8]) -> Vec<u8> {
798+ let body = match head.starts_with(b"OpusHead") {
799+ true => &head[8..],
800+ false => head,
801+ };
802+ let le16 = |at: usize| {
803+ u16::from_le_bytes([
804+ body.get(at).copied().unwrap_or(0),
805+ body.get(at + 1).copied().unwrap_or(0),
806+ ])
807+ };
808+ let mut out = Vec::with_capacity(body.len());
809+ out.push(0); // dOps version
810+ out.push(body.get(1).copied().unwrap_or(2)); // channel count
811+ out.extend_from_slice(&le16(2).to_be_bytes()); // pre-skip
812+ let rate = u32::from_le_bytes([
813+ body.get(4).copied().unwrap_or(0),
814+ body.get(5).copied().unwrap_or(0),
815+ body.get(6).copied().unwrap_or(0),
816+ body.get(7).copied().unwrap_or(0),
817+ ]);
818+ out.extend_from_slice(&rate.to_be_bytes());
819+ out.extend_from_slice(&le16(8).to_be_bytes()); // output gain
820+ out.extend_from_slice(&body[10.min(body.len())..]);
821+ out
822+}
823+
824+/// Three lowercase letters into the five-bit-a-letter packing an `mdhd` states a
825+/// language in; `und` where the track never said.
826+fn pack_language(language: Option<&str>) -> u16 {
827+ let tag = language.filter(|l| l.len() == 3).unwrap_or("und");
828+ tag.bytes().fold(0u16, |packed, b| {
829+ (packed << 5) | u16::from(b.to_ascii_lowercase().wrapping_sub(0x60) & 0x1F)
830+ })
831+}
832+
833+#[cfg(test)]
834+mod tests {
835+ use super::*;
836+
837+ #[test]
838+ fn language_packing_is_the_demuxers_inverse() {
839+ for tag in ["tur", "eng", "und"] {
840+ let packed = pack_language(Some(tag));
841+ let back: String = (0..3)
842+ .rev()
843+ .map(|i| char::from(0x60 + ((packed >> (i * 5)) & 0x1F) as u8))
844+ .collect();
845+ assert_eq!(back, tag);
846+ }
847+ assert_eq!(pack_language(None), pack_language(Some("und")));
848+ assert_eq!(pack_language(Some("nonsense")), pack_language(Some("und")));
849+ }
850+
851+ #[test]
852+ fn an_opus_head_round_trips_through_dops() {
853+ let head = crate::demux::opus_head(&[0, 2, 0x01, 0x38, 0, 0, 0xBB, 0x80, 0, 0, 1, 2, 3]);
854+ let back = dops(&head);
855+ assert_eq!(back[0], 0, "dOps version");
856+ assert_eq!(back[1], 2, "channels");
857+ assert_eq!(u16::from_be_bytes([back[2], back[3]]), 312);
858+ assert_eq!(
859+ u32::from_be_bytes([back[4], back[5], back[6], back[7]]),
860+ 48_000
861+ );
862+ assert_eq!(&back[10..], &[1, 2, 3], "mapping family and table");
863+ }
864+}