forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

export_m4a_range.rs159 lines, 5.9 KiBHistoryRawDownload
1//! A ranged audio-only AAC export states, in its `elst`, exactly the samples the
2//! range holds, and not the last AAC frame's padding rounded up to a whole
3//! packet. The timeline is a 48 kHz tone on the 30 fps canvas an audio-only
4//! timeline gets, so frame `f` is sample `f * 1600`.
5//!
6//! ```text
7//! cargo test -p engine --release --test export_m4a_range
8//! ```
9
10use std::path::Path;
11use std::time::{Duration, Instant};
12
13use engine::export::{ExportSettings, Format};
14use engine::scratch::Scratch;
15use engine::{ExportHandle, PlaybackSession};
16
17const RATE: u32 = 48_000;
18const FPS: u32 = 30;
19/// Long enough that the last range below is inside the timeline.
20const SECONDS: u32 = 14;
21
22/// A 16-bit stereo sine at [`RATE`], written by hand so no tool is needed.
23fn write_tone(path: &Path) {
24 let frames = RATE * SECONDS;
25 let data_len = frames * 2 * 2;
26 let mut wav = Vec::with_capacity(44 + data_len as usize);
27 wav.extend_from_slice(b"RIFF");
28 wav.extend_from_slice(&(36 + data_len).to_le_bytes());
29 wav.extend_from_slice(b"WAVEfmt ");
30 wav.extend_from_slice(&16u32.to_le_bytes());
31 wav.extend_from_slice(&1u16.to_le_bytes()); // PCM
32 wav.extend_from_slice(&2u16.to_le_bytes()); // stereo
33 wav.extend_from_slice(&RATE.to_le_bytes());
34 wav.extend_from_slice(&(RATE * 4).to_le_bytes());
35 wav.extend_from_slice(&4u16.to_le_bytes());
36 wav.extend_from_slice(&16u16.to_le_bytes());
37 wav.extend_from_slice(b"data");
38 wav.extend_from_slice(&data_len.to_le_bytes());
39 for n in 0..frames {
40 let t = f64::from(n) / f64::from(RATE);
41 let left = (t * 440.0 * std::f64::consts::TAU).sin() * 8000.0;
42 let right = (t * 880.0 * std::f64::consts::TAU).sin() * 8000.0;
43 wav.extend_from_slice(&(left as i16).to_le_bytes());
44 wav.extend_from_slice(&(right as i16).to_le_bytes());
45 }
46 std::fs::write(path, wav).expect("write the source tone");
47}
48
49fn wait(handle: &ExportHandle) -> engine::Result<()> {
50 let deadline = Instant::now() + Duration::from_secs(120);
51 loop {
52 if let Some(result) = handle.result() {
53 return result;
54 }
55 assert!(Instant::now() < deadline, "export never settled");
56 std::thread::sleep(Duration::from_millis(20));
57 }
58}
59
60/// The payload of the first box called `name` in `data`, which is a sequence of
61/// boxes.
62fn child<'a>(data: &'a [u8], name: &[u8]) -> Option<&'a [u8]> {
63 let mut at = 0;
64 while at + 8 <= data.len() {
65 let size = u32::from_be_bytes(data[at..at + 4].try_into().ok()?) as usize;
66 let kind = &data[at + 4..at + 8];
67 let (header, len) = match size {
68 0 => (8, data.len() - at),
69 1 => (
70 16,
71 u64::from_be_bytes(data[at + 8..at + 16].try_into().ok()?) as usize,
72 ),
73 n => (8, n),
74 };
75 if len < header || at + len > data.len() {
76 return None;
77 }
78 if kind == name {
79 return Some(&data[at + header..at + len]);
80 }
81 at += len;
82 }
83 None
84}
85
86fn be32(data: &[u8], at: usize) -> u32 {
87 u32::from_be_bytes(data[at..at + 4].try_into().unwrap())
88}
89
90/// The movie timescale, and the first track's single `elst` entry as
91/// `(segment_duration, media_time)`, read straight from the boxes.
92fn edit_of(path: &Path) -> (u32, u32, i64) {
93 let file = std::fs::read(path).expect("read the export back");
94 let moov = child(&file, b"moov").expect("a moov box");
95 let mvhd = child(moov, b"mvhd").expect("an mvhd box");
96 // mvhd version 0, as the writer declares it: the timescale is at byte 12.
97 let timescale = be32(mvhd, 12);
98 let trak = child(moov, b"trak").expect("a trak box");
99 let elst = child(child(trak, b"edts").expect("an edts box"), b"elst").expect("an elst box");
100 assert_eq!(be32(elst, 4), 1, "one edit: {}", path.display());
101 let segment = be32(elst, 8);
102 let media_time = be32(elst, 12) as i32 as i64;
103 let rate = be32(elst, 16);
104 assert_eq!(rate, 0x0001_0000, "media rate 1.0");
105 (timescale, segment, media_time)
106}
107
108/// Exports the timeline's frames `start..end` as `format`, and checks the edit
109/// list states exactly those frames' samples after the encoder's priming.
110fn ranged_edit(format: Format, name: &str, start: u32, end: u32) {
111 let tone = Scratch::file(&format!("ve_m4a_range_src_{name}"), "wav");
112 write_tone(&tone);
113 let session = PlaybackSession::open(&*tone).expect("open the tone");
114 let ext = match format {
115 Format::M4a => "m4a",
116 _ => "mp4",
117 };
118 let out = Scratch::file(&format!("ve_m4a_range_{name}"), ext);
119 wait(&session.export_to_with(
120 &out,
121 &ExportSettings {
122 format,
123 range: Some((start, end)),
124 ..ExportSettings::default()
125 },
126 ))
127 .expect("the ranged audio-only export finishes");
128
129 let samples = u64::from(end - start) * u64::from(RATE) / u64::from(FPS);
130 let (timescale, segment, media_time) = edit_of(&out);
131 // The movie clock rounds up to whole ticks, as the writer's durations do.
132 let want = (samples * u64::from(timescale)).div_ceil(u64::from(RATE));
133 assert_eq!(
134 u64::from(segment),
135 want,
136 "{}: segment_duration in {timescale}/s ticks for {samples} samples",
137 out.display()
138 );
139 assert_eq!(media_time, 1024, "{}: the AAC priming", out.display());
140}
141
142/// 5 s to 7 s: 336000 samples, a whole number of seconds on the movie clock.
143#[test]
144fn an_m4a_range_states_exactly_its_samples() {
145 ranged_edit(Format::M4a, "whole", 150, 360);
146}
147
148/// 5 s to 7.0333 s: 337600 samples, not a multiple of the 1024-sample frame and
149/// not a whole number of milliseconds, so the movie clock rounds it up.
150#[test]
151fn a_non_integral_frame_range_states_exactly_its_samples() {
152 ranged_edit(Format::M4a, "fraction", 150, 361);
153}
154
155/// The sound-only `.mp4` is the same AAC track and takes the same edit.
156#[test]
157fn an_audio_only_mp4_range_states_exactly_its_samples() {
158 ranged_edit(Format::Mp4, "mp4", 150, 361);
159}