forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

chapters.rs139 lines, 5.3 KiBHistoryRawDownload
1//! Chapters written by `Mp4Muxer::set_chapters`, read back by ffprobe: the starts
2//! (to the millisecond) and the titles must be the ones given, whether ffprobe
3//! reads them from the `chpl` box or from the QuickTime chapter track.
4
5use std::io::Cursor;
6use std::path::PathBuf;
7use std::process::Command;
8
9use ec_core::{
10 AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, Demuxer, MediaParameters, Muxer, Packet,
11 StreamInfo, TimeBase,
12};
13use ec_mp4::Mp4Muxer;
14
15/// `seconds` of silent AAC (one 1024-sample packet a step), with the chapters set.
16fn audio_file(chapters: &[(u64, String)], seconds: u32) -> Vec<u8> {
17 let mut params = CodecParameters::new(CodecId::Aac);
18 params.extradata = Some(Buf::from(vec![0x12, 0x10]));
19 params.media = MediaParameters::Audio(AudioParameters {
20 sample_rate: 44_100,
21 layout: ChannelLayout::from_count(2),
22 ..Default::default()
23 });
24 let mut muxer = Mp4Muxer::new(Cursor::new(Vec::new())).unwrap();
25 muxer.set_chapters(chapters).unwrap();
26 let stream = muxer
27 .add_stream(StreamInfo::new(0, TimeBase::from_rate(44_100), params))
28 .unwrap();
29 for i in 0..seconds * 44_100 / 1024 {
30 let mut packet = Packet::new(stream, TimeBase::from_rate(44_100), vec![0xAA, 0x55, i as u8]);
31 packet.dts = Some(i64::from(i) * 1024);
32 packet.duration = Some(1024);
33 packet.flags.keyframe = true;
34 muxer.write_packet(&packet).unwrap();
35 }
36 muxer.finish().unwrap();
37 muxer.into_inner().into_inner()
38}
39
40/// `(start in ms, title)` per chapter, as ffprobe reads them from the file.
41fn ffprobe_chapters(bytes: &[u8], name: &str) -> Vec<(i64, String)> {
42 let dir = std::env::temp_dir().join(format!("ec-mp4-chapters-{}", std::process::id()));
43 std::fs::create_dir_all(&dir).unwrap();
44 let path: PathBuf = dir.join(name);
45 std::fs::write(&path, bytes).unwrap();
46 let out = Command::new("ffprobe")
47 .args(["-v", "error", "-show_chapters", "-of", "default"])
48 .arg(&path)
49 .output()
50 .expect("ffprobe on PATH");
51 assert!(out.status.success(), "ffprobe failed: {:?}", out.stderr);
52 let text = String::from_utf8_lossy(&out.stdout);
53 let mut chapters = Vec::new();
54 let mut start = None;
55 let mut title = None;
56 for line in text.lines() {
57 if let Some(value) = line.strip_prefix("start_time=") {
58 start = Some((value.parse::<f64>().unwrap() * 1000.0).round() as i64);
59 } else if let Some(value) = line.strip_prefix("TAG:title=") {
60 title = Some(value.to_string());
61 } else if line == "[/CHAPTER]" {
62 chapters.push((start.take().unwrap(), title.take().unwrap_or_default()));
63 }
64 }
65 let _ = std::fs::remove_file(&path);
66 chapters
67}
68
69fn expect(chapters: &[(u64, &str)]) -> Vec<(i64, String)> {
70 chapters
71 .iter()
72 .map(|(ns, title)| (((ns + 500_000) / 1_000_000) as i64, title.to_string()))
73 .collect()
74}
75
76#[test]
77fn ffprobe_reads_the_chapters_back_with_their_starts_and_titles() {
78 let given = [
79 (0u64, "Intro"),
80 (5_000_000_000, "Middle, with ünïcode"),
81 (12_345_000_000, "Ending"),
82 ];
83 let chapters: Vec<(u64, String)> = given.iter().map(|(n, t)| (*n, t.to_string())).collect();
84 let bytes = audio_file(&chapters, 15);
85 assert_eq!(ffprobe_chapters(&bytes, "three.m4a"), expect(&given));
86}
87
88#[test]
89fn a_first_chapter_that_is_not_at_zero_keeps_its_start() {
90 let given = [(1_500_000_000u64, "Cold open"), (4_000_000_000, "Credits")];
91 let chapters: Vec<(u64, String)> = given.iter().map(|(n, t)| (*n, t.to_string())).collect();
92 let bytes = audio_file(&chapters, 6);
93 assert_eq!(ffprobe_chapters(&bytes, "offset.m4a"), expect(&given));
94}
95
96#[test]
97fn a_file_without_chapters_has_none_for_ffprobe() {
98 let bytes = audio_file(&[], 3);
99 assert!(ffprobe_chapters(&bytes, "none.m4a").is_empty());
100}
101
102/// The chapter track is a stream the demuxer walks past like any other `text` track: the file
103/// still opens, and its one audio track reads back with every sample.
104#[test]
105fn the_demuxer_reads_a_chaptered_file_as_it_always_did() {
106 let chapters = vec![(0u64, "A".to_string()), (500_000_000, "B".to_string())];
107 let bytes = audio_file(&chapters, 2);
108 let mut demuxer = ec_mp4::Mp4Demuxer::new(Cursor::new(bytes)).expect("the file opens");
109 let audio = demuxer
110 .streams()
111 .iter()
112 .filter(|s| s.params.codec == CodecId::Aac)
113 .count();
114 assert_eq!(audio, 1, "one AAC track");
115 let mut packets = 0;
116 loop {
117 match demuxer.next_packet() {
118 Ok(_) => packets += 1,
119 Err(ec_core::Error::Eof) => break,
120 Err(e) => panic!("{e}"),
121 }
122 }
123 assert_eq!(packets, 2 * 44_100 / 1024, "every audio packet reads back");
124}
125
126/// Past 255 chapters the `chpl` box is left out, and the chapter track carries every one:
127/// ffprobe lists all 300, with the starts and titles given.
128#[test]
129fn ffprobe_lists_all_300_chapters_when_chpl_cannot_hold_them() {
130 let given: Vec<(u64, String)> = (0..300u64)
131 .map(|i| (i * 100_000_000, format!("Chapter {i}")))
132 .collect();
133 let bytes = audio_file(&given, 31);
134 let expected: Vec<(i64, String)> = given
135 .iter()
136 .map(|(ns, t)| (((ns + 500_000) / 1_000_000) as i64, t.clone()))
137 .collect();
138 assert_eq!(ffprobe_chapters(&bytes, "three_hundred.m4a"), expected);
139}