forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

container_roundtrip.rs123 lines, 4.9 KiBHistoryRawDownload
1//! The `.amr` demuxer and the mp4 `samr` path against ffmpeg-made files: one
2//! synthetic sine per AMR-NB mode, stream-copied into `.amr`, `.3gp` and `.mp4`.
3//! All three must yield the same packets, and the `.amr` bytes must be exactly
4//! the magic followed by those packets back to back.
5
6use std::fs::File;
7use std::io::BufReader;
8use std::process::Command;
9
10use ec_amr::container::{AmrDemuxer, Kind, probe};
11use ec_core::registry::{CodecId, Demuxer, MediaParameters, SeekMode};
12use ec_core::timebase::{TimeBase, Timestamp};
13
14const RATES: [u32; 8] = [4750, 5150, 5900, 6700, 7400, 7950, 10200, 12200];
15const PAYLOAD: [usize; 8] = [12, 13, 15, 17, 19, 20, 26, 31];
16
17fn ffmpeg(args: &[&str]) -> bool {
18 Command::new("ffmpeg")
19 .args(["-nostdin", "-v", "error", "-y"])
20 .args(args)
21 .status()
22 .map(|s| s.success())
23 .unwrap_or(false)
24}
25
26fn skip(why: &str) -> bool {
27 assert!(
28 std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
29 "EC_REQUIRE_FIXTURES=1 but {why}"
30 );
31 eprintln!("SKIP: {why}");
32 true
33}
34
35fn drain(d: &mut dyn Demuxer) -> Vec<Vec<u8>> {
36 let mut out = Vec::new();
37 loop {
38 match d.next_packet() {
39 Ok(p) => out.push(p.data.to_vec()),
40 Err(e) if e.is_eof() => return out,
41 Err(e) => panic!("{e}"),
42 }
43 }
44}
45
46#[test]
47fn amr_3gp_mp4_agree_for_all_modes() {
48 let dir = std::env::temp_dir().join(format!("ec-amr-container-{}", std::process::id()));
49 std::fs::create_dir_all(&dir).unwrap();
50 for (mode, rate) in RATES.iter().enumerate() {
51 let amr = dir.join(format!("m{mode}.amr"));
52 let enc = ffmpeg(&[
53 "-f", "lavfi", "-i", "sine=frequency=440:duration=1.5", "-ar", "8000", "-ac", "1",
54 "-c:a", "libopencore_amrnb", "-b:a", &rate.to_string(), "-f", "amr",
55 amr.to_str().unwrap(),
56 ]);
57 if !enc {
58 skip("ffmpeg with libopencore_amrnb is not available");
59 return;
60 }
61 let bytes = std::fs::read(&amr).unwrap();
62 assert_eq!(probe(&bytes), Some(Kind::Nb));
63
64 let mut d = AmrDemuxer::new(BufReader::new(File::open(&amr).unwrap())).unwrap();
65 let s = &d.streams()[0];
66 assert_eq!(s.params.codec, CodecId::AmrNb);
67 let MediaParameters::Audio(a) = &s.params.media else { panic!() };
68 assert_eq!(a.sample_rate, 8000);
69 let mut packets = Vec::new();
70 let mut n = 0i64;
71 loop {
72 match d.next_packet() {
73 Ok(p) => {
74 assert_eq!((p.pts, p.duration), (Some(n * 160), Some(160)));
75 assert_eq!(p.time_base, TimeBase::from_rate(8000));
76 packets.push(p.data.to_vec());
77 n += 1;
78 }
79 Err(e) if e.is_eof() => break,
80 Err(e) => panic!("{e}"),
81 }
82 }
83 // ffprobe's own packet count for the same file (75 frames of 20 ms plus
84 // the encoder's flush frame).
85 let probed = Command::new("ffprobe")
86 .args(["-v", "error", "-count_packets", "-select_streams", "a:0"])
87 .args(["-show_entries", "stream=nb_read_packets", "-of", "csv=p=0"])
88 .arg(&amr)
89 .output()
90 .expect("ffprobe");
91 let probed: usize = String::from_utf8_lossy(&probed.stdout).trim().parse().unwrap();
92 assert_eq!(packets.len(), probed, "mode {mode} frame count");
93 assert!((75..=76).contains(&packets.len()));
94 for p in &packets {
95 assert_eq!(p.len(), 1 + PAYLOAD[mode], "mode {mode} packet size");
96 assert_eq!((p[0] >> 3) & 15, mode as u8);
97 }
98 assert_eq!(bytes[6..], packets.concat()[..], "mode {mode} byte-identical");
99
100 // Seek by index, then the next packet is the one at that frame.
101 d.seek(0, Timestamp::new(40 * 160 + 7, TimeBase::from_rate(8000)), SeekMode::SyncBefore)
102 .unwrap();
103 let p = d.next_packet().unwrap();
104 assert_eq!((p.pts, p.data.to_vec()), (Some(40 * 160), packets[40].clone()));
105
106 // The same stream in 3gp and mp4 (samr + damr; ffmpeg refuses amr in .mp4).
107 for ext in ["3gp", "3g2", "mov"] {
108 let out = dir.join(format!("m{mode}.{ext}"));
109 assert!(ffmpeg(&[
110 "-i", amr.to_str().unwrap(), "-c", "copy", out.to_str().unwrap()
111 ]));
112 let mut m = ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&out).unwrap())).unwrap();
113 let s = &m.streams()[0];
114 assert_eq!(s.params.codec, CodecId::AmrNb, "{ext} codec");
115 assert!(ext == "mov" || s.params.extradata.is_some(), "{ext} damr extradata");
116 let MediaParameters::Audio(a) = &s.params.media else { panic!() };
117 assert_eq!(a.sample_rate, 8000);
118 assert_eq!(a.layout, ec_core::frame::ChannelLayout::Mono);
119 assert_eq!(drain(&mut m), packets, "mode {mode} {ext} packets");
120 }
121 }
122 let _ = std::fs::remove_dir_all(&dir);
123}