forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

audio_copy.rs130 lines, 4.7 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 ec_core::Demuxer as _;
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.
33/// The stream of an mp4's first AAC track, as `ec-mp4` numbers it.
34fn aac_stream(reader: &ec_mp4::Mp4Demuxer<BufReader<File>>) -> u32 {
35 reader
36 .streams()
37 .iter()
38 .find(|s| s.params.codec == ec_core::CodecId::Aac)
39 .expect("an AAC track")
40 .index
41}
42
43fn raw(ids: impl IntoIterator<Item = u32>) -> Vec<Vec<u8>> {
44 let file = File::open(asset("test_av.mp4")).unwrap();
45 let mut reader = ec_mp4::Mp4Demuxer::new(BufReader::new(file)).unwrap();
46 let stream = aac_stream(&reader);
47 ids.into_iter()
48 .map(|id| {
49 reader
50 .read_sample(stream, id as usize - 1)
51 .unwrap_or_else(|e| panic!("no sample {id}: {e:?}"))
52 .data
53 .to_vec()
54 })
55 .collect()
56}
57
58fn assert_same_bytes(got: &[AacPacket], want: &[Vec<u8>], what: &str) {
59 assert_eq!(got.len(), want.len(), "{what}: packet count");
60 for (i, (p, w)) in got.iter().zip(want).enumerate() {
61 assert_eq!(&p.bytes, w, "{what}: packet {i} ({} bytes)", p.bytes.len());
62 assert_eq!(p.samples as usize, PACKET, "{what}: packet {i} duration");
63 }
64}
65
66#[test]
67fn whole_track_copy_is_byte_identical() {
68 // The fixture is 5 s, so this asks for all of it: the copy must be the raw
69 // sample table from id 1 (priming packet included) with nothing rewritten.
70 let packets = copy(&[(0.0, 5.0)]);
71 let ids = 1..=packets.len() as u32;
72 eprintln!("copied {} packets", packets.len());
73 assert_same_bytes(&packets, &raw(ids), "0..5 s");
74
75 // Audible length (priming dropped by the reader) inside half a packet of 5 s.
76 let audible = ((packets.len() - 1) * PACKET) as f64;
77 assert!(
78 (audible - 5.0 * RATE).abs() < PACKET as f64,
79 "{audible} samples for 5 s"
80 );
81}
82
83#[test]
84fn two_segments_match_the_bresenham_prediction() {
85 let packets = copy(&[(0.0, 1.0), (2.0, 3.0)]);
86 // One second is 43.07 packets: the first segment is not the last, so it
87 // copies 43 and owes 68 samples. The second is the last segment, and its
88 // run rounds up (`packet_run_last`) so the copy reaches its picture: it is
89 // measured against 44100 + 68 = 43.13 packets and takes the 44th, which
90 // runs 956 samples past the second it was asked for -- under a packet.
91 let n1 = (RATE / PACKET as f64).round();
92 let err = n1 * PACKET as f64 - RATE;
93 let n2 = ((RATE - err) / PACKET as f64).ceil();
94 assert_eq!((n1, n2), (43.0, 44.0), "arithmetic changed, not the code");
95 assert_eq!(packets.len(), 1 + n1 as usize + n2 as usize);
96
97 // Segment 1 is ids 1 (priming) .. 1 + 43; the fixture carries the standard
98 // 1024 priming (see tests/audio_segments.rs), so 2.0 s is media sample
99 // 88200 + 1024 = 89224, which packet 88 ([89088, 90112)) holds.
100 let split = 1 + n1 as usize;
101 assert_same_bytes(&packets[..split], &raw(1..=split as u32), "0..1 s");
102 assert_same_bytes(
103 &packets[split..],
104 &raw(88..88 + n2 as u32),
105 "2..3 s starting at packet 88",
106 );
107
108 // Two seconds asked for, two seconds copied, to inside half a packet.
109 let audible = ((packets.len() - 1) * PACKET) as f64;
110 assert!(
111 (audible - 2.0 * RATE).abs() < PACKET as f64,
112 "{audible} samples for 2 s over one join"
113 );
114}
115
116#[test]
117fn nothing_to_copy_is_a_clean_none() {
118 assert!(
119 AudioSession::copy_segments(asset("test_av.mp4"), &[])
120 .unwrap()
121 .is_none(),
122 "an empty edit list copies nothing"
123 );
124 assert!(
125 AudioSession::copy_segments(asset("test_baseline.mp4"), &[(0.0, 1.0)])
126 .unwrap()
127 .is_none(),
128 "a file with no AAC track is a valid silent session"
129 );
130}