forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

export_chapters.rs343 lines, 11.8 KiBHistoryRawDownload
1//! Chapter marks an export carries: an mp4 gets them as a Nero `chpl` and a QuickTime chapter
2//! track, a Matroska file as a `Chapters` element. ffprobe, the one reader that is not this
3//! project's own, must list the same starts (to the millisecond) and titles, a timeline with
4//! no chapters must list none, and the last chapter must run to the end of the file as ffprobe
5//! reads it, for a whole timeline and for a ranged export.
6//!
7//! The sources are made here with ffmpeg in this test's scratch directory, one per test so that
8//! tests running in parallel never write or read the same file. Where there is no ffmpeg or
9//! ffprobe on the box, the test says so and passes.
10//!
11//! ```text
12//! cargo test -p engine --release --test export_chapters -- --nocapture
13//! ```
14
15use std::path::{Path, PathBuf};
16use std::process::Command;
17use std::sync::Once;
18use std::time::{Duration, Instant};
19
20use engine::export::{ExportSettings, Format};
21use engine::scratch::Scratch;
22use engine::{ExportHandle, Project};
23
24/// The frame rate of the generated sources.
25const FPS: u32 = 30;
26
27/// Thirty frames: one second of picture, short enough that the software encoder is not the cost.
28const FRAMES: u32 = FPS;
29
30/// Ten seconds of picture, for the exports that must end at a film's end well past the first
31/// chapter.
32const TEN_SECONDS: u32 = 10 * FPS;
33
34/// The chapters as given: `(start in ns, title)`. The second one is not a whole millisecond
35/// from the first, so the rounding ffprobe reads back is the one a whole-ms start gives.
36const CHAPTERS: [(u64, &str); 3] = [
37 (0, "Opening"),
38 (300_400_000, "Middle, with ünïcode"),
39 (700_000_000, "Closing"),
40];
41
42fn pin_software() {
43 static PIN: Once = Once::new();
44 PIN.call_once(|| {
45 engine::envcfg::set("VE_SW", "1");
46 engine::envcfg::set("VE_SW_ENC", "1");
47 });
48}
49
50fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
51 let started = Instant::now();
52 while !handle.is_finished() {
53 assert!(
54 started.elapsed() < limit,
55 "export did not finish in {limit:?}"
56 );
57 std::thread::sleep(Duration::from_millis(20));
58 }
59 handle.result().expect("a finished export has an outcome")
60}
61
62/// A H.264 and AAC Matroska source of `frames` frames, made for the test called `name` and no
63/// other, or `None` when ffmpeg cannot make one here.
64fn source(name: &str, frames: u32) -> Option<PathBuf> {
65 let path = Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("chapters_source_{name}-{}.mkv", std::process::id()));
66 let seconds = format!("{}", f64::from(frames) / f64::from(FPS));
67 let ok = Command::new("ffmpeg")
68 .args(["-y", "-v", "error", "-f", "lavfi", "-i"])
69 .arg(format!("testsrc=size=320x240:rate={FPS}"))
70 .args(["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000"])
71 .args(["-t", &seconds, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac"])
72 .arg(&path)
73 .status()
74 .ok()?
75 .success();
76 ok.then_some(path)
77}
78
79fn have_ffprobe() -> bool {
80 Command::new("ffprobe").arg("-version").output().is_ok()
81}
82
83/// `(start in ms, end in ms, title)` per chapter as ffprobe reads them from `path`.
84fn ffprobe_chapters(path: &Path) -> Vec<(i64, i64, String)> {
85 let out = Command::new("ffprobe")
86 .args(["-v", "error", "-show_chapters", "-of", "default"])
87 .arg(path)
88 .output()
89 .expect("ffprobe runs");
90 assert!(out.status.success(), "ffprobe failed on {}", path.display());
91 let text = String::from_utf8_lossy(&out.stdout).into_owned();
92 let mut chapters = Vec::new();
93 let mut start = None;
94 let mut end = None;
95 let mut title = None;
96 for line in text.lines() {
97 if let Some(value) = line.strip_prefix("start_time=") {
98 start = Some((value.parse::<f64>().unwrap() * 1000.0).round() as i64);
99 } else if let Some(value) = line.strip_prefix("end_time=") {
100 end = Some((value.parse::<f64>().unwrap() * 1000.0).round() as i64);
101 } else if let Some(value) = line.strip_prefix("TAG:title=") {
102 title = Some(value.to_string());
103 } else if line == "[/CHAPTER]" {
104 chapters.push((
105 start.take().unwrap(),
106 end.take().unwrap(),
107 title.take().unwrap_or_default(),
108 ));
109 }
110 }
111 chapters
112}
113
114/// The file's duration in ms as ffprobe's format section reads it.
115fn ffprobe_duration_ms(path: &Path) -> f64 {
116 let out = Command::new("ffprobe")
117 .args(["-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1"])
118 .arg(path)
119 .output()
120 .expect("ffprobe runs");
121 assert!(out.status.success(), "ffprobe failed on {}", path.display());
122 let seconds: f64 = String::from_utf8_lossy(&out.stdout)
123 .trim()
124 .parse()
125 .expect("ffprobe prints a duration");
126 seconds * 1000.0
127}
128
129/// What an export wrote, as ffprobe reads it back.
130struct Exported {
131 chapters: Vec<(i64, i64, String)>,
132 duration_ms: f64,
133}
134
135/// Exports the `frames`-long `source` to `format` with `chapters` and `range` on the settings,
136/// and returns what ffprobe reads back.
137fn export_and_read(
138 name: &str,
139 source: &Path,
140 frames: u32,
141 format: Format,
142 chapters: Vec<(u64, String)>,
143 range: Option<(u32, u32)>,
144) -> Exported {
145 pin_software();
146 let (meta, _) = engine::demux::Demuxer::open(source).expect("probe the source");
147 let ext = match format {
148 Format::Mp4 => "mp4",
149 _ => "mkv",
150 };
151 let out = Scratch::file(&format!("ve_export_chapters_{name}"), ext);
152 let handle = engine::export::start(
153 Project::single(source, frames),
154 meta,
155 &out,
156 &ExportSettings {
157 format,
158 chapters,
159 range,
160 ..Default::default()
161 },
162 None,
163 );
164 wait(&handle, Duration::from_secs(900)).expect("the export finishes");
165 Exported {
166 chapters: ffprobe_chapters(&out),
167 duration_ms: ffprobe_duration_ms(&out),
168 }
169}
170
171fn given() -> Vec<(u64, String)> {
172 CHAPTERS.iter().map(|(ns, t)| (*ns, t.to_string())).collect()
173}
174
175/// The starts and titles as given, to the millisecond.
176fn starts_and_titles(read: &[(i64, i64, String)]) -> Vec<(i64, String)> {
177 read.iter().map(|(s, _, t)| (*s, t.clone())).collect()
178}
179
180/// Every chapter has a length, each runs to the next one's start, and the last runs to the end
181/// of the file ffprobe reports, to within a frame.
182fn check_ends(read: &[(i64, i64, String)], duration_ms: f64) {
183 for (start, end, title) in read {
184 assert!(end > start, "chapter {title:?} has no length: {start} to {end}");
185 }
186 for pair in read.windows(2) {
187 assert_eq!(pair[0].1, pair[1].0, "a chapter ends where the next one starts");
188 }
189 let (_, last_end, _) = read.last().expect("chapters");
190 let frame_ms = 1000.0 / f64::from(FPS);
191 assert!(
192 (*last_end as f64 - duration_ms).abs() <= frame_ms + 1.0,
193 "the last chapter ends at {last_end} ms, but the file is {duration_ms:.1} ms long"
194 );
195}
196
197fn expected() -> Vec<(i64, String)> {
198 CHAPTERS
199 .iter()
200 .map(|(ns, t)| (((ns + 500_000) / 1_000_000) as i64, t.to_string()))
201 .collect()
202}
203
204fn have_tools() -> bool {
205 if Command::new("ffmpeg").arg("-version").output().is_err() {
206 eprintln!("no ffmpeg on this box: skipped");
207 return false;
208 }
209 if !have_ffprobe() {
210 eprintln!("no ffprobe on this box: skipped");
211 return false;
212 }
213 true
214}
215
216#[test]
217fn an_mp4_export_lists_its_chapters_in_ffprobe() {
218 if !have_tools() {
219 return;
220 }
221 let name = "an_mp4_export_lists_its_chapters_in_ffprobe";
222 let Some(src) = source(name, FRAMES) else {
223 eprintln!("ffmpeg could not make a source: skipped");
224 return;
225 };
226 let read = export_and_read(name, &src, FRAMES, Format::Mp4, given(), None);
227 assert_eq!(starts_and_titles(&read.chapters), expected());
228 check_ends(&read.chapters, read.duration_ms);
229 assert!((read.duration_ms - 1000.0).abs() <= 40.0, "a one second file");
230}
231
232#[test]
233fn a_matroska_export_lists_its_chapters_in_ffprobe() {
234 if !have_tools() {
235 return;
236 }
237 let name = "a_matroska_export_lists_its_chapters_in_ffprobe";
238 let Some(src) = source(name, FRAMES) else {
239 eprintln!("ffmpeg could not make a source: skipped");
240 return;
241 };
242 let read = export_and_read(name, &src, FRAMES, Format::Hevc, given(), None);
243 assert_eq!(starts_and_titles(&read.chapters), expected());
244 check_ends(&read.chapters, read.duration_ms);
245 assert!((read.duration_ms - 1000.0).abs() <= 40.0, "a one second file");
246}
247
248#[test]
249fn an_export_with_no_chapters_lists_none() {
250 if !have_tools() {
251 return;
252 }
253 let name = "an_export_with_no_chapters_lists_none";
254 let Some(src) = source(name, FRAMES) else {
255 eprintln!("ffmpeg could not make a source: skipped");
256 return;
257 };
258 assert!(export_and_read(&format!("{name}_mp4"), &src, FRAMES, Format::Mp4, Vec::new(), None)
259 .chapters
260 .is_empty());
261 assert!(export_and_read(&format!("{name}_mkv"), &src, FRAMES, Format::Hevc, Vec::new(), None)
262 .chapters
263 .is_empty());
264}
265
266/// Ten seconds with chapters at 1, 3 and 6 s: the last chapter must end at the file's end, 10 s.
267fn whole_ten_second_export_ends_its_last_chapter_at_the_end(name: &str, format: Format) {
268 if !have_tools() {
269 return;
270 }
271 let Some(src) = source(name, TEN_SECONDS) else {
272 eprintln!("ffmpeg could not make a source: skipped");
273 return;
274 };
275 let chapters = vec![
276 (1_000_000_000, "One".to_string()),
277 (3_000_000_000, "Three".to_string()),
278 (6_000_000_000, "Six".to_string()),
279 ];
280 let read = export_and_read(name, &src, TEN_SECONDS, format, chapters, None);
281 assert_eq!(
282 starts_and_titles(&read.chapters),
283 vec![(1000, "One".into()), (3000, "Three".into()), (6000, "Six".into())]
284 );
285 assert!((read.duration_ms - 10_000.0).abs() <= 40.0, "a ten second file");
286 check_ends(&read.chapters, read.duration_ms);
287}
288
289#[test]
290fn a_ten_second_mp4_export_ends_its_last_chapter_at_the_end() {
291 whole_ten_second_export_ends_its_last_chapter_at_the_end(
292 "a_ten_second_mp4_export_ends_its_last_chapter_at_the_end",
293 Format::Mp4,
294 );
295}
296
297#[test]
298fn a_ten_second_matroska_export_ends_its_last_chapter_at_the_end() {
299 whole_ten_second_export_ends_its_last_chapter_at_the_end(
300 "a_ten_second_matroska_export_ends_its_last_chapter_at_the_end",
301 Format::Hevc,
302 );
303}
304
305/// Ten seconds exported from 2 s to 7 s. The chapters arrive from the range start, so the ones
306/// at 3 s and 6 s of the timeline come in as 1 s and 4 s, and the film is 5 s long.
307fn ranged_export_ends_its_last_chapter_at_the_range_end(name: &str, format: Format) {
308 if !have_tools() {
309 return;
310 }
311 let Some(src) = source(name, TEN_SECONDS) else {
312 eprintln!("ffmpeg could not make a source: skipped");
313 return;
314 };
315 let chapters = vec![
316 (1_000_000_000, "Three".to_string()),
317 (4_000_000_000, "Six".to_string()),
318 ];
319 let range = Some((2 * FPS, 7 * FPS));
320 let read = export_and_read(name, &src, TEN_SECONDS, format, chapters, range);
321 assert_eq!(
322 starts_and_titles(&read.chapters),
323 vec![(1000, "Three".into()), (4000, "Six".into())]
324 );
325 assert!((read.duration_ms - 5000.0).abs() <= 40.0, "a five second file");
326 check_ends(&read.chapters, read.duration_ms);
327}
328
329#[test]
330fn a_ranged_mp4_export_ends_its_last_chapter_at_the_range_end() {
331 ranged_export_ends_its_last_chapter_at_the_range_end(
332 "a_ranged_mp4_export_ends_its_last_chapter_at_the_range_end",
333 Format::Mp4,
334 );
335}
336
337#[test]
338fn a_ranged_matroska_export_ends_its_last_chapter_at_the_range_end() {
339 ranged_export_ends_its_last_chapter_at_the_range_end(
340 "a_ranged_matroska_export_ends_its_last_chapter_at_the_range_end",
341 Format::Hevc,
342 );
343}