forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB0563cbfTahinli2 months ago824 commits

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