forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB8c7bf80Tahinli3 months ago114 commits

audio_copy.rs124 lines, 4.3 KiBHistoryRawDownload
1//! `AudioSession::copy_segments` hands out the source's own AAC bytes — nothing
2//! is decoded and nothing is re-encoded. What has to hold: the bytes are
3//! verbatim, the run starts one packet early (the source priming packet), and
4//! the per-segment packet counts follow the bresenham rounding so a cut list
5//! does not walk out of lip sync.
6
7use std::fs::File;
8use std::io::BufReader;
9use std::path::PathBuf;
10
11use engine::audio::{AacPacket, AudioSession};
12use mp4::{MediaType, Mp4Reader};
13
14const RATE: f64 = 44100.0;
15/// Frames per channel in one AAC-LC packet.
16const PACKET: usize = 1024;
17
18fn asset(name: &str) -> PathBuf {
19 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
20 .join("../../assets")
21 .join(name)
22}
23
24fn copy(segs: &[(f64, f64)]) -> Vec<AacPacket> {
25 AudioSession::copy_segments(asset("test_av.mp4"), segs)
26 .expect("copy")
27 .expect("test_av.mp4 has an audio track")
28 .1
29}
30
31/// The AAC track's sample bytes for 1-based `ids`, read straight from the
32/// demuxer — the reference the copy must match byte for byte.
33fn raw(ids: impl IntoIterator<Item = u32>) -> Vec<Vec<u8>> {
34 let file = File::open(asset("test_av.mp4")).unwrap();
35 let size = file.metadata().unwrap().len();
36 let mut reader = Mp4Reader::read_header(BufReader::new(file), size).unwrap();
37 let track = reader
38 .tracks()
39 .values()
40 .find(|t| matches!(t.media_type(), Ok(MediaType::AAC)))
41 .unwrap()
42 .track_id();
43 ids.into_iter()
44 .map(|id| {
45 reader
46 .read_sample(track, id)
47 .unwrap()
48 .unwrap_or_else(|| panic!("no sample {id}"))
49 .bytes
50 .to_vec()
51 })
52 .collect()
53}
54
55fn assert_same_bytes(got: &[AacPacket], want: &[Vec<u8>], what: &str) {
56 assert_eq!(got.len(), want.len(), "{what}: packet count");
57 for (i, (p, w)) in got.iter().zip(want).enumerate() {
58 assert_eq!(&p.bytes, w, "{what}: packet {i} ({} bytes)", p.bytes.len());
59 assert_eq!(p.samples as usize, PACKET, "{what}: packet {i} duration");
60 }
61}
62
63#[test]
64fn whole_track_copy_is_byte_identical() {
65 // The fixture is 5 s, so this asks for all of it: the copy must be the raw
66 // sample table from id 1 (priming packet included) with nothing rewritten.
67 let packets = copy(&[(0.0, 5.0)]);
68 let ids = 1..=packets.len() as u32;
69 eprintln!("copied {} packets", packets.len());
70 assert_same_bytes(&packets, &raw(ids), "0..5 s");
71
72 // Audible length (priming dropped by the reader) inside half a packet of 5 s.
73 let audible = ((packets.len() - 1) * PACKET) as f64;
74 assert!(
75 (audible - 5.0 * RATE).abs() < PACKET as f64,
76 "{audible} samples for 5 s"
77 );
78}
79
80#[test]
81fn two_segments_match_the_bresenham_prediction() {
82 let packets = copy(&[(0.0, 1.0), (2.0, 3.0)]);
83 // One second is 43.07 packets: the first segment copies 43 and owes 68
84 // samples, so the second is measured against 44100 + 68 = 43.13 -> 43 too.
85 let n1 = (RATE / PACKET as f64).round();
86 let err = n1 * PACKET as f64 - RATE;
87 let n2 = ((RATE - err) / PACKET as f64).round();
88 assert_eq!((n1, n2), (43.0, 43.0), "arithmetic changed, not the code");
89 assert_eq!(packets.len(), 1 + n1 as usize + n2 as usize);
90
91 // Segment 1 is ids 1 (priming) .. 1 + 43; the fixture carries the standard
92 // 1024 priming (see tests/audio_segments.rs), so 2.0 s is media sample
93 // 88200 + 1024 = 89224, which packet 88 ([89088, 90112)) holds.
94 let split = 1 + n1 as usize;
95 assert_same_bytes(&packets[..split], &raw(1..=split as u32), "0..1 s");
96 assert_same_bytes(
97 &packets[split..],
98 &raw(88..88 + n2 as u32),
99 "2..3 s starting at packet 88",
100 );
101
102 // Two seconds asked for, two seconds copied, to inside half a packet.
103 let audible = ((packets.len() - 1) * PACKET) as f64;
104 assert!(
105 (audible - 2.0 * RATE).abs() < PACKET as f64,
106 "{audible} samples for 2 s over one join"
107 );
108}
109
110#[test]
111fn nothing_to_copy_is_a_clean_none() {
112 assert!(
113 AudioSession::copy_segments(asset("test_av.mp4"), &[])
114 .unwrap()
115 .is_none(),
116 "an empty edit list copies nothing"
117 );
118 assert!(
119 AudioSession::copy_segments(asset("test_baseline.mp4"), &[(0.0, 1.0)])
120 .unwrap()
121 .is_none(),
122 "a file with no AAC track is a valid silent session"
123 );
124}