forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

mux.rs2916 lines, 126.6 KiBHistoryRawDownload
1//! Annex-B -> MP4, the mirror of `demux`: encoders emit start-code framed NALs,
2//! an mp4 sample wants 4-byte length prefixes with SPS/PPS living in `avcC`.
3//!
4//! ...and AV1 -> Matroska, the mirror of the *other* half of `demux`, for the
5//! same reason that half exists: `mp4 0.14` has no `av01` sample entry at all,
6//! so an AV1 export is written as EBML by hand exactly as an AV1 import is read
7//! as EBML by hand ([`MkvMuxer`]).
8//!
9//! AV1 goes into an **mp4** too, and the missing sample entry is written by hand
10//! there as well ([`Mp4Muxer::create_av1`]): the crate writes the file with an
11//! `avc1` entry and this patches that entry into the `av01` + `av1C` pair the
12//! spec asks for, which is the only box in a whole mp4 the crate cannot spell.
13//! Both containers carry the timeline's AAC, so no format here writes a picture
14//! whose sound was silently left behind -- and both carry its subtitles, an mp4
15//! as the `tx3g` timed text `mp4 0.14` *can* spell ([`Mp4Muxer::write_subtitles`])
16//! and Matroska as `S_TEXT/UTF8` blocks, so neither is a file whose words were.
17
18use std::collections::VecDeque;
19use std::fs::{File, OpenOptions};
20use std::io::{BufWriter, Read, Seek, SeekFrom, Write};
21use std::path::{Path, PathBuf};
22
23use mp4::{
24 AacConfig, AudioObjectType, AvcConfig, Bytes, ChannelConfig, FourCC, MediaConfig, Mp4Config,
25 Mp4Sample, Mp4Writer, SampleFreqIndex, TrackConfig, TrackType, TtxtConfig,
26};
27
28use crate::colorspace::ColorDescription;
29
30/// 90 kHz is the H.264 convention, and it divides exactly at every *integer*
31/// fps (3000 ticks at 30, 3600 at 25). The NTSC rates do not divide into it at
32/// all -- 24000/1001 wants 3753.75 -- so those get their own clock; see
33/// [`frame_timing`].
34const VIDEO_TIMESCALE: u32 = 90_000;
35/// Ticks per frame for a rate the 90 kHz clock cannot express: every NTSC rate
36/// is `n/1001`, so 1001 ticks a frame makes the timescale a whole `n`.
37const NTSC_TICKS: u32 = 1001;
38/// An AAC-LC packet is always 1024 samples, so with timescale == sample rate the
39/// per-packet duration is this constant.
40const AAC_PACKET_SAMPLES: u32 = 1024;
41/// The clock a `tx3g` track counts in: one millisecond, the very tick a Matroska
42/// block's timestamp is written at ([`TIMESTAMP_SCALE_NS`]), so a cue lands on
43/// the same instant whichever of the two containers carries it.
44const SUB_TIMESCALE: u32 = 1_000;
45/// How much coded picture [`Mp4Muxer`] holds unwritten waiting for the sound
46/// to catch up ([`Mp4Muxer::hold`]) before it gives up and flushes video-only.
47/// Two seconds is the ceiling `export`'s own progress granularity already
48/// tolerates (`AUDIO_BAND`), and it bounds the hold's memory to two seconds
49/// of coded pictures -- kilobytes, not the tens of megabytes a whole film's
50/// worth would be.
51const HOLD_SECONDS: u64 = 2;
52
53const NAL_IDR: u8 = 5;
54const NAL_SEI: u8 = 6;
55const NAL_SPS: u8 = 7;
56const NAL_PPS: u8 = 8;
57const NAL_AUD: u8 = 9;
58
59pub struct VideoParams<'a> {
60 pub width: u32,
61 pub height: u32,
62 pub frame_rate: f64,
63 pub sps: &'a [u8],
64 pub pps: &'a [u8],
65}
66
67/// What the audio track declares: read straight off the source file's `esds`
68/// where the export copies packets, and off this project's own encoder where it
69/// re-encodes ([`crate::export`] decides which). `sample_rate` says the same
70/// thing `freq_index` does and is carried beside it because Matroska states the
71/// rate as a number rather than as an index into the AAC table.
72pub struct AudioParams {
73 pub freq_index: u8,
74 pub chan_conf: u8,
75 pub sample_rate: u32,
76 /// Set where the packets are **Opus** and not AAC, to the track's pre-skip
77 /// in samples at 48 kHz ([`crate::export`] writes those only for a Matroska
78 /// file). It is the whole difference between the two tracks a writer here
79 /// can declare: `A_OPUS` with an `OpusHead` in `CodecPrivate`
80 /// ([`opus_track_entry`]) against `A_AAC` with an `AudioSpecificConfig`
81 /// ([`aac_track_entry`]). `None` is AAC, which is every mp4 and every copy.
82 pub opus_pre_skip: Option<u16>,
83}
84
85/// Writes one H.264 *or* AV1 track plus an optional AAC track. mp4 0.14 ignores
86/// `Mp4Sample::start_time` and builds all timing by accumulating `duration`, so
87/// every sample handed over must carry an exact duration or the tracks drift.
88pub struct Mp4Muxer {
89 writer: Mp4Writer<BufWriter<File>>,
90 frame_duration: u32,
91 has_audio: bool,
92 /// The sample entry an AV1 or HEVC file's is patched into at
93 /// [`finish`](Mp4Muxer::finish) -- entry type, configuration box type and
94 /// its payload (`av01`/`av1C`, `hvc1`/`hvcC`). `None` for H.264, which the
95 /// crate spells itself. See [`create_av1`](Mp4Muxer::create_av1).
96 entry: Option<([u8; 4], [u8; 4], Vec<u8>)>,
97 /// The `colr` box that entry gets either way -- what the samples in it mean
98 /// ([`colr_nclx`]). `mp4 0.14` writes no `colr` of its own, so this is
99 /// patched in at [`finish`](Mp4Muxer::finish) beside the entry rewrite,
100 /// which is why an H.264 file is patched at all now.
101 colr: [u8; 11],
102 /// Where the file is, for that patch: the writer owns the handle it wrote
103 /// through and the patch reopens the finished file.
104 path: PathBuf,
105 /// The video track's clock and how many pictures have been written on it --
106 /// which is where the file *ends*, and a timed-text track is written out to
107 /// that instant ([`write_subtitles`](Mp4Muxer::write_subtitles)).
108 timescale: u32,
109 frames: u64,
110 /// What the subtitle tracks are *called*, in the order they were written:
111 /// an mp4 states a track's title in a `trak/udta/name` box, which `mp4 0.14`
112 /// has no field for, so it is patched in at [`finish`](Mp4Muxer::finish)
113 /// beside the sample entry. Empty where no track carries a title, which is
114 /// every file that has no subtitles at all.
115 sub_names: Vec<String>,
116 /// Coded pictures not yet handed to the writer, oldest first -- how the
117 /// overlapped audio pass gets to land *under* the picture instead of
118 /// after all of it: every `write_video_au`/`write_coded_sample` queues
119 /// here and [`drain`](Mp4Muxer::drain) interleaves it against
120 /// [`audio_queue`](Mp4Muxer::audio_queue) by presentation time, so the
121 /// two tracks' bytes end up beside each other in `mdat` rather than one
122 /// whole track then the other. `(bytes, is_sync)`.
123 ///
124 /// NONDETERMINISM: how tightly the two interleave depends on when the
125 /// mix thread's join lands relative to the picture loop -- a mix that
126 /// finishes before this hold fills stays byte-interleaved from the
127 /// start; a mix that lands late only interleaves the tail. A test on
128 /// this has to pin that landing (force the join before frame N in a
129 /// fixture) rather than race the real mixer thread.
130 hold: VecDeque<(Vec<u8>, bool)>,
131 /// `hold`'s span, in the video track's own ticks -- flushed video-only
132 /// once it passes [`HOLD_SECONDS`], so a mix that never lands (or lands
133 /// very late) cannot stall the encode behind an unbounded queue.
134 hold_ticks: u64,
135 /// AAC packets handed over by [`write_audio_packet`](Mp4Muxer::write_audio_packet)
136 /// before `drain` has caught up to them -- normally empty the instant
137 /// after that call returns; only grows past one packet where the whole
138 /// track lands in one call while the hold is still short (a picture that
139 /// finished before its own sound).
140 audio_queue: VecDeque<Vec<u8>>,
141 /// Ticks, in the audio track's own rate, already written to the file --
142 /// `drain`'s clock for comparing against `flushed_video_ticks`.
143 audio_ticks: u64,
144 /// Ticks, in the video track's own timescale, already written to the
145 /// file (as opposed to merely queued in `hold`).
146 flushed_video_ticks: u64,
147 /// The audio track's sample rate, once [`add_audio_track`](Mp4Muxer::add_audio_track)
148 /// has declared one -- `drain`'s clock for `audio_ticks`. 0 until then,
149 /// which is also exactly when `audio_queue` can have nothing in it.
150 audio_rate: u32,
151}
152
153/// A `ColourInformationBox` payload, ISO/IEC 14496-12 §12.1.5: the `nclx` tag
154/// and the same three H.273 code points Matroska's `Colour` carries, plus the
155/// range as the one-bit flag an mp4 says it with rather than Matroska's code.
156fn colr_nclx(colour: ColorDescription) -> [u8; 11] {
157 let (primaries, transfer, matrix) = colour.codes();
158 let mut out = [0u8; 11];
159 out[..4].copy_from_slice(b"nclx");
160 out[4..6].copy_from_slice(&primaries.to_be_bytes());
161 out[6..8].copy_from_slice(&transfer.to_be_bytes());
162 out[8..10].copy_from_slice(&matrix.to_be_bytes());
163 out[10] = u8::from(colour.full_range) << 7;
164 out
165}
166
167/// The language an mp4 track states, from whatever a caller said the track is
168/// in.
169///
170/// `mdhd` packs exactly three ISO 639-2 letters into its 16-bit field, and the
171/// `mp4` crate's own `language_code` (`vendor/mp4/src/mp4box/mdhd.rs:157`)
172/// masks the three UTF-16 units it is handed with `0x1F` and drops the rest --
173/// so a two-letter `en` is written as `en` and a backtick, and a `pt-BR` tag as
174/// `ptm`, silently, with a player's subtitle menu then offering a language
175/// nobody speaks. Matroska's `Language` is raw UTF-8 beside that and may carry
176/// a BCP-47 tag, so the tag is cut to its primary subtag here, mapped through
177/// [`crate::demux::ISO_639_1_TO_2`] where it is two letters, and left `und`
178/// -- the code that says *undetermined* -- where nothing names it.
179///
180/// Three lowercase letters are taken as they are: that is the code the field
181/// holds, and it is what an ISO 639-3 tag like `fil` and every language
182/// `crate::demux::mkv_language` hands over already are.
183fn mp4_language(language: &str) -> String {
184 let primary = language
185 .split('-')
186 .next()
187 .unwrap_or_default()
188 .to_ascii_lowercase();
189 let code = match primary.len() {
190 2 => crate::demux::ISO_639_1_TO_2
191 .iter()
192 .find(|(two, _)| *two == primary)
193 .map(|(_, three)| *three),
194 3 if primary.bytes().all(|b| b.is_ascii_lowercase()) => Some(primary.as_str()),
195 _ => None,
196 };
197 code.unwrap_or("und").to_owned()
198}
199
200const VIDEO_TRACK: u32 = 1;
201const AUDIO_TRACK: u32 = 2;
202
203impl Mp4Muxer {
204 pub fn create(
205 path: &Path,
206 video: &VideoParams,
207 audio: Option<&AudioParams>,
208 ) -> crate::Result<Self> {
209 Self::open(path, video, audio, None)
210 }
211
212 /// The same file with an AV1 track in it. `mp4 0.14` writes no `av01` sample
213 /// entry -- it has no AV1 anything -- so the file is written with an `avc1`
214 /// entry of placeholder parameter sets and that one entry is rewritten at
215 /// [`finish`](Mp4Muxer::finish) into the `av01` + `av1C` pair AV1-ISOBMFF
216 /// §2.2 asks for. Everything else in an mp4 is codec-blind (the sample
217 /// tables, the audio track, the movie header), so the entry is the only box
218 /// this has to spell by hand -- and the `moov` it lives in is written *after*
219 /// `mdat`, so growing it moves no sample and invalidates no chunk offset.
220 ///
221 /// The record's layout is the one OxideAV's `oxideav-mp4` writes
222 /// (`src/sample_entries.rs`, MIT): a `VisualSampleEntry` header verbatim,
223 /// then `av1C` -- the very four bytes and sequence header OBU [`MkvMuxer`]
224 /// puts in `CodecPrivate`, which is what makes the two containers' AV1 one
225 /// stream written twice rather than two.
226 ///
227 /// corner-cut: the ceiling is that one entry. A second video track, or an AV1
228 /// track beside an H.264 one, would need the walk in [`patch_av01`] to be
229 /// told *which* track it is patching; the upgrade path is passing the track
230 /// id it already knows down that walk.
231 pub fn create_av1(
232 path: &Path,
233 video: &Av1Params,
234 audio: Option<&AudioParams>,
235 ) -> crate::Result<Self> {
236 if video.config.is_empty() {
237 return Err("no AV1 sequence header for the track's av1C record".into());
238 }
239 let mut av1c = AV1C_HEAD.to_vec();
240 av1c.extend_from_slice(video.config);
241 Self::open(
242 path,
243 &VideoParams {
244 width: video.width,
245 height: video.height,
246 frame_rate: video.frame_rate,
247 // Never read by anything: the entry that holds them is replaced
248 // whole at `finish`. Four bytes because `AvcCBox::new` indexes
249 // `sps[1..=3]` for the profile it will never be asked for.
250 sps: &[0x67, 0x42, 0x00, 0x1E],
251 pps: &[0x68, 0xCE, 0x3C, 0x80],
252 },
253 audio,
254 Some((*b"av01", *b"av1C", av1c)),
255 )
256 }
257
258 /// ...and the same trick for HEVC, which `mp4 0.14` cannot spell either:
259 /// the file is written with an `avc1` entry and that entry is rewritten at
260 /// [`finish`](Mp4Muxer::finish) into the `hvc1` + `hvcC` pair ISO/IEC
261 /// 14496-15 §8.4.1 asks for -- the record being the very bytes the Matroska
262 /// file puts in `CodecPrivate`, so the two containers carry one stream.
263 /// `hvc1` rather than `hev1`: the samples this writes carry no parameter
264 /// sets (they are dropped into `hvcC`), which is exactly what the `hvc1`
265 /// name promises a reader.
266 pub fn create_hevc(
267 path: &Path,
268 video: &HevcParams,
269 audio: Option<&AudioParams>,
270 ) -> crate::Result<Self> {
271 if video.hvcc.is_empty() {
272 return Err("no hvcC record for the track's sample entry".into());
273 }
274 Self::open(
275 path,
276 &VideoParams {
277 width: video.width,
278 height: video.height,
279 frame_rate: video.frame_rate,
280 sps: &[0x67, 0x42, 0x00, 0x1E],
281 pps: &[0x68, 0xCE, 0x3C, 0x80],
282 },
283 audio,
284 Some((*b"hvc1", *b"hvcC", video.hvcc.to_vec())),
285 )
286 }
287
288 fn open(
289 path: &Path,
290 video: &VideoParams,
291 audio: Option<&AudioParams>,
292 entry: Option<([u8; 4], [u8; 4], Vec<u8>)>,
293 ) -> crate::Result<Self> {
294 if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 {
295 return Err(format!("bad frame rate {}", video.frame_rate).into());
296 }
297 if video.width == 0
298 || video.height == 0
299 || video.width > u16::MAX as u32
300 || video.height > u16::MAX as u32
301 {
302 return Err(format!("bad dimensions {}x{}", video.width, video.height).into());
303 }
304 // AvcCBox::new indexes sps[1..=3] for profile/level, so a short SPS panics
305 // inside the mp4 crate; refuse it here where the message still means something.
306 if video.sps.len() < 4 || video.pps.is_empty() {
307 return Err("no usable SPS/PPS for the video track".into());
308 }
309
310 let (timescale, frame_duration) = frame_timing(video.frame_rate)?;
311 let mut writer = Mp4Writer::write_start(
312 BufWriter::new(File::create(path)?),
313 &Mp4Config {
314 major_brand: FourCC::from(*b"isom"),
315 minor_version: 512,
316 // The codec's own brand among them, so a reader that picks a
317 // parser off `ftyp` is told which of the two this is.
318 compatible_brands: vec![
319 FourCC::from(*b"isom"),
320 FourCC::from(*b"iso2"),
321 FourCC::from(match &entry {
322 Some((kind, ..)) => *kind,
323 None => *b"avc1",
324 }),
325 FourCC::from(*b"mp41"),
326 ],
327 // The video track's own, deliberately: `mp4` converts every
328 // sample duration into the movie timescale with an integer
329 // division of its own (track.rs:752), so a coarser movie clock
330 // loses a fraction of a millisecond *per frame* -- 1 kHz makes a
331 // 4.000 s export announce itself as 3.960 s. Equal timescales
332 // make the video conversion exact.
333 timescale,
334 },
335 )?;
336 writer.add_track(&TrackConfig {
337 track_type: TrackType::Video,
338 timescale,
339 language: "und".to_string(),
340 media_conf: MediaConfig::AvcConfig(AvcConfig {
341 width: video.width as u16,
342 height: video.height as u16,
343 seq_param_set: video.sps.to_vec(),
344 pic_param_set: video.pps.to_vec(),
345 }),
346 })?;
347 let mut muxer = Self {
348 writer,
349 frame_duration,
350 has_audio: false,
351 entry,
352 colr: colr_nclx(ColorDescription::output(video.height)),
353 path: path.to_path_buf(),
354 timescale,
355 frames: 0,
356 sub_names: Vec::new(),
357 hold: VecDeque::new(),
358 hold_ticks: 0,
359 audio_queue: VecDeque::new(),
360 audio_ticks: 0,
361 flushed_video_ticks: 0,
362 audio_rate: 0,
363 };
364 if let Some(audio) = audio {
365 muxer.add_audio_track(audio)?;
366 }
367 Ok(muxer)
368 }
369
370 /// Declares the AAC track, which an mp4 may do at any point before its
371 /// first packet is written: the sample table is built from the samples as
372 /// they are handed over, and this file's audio is handed over after the
373 /// whole picture ([`write_audio_packet`](Mp4Muxer::write_audio_packet)).
374 ///
375 /// That is what lets an export mix and encode its sound *while* it encodes
376 /// the picture rather than before it: the picture's loop no longer needs to
377 /// know the track's shape to start. Declaring it at the open, which is what
378 /// a caller that already has the sound does, writes the same file --
379 /// `mp4 0.14` builds the movie box at `finish` from tracks in the order
380 /// they were added, and the samples themselves are written in the order the
381 /// caller writes them either way.
382 pub fn add_audio_track(&mut self, audio: &AudioParams) -> crate::Result<()> {
383 // The one thing this writer must never do quietly: an `mp4a` sample
384 // entry declares AAC, so Opus packets in it would be a file that says
385 // one codec and holds another. `export` never asks -- Opus is written
386 // for Matroska alone -- and this is the backstop that keeps that true
387 // if a format is ever added on the other side.
388 if audio.opus_pre_skip.is_some() {
389 return Err("an Opus track in an mp4: this writer declares `mp4a` only".into());
390 }
391 if self.has_audio {
392 return Err("an mp4 declares its audio track once".into());
393 }
394 let freq_index = SampleFreqIndex::try_from(audio.freq_index)?;
395 // The index's own rate, not `audio.sample_rate`: this is the clock an
396 // `stts` counts in and the `esds` states the index, so the two must not
397 // be able to disagree.
398 let sample_rate = freq_index.freq();
399 self.writer.add_track(&TrackConfig {
400 track_type: TrackType::Audio,
401 timescale: sample_rate,
402 language: "und".to_string(),
403 media_conf: MediaConfig::AacConfig(AacConfig {
404 bitrate: 0,
405 profile: AudioObjectType::AacLowComplexity,
406 freq_index,
407 chan_conf: ChannelConfig::try_from(audio.chan_conf)?,
408 }),
409 })?;
410 self.has_audio = true;
411 self.audio_rate = sample_rate;
412 Ok(())
413 }
414
415 /// Says what this file's samples mean, where that is *not* the rule the
416 /// height implies -- a picture written in its source's own space rather
417 /// than converted into the output one ([`crate::proxy`] is why: a stand-in
418 /// carries the film's colour and lets the screen convert it, once, at
419 /// preview size). The box is written when the file is finished, so this may
420 /// be said any time before then.
421 pub fn set_colour(&mut self, colour: ColorDescription) {
422 self.colr = colr_nclx(colour);
423 }
424
425 /// One coded picture, Annex-B framed. Parameter sets inside it are dropped
426 /// (they are already in `avcC`); an IDR slice marks the sample as a sync point.
427 pub fn write_video_au(&mut self, annex_b: &[u8]) -> crate::Result<()> {
428 let (bytes, is_sync) = annex_b_to_avcc(annex_b)?;
429 self.queue_video(bytes, is_sync)
430 }
431
432 /// One coded picture already framed the way its sample carries it: an AV1
433 /// temporal unit is the low-overhead OBU stream the encoder handed over
434 /// (nothing to reframe, exactly as a Matroska block holds it), and an HEVC
435 /// sample is the length-prefixed NALs [`annex_b_to_hvcc`] made. `key` is the
436 /// encoder's own word for a unit a decoder may start on -- an mp4 says it in
437 /// `stss` where Matroska says it in the block flags.
438 pub fn write_coded_sample(&mut self, obus: &[u8], key: bool) -> crate::Result<()> {
439 if obus.is_empty() {
440 return Err("an empty coded picture".into());
441 }
442 self.queue_video(obus.to_vec(), key)
443 }
444
445 /// Queues one coded picture and tries to advance the interleave --
446 /// shared by [`write_video_au`](Mp4Muxer::write_video_au) and
447 /// [`write_coded_sample`](Mp4Muxer::write_coded_sample), which differ
448 /// only in how the bytes were framed before they got here.
449 fn queue_video(&mut self, bytes: Vec<u8>, is_sync: bool) -> crate::Result<()> {
450 self.hold.push_back((bytes, is_sync));
451 self.hold_ticks += u64::from(self.frame_duration);
452 self.drain()
453 }
454
455 /// Advances the interleave as far as it currently can, called after
456 /// every single sample either track hands over: for as long as both
457 /// queues have something in them, writes whichever track's next sample
458 /// has the earlier presentation time -- which is what makes the release
459 /// of a mix that landed all at once ([`write_audio_packet`](Mp4Muxer::write_audio_packet)
460 /// fed in one tight loop) paced by how much *video* keeps arriving to
461 /// match it against, rather than dumped in one uninterrupted run the
462 /// moment it lands.
463 ///
464 /// Video queued with nothing to interleave against yet -- no audio
465 /// track, or one declared but not fed this far ahead -- is left held,
466 /// unless the hold has grown past [`HOLD_SECONDS`], which gives up
467 /// waiting and writes video-only to relieve it (a mix that never lands,
468 /// or one running well behind the picture). Audio queued with no video
469 /// to interleave against is always left held: nothing bounds how far
470 /// *behind* the sound the picture may run, but every path that can end
471 /// the file ([`finish`](Mp4Muxer::finish), [`write_subtitles`](Mp4Muxer::write_subtitles))
472 /// drains it in full first.
473 fn drain(&mut self) -> crate::Result<()> {
474 loop {
475 match (self.hold.front(), self.audio_queue.front()) {
476 (Some(_), Some(_)) => {
477 let video_pts = self.flushed_video_ticks as f64 / f64::from(self.timescale);
478 let audio_pts = self.audio_ticks as f64 / f64::from(self.audio_rate);
479 if audio_pts <= video_pts {
480 self.flush_audio_front()?;
481 } else {
482 self.flush_video_front()?;
483 }
484 }
485 (Some(_), None) if self.hold_ticks > HOLD_SECONDS * u64::from(self.timescale) => {
486 self.flush_video_front()?;
487 }
488 (Some(_), None) | (None, Some(_)) | (None, None) => break,
489 }
490 }
491 Ok(())
492 }
493
494 fn flush_video_front(&mut self) -> crate::Result<()> {
495 let Some((bytes, is_sync)) = self.hold.pop_front() else {
496 return Ok(());
497 };
498 self.hold_ticks -= u64::from(self.frame_duration);
499 self.writer.write_sample(
500 VIDEO_TRACK,
501 &Mp4Sample {
502 start_time: 0, // ignored by the writer; timing is duration-accumulated
503 duration: self.frame_duration,
504 rendering_offset: 0, // no B-frames on either encode path
505 is_sync,
506 bytes: Bytes::from(bytes),
507 },
508 )?;
509 self.frames += 1;
510 self.flushed_video_ticks += u64::from(self.frame_duration);
511 Ok(())
512 }
513
514 fn flush_audio_front(&mut self) -> crate::Result<()> {
515 let Some(bytes) = self.audio_queue.pop_front() else {
516 return Ok(());
517 };
518 self.writer.write_sample(
519 AUDIO_TRACK,
520 &Mp4Sample {
521 start_time: 0,
522 duration: AAC_PACKET_SAMPLES,
523 rendering_offset: 0,
524 // Every AAC packet is a sync point; saying so per-sample would emit
525 // an `stss` listing all of them, while no `stss` means the same thing.
526 is_sync: false,
527 bytes: Bytes::from(bytes),
528 },
529 )?;
530 self.audio_ticks += u64::from(AAC_PACKET_SAMPLES);
531 Ok(())
532 }
533
534 /// Everything either queue has left, in presentation order regardless of
535 /// the hold cap -- called from [`finish`](Mp4Muxer::finish), where there
536 /// is no more picture coming for a short hold to wait on.
537 fn drain_all(&mut self) -> crate::Result<()> {
538 loop {
539 match (self.hold.front(), self.audio_queue.front()) {
540 (Some(_), Some(_)) => {
541 let video_pts = self.flushed_video_ticks as f64 / f64::from(self.timescale);
542 let audio_pts = self.audio_ticks as f64 / f64::from(self.audio_rate);
543 if audio_pts <= video_pts {
544 self.flush_audio_front()?;
545 } else {
546 self.flush_video_front()?;
547 }
548 }
549 (Some(_), None) => self.flush_video_front()?,
550 (None, Some(_)) => self.flush_audio_front()?,
551 (None, None) => break,
552 }
553 }
554 Ok(())
555 }
556
557 /// One raw AAC packet (no ADTS header), copied verbatim from the source --
558 /// or one of the hand-written silent ones a gap is filled with. Every AAC-LC
559 /// access unit is [`AAC_PACKET_SAMPLES`] frames, gap or not.
560 ///
561 /// Queues rather than writes straight through: a caller feeding packets
562 /// while the picture is still running (the overlapped export path,
563 /// [`crate::export::run`]) gets them woven into the file under the
564 /// pictures still queued in [`hold`](Mp4Muxer::hold) instead of parked
565 /// until the picture ends, which is the whole point of calling this
566 /// before the picture loop is done rather than after.
567 pub fn write_audio_packet(&mut self, bytes: &[u8]) -> crate::Result<()> {
568 if !self.has_audio {
569 return Err("audio packet written to a video-only file".into());
570 }
571 self.audio_queue.push_back(bytes.to_vec());
572 self.drain()
573 }
574
575 /// The soft subtitle tracks this file carries, written after the picture and
576 /// the sound exactly as [`MkvMuxer`] writes its own into the clusters -- one
577 /// `tx3g` timed-text track per [`SubParams`], which is the text an mp4 says
578 /// a cue with and the one `ffmpeg` calls `mov_text`. Called once, before
579 /// [`finish`](Mp4Muxer::finish); an empty list writes nothing at all, which
580 /// is why an export with no pick is the file it always was, byte for byte.
581 ///
582 /// The samples are *continuous*: a timed-text track states one sample per
583 /// instant of the film and nothing between them, so the stretches with
584 /// nothing to say are empty samples (a 16-bit zero length and no text) and
585 /// not holes -- a hole is where a player keeps the last line on screen until
586 /// the next one arrives. The run is built out of the cue *boundaries*, so
587 /// cues that overlap are one sample of both their lines rather than one of
588 /// them dropped: a `tx3g` track shows one sample at a time where a Matroska
589 /// one may show two blocks at once, and joining them is what keeps the words
590 /// a viewer saw over the picture.
591 ///
592 /// corner-cut: the `tx3g` sample entry is the one `mp4 0.14` writes and there
593 /// is no field to reach into it -- `MediaConfig::TtxtConfig` carries nothing
594 /// -- so its `data_reference_index` is the crate's 0 where §8.5.2 says an
595 /// index into `dref` counts from 1, and it holds no `ftab` font table.
596 /// ffmpeg and mpv both read the track (measured, 2026-08-12); a reader that
597 /// checks the index would not. The upgrade path is the trick the `av01`
598 /// entry already takes: rewrite the 46 fixed bytes of that entry in
599 /// [`patch_entry`] the way the video one is rewritten.
600 pub fn write_subtitles(&mut self, subs: &[SubParams]) -> crate::Result<()> {
601 if subs.is_empty() {
602 return Ok(());
603 }
604 // `self.frames` below counts only pictures already handed to the
605 // writer, and the interleave above can still be holding some back:
606 // drained first, or a text track written under a short hold would
607 // end short of the picture that has not landed yet.
608 self.drain_all()?;
609 // Where the picture ends, in the text track's own tick: the last sample
610 // runs out to it, so the track covers the film rather than stopping at
611 // the last thing anybody says.
612 let end = (self.frames * u64::from(self.frame_duration) * u64::from(SUB_TIMESCALE)
613 / u64::from(self.timescale)) as i64;
614 // The picture is track 1 and the sound, where there is any, track 2:
615 // `mp4 0.14` numbers a track by the order it was added in, so the text
616 // starts after them and each further track is the next number up.
617 for (track_id, subs) in (2 + u32::from(self.has_audio)..).zip(subs) {
618 self.writer.add_track(&TrackConfig {
619 track_type: TrackType::Subtitle,
620 timescale: SUB_TIMESCALE,
621 // The field's own contract, enforced here rather than trusted:
622 // an mp4 packs exactly three ISO 639-2 letters into 16 bits, and
623 // the `mp4` crate's own `language_code` masks whatever it is
624 // handed into that shape without a word -- a two-letter `en`
625 // comes out as `en` and a backtick, a `pt-BR` tag as `ptm` --
626 // while Matroska may state a BCP-47 tag for the same track.
627 // `mp4_language` is the one place a tag becomes a code, and
628 // `und` (the code that means *undetermined*) is what a tag
629 // nothing names leaves as, rather than a language nobody speaks.
630 language: mp4_language(&subs.language),
631 media_conf: MediaConfig::TtxtConfig(TtxtConfig {}),
632 })?;
633 for (bytes, duration) in timed_text(&subs.cues, end)? {
634 self.writer.write_sample(
635 track_id,
636 &Mp4Sample {
637 start_time: 0, // ignored by the writer, as everywhere here
638 duration,
639 rendering_offset: 0,
640 // Every text sample is one a player may start at, and
641 // saying so per-sample would emit an `stss` listing all
642 // of them where no `stss` means the same thing -- the
643 // audio track's reason, and what ffmpeg's own `tx3g`
644 // track does.
645 is_sync: false,
646 bytes: Bytes::from(bytes),
647 },
648 )?;
649 }
650 }
651 self.sub_names = subs.iter().map(|subs| subs.name.clone()).collect();
652 Ok(())
653 }
654
655 pub fn finish(mut self) -> crate::Result<()> {
656 // Whatever the hold and the audio queue still carry: nothing further
657 // is coming for either to wait on, so this drains both fully rather
658 // than leaving a video-only tail queued.
659 self.drain_all()?;
660 // Both containers refuse a file nobody put a picture in, by name and in
661 // their own container's words ([`MkvMuxer::finish`] is the twin): an mp4
662 // whose picture track holds no sample is a file that opens on a blank
663 // window with nothing said, which is worse than an export that fails.
664 if self.frames == 0 {
665 return Err("no frames were written to the mp4 file".into());
666 }
667 self.writer.write_end()?;
668 let Self {
669 writer,
670 entry,
671 colr,
672 path,
673 sub_names,
674 ..
675 } = self;
676 // Not a `drop`: the buffered tail of `moov` has to be on disk before the
677 // patch below reads it back, and a `BufWriter` swallows the error of
678 // flushing it on drop.
679 writer.into_writer().flush()?;
680 patch_entry(&path, entry.as_ref(), &colr, &sub_names)
681 }
682}
683
684/// The cues of one subtitle track as the run of `tx3g` samples an mp4 carries
685/// them in -- `(payload, duration in milliseconds)`, from instant 0 to `end`,
686/// with no instant left out.
687///
688/// A sample's payload is the ISO/IEC 14496-17 one: the text's length in 16 bits
689/// and then the UTF-8 itself, which is two zero bytes where there is nothing on
690/// screen. The run is walked over the cue *boundaries* rather than over the cues,
691/// which is what makes a gap an empty sample and an overlap one sample carrying
692/// both lines -- the two things a track of samples has to say that a list of
693/// cues does not.
694///
695/// corner-cut: the active set is looked for from the front of the list at every
696/// boundary, so this is quadratic in the cues of one track (a 5 000-cue film
697/// costs ~25 M compares once, at the end of an export that took minutes). The
698/// upgrade path is a sweep holding the open cues in a heap keyed on their end.
699fn timed_text(cues: &[crate::subtitle::Cue], end: i64) -> crate::Result<Vec<(Vec<u8>, u32)>> {
700 // Milliseconds, the tick this track is written in -- and a cue that rounds
701 // onto its own start stays up for one of them rather than vanishing, which
702 // is what the Matroska writer's `BlockDuration` does with it.
703 let ms = |us: i64| (us + 500) / 1_000;
704 let spans: Vec<(i64, i64)> = cues
705 .iter()
706 .map(|cue| {
707 let start = ms(cue.start_us);
708 (start, ms(cue.end_us).max(start + 1))
709 })
710 .collect();
711 let mut times: Vec<i64> = vec![0, end.max(0)];
712 for &(start, stop) in &spans {
713 times.push(start);
714 times.push(stop);
715 }
716 times.sort_unstable();
717 times.dedup();
718 let mut out = Vec::with_capacity(times.len());
719 for pair in times.windows(2) {
720 let (from, to) = (pair[0], pair[1]);
721 let mut text = String::new();
722 for (span, cue) in spans.iter().zip(cues) {
723 // The cues arrive in start order (`export::timeline_cues` sorts
724 // them), so nothing past this one has opened yet.
725 if span.0 > from {
726 break;
727 }
728 if span.1 > from {
729 if !text.is_empty() {
730 text.push('\n');
731 }
732 text.push_str(&cue.text);
733 }
734 }
735 let len = u16::try_from(text.len()).map_err(|_| {
736 format!(
737 "a subtitle cue of {} bytes: a tx3g sample states its text length in 16 bits, so \
738 one cue carries at most {} -- export a Matroska, whose blocks state no length at \
739 all",
740 text.len(),
741 u16::MAX
742 )
743 })?;
744 let mut bytes = Vec::with_capacity(text.len() + 2);
745 bytes.extend_from_slice(&len.to_be_bytes());
746 bytes.extend_from_slice(text.as_bytes());
747 out.push((bytes, u32::try_from(to - from)?));
748 }
749 Ok(out)
750}
751
752/// Rewrites the finished file's one video sample entry: `colr` appended to it
753/// always (the crate writes none), and where `entry` says so the `avc1` header
754/// itself replaced by the `av01` + `av1C` an AV1 track declares -- or the `hvc1`
755/// + `hvcC` an HEVC one does. Called once, on a complete file.
756///
757/// `moov` sits after `mdat` (the crate writes it at `write_end`), so this only
758/// ever rewrites the tail of the file: no sample moves and no chunk offset in
759/// `co64` changes. The box tree is rebuilt rather than patched in place, which
760/// is what keeps every ancestor's size right by construction.
761fn patch_entry(
762 path: &Path,
763 entry: Option<&([u8; 4], [u8; 4], Vec<u8>)>,
764 colr: &[u8],
765 sub_names: &[String],
766) -> crate::Result<()> {
767 let mut file = OpenOptions::new().read(true).write(true).open(path)?;
768 let end = file.metadata()?.len();
769 let (at, payload) = top_level(&mut file, end, b"moov")?.ok_or("no moov box to patch")?;
770 let patched = swap_entry(&payload, 0, entry, colr).ok_or("no avc1 sample entry to rewrite")?;
771 let patched = name_subtitles(patched, sub_names);
772 let mut out = Vec::with_capacity(patched.len() + 8);
773 push_box(&mut out, b"moov", &patched);
774 file.seek(SeekFrom::Start(at))?;
775 file.write_all(&out)?;
776 file.set_len(at + out.len() as u64)?;
777 file.flush()?;
778 Ok(())
779}
780
781/// Offset and payload of the first top-level box of type `want`.
782fn top_level(file: &mut File, end: u64, want: &[u8; 4]) -> crate::Result<Option<(u64, Vec<u8>)>> {
783 let mut at = 0u64;
784 while at + 8 <= end {
785 let mut header = [0u8; 8];
786 file.seek(SeekFrom::Start(at))?;
787 file.read_exact(&mut header)?;
788 let (size, head_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) {
789 0 => (end - at, 8),
790 1 => {
791 let mut large = [0u8; 8];
792 file.read_exact(&mut large)?;
793 (u64::from_be_bytes(large), 16)
794 }
795 size => (u64::from(size), 8),
796 };
797 if size < head_len || at + size > end {
798 return Err("truncated box in the file's top level".into());
799 }
800 if &header[4..8] == want {
801 let mut payload = vec![0u8; (size - head_len) as usize];
802 file.read_exact(&mut payload)?;
803 return Ok(Some((at, payload)));
804 }
805 at += size;
806 }
807 Ok(None)
808}
809
810/// `moov` down to the sample descriptions, which is where the entry lives.
811const STSD_PATH: [&[u8; 4]; 5] = [b"trak", b"mdia", b"minf", b"stbl", b"stsd"];
812
813/// The box at `depth` of [`STSD_PATH`], rebuilt with its `avc1` entry given a
814/// `colr` box and, where `entry` says so, another four-character name and
815/// configuration box. `None` where this branch holds no such entry -- an audio
816/// `trak` is walked into and comes back untouched, which is how the *video*
817/// track is found without being told which id it has.
818fn swap_entry(
819 payload: &[u8],
820 depth: usize,
821 entry: Option<&([u8; 4], [u8; 4], Vec<u8>)>,
822 colr: &[u8],
823) -> Option<Vec<u8>> {
824 if depth == STSD_PATH.len() {
825 // stsd is a FullBox (4) plus entry_count (4), then the sample entries.
826 let mut out = payload.get(..8)?.to_vec();
827 let (kind, sample_entry) = crate::demux::boxes(payload.get(8..)?).next()?;
828 if kind != b"avc1" {
829 return None;
830 }
831 let (name, mut swapped) = match entry {
832 // A `VisualSampleEntry` is 78 bytes of fixed fields (dimensions and
833 // all) before its codec box, and `av01` and `hvc1` carry exactly the
834 // same ones -- so the header is kept and only the configuration box
835 // is swapped.
836 Some((want, config_kind, config)) => {
837 let mut swapped = sample_entry.get(..78)?.to_vec();
838 push_box(&mut swapped, config_kind, config);
839 (want, swapped)
840 }
841 // H.264: the crate spelled the whole entry, `avcC` and all, and only
842 // the colour tag is missing from it.
843 None => (b"avc1", sample_entry.to_vec()),
844 };
845 push_box(&mut swapped, b"colr", colr);
846 push_box(&mut out, name, &swapped);
847 return Some(out);
848 }
849 let mut out = Vec::with_capacity(payload.len());
850 let mut done = false;
851 for (kind, child) in crate::demux::boxes(payload) {
852 let patched = match !done && kind == STSD_PATH[depth] {
853 true => swap_entry(child, depth + 1, entry, colr),
854 false => None,
855 };
856 match patched {
857 Some(child) => {
858 push_box(&mut out, kind, &child);
859 done = true;
860 }
861 None => push_box(&mut out, kind, child),
862 }
863 }
864 done.then_some(out)
865}
866
867/// The title of each subtitle track into the `trak` that carries it, in the
868/// order they were written: a `udta` holding a `name` box, which is where an mp4
869/// says what a track is *called* (`Signs`) beside the `mdhd` language it is in
870/// -- the pair Matroska spells as `Name` and `Language`, and the very boxes
871/// ffmpeg writes a `-metadata:s:s:0 title=` into and reads back out.
872/// `mp4 0.14`'s `TrakBox` has no `udta` field at all, so it is appended here
873/// beside the sample entry rewrite, on the same rebuilt `moov`.
874///
875/// Untouched where no track has a title -- and returned as it came for a file
876/// with no subtitles at all, which is every export that picked none.
877fn name_subtitles(moov: Vec<u8>, names: &[String]) -> Vec<u8> {
878 if names.iter().all(|name| name.is_empty()) {
879 return moov;
880 }
881 let mut names = names.iter();
882 let mut out = Vec::with_capacity(moov.len() + 32 * names.len());
883 for (kind, child) in crate::demux::boxes(&moov) {
884 // A subtitle `trak` is the one whose media handler says `sbtl`, which is
885 // what `TrackType::Subtitle` wrote -- asked of the file rather than
886 // counted, so the picture's and the sound's `trak`s cannot be miscounted
887 // into.
888 let name = match kind == b"trak" && is_subtitle_trak(child) {
889 true => names.next().filter(|name| !name.is_empty()),
890 false => None,
891 };
892 let Some(name) = name else {
893 push_box(&mut out, kind, child);
894 continue;
895 };
896 let mut trak = child.to_vec();
897 let mut udta = Vec::new();
898 push_box(&mut udta, b"name", name.as_bytes());
899 push_box(&mut trak, b"udta", &udta);
900 push_box(&mut out, kind, &trak);
901 }
902 out
903}
904
905/// Whether a `trak` is a subtitle one: its `mdia`'s `hdlr` names the `sbtl`
906/// handler, which sits after the box's version, flags and the four `pre_defined`
907/// bytes.
908fn is_subtitle_trak(trak: &[u8]) -> bool {
909 crate::demux::boxes(trak)
910 .filter(|(kind, _)| *kind == b"mdia")
911 .flat_map(|(_, mdia)| crate::demux::boxes(mdia))
912 .any(|(kind, hdlr)| kind == b"hdlr" && hdlr.get(8..12) == Some(&b"sbtl"[..]))
913}
914
915/// One mp4 box: 32-bit size, four-character type, payload. Every box inside a
916/// `moov` fits that form -- the 64-bit one exists for `mdat`, which this never
917/// rewrites.
918fn push_box(out: &mut Vec<u8>, kind: &[u8; 4], payload: &[u8]) {
919 out.extend_from_slice(&(payload.len() as u32 + 8).to_be_bytes());
920 out.extend_from_slice(kind);
921 out.extend_from_slice(payload);
922}
923
924// Matroska element ids, written with the leading length marker they carry in the
925// file -- the same spelling `demux` reads them back with.
926const EBML: u32 = 0x1A45_DFA3;
927const EBML_VERSION: u32 = 0x4286;
928const EBML_READ_VERSION: u32 = 0x42F7;
929const EBML_MAX_ID_LENGTH: u32 = 0x42F2;
930const EBML_MAX_SIZE_LENGTH: u32 = 0x42F3;
931const DOC_TYPE: u32 = 0x4282;
932const DOC_TYPE_VERSION: u32 = 0x4287;
933const DOC_TYPE_READ_VERSION: u32 = 0x4285;
934const SEGMENT: u32 = 0x1853_8067;
935const INFO: u32 = 0x1549_A966;
936const TIMESTAMP_SCALE: u32 = 0x2AD7B1;
937const DURATION: u32 = 0x4489;
938const MUXING_APP: u32 = 0x4D80;
939const WRITING_APP: u32 = 0x5741;
940const TRACKS: u32 = 0x1654_AE6B;
941const TRACK_ENTRY: u32 = 0xAE;
942const TRACK_NUMBER: u32 = 0xD7;
943const TRACK_UID: u32 = 0x73C5;
944const TRACK_TYPE: u32 = 0x83;
945const FLAG_LACING: u32 = 0x9C;
946const CODEC_ID: u32 = 0x86;
947const CODEC_PRIVATE: u32 = 0x63A2;
948const DEFAULT_DURATION: u32 = 0x23E383;
949const VIDEO: u32 = 0xE0;
950const PIXEL_WIDTH: u32 = 0xB0;
951const PIXEL_HEIGHT: u32 = 0xBA;
952// How the copied picture is drawn: the same elements [`crate::demux`] reads
953// back. `DisplayUnit` 4 spells the pair as the sample aspect ratio itself and
954// 3 as a display aspect ratio; this writer says SAR (unit 4) because that is
955// the ratio it was handed ([`crate::demux::PixelAspect`]) and the one a
956// round-trip through this engine's own reader reproduces exactly. Square --
957// the default these elements are optional for -- writes none of them, which is
958// what keeps every existing copy's header byte-identical.
959const DISPLAY_WIDTH: u32 = 0x54B0;
960const DISPLAY_HEIGHT: u32 = 0x54BA;
961const DISPLAY_UNIT: u32 = 0x54B2;
962const DISPLAY_UNIT_SAR: u64 = 4;
963// `Colour` and the four children this writes, all inside `Video`. Byte-verified
964// against what `demux` reads back and what ffprobe reports: the spec tables that
965// list Range as 0x55B3 are describing ChromaSubsamplingHorz.
966const COLOUR: u32 = 0x55B0;
967const MATRIX_COEFFICIENTS: u32 = 0x55B1;
968const RANGE: u32 = 0x55B9;
969const TRANSFER_CHARACTERISTICS: u32 = 0x55BA;
970const PRIMARIES: u32 = 0x55BB;
971const AUDIO: u32 = 0xE1;
972const SAMPLING_FREQUENCY: u32 = 0xB5;
973const CHANNELS: u32 = 0x9F;
974const CODEC_DELAY: u32 = 0x56AA;
975const SEEK_PRE_ROLL: u32 = 0x56BB;
976const CLUSTER: u32 = 0x1F43_B675;
977const CLUSTER_TIMESTAMP: u32 = 0xE7;
978const SIMPLE_BLOCK: u32 = 0xA3;
979const TRACK_NAME: u32 = 0x536E;
980const TRACK_LANGUAGE: u32 = 0x22B59C;
981const BLOCK_GROUP: u32 = 0xA0;
982const BLOCK: u32 = 0xA1;
983const BLOCK_DURATION: u32 = 0x9B;
984
985/// One millisecond, the tick every Matroska muxer writes and this one's block
986/// timestamps are in. The *rate* is not derived from these -- `DefaultDuration`
987/// is, in exact nanoseconds -- so a millisecond is precise enough for the
988/// presentation times and coarse enough to keep a cluster's 16-bit relative
989/// timestamp covering half a minute.
990const TIMESTAMP_SCALE_NS: u64 = 1_000_000;
991/// A cluster is buffered whole (its size is a header field), so it is flushed
992/// at the first keyframe past this -- a ceiling on what the muxer holds, not a
993/// target.
994const CLUSTER_BYTES: usize = 4 << 20;
995/// ...and on how far a block's timestamp may sit from its cluster's, *either*
996/// way: the field is a signed 16-bit millisecond count, and a copy's backwards
997/// steps over a group of pictures are the direction nothing else bounds.
998const CLUSTER_MS: i64 = 30_000;
999
1000/// The fixed four bytes of an `AV1CodecConfigurationRecord` for what both encode
1001/// paths here are configured to produce: profile 0, 8-bit, 4:2:0, no operating
1002/// point delay. `seq_level_idx` is written as 31 -- "maximum parameters", i.e.
1003/// unstated -- which is what rav1e's own `container_sequence_header` writes and
1004/// what keeps this record from claiming a level neither encoder promised. The
1005/// sequence header OBU follows it; that is where a decoder reads the real
1006/// parameters from, and `demux::parse_av1c` hands exactly those bytes back.
1007const AV1C_HEAD: [u8; 4] = [
1008 0x81, // marker 1, version 1
1009 0x1F, // seq_profile 0, seq_level_idx_0 31
1010 0x0C, // tier 0, 8-bit, colour, chroma subsampled both ways
1011 0x00, // no initial presentation delay
1012];
1013
1014/// What an AV1 Matroska track declares. `config` is the sequence header OBU,
1015/// which is [`av1_sequence_header`]'s answer for the first coded keyframe.
1016pub struct Av1Params<'a> {
1017 pub width: u32,
1018 pub height: u32,
1019 pub frame_rate: f64,
1020 pub config: &'a [u8],
1021}
1022
1023/// What an HEVC track declares in either container: the `hvcC` record
1024/// [`hvcc_record`] built out of the encoder's own VPS/SPS/PPS. The dimensions
1025/// are the *displayed* ones -- the coded picture is padded up to the 16-sample
1026/// CTB grid and the SPS crops it back with a conformance window, which is the
1027/// size a decoder outputs and therefore the size the container states.
1028pub struct HevcParams<'a> {
1029 pub width: u32,
1030 pub height: u32,
1031 pub frame_rate: f64,
1032 pub hvcc: &'a [u8],
1033}
1034
1035/// What a *copied* track declares: the source's own codec id and configuration
1036/// record, in the space its samples are really in.
1037///
1038/// Nothing here is derived from the timeline -- the copy exists precisely
1039/// because none of it changed -- so the picture keeps the size, the rate, the
1040/// curve and the parameter sets it was coded with.
1041pub struct CopyParams<'a> {
1042 pub width: u32,
1043 pub height: u32,
1044 pub frame_rate: f64,
1045 /// The Matroska codec id, `V_MPEGH/ISO/HEVC` or `V_AV1`.
1046 pub codec_id: &'a [u8],
1047 /// `CodecPrivate` as the source holds it ([`crate::demux::MkvDemuxer::codec_private`]).
1048 pub codec_private: &'a [u8],
1049 /// The source's own `Colour`: a copied HDR film leaves as the HDR film it
1050 /// is, because not one of its samples was touched.
1051 ///
1052 /// corner-cut: the `MasteringMetadata` and MaxCLL beside it are not carried --
1053 /// this engine parses them ([`crate::demux::ContentLight`]) but has nowhere
1054 /// to write them yet, so a copied HDR file states its curve and not its
1055 /// grading display. Upgrade path is a `Colour` element written from that
1056 /// same struct.
1057 pub colour: ColorDescription,
1058 /// The ratio one of the copied samples' pixels is drawn at, written as the
1059 /// track's `Display*` elements: the aspect is metadata about the samples,
1060 /// which are the source's own, so it travels instead of being baked in --
1061 /// ffmpeg's own copy behaviour. [`PixelAspect::SQUARE`] writes nothing,
1062 /// which is every square-pixel file's header exactly as it was.
1063 pub pixel_aspect: crate::demux::PixelAspect,
1064}
1065
1066/// The soft subtitle track a file carries beside the picture: text, timed, still
1067/// text in the file -- a player draws it and a user can turn it off, which is
1068/// what "soft" means and what burning it into the pixels is not.
1069///
1070/// Both containers carry one: Matroska as an `S_TEXT/UTF8` track whose blocks
1071/// are the cues themselves ([`MkvMuxer`]), an mp4 as a `tx3g` timed-text track
1072/// whose samples run end to end over the film
1073/// ([`Mp4Muxer::write_subtitles`]).
1074///
1075/// The cues are the *exported timeline's* (`export::timeline_cues` puts them
1076/// there), because the file's clock is the timeline's; nothing here shifts
1077/// anything.
1078pub struct SubParams {
1079 /// What language the track is in, as the three-letter code Matroska says it
1080 /// with (`fra`, `tur`): the field a player's subtitle menu reads. Empty
1081 /// where the source states none -- and *only* then, because a `TrackEntry`
1082 /// without a `Language` means `eng` by spec, so a French track that leaves
1083 /// this empty leaves as an English one.
1084 ///
1085 /// Matroska carries whatever bytes this holds, and a file may state a
1086 /// BCP-47 tag in them (`pt-BR`); an mp4 has one 16-bit field of exactly
1087 /// three ISO 639-2 letters, so [`Mp4Muxer::write_subtitles`] turns a tag
1088 /// into a code -- or into `und`, where nothing names it -- rather than
1089 /// letting the container mangle it.
1090 pub language: String,
1091 /// What the track is *called*, where it has a title of its own beside its
1092 /// language (`Signs`, `Forced`). Empty where it has none.
1093 pub name: String,
1094 /// In start order, which is the order they are written in.
1095 pub cues: Vec<crate::subtitle::Cue>,
1096}
1097
1098/// The cues of one subtitle track waiting to be interleaved into the clusters,
1099/// [`MkvAudio`]'s twin. One of these per track the file carries.
1100struct MkvSubs {
1101 cues: Vec<crate::subtitle::Cue>,
1102 /// Cues already written.
1103 next: usize,
1104 /// Which track its blocks name -- 3 for the first, one more for each after
1105 /// it ([`SUB_TRACK_FIRST`]).
1106 track_no: u8,
1107}
1108
1109/// Writes one AV1 video track as Matroska (`.mkv`), and the timeline's AAC
1110/// beside it where there is any: an `A_AAC` track whose `CodecPrivate` is the
1111/// two-byte `AudioSpecificConfig` an mp4's `esds` carries, which is what
1112/// symphonia's `mkv` reader -- this project's own way back in -- configures its
1113/// decoder from. An AV1 export used to be picture alone; a video file whose
1114/// sound was silently left behind is exactly the failure nobody notices until
1115/// the file has gone somewhere.
1116///
1117/// The sound is *interleaved*: each packet is written into the cluster of the
1118/// picture it plays under, so a player has both by the time it needs them rather
1119/// than a file it must read to the end of to hear.
1120///
1121/// The file is patched twice at [`finish`](MkvMuxer::finish) -- the segment size
1122/// and the duration -- so a killed process leaves an unfinished file rather than
1123/// a wrong one; the export's `.part` rename covers that already.
1124pub struct MkvMuxer {
1125 file: File,
1126 /// Nanoseconds a frame lasts: `DefaultDuration`, which is the *only* exact
1127 /// statement of the frame rate in the file (see `demux::MkvDemuxer::open`).
1128 frame_ns: u64,
1129 segment_size_at: u64,
1130 duration_at: u64,
1131 /// The cluster being built: everything after its id and size, so it can be
1132 /// written once its length is known.
1133 cluster: Vec<u8>,
1134 cluster_ts: i64,
1135 frames: u64,
1136 /// The latest timestamp any picture was written at. Equal to the frame
1137 /// counter's own for a track this project encoded; for a *copied* one the
1138 /// blocks carry their source's timing and a cut can leave the last picture
1139 /// on screen, so the duration is measured rather than counted.
1140 last_ts: i64,
1141 /// The AAC track, if the timeline has sound, and how far it has been
1142 /// written.
1143 audio: Option<MkvAudio>,
1144 /// The subtitle tracks travelling with the file, in the order they were
1145 /// declared, and how far each has been written. Empty where none does.
1146 subs: Vec<MkvSubs>,
1147}
1148
1149/// The sound waiting to be interleaved into the clusters.
1150struct MkvAudio {
1151 packets: Vec<crate::AacPacket>,
1152 /// Packets already written.
1153 next: usize,
1154 /// Frames already written, which is what the next packet's timestamp is
1155 /// counted from: every AAC-LC packet says its own length and they are not
1156 /// assumed equal here.
1157 samples: u64,
1158 sample_rate: u32,
1159}
1160
1161impl MkvMuxer {
1162 /// `audio` is the whole track at once -- the export has it before it has a
1163 /// single coded picture, and interleaving needs to look ahead of the frame
1164 /// being written.
1165 ///
1166 /// corner-cut: that is the copy path's own ceiling reappearing (the track sits
1167 /// in memory, ~500 MB an hour); the upgrade path is the same streaming
1168 /// `copy_segments` `export::copy_audio` names.
1169 pub fn create(
1170 path: &Path,
1171 video: &Av1Params,
1172 audio: Option<(&AudioParams, Vec<crate::AacPacket>)>,
1173 subs: Vec<SubParams>,
1174 ) -> crate::Result<Self> {
1175 if video.config.is_empty() {
1176 return Err("no AV1 sequence header for the track's CodecPrivate".into());
1177 }
1178 let mut av1c = AV1C_HEAD.to_vec();
1179 av1c.extend_from_slice(video.config);
1180 Self::open(
1181 path,
1182 video.width,
1183 video.height,
1184 video.frame_rate,
1185 b"V_AV1",
1186 &av1c,
1187 ColorDescription::output(video.height),
1188 crate::demux::PixelAspect::SQUARE,
1189 audio,
1190 subs,
1191 )
1192 }
1193
1194 /// The same file with an HEVC track in it: `V_MPEGH/ISO/HEVC`, whose
1195 /// `CodecPrivate` is the very `hvcC` record an mp4 puts in its sample entry
1196 /// ([`hvcc_record`]) -- and whose blocks are therefore length-prefixed NALs
1197 /// like an mp4 sample's, not Annex B. That is what this engine's own reader
1198 /// expects back (`demux`'s Matroska branch parses `CodecPrivate` as `hvcC`
1199 /// and reframes the blocks by the length it states), and what every other
1200 /// Matroska reader expects too.
1201 pub fn create_hevc(
1202 path: &Path,
1203 video: &HevcParams,
1204 audio: Option<(&AudioParams, Vec<crate::AacPacket>)>,
1205 subs: Vec<SubParams>,
1206 ) -> crate::Result<Self> {
1207 if video.hvcc.is_empty() {
1208 return Err("no hvcC record for the track's CodecPrivate".into());
1209 }
1210 Self::open(
1211 path,
1212 video.width,
1213 video.height,
1214 video.frame_rate,
1215 b"V_MPEGH/ISO/HEVC",
1216 video.hvcc,
1217 ColorDescription::output(video.height),
1218 crate::demux::PixelAspect::SQUARE,
1219 audio,
1220 subs,
1221 )
1222 }
1223
1224 /// The same file with a track *copied* out of another one: the source's own
1225 /// codec id and `CodecPrivate`, and its own `Colour` beside them
1226 /// ([`crate::export`]'s copy path).
1227 ///
1228 /// Not [`Self::create_hevc`] with the source's record, because the picture
1229 /// is not this project's own: a copy writes the file the source's samples
1230 /// already are -- an HDR film stays on its PQ curve rather than being
1231 /// declared the SDR the encoders here write -- and the blocks are timed by
1232 /// [`Self::write_block`] off the source's clock rather than by a frame
1233 /// counter, which is the other half of the same statement.
1234 pub fn create_copy(
1235 path: &Path,
1236 video: &CopyParams,
1237 audio: Option<(&AudioParams, Vec<crate::AacPacket>)>,
1238 subs: Vec<SubParams>,
1239 ) -> crate::Result<Self> {
1240 if video.codec_private.is_empty() {
1241 return Err("the source track carries no CodecPrivate to copy".into());
1242 }
1243 Self::open(
1244 path,
1245 video.width,
1246 video.height,
1247 video.frame_rate,
1248 video.codec_id,
1249 video.codec_private,
1250 video.colour,
1251 video.pixel_aspect,
1252 audio,
1253 subs,
1254 )
1255 }
1256
1257 #[allow(clippy::too_many_arguments)]
1258 fn open(
1259 path: &Path,
1260 width: u32,
1261 height: u32,
1262 frame_rate: f64,
1263 codec_id: &[u8],
1264 codec_private: &[u8],
1265 colour: ColorDescription,
1266 pixel_aspect: crate::demux::PixelAspect,
1267 audio: Option<(&AudioParams, Vec<crate::AacPacket>)>,
1268 subs: Vec<SubParams>,
1269 ) -> crate::Result<Self> {
1270 if !frame_rate.is_finite() || frame_rate <= 0.0 {
1271 return Err(format!("bad frame rate {frame_rate}").into());
1272 }
1273 // Said before a byte is written, and by name: past this the block header
1274 // could not hold the track number ([`MAX_SUB_TRACKS`]) and the file would
1275 // be quietly wrong rather than absent.
1276 if subs.len() > MAX_SUB_TRACKS {
1277 return Err(format!(
1278 "{} subtitle tracks: a Matroska block writes its track number in \
1279 one byte, so one file carries at most {MAX_SUB_TRACKS}",
1280 subs.len()
1281 )
1282 .into());
1283 }
1284 if width == 0 || height == 0 {
1285 return Err(format!("bad dimensions {width}x{height}").into());
1286 }
1287 let frame_ns = (1e9 / frame_rate).round() as u64;
1288 if frame_ns == 0 {
1289 return Err(format!("frame rate {frame_rate} is too fast to time").into());
1290 }
1291
1292 let mut head = Vec::new();
1293 let mut ebml = Vec::new();
1294 uint(&mut ebml, EBML_VERSION, 1);
1295 uint(&mut ebml, EBML_READ_VERSION, 1);
1296 uint(&mut ebml, EBML_MAX_ID_LENGTH, 4);
1297 uint(&mut ebml, EBML_MAX_SIZE_LENGTH, 8);
1298 elem(&mut ebml, DOC_TYPE, b"matroska");
1299 uint(&mut ebml, DOC_TYPE_VERSION, 4);
1300 uint(&mut ebml, DOC_TYPE_READ_VERSION, 2);
1301 elem(&mut head, EBML, &ebml);
1302
1303 // The segment's size is only known at `finish`; it is reserved at the
1304 // widest encoding (8 bytes) so patching it never moves a byte after it.
1305 put_id(&mut head, SEGMENT);
1306 let segment_size_at = head.len() as u64;
1307 head.extend_from_slice(&[0x01, 0, 0, 0, 0, 0, 0, 0]);
1308
1309 let mut info = Vec::new();
1310 uint(&mut info, TIMESTAMP_SCALE, TIMESTAMP_SCALE_NS);
1311 elem(&mut info, MUXING_APP, b"edith");
1312 elem(&mut info, WRITING_APP, b"edith");
1313 put_id(&mut info, DURATION);
1314 put_size(&mut info, 8);
1315 // Where those eight bytes will land once `Info` is written into `head`,
1316 // which is what `finish` seeks back to.
1317 let duration_at = (head.len() + elem_head_len(INFO, info.len() + 8) + info.len()) as u64;
1318 info.extend_from_slice(&0f64.to_be_bytes());
1319 elem(&mut head, INFO, &info);
1320
1321 let mut entry = Vec::new();
1322 uint(&mut entry, TRACK_NUMBER, 1);
1323 uint(&mut entry, TRACK_UID, 1);
1324 uint(&mut entry, TRACK_TYPE, 1); // video
1325 uint(&mut entry, FLAG_LACING, 0);
1326 elem(&mut entry, CODEC_ID, codec_id);
1327 elem(&mut entry, CODEC_PRIVATE, codec_private);
1328 uint(&mut entry, DEFAULT_DURATION, frame_ns);
1329 let mut dims = Vec::new();
1330 uint(&mut dims, PIXEL_WIDTH, u64::from(width));
1331 uint(&mut dims, PIXEL_HEIGHT, u64::from(height));
1332 // The copied samples' aspect, where it is not square: the same three
1333 // elements this engine's own reader asks a Matroska track for, as a
1334 // sample aspect ratio (unit 4). A square copy writes none of them --
1335 // exactly the header every square-pixel copy wrote before this.
1336 if !pixel_aspect.is_square() {
1337 uint(&mut dims, DISPLAY_WIDTH, u64::from(pixel_aspect.h));
1338 uint(&mut dims, DISPLAY_HEIGHT, u64::from(pixel_aspect.v));
1339 uint(&mut dims, DISPLAY_UNIT, DISPLAY_UNIT_SAR);
1340 }
1341 // What the samples in those pixels mean. Written rather than left to a
1342 // reader's own 720-line guess -- the guess is right for an encoded file
1343 // (the export remaps every clip into exactly that space) but a remuxer
1344 // or a scaler downstream has no reason to make it, and an untagged file
1345 // is how a 601 source ends up displayed as 709. A *copied* track states
1346 // its source's space instead, which is the one its samples are in.
1347 let (primaries, transfer, matrix) = colour.codes();
1348 let mut tags = Vec::new();
1349 uint(&mut tags, MATRIX_COEFFICIENTS, u64::from(matrix));
1350 // Matroska says the range as a code, not a flag: 1 limited, 2 full.
1351 uint(&mut tags, RANGE, 1 + u64::from(colour.full_range));
1352 uint(&mut tags, TRANSFER_CHARACTERISTICS, u64::from(transfer));
1353 uint(&mut tags, PRIMARIES, u64::from(primaries));
1354 elem(&mut dims, COLOUR, &tags);
1355 elem(&mut entry, VIDEO, &dims);
1356 let mut tracks = Vec::new();
1357 elem(&mut tracks, TRACK_ENTRY, &entry);
1358 if let Some((audio, _)) = &audio {
1359 let entry = match audio.opus_pre_skip {
1360 Some(pre_skip) => opus_track_entry(audio, pre_skip)?,
1361 None => aac_track_entry(audio)?,
1362 };
1363 elem(&mut tracks, TRACK_ENTRY, &entry);
1364 }
1365 // Declared even where the audio track is not: the picture is always 1
1366 // and the sound always 2, so the text starts at 3 whether or not there
1367 // is any sound -- and each further track is the next number up, which is
1368 // the only counting in the file.
1369 for (i, subs) in subs.iter().enumerate() {
1370 let track_no = SUB_TRACK_FIRST + i as u8;
1371 elem(
1372 &mut tracks,
1373 TRACK_ENTRY,
1374 &subtitle_track_entry(&subs.language, &subs.name, track_no),
1375 );
1376 }
1377 elem(&mut head, TRACKS, &tracks);
1378
1379 let mut file = File::create(path)?;
1380 file.write_all(&head)?;
1381 Ok(Self {
1382 file,
1383 frame_ns,
1384 segment_size_at,
1385 duration_at,
1386 cluster: Vec::new(),
1387 cluster_ts: 0,
1388 frames: 0,
1389 last_ts: 0,
1390 audio: audio.map(|(params, packets)| MkvAudio {
1391 packets,
1392 next: 0,
1393 samples: 0,
1394 sample_rate: params.sample_rate.max(1),
1395 }),
1396 subs: subs
1397 .into_iter()
1398 .enumerate()
1399 .map(|(i, subs)| MkvSubs {
1400 cues: subs.cues,
1401 next: 0,
1402 track_no: SUB_TRACK_FIRST + i as u8,
1403 })
1404 .collect(),
1405 })
1406 }
1407
1408 /// One coded picture: a whole AV1 temporal unit, in the low-overhead OBU
1409 /// format the demuxer hands back. `key` marks a block a decoder may be
1410 /// started from -- said by the encoder rather than guessed at here, and a
1411 /// keyframe is where a new cluster opens, so every seek target is one.
1412 pub fn write_frame(&mut self, obus: &[u8], key: bool) -> crate::Result<()> {
1413 if obus.is_empty() {
1414 return Err("an empty AV1 temporal unit".into());
1415 }
1416 let ts = (self.frames * self.frame_ns + TIMESTAMP_SCALE_NS / 2) as i64
1417 / TIMESTAMP_SCALE_NS as i64;
1418 self.put(obus, key, ts)
1419 }
1420
1421 /// One coded picture *copied* out of another file, shown at `ts_ns` on this
1422 /// file's clock rather than at the next frame of a counter.
1423 ///
1424 /// A copy has to be timed by the source's own timestamps and not by the
1425 /// order the blocks arrive in: a stream with B-frames is stored in decode
1426 /// order, so its timestamps step backwards over a group of pictures, and
1427 /// re-timing those blocks one frame apart would play the group in the order
1428 /// it was coded in. Matroska times every block in presentation and the
1429 /// relative timestamp in a block header is signed, so what a copy writes
1430 /// here is exactly what its source said -- and a step back wider than that
1431 /// signed field reaches opens a cluster of its own rather than being
1432 /// truncated into an instant nobody asked for ([`Self::cluster_holds`]).
1433 pub fn write_block(&mut self, payload: &[u8], key: bool, ts_ns: i64) -> crate::Result<()> {
1434 if payload.is_empty() {
1435 return Err("an empty coded block".into());
1436 }
1437 let ts = (ts_ns + TIMESTAMP_SCALE_NS as i64 / 2) / TIMESTAMP_SCALE_NS as i64;
1438 self.put(payload, key, ts)
1439 }
1440
1441 /// One block into the cluster it belongs in, whatever timed it.
1442 fn put(&mut self, payload: &[u8], key: bool, ts: i64) -> crate::Result<()> {
1443 // A new cluster at every keyframe -- a seek lands on one, so a cluster
1444 // is a whole GOP -- and at the two limits a cluster has whatever the
1445 // encoder keys: what it may weigh, and how far a 16-bit relative
1446 // timestamp reaches, either way.
1447 if self.cluster.is_empty()
1448 || key
1449 || self.cluster.len() >= CLUSTER_BYTES
1450 || !self.cluster_holds(ts)
1451 {
1452 self.open_cluster(ts)?;
1453 }
1454 // The sound this picture plays under goes in first, into the cluster the
1455 // picture opened: a player reads the two together. The cue over it with
1456 // them, for the same reason.
1457 self.drain_audio(ts)?;
1458 self.drain_subs(ts)?;
1459 // ...unless a track lagged this picture by more than a cluster reaches
1460 // and opened one of its own behind it, in which case the picture gets a
1461 // cluster named after its own instant rather than a distance its block
1462 // header cannot state.
1463 if !self.cluster_holds(ts) {
1464 self.open_cluster(ts)?;
1465 }
1466 self.block(1, ts, key, payload)?;
1467 self.frames += 1;
1468 self.last_ts = self.last_ts.max(ts);
1469 Ok(())
1470 }
1471
1472 /// Whether the open cluster can hold a block at `ts`. A cluster is buffered
1473 /// whole and its blocks are timed *relative* to it, in a signed 16-bit
1474 /// millisecond field ([`CLUSTER_MS`]), so a block further from the cluster's
1475 /// own timestamp than that -- in **either** direction -- needs a cluster of
1476 /// its own. The backwards one is the side a copy really takes: a stream with
1477 /// B-frames is stored in decode order, so its presentation times step back
1478 /// over a group of pictures.
1479 ///
1480 /// This is what keeps every distance written inside the field, which is what
1481 /// makes [`Self::relative_ms`]'s checked cast a guard of last resort rather
1482 /// than the place a real block lands.
1483 fn cluster_holds(&self, ts: i64) -> bool {
1484 !self.cluster.is_empty() && (ts - self.cluster_ts).unsigned_abs() < CLUSTER_MS as u64
1485 }
1486
1487 /// Opens a cluster stating `ts`, closing whatever was open: a cluster's size
1488 /// is a header field, so it is written whole or not at all.
1489 fn open_cluster(&mut self, ts: i64) -> crate::Result<()> {
1490 self.flush()?;
1491 self.cluster_ts = ts;
1492 uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64);
1493 Ok(())
1494 }
1495
1496 /// Every audio packet whose timestamp has been reached, into the current
1497 /// cluster. `i64::MAX` at [`finish`](MkvMuxer::finish) drains what is left --
1498 /// the sound of a timeline can outlast its last picture by a packet.
1499 fn drain_audio(&mut self, until: i64) -> crate::Result<()> {
1500 loop {
1501 let Some(audio) = &mut self.audio else {
1502 return Ok(());
1503 };
1504 let Some(packet) = audio.packets.get_mut(audio.next) else {
1505 return Ok(());
1506 };
1507 // The packet's own start, in whole milliseconds: every AAC-LC packet
1508 // states its length, so a track of them is counted rather than
1509 // assumed to be 1024 frames each.
1510 let rate = i64::from(audio.sample_rate);
1511 let ts = (audio.samples as i64 * 1000 + rate / 2) / rate;
1512 if ts > until {
1513 return Ok(());
1514 }
1515 // Taken, not copied: the packet is written once and the track can be
1516 // hundreds of megabytes.
1517 let bytes = std::mem::take(&mut packet.bytes);
1518 audio.samples += u64::from(packet.samples);
1519 audio.next += 1;
1520 // A cluster of its own where the sound has run further from the open
1521 // one than a 16-bit relative timestamp reaches, either way.
1522 if !self.cluster_holds(ts) {
1523 self.open_cluster(ts)?;
1524 }
1525 self.block(2, ts, true, &bytes)?;
1526 }
1527 }
1528
1529 /// Every cue that has come up by `until`, into the current cluster --
1530 /// [`drain_audio`](MkvMuxer::drain_audio)'s twin, and `i64::MAX` at
1531 /// [`finish`](MkvMuxer::finish) writes what is left: a cue may still be on
1532 /// screen over the last picture, and one written nowhere is one a player
1533 /// never shows. Every track in turn, in the order they were declared.
1534 fn drain_subs(&mut self, until: i64) -> crate::Result<()> {
1535 for track in 0..self.subs.len() {
1536 loop {
1537 let subs = &mut self.subs[track];
1538 let Some(cue) = subs.cues.get_mut(subs.next) else {
1539 break;
1540 };
1541 // Milliseconds, the tick this file is written in: a cue is read
1542 // for a second or more and no eye finds the half a tick it
1543 // rounds by.
1544 let ts = (cue.start_us + 500) / 1_000;
1545 if ts > until {
1546 break;
1547 }
1548 // A cue that says it ends before it starts stays up for one tick
1549 // rather than for a duration a reader would take as unsigned.
1550 let ms = ((cue.end_us - cue.start_us + 500) / 1_000).max(1) as u64;
1551 let text = std::mem::take(&mut cue.text);
1552 subs.next += 1;
1553 let track_no = subs.track_no;
1554 // A cluster of its own where the text has run further from the
1555 // open one than a 16-bit relative timestamp reaches, either way,
1556 // exactly as the sound's drain does.
1557 if !self.cluster_holds(ts) {
1558 self.open_cluster(ts)?;
1559 }
1560 self.block_group(track_no, ts, ms, text.as_bytes())?;
1561 }
1562 }
1563 Ok(())
1564 }
1565
1566 /// One `SimpleBlock` of `track`, timed against the open cluster. Every AAC
1567 /// packet is a keyframe; a picture is one when the encoder said so.
1568 fn block(&mut self, track: u8, ts: i64, key: bool, payload: &[u8]) -> crate::Result<()> {
1569 let relative = self.relative_ms(ts)?;
1570 let mut block = Vec::with_capacity(payload.len() + 4);
1571 block.push(0x80 | track); // the track number as a one-byte EBML integer
1572 block.extend_from_slice(&relative);
1573 block.push(if key { 0x80 } else { 0 });
1574 block.extend_from_slice(payload);
1575 elem(&mut self.cluster, SIMPLE_BLOCK, &block);
1576 Ok(())
1577 }
1578
1579 /// A block's own timestamp less its cluster's, in the signed 16-bit
1580 /// milliseconds the block header carries.
1581 ///
1582 /// Checked and not cast: a distance that does not fit is a block at an
1583 /// instant nobody asked for -- `as i16` of a step back wider than the field
1584 /// lands as a *positive* offset, 65.536 s past its cluster -- and the error
1585 /// names the distance instead. Both callers keep the open cluster within
1586 /// [`CLUSTER_MS`] of every block they write ([`Self::cluster_holds`]), so
1587 /// this is the guard of last resort rather than a case a file reaches.
1588 fn relative_ms(&self, ts: i64) -> crate::Result<[u8; 2]> {
1589 let ms = ts - self.cluster_ts;
1590 i16::try_from(ms).map(i16::to_be_bytes).map_err(|_| {
1591 format!(
1592 "a block {ms} ms from its cluster's timestamp does not fit the 16-bit \
1593 relative field"
1594 )
1595 .into()
1596 })
1597 }
1598
1599 /// One `BlockGroup`: a `Block` and the `BlockDuration` beside it. That pair
1600 /// is how a cue says when it goes away -- a `SimpleBlock` has nowhere to put
1601 /// a duration, and a subtitle without one stays up until whatever a player
1602 /// decides, which is what a subtitle must never do.
1603 fn block_group(
1604 &mut self,
1605 track: u8,
1606 ts: i64,
1607 duration_ms: u64,
1608 payload: &[u8],
1609 ) -> crate::Result<()> {
1610 let relative = self.relative_ms(ts)?;
1611 let mut block = Vec::with_capacity(payload.len() + 4);
1612 block.push(0x80 | track); // the track number as a one-byte EBML integer
1613 block.extend_from_slice(&relative);
1614 // No flags a text block can carry: not lacing, and "keyframe" is a
1615 // `SimpleBlock` field that a plain `Block` does not have at all.
1616 block.push(0);
1617 block.extend_from_slice(payload);
1618 let mut group = Vec::new();
1619 elem(&mut group, BLOCK, &block);
1620 uint(&mut group, BLOCK_DURATION, duration_ms);
1621 elem(&mut self.cluster, BLOCK_GROUP, &group);
1622 Ok(())
1623 }
1624
1625 fn flush(&mut self) -> crate::Result<()> {
1626 if self.cluster.is_empty() {
1627 return Ok(());
1628 }
1629 let mut head = Vec::new();
1630 put_id(&mut head, CLUSTER);
1631 put_size(&mut head, self.cluster.len() as u64);
1632 self.file.write_all(&head)?;
1633 self.file.write_all(&self.cluster)?;
1634 self.cluster.clear();
1635 Ok(())
1636 }
1637
1638 /// Closes the last cluster and patches the two fields that could not be
1639 /// known while writing: the segment's size and the presentation duration.
1640 pub fn finish(mut self) -> crate::Result<()> {
1641 // Whatever sound outlasts the last picture, before the last cluster is
1642 // closed: a track cut short here is a file that goes silent at the end.
1643 self.drain_audio(i64::MAX)?;
1644 self.drain_subs(i64::MAX)?;
1645 self.flush()?;
1646 if self.frames == 0 {
1647 return Err("no frames were written to the Matroska file".into());
1648 }
1649 let end = self.file.stream_position()?;
1650 let body = end - (self.segment_size_at + 8);
1651 // The reserved 8-byte size: marker bit in the top byte, value under it.
1652 let size = (1u64 << 56) | body;
1653 self.file.seek(SeekFrom::Start(self.segment_size_at))?;
1654 self.file.write_all(&size.to_be_bytes())?;
1655 // One frame past the last picture shown, which is where the file really
1656 // ends: counting the frames instead would cut a copied track short by
1657 // however many pictures a cut left the one before it on screen for.
1658 let ms = (self.frames as f64 * self.frame_ns as f64 / TIMESTAMP_SCALE_NS as f64)
1659 .max(self.last_ts as f64 + self.frame_ns as f64 / TIMESTAMP_SCALE_NS as f64);
1660 self.file.seek(SeekFrom::Start(self.duration_at))?;
1661 self.file.write_all(&ms.to_be_bytes())?;
1662 self.file.flush()?;
1663 Ok(())
1664 }
1665}
1666
1667/// The `TrackEntry` of the AAC track: `A_AAC`, whose `CodecPrivate` is the
1668/// two-byte `AudioSpecificConfig` an mp4 states inside its `esds` -- object type
1669/// 2 (AAC-LC), the sample rate as its index into the AAC table, and the channel
1670/// configuration. symphonia's `mkv` reader hands exactly these bytes to its AAC
1671/// decoder, which is how a file written here reads back here.
1672///
1673/// `CodecDelay` is one packet: the first AAC access unit of both paths that
1674/// reach this -- a copy, whose head packet is the source's priming, and this
1675/// project's own encoder, whose delay is one 1024-frame block -- is that delay,
1676/// and an mp4 reader drops it by convention where Matroska has to be told in
1677/// nanoseconds.
1678fn aac_track_entry(audio: &AudioParams) -> crate::Result<Vec<u8>> {
1679 let rate = audio.sample_rate;
1680 if rate == 0 || audio.chan_conf == 0 {
1681 return Err(format!(
1682 "an AAC track at {rate} Hz with {} channels",
1683 audio.chan_conf
1684 )
1685 .into());
1686 }
1687 let mut entry = Vec::new();
1688 uint(&mut entry, TRACK_NUMBER, 2);
1689 uint(&mut entry, TRACK_UID, 2);
1690 uint(&mut entry, TRACK_TYPE, 2); // audio
1691 uint(&mut entry, FLAG_LACING, 0);
1692 elem(&mut entry, CODEC_ID, b"A_AAC");
1693 // 5 bits object type, 4 bits sample rate index, 4 bits channel config, and
1694 // three zero bits to the byte -- the whole of an AAC-LC AudioSpecificConfig.
1695 let asc = (2u16 << 11)
1696 | (u16::from(audio.freq_index & 0xF) << 7)
1697 | (u16::from(audio.chan_conf & 0xF) << 3);
1698 elem(&mut entry, CODEC_PRIVATE, &asc.to_be_bytes());
1699 uint(
1700 &mut entry,
1701 CODEC_DELAY,
1702 u64::from(AAC_PACKET_SAMPLES) * 1_000_000_000 / u64::from(rate),
1703 );
1704 let mut audio_elem = Vec::new();
1705 put_id(&mut audio_elem, SAMPLING_FREQUENCY);
1706 put_size(&mut audio_elem, 8);
1707 audio_elem.extend_from_slice(&f64::from(rate).to_be_bytes());
1708 uint(&mut audio_elem, CHANNELS, u64::from(audio.chan_conf));
1709 elem(&mut entry, AUDIO, &audio_elem);
1710 Ok(entry)
1711}
1712
1713/// The same track when the sound is Opus: `A_OPUS`, whose `CodecPrivate` is the
1714/// 19-byte `OpusHead` identification header of RFC 7845 §5.1 -- the very bytes
1715/// an Ogg Opus file opens with, which is why one writer serves both containers
1716/// and why this project's own reader configures itself from it unchanged
1717/// (`audio::opus_pre_skip` and `audio::opus_layout` parse exactly this).
1718///
1719/// Mapping family 0: mono or stereo, no channel-mapping table, which is the only
1720/// shape [`crate::export::encode_opus`] writes. The rate field is what the
1721/// *input* was, not what the stream is coded at -- every Opus decoder runs at
1722/// 48 kHz whatever it says -- and the output gain is 0 because the mix is
1723/// already at the level the timeline asked for.
1724///
1725/// Two elements no AAC track needs, and both are the difference between a file
1726/// that plays in sync and one that does not:
1727/// * `CodecDelay`, the pre-skip in nanoseconds. Matroska times an Opus block for
1728/// the *audible* stream while the decoder hands back the pre-skip in front of
1729/// it, so a reader that ignores this starts 2.5 ms early -- measured the other
1730/// way round on a real film remux (`audio::Track::samples_at`).
1731/// * `SeekPreRoll`, fixed at 80 ms for Opus by the Matroska spec: how much has
1732/// to be decoded and thrown away before a seek target for the decoder to be
1733/// warm. It is a constant of the codec, not of the file.
1734fn opus_track_entry(audio: &AudioParams, pre_skip: u16) -> crate::Result<Vec<u8>> {
1735 let rate = audio.sample_rate;
1736 if rate == 0 || !(1..=2).contains(&audio.chan_conf) {
1737 return Err(format!(
1738 "an Opus track at {rate} Hz with {} channels",
1739 audio.chan_conf
1740 )
1741 .into());
1742 }
1743 let mut head = Vec::with_capacity(19);
1744 head.extend_from_slice(b"OpusHead");
1745 head.push(1); // version
1746 head.push(audio.chan_conf);
1747 head.extend_from_slice(&pre_skip.to_le_bytes());
1748 head.extend_from_slice(&rate.to_le_bytes());
1749 head.extend_from_slice(&0i16.to_le_bytes()); // output gain
1750 head.push(0); // mapping family
1751
1752 let mut entry = Vec::new();
1753 uint(&mut entry, TRACK_NUMBER, 2);
1754 uint(&mut entry, TRACK_UID, 2);
1755 uint(&mut entry, TRACK_TYPE, 2); // audio
1756 uint(&mut entry, FLAG_LACING, 0);
1757 elem(&mut entry, CODEC_ID, b"A_OPUS");
1758 elem(&mut entry, CODEC_PRIVATE, &head);
1759 uint(
1760 &mut entry,
1761 CODEC_DELAY,
1762 u64::from(pre_skip) * 1_000_000_000 / u64::from(rate),
1763 );
1764 uint(&mut entry, SEEK_PRE_ROLL, 80_000_000);
1765 let mut audio_elem = Vec::new();
1766 put_id(&mut audio_elem, SAMPLING_FREQUENCY);
1767 put_size(&mut audio_elem, 8);
1768 audio_elem.extend_from_slice(&f64::from(rate).to_be_bytes());
1769 uint(&mut audio_elem, CHANNELS, u64::from(audio.chan_conf));
1770 elem(&mut entry, AUDIO, &audio_elem);
1771 Ok(entry)
1772}
1773
1774/// Which track the *first* subtitle block names, the picture's 1 and the sound's
1775/// 2 being fixed: a file with no audio track still writes its first text track
1776/// on 3, so nothing has to count the tracks before it to read a block. Each
1777/// further subtitle track is the next number up.
1778const SUB_TRACK_FIRST: u8 = 3;
1779
1780/// How many subtitle tracks one file may carry. A block writes its track number
1781/// as a one-byte EBML integer (`0x80 | track`, [`MkvMuxer::block`]), and 127 is
1782/// one number too far: its byte is `0xFF`, the all-ones variable-length integer
1783/// EBML spells *unknown* with, which this project's own reader hands back as
1784/// `u64::MAX` (`demux`'s `vint`) -- so track 127's blocks would match no track,
1785/// its cues would vanish on the way back in, and the file would be one edith
1786/// wrote and cannot read. The numbers therefore run `3..=126` and the count is
1787/// what is left of them -- derived from the encoding, so it cannot drift from
1788/// it. A file asking for more is refused by name in [`MkvMuxer::open`] rather
1789/// than written with a byte that means another track, or none.
1790pub const MAX_SUB_TRACKS: usize = 0x7F - SUB_TRACK_FIRST as usize;
1791
1792/// The `TrackEntry` of the subtitle track: type 0x11 (subtitles) and
1793/// `S_TEXT/UTF8`, whose blocks are the cue's own UTF-8 text and whose timing is
1794/// the block's -- the codec every player draws and the one this project's own
1795/// reader parses back (`subtitle::cues_of`).
1796///
1797/// The two names a track has are written as the two fields Matroska has for
1798/// them: `Language` is what a player's subtitle menu offers and what a "play
1799/// French" setting matches on, `Name` is the title beside it (`Signs`). Both
1800/// where the source has both -- a track carrying only a name is an *English*
1801/// track to every reader, that being the spec's default, which is how a
1802/// multi-language film used to export as several English ones. Either is left
1803/// out where it is empty, and [`crate::subtitle::of_matroska`] reads exactly
1804/// this back, so a track exported and re-imported keeps what it had.
1805fn subtitle_track_entry(language: &str, name: &str, track_no: u8) -> Vec<u8> {
1806 let mut entry = Vec::new();
1807 uint(&mut entry, TRACK_NUMBER, u64::from(track_no));
1808 uint(&mut entry, TRACK_UID, u64::from(track_no));
1809 uint(&mut entry, TRACK_TYPE, 0x11);
1810 uint(&mut entry, FLAG_LACING, 0);
1811 elem(&mut entry, CODEC_ID, b"S_TEXT/UTF8");
1812 if !language.is_empty() {
1813 elem(&mut entry, TRACK_LANGUAGE, language.as_bytes());
1814 }
1815 if !name.is_empty() {
1816 elem(&mut entry, TRACK_NAME, name.as_bytes());
1817 }
1818 entry
1819}
1820
1821/// The sequence header OBU of a coded temporal unit, for the track's
1822/// `CodecPrivate`. `None` when the unit carries none, which the first keyframe
1823/// of a stream never may -- no decoder can start without it.
1824pub fn av1_sequence_header(obus: &[u8]) -> Option<&[u8]> {
1825 let mut at = 0;
1826 while at < obus.len() {
1827 let header = obus[at];
1828 // OBU header: type in bits 6..3, then the extension and size flags.
1829 let kind = (header >> 3) & 0xF;
1830 let mut len = 1 + usize::from(header & 0x4 != 0);
1831 // Only the low-overhead format is written or read here: an OBU with no
1832 // size field runs to the end of the unit, which makes the rest of it
1833 // unwalkable, so it is not something to guess at.
1834 if header & 0x2 == 0 {
1835 return None;
1836 }
1837 let (size, size_len) = leb128(obus.get(at + len..)?)?;
1838 len += size_len;
1839 let body = obus.get(at + len..at + len + size)?;
1840 if kind == 1 {
1841 return Some(&obus[at..at + len + body.len()]);
1842 }
1843 at += len + size;
1844 }
1845 None
1846}
1847
1848/// An unsigned LEB128 as AV1 writes its OBU sizes: `(value, bytes read)`.
1849fn leb128(buf: &[u8]) -> Option<(usize, usize)> {
1850 let mut value = 0usize;
1851 for (i, &byte) in buf.iter().take(8).enumerate() {
1852 value |= usize::from(byte & 0x7F) << (i * 7);
1853 if byte & 0x80 == 0 {
1854 return Some((value, i + 1));
1855 }
1856 }
1857 None
1858}
1859
1860/// An element id, written as the bytes it is spelled with -- the leading zeros
1861/// of the constant are not part of it.
1862fn put_id(out: &mut Vec<u8>, id: u32) {
1863 let bytes = id.to_be_bytes();
1864 let skip = bytes.iter().take_while(|&&b| b == 0).count();
1865 out.extend_from_slice(&bytes[skip..]);
1866}
1867
1868/// An element size as an EBML variable-length integer, in the fewest bytes that
1869/// hold it. A value of all ones means *unknown* length, so a size that would
1870/// land on one takes a byte more.
1871fn put_size(out: &mut Vec<u8>, size: u64) {
1872 let mut len = 1;
1873 while len < 8 && size >= (1u64 << (7 * len)) - 1 {
1874 len += 1;
1875 }
1876 let value = (1u64 << (7 * len)) | size;
1877 out.extend_from_slice(&value.to_be_bytes()[8 - len..]);
1878}
1879
1880fn elem(out: &mut Vec<u8>, id: u32, payload: &[u8]) {
1881 put_id(out, id);
1882 put_size(out, payload.len() as u64);
1883 out.extend_from_slice(payload);
1884}
1885
1886/// An unsigned integer element, big-endian in as few bytes as it takes (one at
1887/// the least: a zero is a byte, not an absence).
1888fn uint(out: &mut Vec<u8>, id: u32, value: u64) {
1889 let bytes = value.to_be_bytes();
1890 let skip = bytes.iter().take_while(|&&b| b == 0).count().min(7);
1891 elem(out, id, &bytes[skip..]);
1892}
1893
1894/// How many bytes an element's id and size take, which is what an offset inside
1895/// a payload has to be moved by to become an offset in the file.
1896fn elem_head_len(id: u32, payload: usize) -> usize {
1897 let (mut head, mut size) = (Vec::new(), Vec::new());
1898 put_id(&mut head, id);
1899 put_size(&mut size, payload as u64);
1900 head.len() + size.len()
1901}
1902
1903/// `(timescale, ticks per frame)` for `fps`, chosen so one frame is a *whole*
1904/// number of ticks: 90 kHz wherever it divides exactly (every integer rate, so
1905/// those exports stay byte for byte what they were), and `round(fps * 1001)`
1906/// over [`NTSC_TICKS`] otherwise, which is exact for the whole `n/1001` family.
1907/// A fixed 90 kHz clock leaves 24000/1001 a quarter tick short *per frame* --
1908/// half a second of drift against the audio track by the end of a two-hour
1909/// export, which is this bug's own truncation reborn at the writing end.
1910pub(crate) fn frame_timing(fps: f64) -> crate::Result<(u32, u32)> {
1911 let ticks = f64::from(VIDEO_TIMESCALE) / fps;
1912 if (ticks - ticks.round()).abs() < 1e-9 && (1.0..=f64::from(u32::MAX)).contains(&ticks.round())
1913 {
1914 return Ok((VIDEO_TIMESCALE, ticks.round() as u32));
1915 }
1916 let timescale = (fps * f64::from(NTSC_TICKS)).round();
1917 if !(1.0..=f64::from(u32::MAX)).contains(&timescale) {
1918 return Err(format!("frame rate {fps} has no usable timescale").into());
1919 }
1920 Ok((timescale as u32, NTSC_TICKS))
1921}
1922
1923/// SPS and PPS of an Annex-B access unit, for the `avcC` box. `None` when the
1924/// unit does not carry both, which the first exported unit always must.
1925pub fn parameter_sets(annex_b: &[u8]) -> Option<(&[u8], &[u8])> {
1926 let nals = split_annex_b(annex_b);
1927 let sps = nals.iter().find(|n| nal_type(n) == NAL_SPS)?;
1928 let pps = nals.iter().find(|n| nal_type(n) == NAL_PPS)?;
1929 Some((sps, pps))
1930}
1931
1932/// The `HEVCDecoderConfigurationRecord` an HEVC track declares, built out of the
1933/// parameter sets the encoder put in its first access unit -- the exact record
1934/// `demux::parse_hvcc` reads back, which is what makes an export of this
1935/// project's own something it can re-open.
1936///
1937/// The 22 fixed bytes before the arrays: the 12-byte `profile_tier_level` is
1938/// copied straight out of the SPS (its first 12 bytes after the two-byte NAL
1939/// header and the four `sps_video_parameter_set_id`/`sps_max_sub_layers_minus1`
1940/// /`sps_temporal_id_nesting_flag` bits -- §7.3.2.2 puts the PTL there and the
1941/// hvcC header states the same fields in the same order), and the rest is what
1942/// this encoder is: 4:2:0, 8-bit, one temporal layer, 4-byte NAL lengths. Only
1943/// the *arrays* are read by anything here, but a record whose header lied about
1944/// the profile would be a file `ffprobe` disagrees with.
1945///
1946/// `None` where the unit carries no VPS, SPS or PPS -- the first coded intra AU
1947/// always carries all three.
1948pub fn hvcc_record(annex_b: &[u8]) -> Option<Vec<u8>> {
1949 let nals = split_annex_b(annex_b);
1950 let of = |kind: u8| nals.iter().copied().find(|n| hevc_nal_type(n) == kind);
1951 let (vps, sps, pps) = (of(HEVC_VPS)?, of(HEVC_SPS)?, of(HEVC_PPS)?);
1952 // The SPS as a decoder reads it: the emulation-prevention bytes the encoder
1953 // escaped it with are not part of the syntax, and a run of zeros in the
1954 // constraint flags is exactly where one lands.
1955 let rbsp = unescape(sps.get(2..)?);
1956 let mut rec = vec![1u8]; // configurationVersion
1957 rec.extend_from_slice(rbsp.get(1..13)?); // profile_tier_level, verbatim
1958 rec.extend_from_slice(&[0xF0, 0x00]); // min_spatial_segmentation_idc = 0
1959 rec.push(0xFC); // parallelismType = 0 (unknown)
1960 rec.push(0xFC | 1); // chroma_format_idc = 1 (4:2:0)
1961 rec.push(0xF8); // bit_depth_luma_minus8 = 0
1962 rec.push(0xF8); // bit_depth_chroma_minus8 = 0
1963 rec.extend_from_slice(&0u16.to_be_bytes()); // avgFrameRate: unstated
1964 // constantFrameRate 0, numTemporalLayers 1, temporalIdNested 1,
1965 // lengthSizeMinusOne 3 -- the same 4-byte prefix `annex_b_to_hvcc` writes.
1966 rec.push(0b00_001_1_11);
1967 rec.push(3); // numOfArrays
1968 for (kind, nal) in [(HEVC_VPS, vps), (HEVC_SPS, sps), (HEVC_PPS, pps)] {
1969 rec.push(0x80 | kind); // array_completeness = 1, NAL_unit_type
1970 rec.extend_from_slice(&1u16.to_be_bytes()); // numNalus
1971 rec.extend_from_slice(&(nal.len() as u16).to_be_bytes());
1972 rec.extend_from_slice(nal);
1973 }
1974 Some(rec)
1975}
1976
1977/// One HEVC access unit as a sample of both containers: 4-byte length prefixes,
1978/// parameter sets dropped (they are in the `hvcC`, which is what `hvc1` and a
1979/// Matroska `CodecPrivate` both promise). `None` where the unit holds no coded
1980/// slice at all.
1981pub(crate) fn annex_b_to_hvcc(annex_b: &[u8]) -> Option<Vec<u8>> {
1982 let mut out = Vec::with_capacity(annex_b.len());
1983 for nal in split_annex_b(annex_b) {
1984 // 32 VPS, 33 SPS, 34 PPS, 35 AUD -- and everything from 40 up is
1985 // non-VCL padding no decoder needs to start.
1986 if matches!(hevc_nal_type(nal), HEVC_VPS | HEVC_SPS | HEVC_PPS | 35) {
1987 continue;
1988 }
1989 out.extend_from_slice(&(nal.len() as u32).to_be_bytes());
1990 out.extend_from_slice(nal);
1991 }
1992 (!out.is_empty()).then_some(out)
1993}
1994
1995/// §7.3.1.2 `nal_unit_type`, the six bits after the forbidden_zero_bit.
1996fn hevc_nal_type(nal: &[u8]) -> u8 {
1997 nal.first().map_or(0xFF, |b| (b >> 1) & 0x3F)
1998}
1999
2000const HEVC_VPS: u8 = 32;
2001const HEVC_SPS: u8 = 33;
2002const HEVC_PPS: u8 = 34;
2003
2004/// A coded NAL payload back to its RBSP: every `00 00 03` loses the `03`
2005/// (§7.3.1.1). Only ever asked of an SPS, which is short.
2006fn unescape(nal: &[u8]) -> Vec<u8> {
2007 let mut out = Vec::with_capacity(nal.len());
2008 for (i, &byte) in nal.iter().enumerate() {
2009 if byte == 3 && i >= 2 && nal[i - 1] == 0 && nal[i - 2] == 0 {
2010 continue;
2011 }
2012 out.push(byte);
2013 }
2014 out
2015}
2016
2017/// Whether the unit carries a coded picture (NAL types 1..=5). An encoder that
2018/// buffered instead of coding hands back an empty buffer, and one that emitted
2019/// only parameter sets has no sample to write -- both are for the caller to skip
2020/// rather than for [`Mp4Muxer::write_video_au`] to reject.
2021pub(crate) fn has_coded_slice(annex_b: &[u8]) -> bool {
2022 split_annex_b(annex_b)
2023 .iter()
2024 .any(|nal| (1..=NAL_IDR).contains(&nal_type(nal)))
2025}
2026
2027/// Exact inverse of `demux::append_annex_b`: 4-byte length prefixes (the only
2028/// prefix size `mp4` writes, avc1.rs hardcodes `length_size_minus_one = 3`).
2029/// Parameter sets, access unit delimiters and SEI are stripped — the first two
2030/// are redundant with `avcC`, SEI is not worth carrying. Returns the sample
2031/// bytes and whether the unit is an IDR.
2032fn annex_b_to_avcc(annex_b: &[u8]) -> crate::Result<(Vec<u8>, bool)> {
2033 let mut out = Vec::with_capacity(annex_b.len());
2034 let mut is_idr = false;
2035 for nal in split_annex_b(annex_b) {
2036 match nal_type(nal) {
2037 NAL_SPS | NAL_PPS | NAL_AUD | NAL_SEI => continue,
2038 NAL_IDR => is_idr = true,
2039 _ => {}
2040 }
2041 out.extend_from_slice(&(nal.len() as u32).to_be_bytes());
2042 out.extend_from_slice(nal);
2043 }
2044 if out.is_empty() {
2045 return Err("access unit has no coded slice".into());
2046 }
2047 Ok((out, is_idr))
2048}
2049
2050/// NAL payloads of an Annex-B buffer, both 3- and 4-byte start codes, trailing
2051/// zero bytes trimmed (they belong to the next start code, or are padding).
2052fn split_annex_b(src: &[u8]) -> Vec<&[u8]> {
2053 let mut nals = Vec::new();
2054 let mut start = None;
2055 let mut i = 0;
2056 while i + 2 < src.len() {
2057 if src[i] == 0 && src[i + 1] == 0 && src[i + 2] == 1 {
2058 if let Some(s) = start {
2059 push_nal(&mut nals, &src[s..i]);
2060 }
2061 i += 3;
2062 start = Some(i);
2063 } else {
2064 i += 1;
2065 }
2066 }
2067 if let Some(s) = start {
2068 push_nal(&mut nals, &src[s..]);
2069 }
2070 nals
2071}
2072
2073fn push_nal<'a>(nals: &mut Vec<&'a [u8]>, nal: &'a [u8]) {
2074 let end = nal.iter().rposition(|&b| b != 0).map_or(0, |p| p + 1);
2075 if end > 0 {
2076 nals.push(&nal[..end]);
2077 }
2078}
2079
2080fn nal_type(nal: &[u8]) -> u8 {
2081 nal[0] & 0x1F
2082}
2083
2084#[cfg(test)]
2085mod tests {
2086 use std::io::BufReader;
2087
2088 use crate::scratch::Scratch;
2089
2090 use super::*;
2091
2092 const SPS: &[u8] = &[0x67, 0x42, 0x00, 0x1E, 0xAB];
2093 const PPS: &[u8] = &[0x68, 0xCE, 0x3C, 0x80];
2094
2095 fn au(nals: &[&[u8]]) -> Vec<u8> {
2096 let mut v = Vec::new();
2097 for nal in nals {
2098 v.extend_from_slice(&[0, 0, 0, 1]);
2099 v.extend_from_slice(nal);
2100 }
2101 v
2102 }
2103
2104 fn cue(start_ms: i64, end_ms: i64, text: &str) -> crate::subtitle::Cue {
2105 crate::subtitle::Cue {
2106 start_us: start_ms * 1_000,
2107 end_us: end_ms * 1_000,
2108 text: text.into(),
2109 image: None,
2110 }
2111 }
2112
2113 /// What a `tx3g` track is made of: one sample per instant of the film and no
2114 /// hole anywhere. The gaps -- before the first cue, between two, after the
2115 /// last -- are empty samples (a 16-bit zero and nothing else), and the whole
2116 /// run adds up to the length it was asked for, which is what stops a player
2117 /// leaving the last line on screen over the rest of the film.
2118 #[test]
2119 fn a_timed_text_track_covers_every_instant() {
2120 let cues = [cue(500, 1_500, "first"), cue(4_000, 4_750, "third")];
2121 let samples = timed_text(&cues, 5_000).unwrap();
2122 let times: Vec<u32> = samples.iter().map(|(_, ms)| *ms).collect();
2123 assert_eq!(times, [500, 1_000, 2_500, 750, 250], "{samples:?}");
2124 assert_eq!(times.iter().sum::<u32>(), 5_000, "the film, end to end");
2125 let texts: Vec<&[u8]> = samples.iter().map(|(bytes, _)| &bytes[..]).collect();
2126 assert_eq!(texts[0], b"\0\0", "nothing is said until 0.5 s");
2127 assert_eq!(texts[1], b"\0\x05first");
2128 assert_eq!(texts[2], b"\0\0", "...nor between the two cues");
2129 assert_eq!(texts[3], b"\0\x05third");
2130 assert_eq!(texts[4], b"\0\0", "...nor after the last one");
2131 }
2132
2133 /// Two cues over one another: a Matroska file shows both blocks at once and
2134 /// a `tx3g` track has one sample per instant, so the overlap is *one* sample
2135 /// carrying both lines rather than one of them dropped -- the words a viewer
2136 /// saw over the picture, which is what this file is a copy of.
2137 #[test]
2138 fn overlapping_cues_are_one_sample_of_both_lines() {
2139 let cues = [cue(0, 2_000, "sign"), cue(1_000, 3_000, "dialogue")];
2140 let samples = timed_text(&cues, 3_000).unwrap();
2141 let got: Vec<(String, u32)> = samples
2142 .iter()
2143 .map(|(bytes, ms)| (String::from_utf8_lossy(&bytes[2..]).into_owned(), *ms))
2144 .collect();
2145 assert_eq!(
2146 got,
2147 [
2148 ("sign".into(), 1_000),
2149 ("sign\ndialogue".into(), 1_000),
2150 ("dialogue".into(), 1_000),
2151 ],
2152 "{samples:?}"
2153 );
2154 }
2155
2156 #[test]
2157 fn splits_both_start_code_lengths() {
2158 let src = [
2159 0, 0, 0, 1, 0x67, 0xAA, 0, 0, 1, 0x68, 0xBB, 0, 0, 0, 1, 0x65, 0xCC,
2160 ];
2161 let nals = split_annex_b(&src);
2162 assert_eq!(nals, [&[0x67, 0xAA][..], &[0x68, 0xBB], &[0x65, 0xCC]]);
2163 }
2164
2165 #[test]
2166 fn trims_trailing_zero_padding() {
2167 let src = [0, 0, 0, 1, 0x65, 0xCC, 0, 0, 0];
2168 assert_eq!(split_annex_b(&src), [&[0x65, 0xCC][..]]);
2169 }
2170
2171 #[test]
2172 fn repacks_multi_nal_unit_and_drops_parameter_sets() {
2173 let slice = [0x65, 0x88, 0x99];
2174 let (bytes, is_idr) = annex_b_to_avcc(&au(&[SPS, PPS, &[0x09, 0x10], &slice])).unwrap();
2175 assert!(is_idr);
2176 assert_eq!(
2177 bytes,
2178 [0, 0, 0, 3, 0x65, 0x88, 0x99],
2179 "4-byte prefix, slice only"
2180 );
2181
2182 let (bytes, is_idr) = annex_b_to_avcc(&au(&[&[0x41, 0x9A], &[0x41, 0x9B]])).unwrap();
2183 assert!(!is_idr, "no IDR slice in the unit");
2184 assert_eq!(bytes, [0, 0, 0, 2, 0x41, 0x9A, 0, 0, 0, 2, 0x41, 0x9B]);
2185 }
2186
2187 #[test]
2188 fn rejects_units_with_no_slice() {
2189 assert!(annex_b_to_avcc(&[]).is_err(), "empty");
2190 assert!(annex_b_to_avcc(&[0x65, 0x88]).is_err(), "no start code");
2191 assert!(
2192 annex_b_to_avcc(&au(&[SPS, PPS])).is_err(),
2193 "parameter sets only"
2194 );
2195 }
2196
2197 #[test]
2198 fn finds_parameter_sets() {
2199 assert_eq!(
2200 parameter_sets(&au(&[SPS, PPS, &[0x65, 0x11]])),
2201 Some((SPS, PPS))
2202 );
2203 assert!(
2204 parameter_sets(&au(&[SPS, &[0x65, 0x11]])).is_none(),
2205 "no PPS"
2206 );
2207 }
2208
2209 /// Every frame must be a whole number of ticks, or the video track drifts
2210 /// against the audio one over a long export -- the truncation this bug is.
2211 #[test]
2212 fn frame_timing_is_exact_at_ntsc_and_unchanged_at_integer_rates() {
2213 assert_eq!(frame_timing(30.0).unwrap(), (90_000, 3_000), "was 90k/3000");
2214 assert_eq!(frame_timing(25.0).unwrap(), (90_000, 3_600));
2215 assert_eq!(frame_timing(24_000.0 / 1001.0).unwrap(), (24_000, 1_001));
2216 // 29.97 is the one NTSC rate 90 kHz already counts exactly (3003 ticks),
2217 // so it keeps the conventional clock rather than growing its own.
2218 assert_eq!(frame_timing(30_000.0 / 1001.0).unwrap(), (90_000, 3_003));
2219 // And the pair plays back as the rate it came from, to the last bit.
2220 for fps in [30.0, 25.0, 24_000.0 / 1001.0, 30_000.0 / 1001.0, 60.0] {
2221 let (ts, ticks) = frame_timing(fps).unwrap();
2222 let played = f64::from(ts) / f64::from(ticks);
2223 assert!((played - fps).abs() < 1e-9, "{fps} writes back as {played}");
2224 }
2225 // Rate so low the 90 kHz clock cannot count it: refused, not truncated.
2226 assert!(frame_timing(1e-9).is_err());
2227 }
2228
2229 #[test]
2230 fn create_rejects_unusable_config() {
2231 let out = Scratch::file("ve_mux_never_written", "mp4");
2232 let ok = VideoParams {
2233 width: 64,
2234 height: 64,
2235 frame_rate: 30.0,
2236 sps: SPS,
2237 pps: PPS,
2238 };
2239 assert!(
2240 Mp4Muxer::create(
2241 &out,
2242 &VideoParams {
2243 sps: &SPS[..3],
2244 ..ok
2245 },
2246 None
2247 )
2248 .is_err(),
2249 "SPS too short for avcC"
2250 );
2251 assert!(Mp4Muxer::create(
2252 &out,
2253 &VideoParams {
2254 frame_rate: 0.0,
2255 ..ok
2256 },
2257 None
2258 )
2259 .is_err());
2260 assert!(
2261 Mp4Muxer::create(&out, &VideoParams { width: 0, ..ok }, None).is_err(),
2262 "zero width"
2263 );
2264 let _ = std::fs::remove_file(&out);
2265 }
2266
2267 /// Three encoder-shaped access units out, then back in through both `mp4`'s
2268 /// own reader and our `Demuxer` — the round trip is what proves the repack is
2269 /// the exact inverse of `demux::append_annex_b`.
2270 #[test]
2271 fn round_trips_through_both_readers() {
2272 let units = [
2273 au(&[SPS, PPS, &[0x65, 0x01, 0x02, 0x03]]),
2274 au(&[&[0x41, 0x04, 0x05]]),
2275 au(&[&[0x41, 0x06]]),
2276 ];
2277 let out = Scratch::file("ve_mux", "mp4");
2278
2279 let mut muxer = Mp4Muxer::create(
2280 &out,
2281 &VideoParams {
2282 width: 1280,
2283 height: 720,
2284 frame_rate: 30.0,
2285 sps: SPS,
2286 pps: PPS,
2287 },
2288 Some(&AudioParams {
2289 freq_index: 4, // 44100
2290 chan_conf: 2,
2291 sample_rate: 44_100,
2292 opus_pre_skip: None,
2293 }),
2294 )
2295 .unwrap();
2296 for unit in &units {
2297 muxer.write_video_au(unit).unwrap();
2298 }
2299 muxer.write_audio_packet(&[0x21, 0x22, 0x23]).unwrap();
2300 muxer.write_audio_packet(&[0x24, 0x25]).unwrap();
2301 muxer.finish().unwrap();
2302
2303 let file = File::open(&out).unwrap();
2304 let size = file.metadata().unwrap().len();
2305 let mut reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();
2306 let (video_id, audio_id) = (VIDEO_TRACK, AUDIO_TRACK);
2307 assert_eq!(reader.sample_count(video_id).unwrap(), 3);
2308 assert_eq!(reader.sample_count(audio_id).unwrap(), 2);
2309 {
2310 let track = &reader.tracks()[&video_id];
2311 assert_eq!((track.width(), track.height()), (1280, 720));
2312 assert_eq!(track.frame_rate().round(), 30.0);
2313 assert_eq!(track.sequence_parameter_set().unwrap(), SPS);
2314 assert_eq!(track.picture_parameter_set().unwrap(), PPS);
2315 }
2316 let first = reader.read_sample(video_id, 1).unwrap().unwrap();
2317 assert!(first.is_sync, "IDR unit is a sync sample");
2318 assert_eq!(first.duration, 3000, "90000 / 30 fps");
2319 assert_eq!(&first.bytes[..], [0, 0, 0, 4, 0x65, 0x01, 0x02, 0x03]);
2320 assert!(!reader.read_sample(video_id, 2).unwrap().unwrap().is_sync);
2321 assert_eq!(
2322 &reader.read_sample(audio_id, 1).unwrap().unwrap().bytes[..],
2323 [0x21, 0x22, 0x23],
2324 "audio packets copied verbatim"
2325 );
2326 let second = reader.read_sample(audio_id, 2).unwrap().unwrap();
2327 assert_eq!(&second.bytes[..], [0x24, 0x25], "verbatim");
2328 assert_eq!(
2329 second.duration, AAC_PACKET_SAMPLES,
2330 "every AAC-LC packet is one 1024-frame stts entry"
2331 );
2332
2333 let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).unwrap();
2334 assert_eq!(meta.frame_count, 3);
2335 assert_eq!((meta.width, meta.height), (1280, 720));
2336 assert_eq!(meta.frame_rate.round(), 30.0);
2337 for expected in &units {
2338 assert_eq!(
2339 &demuxer.next_access_unit().unwrap().unwrap(),
2340 expected,
2341 "demux returns the exact bytes that went in"
2342 );
2343 }
2344 assert!(demuxer.next_access_unit().unwrap().is_none());
2345
2346 std::fs::remove_file(&out).unwrap();
2347 }
2348
2349 /// One OBU in the low-overhead format: header byte, then a one-byte LEB128
2350 /// size, which is all a payload this short needs.
2351 fn obu(kind: u8, payload: &[u8]) -> Vec<u8> {
2352 let mut out = vec![(kind << 3) | 0x02, payload.len() as u8];
2353 out.extend_from_slice(payload);
2354 out
2355 }
2356
2357 /// An EBML size is written in the fewest bytes that hold it -- and never in
2358 /// a length whose value is all ones, which is the *unknown* size the reader
2359 /// would take for "runs to the end of its parent".
2360 #[test]
2361 fn element_sizes_never_spell_an_unknown_length() {
2362 let size = |n| {
2363 let mut out = Vec::new();
2364 put_size(&mut out, n);
2365 out
2366 };
2367 assert_eq!(size(0), [0x80]);
2368 assert_eq!(size(126), [0xFE]);
2369 assert_eq!(size(127), [0x40, 0x7F], "127 is all ones in one byte");
2370 assert_eq!(size(128), [0x40, 0x80]);
2371 assert_eq!(size(0x3FFE), [0x7F, 0xFE]);
2372 assert_eq!(size(0x3FFF), [0x20, 0x3F, 0xFF], "and again at two bytes");
2373 // Ids are their own bytes, marker and all: that is how `demux` compares
2374 // them, so a one-byte id must not grow leading zeros here.
2375 let mut id = Vec::new();
2376 put_id(&mut id, SIMPLE_BLOCK);
2377 assert_eq!(id, [0xA3]);
2378 let mut id = Vec::new();
2379 put_id(&mut id, CLUSTER);
2380 assert_eq!(id, [0x1F, 0x43, 0xB6, 0x75]);
2381 }
2382
2383 /// One second of a 440 Hz tone as AAC-LC packets, through the very encoder
2384 /// an export re-encodes with: real bitstream, so a file written with it is
2385 /// one a decoder either plays or does not.
2386 fn tone_packets(rate: u32, channels: u16) -> Vec<crate::AacPacket> {
2387 let frames = rate as usize;
2388 let mut pcm = Vec::with_capacity(frames * usize::from(channels));
2389 for i in 0..frames {
2390 let s = (i as f32 * 440.0 * std::f32::consts::TAU / rate as f32).sin() * 0.5;
2391 for _ in 0..channels {
2392 pcm.push(s);
2393 }
2394 }
2395 let mut encoder = ec_aac::AacEncoder::new(ec_aac::AacEncoderConfig::default());
2396 encoder.push_pcm(&pcm, channels, rate).unwrap();
2397 encoder.finish();
2398 let mut packets = Vec::new();
2399 while let Ok(packet) = encoder.next_packet() {
2400 packets.push(crate::AacPacket {
2401 bytes: packet.data,
2402 samples: packet.duration,
2403 });
2404 }
2405 assert!(packets.len() > 10, "a second of audio is many packets");
2406 packets
2407 }
2408
2409 /// The Matroska file carries **sound**, and this project's own reader is
2410 /// what hears it: picture and an AAC track out through the muxer, then the
2411 /// picture back through our EBML reader and the sound back through the
2412 /// symphonia `mkv` reader `audio::Track::open` uses. An AV1 export used to be
2413 /// picture alone, which is a file whose sound went missing with nobody told.
2414 #[test]
2415 fn a_matroska_file_carries_its_picture_and_its_sound() {
2416 let sequence = obu(1, &[0x11, 0x22, 0x33]);
2417 let mut key = sequence.clone();
2418 key.extend_from_slice(&obu(6, &[0xAA; 8]));
2419 let inter = obu(6, &[0xBB; 5]);
2420 let packets = tone_packets(48_000, 2);
2421 let heard: usize = packets.iter().map(|p| p.samples as usize).sum();
2422
2423 let out = Scratch::file("ve_mkv_sound", "mkv");
2424 let mut muxer = MkvMuxer::create(
2425 &out,
2426 &Av1Params {
2427 width: 640,
2428 height: 360,
2429 frame_rate: 30.0,
2430 config: av1_sequence_header(&key).unwrap(),
2431 },
2432 Some((
2433 &AudioParams {
2434 freq_index: 3, // 48000
2435 chan_conf: 2,
2436 sample_rate: 48_000,
2437 opus_pre_skip: None,
2438 },
2439 packets,
2440 )),
2441 Vec::new(),
2442 )
2443 .unwrap();
2444 // Half a second of picture under a second of sound: the tail of the
2445 // audio outlives the last frame and must still be in the file.
2446 muxer.write_frame(&key, true).unwrap();
2447 for _ in 0..14 {
2448 muxer.write_frame(&inter, false).unwrap();
2449 }
2450 muxer.finish().unwrap();
2451
2452 // The picture is untouched by the sound beside it: same units, same
2453 // count, same sequence header in front of the keyframe.
2454 let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).expect("reopen");
2455 assert_eq!(meta.frame_count, 15);
2456 assert_eq!(meta.codec, crate::demux::Codec::Av1);
2457 let first = demuxer.next_access_unit().unwrap().unwrap();
2458 assert_eq!(&first[sequence.len()..], &key[..]);
2459 assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter);
2460
2461 // ...and the sound is there, by name and then by ear.
2462 assert_eq!(
2463 crate::demux::matroska_audio_codec(&out).unwrap().as_deref(),
2464 Some("A_AAC")
2465 );
2466 let probe = crate::audio::AudioSession::probe(&out, 0)
2467 .unwrap()
2468 .expect("the file has an audio track");
2469 assert_eq!((probe.sample_rate, probe.channels), (48_000, 2));
2470 let (audio, chunks) = crate::audio::AudioSession::open(&out)
2471 .unwrap()
2472 .expect("decodes through symphonia's mkv reader");
2473 assert_eq!((audio.sample_rate, audio.channels), (48_000, 2));
2474 let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect();
2475 let frames = samples.len() / 2;
2476 assert!(
2477 frames + 1024 >= heard && frames <= heard + 2048,
2478 "{frames} frames read back of {heard} written"
2479 );
2480 let rms = (samples.iter().map(|s| s * s).sum::<f32>() / samples.len() as f32).sqrt();
2481 assert!(rms > 0.1, "the tone came back silent (rms {rms})");
2482 std::fs::remove_file(&out).unwrap();
2483 }
2484
2485 /// The seat an export encodes with, at every width the Matroska muxer can
2486 /// carry: a track it encoded comes back through the project's own decode
2487 /// door -- symphonia's reader for mono and stereo, the family's own
2488 /// `ec-aac` decoder for 5.1, which is where the decode splits -- with its
2489 /// rate and loudness intact, no delivered channel silent. A width wider
2490 /// than a pair arrives folded to stereo ([`crate::audio::downmix`] at the
2491 /// decoder's door), so the 5.1 leg asserts the pair, not the six.
2492 #[test]
2493 fn a_seat_encoded_track_round_trips_at_mono_stereo_and_five_one_widths() {
2494 let sequence = obu(1, &[0x11, 0x22, 0x33]);
2495 let mut key = sequence.clone();
2496 key.extend_from_slice(&obu(6, &[0xAA; 8]));
2497 let inter = obu(6, &[0xBB; 5]);
2498 for (channels, name) in [(1u16, "mono"), (2, "stereo"), (6, "5.1")] {
2499 let packets = tone_packets(48_000, channels);
2500 let heard: usize = packets.iter().map(|p| p.samples as usize).sum();
2501
2502 let out = Scratch::file("ve_mkv_seat_widths", "mkv");
2503 let mut muxer = MkvMuxer::create(
2504 &out,
2505 &Av1Params {
2506 width: 640,
2507 height: 360,
2508 frame_rate: 30.0,
2509 config: av1_sequence_header(&key).unwrap(),
2510 },
2511 Some((
2512 &AudioParams {
2513 freq_index: 3, // 48000
2514 chan_conf: channels as u8,
2515 sample_rate: 48_000,
2516 opus_pre_skip: None,
2517 },
2518 packets,
2519 )),
2520 Vec::new(),
2521 )
2522 .unwrap();
2523 muxer.write_frame(&key, true).unwrap();
2524 for _ in 0..14 {
2525 muxer.write_frame(&inter, false).unwrap();
2526 }
2527 muxer.finish().unwrap();
2528
2529 // What the door reports: the file's own width, folded to a pair
2530 // for anything wider -- the door's contract, not a defect.
2531 let want = channels.min(2);
2532 let probe = crate::audio::AudioSession::probe(&out, 0)
2533 .unwrap()
2534 .expect("the file has an audio track");
2535 assert_eq!(
2536 (probe.sample_rate, probe.channels),
2537 (48_000, want),
2538 "{name}: probed with the wrong shape"
2539 );
2540 let (audio, chunks) = crate::audio::AudioSession::open(&out)
2541 .unwrap()
2542 .unwrap_or_else(|| {
2543 panic!("{name}: track decodes through the project's own reader")
2544 });
2545 assert_eq!(
2546 (audio.sample_rate, audio.channels),
2547 (48_000, want),
2548 "{name}: opened with the wrong shape"
2549 );
2550 let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect();
2551 let frames = samples.len() / usize::from(want);
2552 assert!(
2553 frames + 1024 >= heard && frames <= heard + 2048,
2554 "{name}: {frames} frames read back of {heard} written"
2555 );
2556 // Every delivered channel carries the tone -- a fold that lost a
2557 // side or a dead decoder would starve one of these.
2558 for c in 0..usize::from(want) {
2559 let n = samples.len() / usize::from(want);
2560 let rms = (samples
2561 .iter()
2562 .skip(c)
2563 .step_by(usize::from(want))
2564 .take(n)
2565 .map(|s| s * s)
2566 .sum::<f32>()
2567 / n as f32)
2568 .sqrt();
2569 assert!(
2570 rms > 0.05,
2571 "{name}: channel {c} came back silent (rms {rms})"
2572 );
2573 }
2574 std::fs::remove_file(&out).unwrap();
2575 }
2576 }
2577
2578 /// The same stream in the other container: AV1 into an mp4, whose `av01`
2579 /// sample entry is written by hand, read back through our own demuxer --
2580 /// which is the only test that the patched box tree is still an mp4.
2581 #[test]
2582 fn an_av1_track_round_trips_through_an_mp4() {
2583 let sequence = obu(1, &[0x11, 0x22, 0x33]);
2584 let mut key = sequence.clone();
2585 key.extend_from_slice(&obu(6, &[0xAA; 8]));
2586 let inter = obu(6, &[0xBB; 5]);
2587 let packets = tone_packets(48_000, 2);
2588
2589 let out = Scratch::file("ve_mp4_av1", "mp4");
2590 let mut muxer = Mp4Muxer::create_av1(
2591 &out,
2592 &Av1Params {
2593 width: 640,
2594 height: 360,
2595 frame_rate: 30.0,
2596 config: av1_sequence_header(&key).unwrap(),
2597 },
2598 Some(&AudioParams {
2599 freq_index: 3,
2600 chan_conf: 2,
2601 sample_rate: 48_000,
2602 opus_pre_skip: None,
2603 }),
2604 )
2605 .unwrap();
2606 muxer.write_coded_sample(&key, true).unwrap();
2607 muxer.write_coded_sample(&inter, false).unwrap();
2608 muxer.write_coded_sample(&inter, false).unwrap();
2609 for packet in &packets {
2610 muxer.write_audio_packet(&packet.bytes).unwrap();
2611 }
2612 muxer.finish().unwrap();
2613
2614 let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).expect("reopen");
2615 assert_eq!(meta.codec, crate::demux::Codec::Av1, "read back as AV1");
2616 assert_eq!((meta.width, meta.height), (640, 360));
2617 assert!((meta.frame_rate - 30.0).abs() < 1e-6, "{}", meta.frame_rate);
2618 assert_eq!(meta.frame_count, 3);
2619 // The sequence header off `av1C` in front of the keyframe, exactly as
2620 // the Matroska reader puts the one off `CodecPrivate` there.
2621 let first = demuxer.next_access_unit().unwrap().unwrap();
2622 assert_eq!(&first[..sequence.len()], &sequence[..]);
2623 assert_eq!(&first[sequence.len()..], &key[..]);
2624 assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter);
2625 assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter);
2626 assert!(demuxer.next_access_unit().unwrap().is_none());
2627 assert_eq!(demuxer.seek_to_sync_at_or_before(2), 0, "one keyframe");
2628
2629 // ...and the audio track beside it is the mp4 path's own, unchanged by
2630 // the patch: same packets, playable through the same reader.
2631 let (audio, chunks) = crate::audio::AudioSession::open(&out)
2632 .unwrap()
2633 .expect("the mp4's AAC track");
2634 assert_eq!((audio.sample_rate, audio.channels), (48_000, 2));
2635 let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect();
2636 let rms = (samples.iter().map(|s| s * s).sum::<f32>() / samples.len() as f32).sqrt();
2637 assert!(rms > 0.1, "the tone came back silent (rms {rms})");
2638 std::fs::remove_file(&out).unwrap();
2639 }
2640
2641 /// The Matroska half of the round trip, with no encoder in it: three coded
2642 /// units out through the muxer and back in through our own demuxer, which is
2643 /// where the hand-written EBML meets the hand-written EBML reader.
2644 #[test]
2645 fn an_av1_track_round_trips_through_our_own_matroska_reader() {
2646 let sequence = obu(1, &[0x11, 0x22, 0x33]);
2647 let mut key = sequence.clone();
2648 key.extend_from_slice(&obu(6, &[0xAA; 8]));
2649 let inter = obu(6, &[0xBB; 5]);
2650
2651 let out = Scratch::file("ve_mkv", "mkv");
2652 let config = av1_sequence_header(&key).expect("the keyframe carries one");
2653 assert_eq!(config, &sequence[..], "the sequence header OBU, whole");
2654 let mut muxer = MkvMuxer::create(
2655 &out,
2656 &Av1Params {
2657 width: 640,
2658 height: 360,
2659 frame_rate: 30.0,
2660 config,
2661 },
2662 None,
2663 Vec::new(),
2664 )
2665 .unwrap();
2666 muxer.write_frame(&key, true).unwrap();
2667 muxer.write_frame(&inter, false).unwrap();
2668 muxer.write_frame(&inter, false).unwrap();
2669 muxer.finish().unwrap();
2670
2671 let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).expect("reopen");
2672 assert_eq!(meta.codec, crate::demux::Codec::Av1);
2673 assert_eq!((meta.width, meta.height), (640, 360));
2674 assert!(
2675 (meta.frame_rate - 30.0).abs() < 1e-6,
2676 "DefaultDuration must state the rate exactly: {}",
2677 meta.frame_rate
2678 );
2679 assert_eq!(meta.frame_count, 3);
2680
2681 // The keyframe comes back with the `CodecPrivate` sequence header in
2682 // front of it, which is the demuxer's own doing -- so what this checks
2683 // is that the record was written and parsed, not that the block grew.
2684 let first = demuxer.next_access_unit().unwrap().unwrap();
2685 assert_eq!(&first[..sequence.len()], &sequence[..]);
2686 assert_eq!(&first[sequence.len()..], &key[..]);
2687 assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter);
2688 assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter);
2689 assert!(demuxer.next_access_unit().unwrap().is_none());
2690 // One keyframe, so every seek rewinds to it -- and the flag really was
2691 // written, or block 0 would be the answer by default rather than by
2692 // being a sync point.
2693 assert_eq!(demuxer.seek_to_sync_at_or_before(2), 0);
2694
2695 // A track with no sequence header to declare is refused where the
2696 // message still means something, rather than written unplayable.
2697 assert!(MkvMuxer::create(
2698 &out,
2699 &Av1Params {
2700 width: 640,
2701 height: 360,
2702 frame_rate: 30.0,
2703 config: &[],
2704 },
2705 None,
2706 Vec::new(),
2707 )
2708 .is_err());
2709 assert!(av1_sequence_header(&inter).is_none(), "no sequence header");
2710 std::fs::remove_file(&out).unwrap();
2711 }
2712
2713 /// The whole pipe at an NTSC rate: what we write is what we read back, to
2714 /// the ninth decimal. Before this bug was fixed the same round trip lost
2715 /// 23.976 on the way out (a rounded frame duration) *and* on the way back
2716 /// in (`mp4`'s integer `frame_rate`), and an hour of export drifted a second.
2717 #[test]
2718 fn an_ntsc_rate_survives_the_round_trip() {
2719 const NTSC: f64 = 24_000.0 / 1001.0;
2720 let out = Scratch::file("ve_mux_ntsc", "mp4");
2721 let mut muxer = Mp4Muxer::create(
2722 &out,
2723 &VideoParams {
2724 width: 640,
2725 height: 360,
2726 frame_rate: NTSC,
2727 sps: SPS,
2728 pps: PPS,
2729 },
2730 None,
2731 )
2732 .unwrap();
2733 muxer
2734 .write_video_au(&au(&[SPS, PPS, &[0x65, 0x01]]))
2735 .unwrap();
2736 muxer.write_video_au(&au(&[&[0x41, 0x02]])).unwrap();
2737 muxer.finish().unwrap();
2738
2739 let file = File::open(&out).unwrap();
2740 let size = file.metadata().unwrap().len();
2741 let mut reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();
2742 assert_eq!(reader.tracks()[&VIDEO_TRACK].timescale(), 24_000);
2743 let first = reader.read_sample(VIDEO_TRACK, 1).unwrap().unwrap();
2744 assert_eq!(first.duration, 1_001, "one frame is a whole 1001 ticks");
2745
2746 let (meta, _) = crate::demux::Demuxer::open(&out).unwrap();
2747 assert!(
2748 (meta.frame_rate - NTSC).abs() < 1e-9,
2749 "read back as {} fps, not {NTSC}",
2750 meta.frame_rate
2751 );
2752 std::fs::remove_file(&out).unwrap();
2753 }
2754
2755 /// A block further from its cluster's own timestamp than the 16-bit
2756 /// *signed* relative field reaches gets a cluster of its own, backwards as
2757 /// well as forwards: a copied stream is stored in decode order, so its
2758 /// presentation times step back over a group of pictures
2759 /// ([`MkvMuxer::write_block`]), and `as i16` of a distance that does not
2760 /// fit lands as a *positive* offset -- the third block here used to be
2761 /// written 25.536 s past the cluster that holds it, a picture at 65.536 s
2762 /// the source put at 0. What is asserted is what a reader sees: every block
2763 /// at the instant its own source said.
2764 #[test]
2765 fn a_block_far_behind_its_cluster_gets_one_rather_than_wrapping() {
2766 let sequence = obu(1, &[0x11, 0x22, 0x33]);
2767 let mut key = sequence.clone();
2768 key.extend_from_slice(&obu(6, &[0xAA; 8]));
2769 let inter = obu(6, &[0xBB; 5]);
2770 let out = Scratch::file("ve_mkv_backward", "mkv");
2771 let mut muxer = MkvMuxer::create(
2772 &out,
2773 &Av1Params {
2774 width: 640,
2775 height: 360,
2776 frame_rate: 30.0,
2777 config: av1_sequence_header(&key).unwrap(),
2778 },
2779 None,
2780 Vec::new(),
2781 )
2782 .unwrap();
2783 // A keyframe opens the file at 0, the next picture is 40 s later --
2784 // past the forward bound, so a cluster of its own -- and the third is a
2785 // non-key block back at the start, which is the second one's reorder
2786 // depth and the direction nothing checked.
2787 muxer.write_block(&key, true, 0).unwrap();
2788 muxer.write_block(&inter, false, 40_000_000_000).unwrap();
2789 muxer.write_block(&inter, false, 0).unwrap();
2790 muxer.finish().unwrap();
2791
2792 let (meta, demuxer) = crate::demux::Demuxer::open(&out).expect("reopen");
2793 assert_eq!(meta.frame_count, 3);
2794 let crate::demux::Demuxer::Mkv(mut demuxer) = demuxer else {
2795 panic!("an mkv file");
2796 };
2797 let times: Vec<i64> = (0..3)
2798 .map(|i| {
2799 demuxer
2800 .coded_block(i)
2801 .unwrap()
2802 .unwrap_or_else(|| panic!("block {i}"))
2803 .ts_ns
2804 })
2805 .collect();
2806 assert_eq!(
2807 times,
2808 [0, 40_000_000_000, 0],
2809 "each block at the instant its source said, not wrapped"
2810 );
2811 std::fs::remove_file(&out).unwrap();
2812 }
2813
2814 /// A tag Matroska permits where an mp4 has one 16-bit field of three ISO
2815 /// 639-2 letters: `mp4`'s own `language_code` masks the three UTF-16 units
2816 /// it is handed with `0x1F` and drops the rest without a word
2817 /// (`vendor/mp4/src/mp4box/mdhd.rs:157`), so a `pt-BR` track used to be
2818 /// written as `ptm` -- a language nobody speaks, offered by a player's
2819 /// subtitle menu as the language the track is not in.
2820 #[test]
2821 fn a_tagged_subtitle_track_states_a_language_the_field_can_hold() {
2822 let out = Scratch::file("ve_mp4_language", "mp4");
2823 let mut muxer = Mp4Muxer::create(
2824 &out,
2825 &VideoParams {
2826 width: 640,
2827 height: 360,
2828 frame_rate: 30.0,
2829 sps: SPS,
2830 pps: PPS,
2831 },
2832 None,
2833 )
2834 .unwrap();
2835 // A second of picture, so the text track has a film to run over.
2836 for _ in 0..30 {
2837 muxer
2838 .write_video_au(&au(&[SPS, PPS, &[0x65, 0x01]]))
2839 .unwrap();
2840 }
2841 muxer
2842 .write_subtitles(&[SubParams {
2843 language: "pt-BR".into(),
2844 name: "Signs".into(),
2845 cues: vec![cue(0, 1_000, "hello")],
2846 }])
2847 .unwrap();
2848 muxer.finish().unwrap();
2849
2850 let file = File::open(&out).unwrap();
2851 let size = file.metadata().unwrap().len();
2852 let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();
2853 let text = 2; // no audio track: the text is the track after the picture
2854 assert_eq!(
2855 reader.tracks()[&text].language(),
2856 "por",
2857 "the tag's own language, not a mangling of it"
2858 );
2859 std::fs::remove_file(&out).unwrap();
2860 }
2861
2862 /// The four shapes a language can arrive in, and what the container is
2863 /// handed for each: the code the field already holds, a tag cut to its
2864 /// primary subtag and mapped, and `und` -- never a string whose first three
2865 /// UTF-16 units the `mp4` crate would mask into a language nobody speaks.
2866 #[test]
2867 fn a_language_is_a_code_before_it_reaches_the_mp4_field() {
2868 assert_eq!(mp4_language("eng"), "eng", "three letters are the code");
2869 assert_eq!(mp4_language("tur"), "tur");
2870 assert_eq!(mp4_language("pt-BR"), "por", "the tag's primary subtag");
2871 assert_eq!(mp4_language("zh-Hans"), "zho");
2872 assert_eq!(mp4_language("en"), "eng", "two letters are mapped");
2873 assert_eq!(
2874 mp4_language("JA"),
2875 "jpn",
2876 "a tag's case is not its language"
2877 );
2878 assert_eq!(mp4_language("fil"), "fil", "639-3 is three letters too");
2879 assert_eq!(mp4_language(""), "und", "nothing stated, undetermined");
2880 assert_eq!(mp4_language("x-pig-latin"), "und", "a tag nothing maps");
2881 }
2882
2883 /// A file nobody put a picture in is refused by name rather than written:
2884 /// [`MkvMuxer::finish`] has always refused the same way, and an mp4 whose
2885 /// picture track holds no sample comes out as a player's blank window with
2886 /// nothing said. One picture is all it takes to make the same file finish.
2887 #[test]
2888 fn an_mp4_with_no_picture_is_refused_by_name() {
2889 let params = VideoParams {
2890 width: 320,
2891 height: 240,
2892 frame_rate: 30.0,
2893 sps: SPS,
2894 pps: PPS,
2895 };
2896 let out = Scratch::file("ve_mp4_no_picture", "mp4");
2897 let err = Mp4Muxer::create(&out, &params, None)
2898 .unwrap()
2899 .finish()
2900 .unwrap_err();
2901 assert_eq!(
2902 err.to_string(),
2903 "no frames were written to the mp4 file",
2904 "the Matroska muxer's refusal, in this container's own name"
2905 );
2906 std::fs::remove_file(&out).unwrap();
2907
2908 let out = Scratch::file("ve_mp4_one_picture", "mp4");
2909 let mut muxer = Mp4Muxer::create(&out, &params, None).unwrap();
2910 muxer
2911 .write_video_au(&au(&[SPS, PPS, &[0x65, 0x01]]))
2912 .unwrap();
2913 muxer.finish().unwrap();
2914 std::fs::remove_file(&out).unwrap();
2915 }
2916}