forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7f487c1Tahinli3 months ago659 commits

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