forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

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