forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB8c7bf80Tahinli3 months ago114 commits

mux.rs528 lines, 19.3 KiBHistoryRawDownload
1//! Annex-B -> MP4, the mirror of `demux`: encoders emit start-code framed NALs,
2//! an mp4 sample wants 4-byte length prefixes with SPS/PPS living in `avcC`.
3
4use std::fs::File;
5use std::io::BufWriter;
6use std::path::Path;
7
8use mp4::{
9 AacConfig, AudioObjectType, AvcConfig, Bytes, ChannelConfig, FourCC, MediaConfig, Mp4Config,
10 Mp4Sample, Mp4Writer, SampleFreqIndex, TrackConfig, TrackType,
11};
12
13/// 90 kHz is the H.264 convention, and it divides exactly at every *integer*
14/// fps (3000 ticks at 30, 3600 at 25). The NTSC rates do not divide into it at
15/// all -- 24000/1001 wants 3753.75 -- so those get their own clock; see
16/// [`frame_timing`].
17const VIDEO_TIMESCALE: u32 = 90_000;
18/// Ticks per frame for a rate the 90 kHz clock cannot express: every NTSC rate
19/// is `n/1001`, so 1001 ticks a frame makes the timescale a whole `n`.
20const NTSC_TICKS: u32 = 1001;
21/// An AAC-LC packet is always 1024 samples, so with timescale == sample rate the
22/// per-packet duration is this constant.
23const AAC_PACKET_SAMPLES: u32 = 1024;
24
25const NAL_IDR: u8 = 5;
26const NAL_SEI: u8 = 6;
27const NAL_SPS: u8 = 7;
28const NAL_PPS: u8 = 8;
29const NAL_AUD: u8 = 9;
30
31pub struct VideoParams<'a> {
32 pub width: u32,
33 pub height: u32,
34 pub frame_rate: f64,
35 pub sps: &'a [u8],
36 pub pps: &'a [u8],
37}
38
39/// Read straight off the source file's `esds`: export copies AAC packets, it
40/// never re-encodes, so the decoder config is passed through unchanged.
41pub struct AudioParams {
42 pub freq_index: u8,
43 pub chan_conf: u8,
44}
45
46/// Writes one H.264 track plus an optional AAC track. mp4 0.14 ignores
47/// `Mp4Sample::start_time` and builds all timing by accumulating `duration`, so
48/// every sample handed over must carry an exact duration or the tracks drift.
49pub struct Mp4Muxer {
50 writer: Mp4Writer<BufWriter<File>>,
51 frame_duration: u32,
52 has_audio: bool,
53}
54
55const VIDEO_TRACK: u32 = 1;
56const AUDIO_TRACK: u32 = 2;
57
58impl Mp4Muxer {
59 pub fn create(
60 path: &Path,
61 video: &VideoParams,
62 audio: Option<&AudioParams>,
63 ) -> crate::Result<Self> {
64 if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 {
65 return Err(format!("bad frame rate {}", video.frame_rate).into());
66 }
67 if video.width == 0
68 || video.height == 0
69 || video.width > u16::MAX as u32
70 || video.height > u16::MAX as u32
71 {
72 return Err(format!("bad dimensions {}x{}", video.width, video.height).into());
73 }
74 // AvcCBox::new indexes sps[1..=3] for profile/level, so a short SPS panics
75 // inside the mp4 crate; refuse it here where the message still means something.
76 if video.sps.len() < 4 || video.pps.is_empty() {
77 return Err("no usable SPS/PPS for the video track".into());
78 }
79
80 let (timescale, frame_duration) = frame_timing(video.frame_rate)?;
81 let mut writer = Mp4Writer::write_start(
82 BufWriter::new(File::create(path)?),
83 &Mp4Config {
84 major_brand: FourCC::from(*b"isom"),
85 minor_version: 512,
86 compatible_brands: vec![
87 FourCC::from(*b"isom"),
88 FourCC::from(*b"iso2"),
89 FourCC::from(*b"avc1"),
90 FourCC::from(*b"mp41"),
91 ],
92 // The video track's own, deliberately: `mp4` converts every
93 // sample duration into the movie timescale with an integer
94 // division of its own (track.rs:752), so a coarser movie clock
95 // loses a fraction of a millisecond *per frame* -- 1 kHz makes a
96 // 4.000 s export announce itself as 3.960 s. Equal timescales
97 // make the video conversion exact.
98 timescale,
99 },
100 )?;
101 writer.add_track(&TrackConfig {
102 track_type: TrackType::Video,
103 timescale,
104 language: "und".to_string(),
105 media_conf: MediaConfig::AvcConfig(AvcConfig {
106 width: video.width as u16,
107 height: video.height as u16,
108 seq_param_set: video.sps.to_vec(),
109 pic_param_set: video.pps.to_vec(),
110 }),
111 })?;
112 if let Some(audio) = audio {
113 let freq_index = SampleFreqIndex::try_from(audio.freq_index)?;
114 let sample_rate = freq_index.freq();
115 writer.add_track(&TrackConfig {
116 track_type: TrackType::Audio,
117 timescale: sample_rate,
118 language: "und".to_string(),
119 media_conf: MediaConfig::AacConfig(AacConfig {
120 bitrate: 0,
121 profile: AudioObjectType::AacLowComplexity,
122 freq_index,
123 chan_conf: ChannelConfig::try_from(audio.chan_conf)?,
124 }),
125 })?;
126 }
127
128 Ok(Self {
129 writer,
130 frame_duration,
131 has_audio: audio.is_some(),
132 })
133 }
134
135 /// One coded picture, Annex-B framed. Parameter sets inside it are dropped
136 /// (they are already in `avcC`); an IDR slice marks the sample as a sync point.
137 pub fn write_video_au(&mut self, annex_b: &[u8]) -> crate::Result<()> {
138 let (bytes, is_sync) = annex_b_to_avcc(annex_b)?;
139 self.writer.write_sample(
140 VIDEO_TRACK,
141 &Mp4Sample {
142 start_time: 0, // ignored by the writer; timing is duration-accumulated
143 duration: self.frame_duration,
144 rendering_offset: 0, // no B-frames on either encode path
145 is_sync,
146 bytes: Bytes::from(bytes),
147 },
148 )?;
149 Ok(())
150 }
151
152 /// One raw AAC packet (no ADTS header), copied verbatim from the source --
153 /// or one of the hand-written silent ones a gap is filled with. Every AAC-LC
154 /// access unit is [`AAC_PACKET_SAMPLES`] frames, gap or not.
155 pub fn write_audio_packet(&mut self, bytes: &[u8]) -> crate::Result<()> {
156 if !self.has_audio {
157 return Err("audio packet written to a video-only file".into());
158 }
159 self.writer.write_sample(
160 AUDIO_TRACK,
161 &Mp4Sample {
162 start_time: 0,
163 duration: AAC_PACKET_SAMPLES,
164 rendering_offset: 0,
165 // Every AAC packet is a sync point; saying so per-sample would emit
166 // an `stss` listing all of them, while no `stss` means the same thing.
167 is_sync: false,
168 bytes: Bytes::copy_from_slice(bytes),
169 },
170 )?;
171 Ok(())
172 }
173
174 pub fn finish(mut self) -> crate::Result<()> {
175 self.writer.write_end()?;
176 Ok(())
177 }
178}
179
180/// `(timescale, ticks per frame)` for `fps`, chosen so one frame is a *whole*
181/// number of ticks: 90 kHz wherever it divides exactly (every integer rate, so
182/// those exports stay byte for byte what they were), and `round(fps * 1001)`
183/// over [`NTSC_TICKS`] otherwise, which is exact for the whole `n/1001` family.
184/// A fixed 90 kHz clock leaves 24000/1001 a quarter tick short *per frame* --
185/// half a second of drift against the audio track by the end of a two-hour
186/// export, which is this bug's own truncation reborn at the writing end.
187pub(crate) fn frame_timing(fps: f64) -> crate::Result<(u32, u32)> {
188 let ticks = f64::from(VIDEO_TIMESCALE) / fps;
189 if (ticks - ticks.round()).abs() < 1e-9 && (1.0..=f64::from(u32::MAX)).contains(&ticks.round())
190 {
191 return Ok((VIDEO_TIMESCALE, ticks.round() as u32));
192 }
193 let timescale = (fps * f64::from(NTSC_TICKS)).round();
194 if !(1.0..=f64::from(u32::MAX)).contains(&timescale) {
195 return Err(format!("frame rate {fps} has no usable timescale").into());
196 }
197 Ok((timescale as u32, NTSC_TICKS))
198}
199
200/// SPS and PPS of an Annex-B access unit, for the `avcC` box. `None` when the
201/// unit does not carry both, which the first exported unit always must.
202pub fn parameter_sets(annex_b: &[u8]) -> Option<(&[u8], &[u8])> {
203 let nals = split_annex_b(annex_b);
204 let sps = nals.iter().find(|n| nal_type(n) == NAL_SPS)?;
205 let pps = nals.iter().find(|n| nal_type(n) == NAL_PPS)?;
206 Some((sps, pps))
207}
208
209/// Whether the unit carries a coded picture (NAL types 1..=5). An encoder that
210/// buffered instead of coding hands back an empty buffer, and one that emitted
211/// only parameter sets has no sample to write -- both are for the caller to skip
212/// rather than for [`Mp4Muxer::write_video_au`] to reject.
213pub(crate) fn has_coded_slice(annex_b: &[u8]) -> bool {
214 split_annex_b(annex_b)
215 .iter()
216 .any(|nal| (1..=NAL_IDR).contains(&nal_type(nal)))
217}
218
219/// Exact inverse of `demux::append_annex_b`: 4-byte length prefixes (the only
220/// prefix size `mp4` writes, avc1.rs hardcodes `length_size_minus_one = 3`).
221/// Parameter sets, access unit delimiters and SEI are stripped — the first two
222/// are redundant with `avcC`, SEI is not worth carrying. Returns the sample
223/// bytes and whether the unit is an IDR.
224fn annex_b_to_avcc(annex_b: &[u8]) -> crate::Result<(Vec<u8>, bool)> {
225 let mut out = Vec::with_capacity(annex_b.len());
226 let mut is_idr = false;
227 for nal in split_annex_b(annex_b) {
228 match nal_type(nal) {
229 NAL_SPS | NAL_PPS | NAL_AUD | NAL_SEI => continue,
230 NAL_IDR => is_idr = true,
231 _ => {}
232 }
233 out.extend_from_slice(&(nal.len() as u32).to_be_bytes());
234 out.extend_from_slice(nal);
235 }
236 if out.is_empty() {
237 return Err("access unit has no coded slice".into());
238 }
239 Ok((out, is_idr))
240}
241
242/// NAL payloads of an Annex-B buffer, both 3- and 4-byte start codes, trailing
243/// zero bytes trimmed (they belong to the next start code, or are padding).
244fn split_annex_b(src: &[u8]) -> Vec<&[u8]> {
245 let mut nals = Vec::new();
246 let mut start = None;
247 let mut i = 0;
248 while i + 2 < src.len() {
249 if src[i] == 0 && src[i + 1] == 0 && src[i + 2] == 1 {
250 if let Some(s) = start {
251 push_nal(&mut nals, &src[s..i]);
252 }
253 i += 3;
254 start = Some(i);
255 } else {
256 i += 1;
257 }
258 }
259 if let Some(s) = start {
260 push_nal(&mut nals, &src[s..]);
261 }
262 nals
263}
264
265fn push_nal<'a>(nals: &mut Vec<&'a [u8]>, nal: &'a [u8]) {
266 let end = nal.iter().rposition(|&b| b != 0).map_or(0, |p| p + 1);
267 if end > 0 {
268 nals.push(&nal[..end]);
269 }
270}
271
272fn nal_type(nal: &[u8]) -> u8 {
273 nal[0] & 0x1F
274}
275
276#[cfg(test)]
277mod tests {
278 use std::io::BufReader;
279
280 use super::*;
281
282 const SPS: &[u8] = &[0x67, 0x42, 0x00, 0x1E, 0xAB];
283 const PPS: &[u8] = &[0x68, 0xCE, 0x3C, 0x80];
284
285 fn au(nals: &[&[u8]]) -> Vec<u8> {
286 let mut v = Vec::new();
287 for nal in nals {
288 v.extend_from_slice(&[0, 0, 0, 1]);
289 v.extend_from_slice(nal);
290 }
291 v
292 }
293
294 #[test]
295 fn splits_both_start_code_lengths() {
296 let src = [
297 0, 0, 0, 1, 0x67, 0xAA, 0, 0, 1, 0x68, 0xBB, 0, 0, 0, 1, 0x65, 0xCC,
298 ];
299 let nals = split_annex_b(&src);
300 assert_eq!(nals, [&[0x67, 0xAA][..], &[0x68, 0xBB], &[0x65, 0xCC]]);
301 }
302
303 #[test]
304 fn trims_trailing_zero_padding() {
305 let src = [0, 0, 0, 1, 0x65, 0xCC, 0, 0, 0];
306 assert_eq!(split_annex_b(&src), [&[0x65, 0xCC][..]]);
307 }
308
309 #[test]
310 fn repacks_multi_nal_unit_and_drops_parameter_sets() {
311 let slice = [0x65, 0x88, 0x99];
312 let (bytes, is_idr) = annex_b_to_avcc(&au(&[SPS, PPS, &[0x09, 0x10], &slice])).unwrap();
313 assert!(is_idr);
314 assert_eq!(
315 bytes,
316 [0, 0, 0, 3, 0x65, 0x88, 0x99],
317 "4-byte prefix, slice only"
318 );
319
320 let (bytes, is_idr) = annex_b_to_avcc(&au(&[&[0x41, 0x9A], &[0x41, 0x9B]])).unwrap();
321 assert!(!is_idr, "no IDR slice in the unit");
322 assert_eq!(bytes, [0, 0, 0, 2, 0x41, 0x9A, 0, 0, 0, 2, 0x41, 0x9B]);
323 }
324
325 #[test]
326 fn rejects_units_with_no_slice() {
327 assert!(annex_b_to_avcc(&[]).is_err(), "empty");
328 assert!(annex_b_to_avcc(&[0x65, 0x88]).is_err(), "no start code");
329 assert!(
330 annex_b_to_avcc(&au(&[SPS, PPS])).is_err(),
331 "parameter sets only"
332 );
333 }
334
335 #[test]
336 fn finds_parameter_sets() {
337 assert_eq!(
338 parameter_sets(&au(&[SPS, PPS, &[0x65, 0x11]])),
339 Some((SPS, PPS))
340 );
341 assert!(
342 parameter_sets(&au(&[SPS, &[0x65, 0x11]])).is_none(),
343 "no PPS"
344 );
345 }
346
347 /// Every frame must be a whole number of ticks, or the video track drifts
348 /// against the audio one over a long export -- the truncation this bug is.
349 #[test]
350 fn frame_timing_is_exact_at_ntsc_and_unchanged_at_integer_rates() {
351 assert_eq!(frame_timing(30.0).unwrap(), (90_000, 3_000), "was 90k/3000");
352 assert_eq!(frame_timing(25.0).unwrap(), (90_000, 3_600));
353 assert_eq!(frame_timing(24_000.0 / 1001.0).unwrap(), (24_000, 1_001));
354 // 29.97 is the one NTSC rate 90 kHz already counts exactly (3003 ticks),
355 // so it keeps the conventional clock rather than growing its own.
356 assert_eq!(frame_timing(30_000.0 / 1001.0).unwrap(), (90_000, 3_003));
357 // And the pair plays back as the rate it came from, to the last bit.
358 for fps in [30.0, 25.0, 24_000.0 / 1001.0, 30_000.0 / 1001.0, 60.0] {
359 let (ts, ticks) = frame_timing(fps).unwrap();
360 let played = f64::from(ts) / f64::from(ticks);
361 assert!((played - fps).abs() < 1e-9, "{fps} writes back as {played}");
362 }
363 // Rate so low the 90 kHz clock cannot count it: refused, not truncated.
364 assert!(frame_timing(1e-9).is_err());
365 }
366
367 #[test]
368 fn create_rejects_unusable_config() {
369 let out = std::env::temp_dir().join("ve_mux_never_written.mp4");
370 let ok = VideoParams {
371 width: 64,
372 height: 64,
373 frame_rate: 30.0,
374 sps: SPS,
375 pps: PPS,
376 };
377 assert!(
378 Mp4Muxer::create(
379 &out,
380 &VideoParams {
381 sps: &SPS[..3],
382 ..ok
383 },
384 None
385 )
386 .is_err(),
387 "SPS too short for avcC"
388 );
389 assert!(
390 Mp4Muxer::create(
391 &out,
392 &VideoParams {
393 frame_rate: 0.0,
394 ..ok
395 },
396 None
397 )
398 .is_err()
399 );
400 assert!(
401 Mp4Muxer::create(&out, &VideoParams { width: 0, ..ok }, None).is_err(),
402 "zero width"
403 );
404 let _ = std::fs::remove_file(&out);
405 }
406
407 /// Three encoder-shaped access units out, then back in through both `mp4`'s
408 /// own reader and our `Demuxer` — the round trip is what proves the repack is
409 /// the exact inverse of `demux::append_annex_b`.
410 #[test]
411 fn round_trips_through_both_readers() {
412 let units = [
413 au(&[SPS, PPS, &[0x65, 0x01, 0x02, 0x03]]),
414 au(&[&[0x41, 0x04, 0x05]]),
415 au(&[&[0x41, 0x06]]),
416 ];
417 let out = std::env::temp_dir().join(format!("ve_mux_{}.mp4", std::process::id()));
418
419 let mut muxer = Mp4Muxer::create(
420 &out,
421 &VideoParams {
422 width: 1280,
423 height: 720,
424 frame_rate: 30.0,
425 sps: SPS,
426 pps: PPS,
427 },
428 Some(&AudioParams {
429 freq_index: 4, // 44100
430 chan_conf: 2,
431 }),
432 )
433 .unwrap();
434 for unit in &units {
435 muxer.write_video_au(unit).unwrap();
436 }
437 muxer.write_audio_packet(&[0x21, 0x22, 0x23]).unwrap();
438 muxer.write_audio_packet(&[0x24, 0x25]).unwrap();
439 muxer.finish().unwrap();
440
441 let file = File::open(&out).unwrap();
442 let size = file.metadata().unwrap().len();
443 let mut reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();
444 let (video_id, audio_id) = (VIDEO_TRACK, AUDIO_TRACK);
445 assert_eq!(reader.sample_count(video_id).unwrap(), 3);
446 assert_eq!(reader.sample_count(audio_id).unwrap(), 2);
447 {
448 let track = &reader.tracks()[&video_id];
449 assert_eq!((track.width(), track.height()), (1280, 720));
450 assert_eq!(track.frame_rate().round(), 30.0);
451 assert_eq!(track.sequence_parameter_set().unwrap(), SPS);
452 assert_eq!(track.picture_parameter_set().unwrap(), PPS);
453 }
454 let first = reader.read_sample(video_id, 1).unwrap().unwrap();
455 assert!(first.is_sync, "IDR unit is a sync sample");
456 assert_eq!(first.duration, 3000, "90000 / 30 fps");
457 assert_eq!(&first.bytes[..], [0, 0, 0, 4, 0x65, 0x01, 0x02, 0x03]);
458 assert!(!reader.read_sample(video_id, 2).unwrap().unwrap().is_sync);
459 assert_eq!(
460 &reader.read_sample(audio_id, 1).unwrap().unwrap().bytes[..],
461 [0x21, 0x22, 0x23],
462 "audio packets copied verbatim"
463 );
464 let second = reader.read_sample(audio_id, 2).unwrap().unwrap();
465 assert_eq!(&second.bytes[..], [0x24, 0x25], "verbatim");
466 assert_eq!(
467 second.duration, AAC_PACKET_SAMPLES,
468 "every AAC-LC packet is one 1024-frame stts entry"
469 );
470
471 let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).unwrap();
472 assert_eq!(meta.frame_count, 3);
473 assert_eq!((meta.width, meta.height), (1280, 720));
474 assert_eq!(meta.frame_rate.round(), 30.0);
475 for expected in &units {
476 assert_eq!(
477 &demuxer.next_access_unit().unwrap().unwrap(),
478 expected,
479 "demux returns the exact bytes that went in"
480 );
481 }
482 assert!(demuxer.next_access_unit().unwrap().is_none());
483
484 std::fs::remove_file(&out).unwrap();
485 }
486
487 /// The whole pipe at an NTSC rate: what we write is what we read back, to
488 /// the ninth decimal. Before this bug was fixed the same round trip lost
489 /// 23.976 on the way out (a rounded frame duration) *and* on the way back
490 /// in (`mp4`'s integer `frame_rate`), and an hour of export drifted a second.
491 #[test]
492 fn an_ntsc_rate_survives_the_round_trip() {
493 const NTSC: f64 = 24_000.0 / 1001.0;
494 let out = std::env::temp_dir().join(format!("ve_mux_ntsc_{}.mp4", std::process::id()));
495 let mut muxer = Mp4Muxer::create(
496 &out,
497 &VideoParams {
498 width: 640,
499 height: 360,
500 frame_rate: NTSC,
501 sps: SPS,
502 pps: PPS,
503 },
504 None,
505 )
506 .unwrap();
507 muxer
508 .write_video_au(&au(&[SPS, PPS, &[0x65, 0x01]]))
509 .unwrap();
510 muxer.write_video_au(&au(&[&[0x41, 0x02]])).unwrap();
511 muxer.finish().unwrap();
512
513 let file = File::open(&out).unwrap();
514 let size = file.metadata().unwrap().len();
515 let mut reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();
516 assert_eq!(reader.tracks()[&VIDEO_TRACK].timescale(), 24_000);
517 let first = reader.read_sample(VIDEO_TRACK, 1).unwrap().unwrap();
518 assert_eq!(first.duration, 1_001, "one frame is a whole 1001 ticks");
519
520 let (meta, _) = crate::demux::Demuxer::open(&out).unwrap();
521 assert!(
522 (meta.frame_rate - NTSC).abs() < 1e-9,
523 "read back as {} fps, not {NTSC}",
524 meta.frame_rate
525 );
526 std::fs::remove_file(&out).unwrap();
527 }
528}