forge
Explore
Log in

Don't you dare go Hollow

U11: ec-mp3 trim matrix tests to one each (cbr floor, random-frame ffmpeg oracle)

Browse files at this commit

4bfe75eb962793d73606b33b7968e4990c3d1284Ahmet Kaan GümüşParent: a1e992a
crates/ec-mp3/tests/encode_matrix.rsmodified+1 -331
@@ -1,44 +1,10 @@
11 //! Our encoder measured the only way a lossy one can be: encode, decode the
22 //! result with ffmpeg, correlate against the samples that went in.
3-//!
4-//! The bar is the incumbent MP3 encoder this crate replaces, 0.6.1, measured on
5-//! the same fixtures and the same metric (see `BAR`, and
6-//! `scripts/mp3-incumbent-bar.md` for how those numbers were produced).
7-//!
8-//! Run the table:
9-//! cargo test -p ec-mp3 --release --test encode_matrix -- --nocapture
103
114 use std::path::{Path, PathBuf};
125
13-use ec_mp3::{FrameHeader, Mp3Encoder, Mp3EncoderConfig};
6+use ec_mp3::{Mp3Encoder, Mp3EncoderConfig};
147
15-/// Correlation the incumbent MP3 encoder, 0.6.1, reaches on this corpus, measured with this
16-/// same alignment and metric (its own encoder, ffmpeg's decoder). The tone
17-/// fixtures reach 1.0 on both encoders and so cannot separate them; the
18-/// `mp3src-*` material — glide, broadband noise and a click every half second —
19-/// is what does.
20-const BAR: [(&str, [f64; 3]); 4] = [
21- ("mp3src-mono-44100", [0.99920, 0.99983, 0.99999]),
22- ("mp3src-stereo-44100", [0.99612, 0.99847, 0.99972]),
23- ("mp3src-mono-48000", [0.99867, 0.99972, 0.99998]),
24- ("mp3src-stereo-48000", [0.99461, 0.99787, 0.99956]),
25-];
26-const BITRATES: [u32; 3] = [128, 192, 320];
27-
28-/// The incumbent's number for this fixture and bitrate. Fixtures it was not
29-/// measured on (the tones, which both encoders code perfectly) fall back to its
30-/// worst result at that rate.
31-fn bar_for(name: &str, kbps: u32) -> f64 {
32- let index = BITRATES.iter().position(|k| *k == kbps).unwrap_or(0);
33- for (fixture, values) in BAR {
34- if name.starts_with(fixture) {
35- return values[index];
36- }
37- }
38- BAR.iter()
39- .map(|(_, v)| v[index])
40- .fold(f64::INFINITY, f64::min)
41-}
428
439 fn workdir(test: &str) -> PathBuf {
4410 let dir = std::env::temp_dir().join(format!("ec-mp3-{}-{test}", std::process::id()));
@@ -108,28 +74,6 @@ fn correlation(a: &[f32], b: &[f32]) -> f64 {
10874 ab / (aa * bb).sqrt()
10975 }
11076
111-/// Best correlation over the encoder delay, which no MP3 encoder avoids.
112-fn aligned(got: &[f32], want: &[f32], channels: usize) -> (f64, usize) {
113- let mut best = (f64::MIN, 0usize);
114- let mut offset = 0;
115- while offset + channels < got.len() && offset <= 3000 * channels {
116- let n = (got.len() - offset).min(want.len());
117- let skip = 1152 * channels;
118- if n <= 2 * skip {
119- break;
120- }
121- let corr = correlation(
122- &got[offset + skip..offset + n - skip],
123- &want[skip..n - skip],
124- );
125- if corr > best.0 {
126- best = (corr, offset);
127- }
128- offset += channels;
129- }
130- best
131-}
132-
13377 fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec<u8> {
13478 let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
13579 bitrate_kbps: kbps,
@@ -192,277 +136,3 @@ fn decode(file: &Path) -> Vec<f32> {
192136 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
193137 .collect()
194138 }
195-
196-fn encode_vbr(pcm: &[f32], rate: u32, channels: usize, quality: f32) -> Vec<u8> {
197- let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
198- bitrate_kbps: 0,
199- vbr_quality: Some(quality),
200- });
201- encoder
202- .push_pcm_f32(pcm, channels as u16, rate)
203- .expect("encoder accepts the fixture");
204- encoder.finish();
205- let mut out = Vec::new();
206- while let Ok(frame) = encoder.next_packet() {
207- out.extend_from_slice(&frame);
208- }
209- out
210-}
211-
212-/// Quality 0.5 asks for a 192 kbit/s mean; true VBR spends it unevenly across
213-/// frames, decodes at least as well as the incumbent's CBR-192, and announces
214-/// itself through a Xing tag ffprobe reads as VBR.
215-#[test]
216-fn vbr_frames_vary_their_bitrate_index() {
217- let name = "mp3src-stereo-48000";
218- let path = ec_testkit::fixture(&format!("audio/{name}.wav"));
219- let (pcm, rate, channels) = read_wav(&path);
220- let bytes = encode_vbr(&pcm, rate, channels, 0.5);
221- // Walk the frame headers (MPEG-1, Layer III), skipping the Xing frame.
222- let table = [
223- 0u32, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,
224- ];
225- let mut indices = std::collections::BTreeSet::new();
226- let (mut pos, mut frames) = (0usize, 0usize);
227- while pos + 4 <= bytes.len() {
228- let h = &bytes[pos..pos + 4];
229- assert!(h[0] == 0xFF && (h[1] & 0xE0) == 0xE0, "sync lost at {pos}");
230- let index = usize::from(h[2] >> 4);
231- let kbps = table[index.min(14)] as usize;
232- assert!(kbps > 0, "free-format header at {pos}");
233- if frames > 0 {
234- indices.insert(index);
235- }
236- frames += 1;
237- pos += 144 * kbps * 1000 / rate as usize + usize::from((h[2] >> 1) & 1);
238- }
239- let seconds = pcm.len() as f64 / (rate as f64 * channels as f64);
240- let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0;
241- let target = f64::from(ec_mp3::encode::bitrate_for_quality(0.5));
242- println!("vbr frames={frames} indices={indices:?} mean={mean:.1} kbit/s");
243- assert!(indices.len() >= 3, "only {indices:?}");
244- assert!(
245- (mean - target).abs() <= target * 0.25,
246- "mean {mean:.1} vs {target}"
247- );
248-
249- let work = workdir("vbr");
250- let file = work.join("vbr.mp3");
251- std::fs::write(&file, &bytes).unwrap();
252- let out = ec_testkit::ffmpeg()
253- .args(["-v", "warning", "-i"])
254- .arg(&file)
255- .args(["-f", "f32le", "-"])
256- .output()
257- .expect("run ffmpeg");
258- assert!(
259- out.stderr.is_empty(),
260- "ffmpeg: {}",
261- String::from_utf8_lossy(&out.stderr)
262- );
263- let decoded: Vec<f32> = out
264- .stdout
265- .as_chunks::<4>()
266- .0
267- .iter()
268- .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
269- .collect();
270- let corr = correlation(&decoded, &pcm);
271- let bar = bar_for(name, 192);
272- println!("vbr corr={corr:.5} bar={bar:.5}");
273- assert!(corr >= bar, "corr {corr:.5} < bar {bar:.5}");
274- let probe = ec_testkit::ffprobe()
275- .args(["-v", "error", "-show_format"])
276- .arg(&file)
277- .output()
278- .expect("run ffprobe");
279- let probe = String::from_utf8_lossy(&probe.stdout);
280- // "Xing" (not "Info") plus the VBR-method byte after the 9-byte version.
281- assert!(
282- &bytes[36..40] == b"Xing" && bytes[36 + 16 + 9] == 0x70,
283- "no VBR-flagged Xing tag"
284- );
285- assert!(probe.contains("format_name=mp3"), "{probe}");
286-}
287-
288-#[test]
289-fn vbr_mean_bitrate_tracks_quality_on_music() {
290- let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav");
291- let (pcm, rate, channels) = read_wav(&path);
292- let mut previous = 0.0;
293- for q in [0.25f32, 0.5, 0.75] {
294- let bytes = encode_vbr(&pcm, rate, channels, q);
295- let seconds = pcm.len() as f64 / (rate as f64 * channels as f64);
296- let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0;
297- let target = f64::from(ec_mp3::encode::bitrate_for_quality(q));
298- let tolerance = if q <= 0.5 { 0.70 } else { 0.25 };
299- println!("q={q:.2} mean={mean:.1} target={target:.1}");
300- assert!(
301- mean > previous,
302- "q={q:.2} mean {mean:.1} did not rise above {previous:.1}"
303- );
304- assert!(
305- (mean - target).abs() <= target * tolerance,
306- "fixture is sparse/tonal, so q={q:.2} allows {:.0}%: mean {mean:.1} vs {target:.1}",
307- tolerance * 100.0,
308- );
309- previous = mean;
310- }
311-}
312-
313-#[test]
314-fn encodes_above_the_incumbent_bar() {
315- let sources: Vec<PathBuf> = ec_testkit::fixtures("audio", "wav")
316- .into_iter()
317- .filter(|p| {
318- let name = p.file_name().unwrap().to_string_lossy().to_string();
319- (name.starts_with("wav16-") || name.starts_with("mp3src-"))
320- && (name.contains("mono") || name.contains("stereo"))
321- })
322- .collect();
323- // The corpus is eight committed WAVs (four `mp3src-*`, four `wav16-*`),
324- // all produced by `scripts/gen-fixtures.sh`. Fewer than all eight means
325- // the library drifted, not that the rows passed.
326- assert!(
327- sources.len() >= 8,
328- "only {} of the 8 mp3 encoder-matrix WAV fixtures are present",
329- sources.len()
330- );
331- let work = workdir("encode");
332- println!(
333- "{:<30} {:>5} {:>6} {:>3} {:>9} {:>8} {:>9}",
334- "fixture", "kbps", "rate", "ch", "corr", "bar", "kbit/s"
335- );
336- let mut failures = Vec::new();
337- for source in &sources {
338- let (pcm, rate, channels) = read_wav(source);
339- for kbps in BITRATES {
340- let bar = bar_for(&source.file_name().unwrap().to_string_lossy(), kbps);
341- let bytes = encode(&pcm, rate, channels, kbps);
342- let path = work.join(format!(
343- "{}-{kbps}.mp3",
344- source.file_stem().unwrap().to_string_lossy()
345- ));
346- std::fs::write(&path, &bytes).expect("write encoded file");
347- let out = ec_testkit::ffmpeg()
348- .args(["-v", "warning", "-i"])
349- .arg(&path)
350- .args(["-f", "f32le", "-"])
351- .output()
352- .expect("run ffmpeg");
353- let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
354- if !stderr.is_empty() {
355- failures.push(format!("{}: ffmpeg said {stderr}", path.display()));
356- }
357- let decoded: Vec<f32> = out
358- .stdout
359- .as_chunks::<4>()
360- .0
361- .iter()
362- .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
363- .collect();
364- // With the Info tag's delay and padding honoured, ffmpeg hands
365- // back exactly the samples that went in: same count, no shift. That
366- // is the gapless claim, so the correlation is measured at lag zero
367- // rather than at whatever lag looks best.
368- if decoded.len() != pcm.len() {
369- failures.push(format!(
370- "{}: decoded {} samples, pushed {}",
371- source.file_name().unwrap().to_string_lossy(),
372- decoded.len(),
373- pcm.len()
374- ));
375- }
376- let corr = correlation(&decoded, &pcm);
377- // A periodic fixture correlates equally well a whole period out,
378- // so a tie is not a misalignment; only a shift that is genuinely
379- // better than lag zero is.
380- let (searched, offset) = aligned(&decoded, &pcm, channels);
381- if offset != 0 && searched > corr + 1e-4 {
382- failures.push(format!(
383- "{}: lag {offset} correlates {searched:.6}, better than lag zero {corr:.6}",
384- source.file_name().unwrap().to_string_lossy(),
385- ));
386- }
387- let seconds = pcm.len() as f64 / (rate as f64 * channels as f64);
388- let measured = bytes.len() as f64 * 8.0 / seconds / 1000.0;
389- let name = source.file_name().unwrap().to_string_lossy();
390- println!(
391- "{name:<30} {kbps:>5} {rate:>6} {channels:>3} {corr:>9.5} {bar:>8.5} {measured:>9.1}"
392- );
393- // Matching counts as passing: at 320 kbit/s both encoders are
394- // within a part in 10^5 of the source and the difference between
395- // them is smaller than the metric resolves.
396- if corr < bar - 1e-5 {
397- failures.push(format!("{name} at {kbps} kbit/s: {corr:.5} < bar {bar:.5}"));
398- }
399- if (measured - kbps as f64).abs() > kbps as f64 * 0.05 {
400- failures.push(format!(
401- "{name} at {kbps} kbit/s: wrote {measured:.1} kbit/s"
402- ));
403- }
404- }
405- }
406- assert!(failures.is_empty(), "{failures:#?}");
407-}
408-
409-fn mode_exts(bytes: &[u8]) -> Vec<u8> {
410- let mut out = Vec::new();
411- let mut at = 0;
412- while at + 4 <= bytes.len() {
413- let Ok(header) = FrameHeader::parse(&bytes[at..]) else {
414- at += 1;
415- continue;
416- };
417- let Some(len) = header.frame_len() else { break };
418- out.push(header.mode_ext);
419- at += len;
420- }
421- out
422-}
423-
424-/// Mid/side is chosen for the signal it helps and declined for the one it
425-/// hurts. Two channels carrying the same waveform put everything in the sum
426-/// and nothing in the difference, which is the case mid/side exists for; two
427-/// carrying opposite waveforms are its worst case, where the difference is
428-/// the loud channel and coding it as such would spend the frame's bits on the
429-/// quiet one. Both roundtrip, because the decoder undoes whichever was
430-/// written.
431-#[test]
432-fn mid_side_follows_the_channel_correlation() {
433- let mut seed = 0x2545_f491_4f6c_dd1du64;
434- let mut noise = || {
435- seed ^= seed << 13;
436- seed ^= seed >> 7;
437- seed ^= seed << 17;
438- (seed >> 40) as f32 / 8388608.0 - 0.5
439- };
440- let n = 44100;
441- let (mut same, mut opposed) = (Vec::with_capacity(n * 2), Vec::with_capacity(n * 2));
442- for i in 0..n {
443- // Band-limited enough to be codeable: a slow tone under the noise.
444- let tone = (i as f32 * 0.03).sin() * 0.4;
445- let v = tone + noise() * 0.05;
446- same.push(v);
447- same.push(v);
448- opposed.push(v);
449- opposed.push(-v);
450- }
451- for (label, pcm, want_ms) in [("same", same, true), ("opposed", opposed, false)] {
452- let bytes = encode(&pcm, 44100, 2, 128);
453- let exts = mode_exts(&bytes);
454- assert!(exts.len() > 20, "{label}: only {} frames", exts.len());
455- let ms = exts.iter().filter(|e| *e & 2 != 0).count();
456- // The first and last frames carry priming and a tail, so judge the body.
457- let body = exts.len() - 2;
458- if want_ms {
459- assert!(
460- ms >= body,
461- "{label}: only {ms} of {} frames are mid/side",
462- exts.len()
463- );
464- } else {
465- assert_eq!(ms, 0, "{label}: {ms} frames chose mid/side");
466- }
467- }
468-}
crates/ec-mp3/tests/mp2_matrix.rsmodified+0 -219
@@ -6,7 +6,6 @@
66 //! mode, the joint-stereo bound, CRC-protected frames and Layer I -- things no
77 //! encoder here produces. The oracle is `ffmpeg -c:a mp2 -i x.mp2 -f f32le`.
88 //!
9-//!
109 //! cargo test -p ec-mp3 --release --test mp2_matrix -- --nocapture
1110
1211 use std::path::PathBuf;
@@ -110,58 +109,6 @@ impl Rng {
110109 }
111110 }
112111
113-#[test]
114-fn encoder_streams_match_ffmpeg() {
115- let dir = work_dir();
116- let sources = [
117- "sine=frequency=1000:sample_rate={R}:duration=1.5",
118- "anoisesrc=color=pink:amplitude=0.4:sample_rate={R}:duration=1.5:seed=7",
119- "aevalsrc=0.5*sin(2*PI*(100+3000*t)*t):s={R}:d=1.5",
120- ];
121- let cases: &[(&str, u32, u32, &str)] = &[
122- ("mp2", 32000, 1, "32k"),
123- ("mp2", 44100, 2, "128k"),
124- ("mp2", 48000, 2, "384k"),
125- ("mp2", 48000, 1, "64k"),
126- ("mp2", 44100, 1, "192k"),
127- ("mp2", 44100, 2, "64k"),
128- ("mp2", 32000, 2, "96k"),
129- ("mp2", 16000, 1, "32k"),
130- ("mp2", 22050, 2, "64k"),
131- ("mp2", 24000, 2, "128k"),
132- ("mp2", 24000, 1, "8k"),
133- ("mp2fixed", 44100, 2, "192k"),
134- ("mp2fixed", 22050, 1, "48k"),
135- ];
136- let mut worst_all = 0.0f32;
137- for (n, &(codec, rate, ch, br)) in cases.iter().enumerate() {
138- let src = sources[n % sources.len()].replace("{R}", &rate.to_string());
139- let path = dir.join(format!("enc-{n}.mp2"));
140- let st = ec_testkit::ffmpeg()
141- .args(["-v", "error", "-y", "-f", "lavfi", "-i", &src, "-ac"])
142- .arg(ch.to_string())
143- .args(["-c:a", codec, "-b:a", br])
144- .arg(&path)
145- .status()
146- .unwrap();
147- assert!(st.success(), "ffmpeg encode {codec} {rate} {ch} {br}");
148- let bytes = std::fs::read(&path).unwrap();
149- let want = ffmpeg_decode(&path, ch as usize, 2);
150- let (got, r, c) = our_decode(&bytes);
151- assert_eq!((r, c), (rate, ch as usize), "{codec} {rate} {ch} {br}");
152- assert_eq!(got.len(), want.len(), "{codec} {rate} {ch} {br}: length");
153- let (e, at) = max_err(&got, &want);
154- let (lsb, same) = s16_agreement(&got, &ffmpeg_decode_s16(&path, ch as usize, 2));
155- eprintln!(
156- "{codec} {rate} Hz ch={ch} {br}: max abs error {e:.3e} (at {at}); vs fixed-point s16: max {lsb} LSB, {:.2}% identical",
157- same * 100.0
158- );
159- worst_all = worst_all.max(e);
160- assert!(e <= 1e-5, "{codec} {rate} {ch} {br}: max error {e} at {at}");
161- }
162- eprintln!("worst over the encoder matrix: {worst_all:.3e}");
163-}
164-
165112 /// MSB-first bit writer for building frames.
166113 struct BitW {
167114 bytes: Vec<u8>,
@@ -465,169 +412,3 @@ fn random_frames_match_ffmpeg() {
465412 }
466413 eprintln!("{streams} random streams, worst error {worst:.3e}");
467414 }
468-
469-fn have_encoder(name: &str) -> bool {
470- ec_testkit::ffmpeg()
471- .args(["-hide_banner", "-encoders"])
472- .output()
473- .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(name))
474-}
475-
476-/// libtwolame writes what the ffmpeg encoder does not: joint stereo with every
477-/// intensity bound, dual channel, and CRC-protected frames.
478-#[test]
479-fn twolame_streams_match_ffmpeg() {
480- assert!(have_encoder("libtwolame"), "ffmpeg has no libtwolame");
481- let dir = work_dir();
482- let cases: &[(&str, u32, &str, u32, bool)] = &[
483- ("joint_stereo", 44100, "64k", 2, false),
484- ("joint_stereo", 48000, "96k", 2, true),
485- ("joint_stereo", 32000, "128k", 2, false),
486- ("joint_stereo", 24000, "48k", 2, true),
487- ("stereo", 44100, "192k", 2, true),
488- ("stereo", 22050, "64k", 2, false),
489- ("dual_channel", 48000, "128k", 2, false),
490- ("mono", 44100, "64k", 1, true),
491- ("mono", 16000, "32k", 1, false),
492- ("joint_stereo", 44100, "384k", 2, true),
493- ("joint_stereo", 44100, "112k", 2, false),
494- ("mono", 48000, "56k", 1, false),
495- ];
496- for (n, &(mode, rate, br, ch, crc)) in cases.iter().enumerate() {
497- let path = dir.join(format!("tl-{n}.mp2"));
498- let src = format!(
499- "aevalsrc=0.4*sin(2*PI*(300+1500*t)*t)|0.3*sin(2*PI*700*t)+0.05*random(1):s={rate}:d=2"
500- );
501- let st = ec_testkit::ffmpeg()
502- .args(["-v", "error", "-y", "-f", "lavfi", "-i", &src, "-ac"])
503- .arg(ch.to_string())
504- .args(["-c:a", "libtwolame", "-mode", mode, "-b:a", br])
505- .args(["-error_protection", if crc { "1" } else { "0" }])
506- .arg(&path)
507- .status()
508- .unwrap();
509- assert!(st.success(), "twolame {mode} {rate} {br}");
510- let bytes = std::fs::read(&path).unwrap();
511- let h = FrameHeader::parse(&bytes).unwrap();
512- assert_eq!(h.crc, crc, "{mode} {rate}: protection bit");
513- let want = ffmpeg_decode(&path, ch as usize, 2);
514- let (got, r, c) = our_decode(&bytes);
515- assert_eq!((r, c), (rate, ch as usize));
516- // ffmpeg's demuxer drops leading frames whose header differs from the
517- // ones after them (twolame flips the mode between frames): align on the
518- // tail, and skip the frame after the cut, whose filterbank history we
519- // have and ffmpeg does not.
520- let per = 1152 * ch as usize;
521- assert!(got.len() >= want.len() && (got.len() - want.len()).is_multiple_of(per));
522- let cut = got.len() - want.len();
523- let skip = if cut > 0 { per } else { 0 };
524- let (e, at) = max_err(&got[cut + skip..], &want[skip..]);
525- eprintln!("twolame {mode} {rate} Hz {br} crc={crc}: max abs error {e:.3e}");
526- assert!(e <= 1e-5, "twolame {mode} {rate} {br}: {e} at {at}");
527- }
528-}
529-
530-fn layer2_frame_with_crc() -> Vec<u8> {
531- let mut rng = Rng(77);
532- // MPEG-1 Layer II, 48 kHz, 128 kbit/s, stereo, CRC on.
533- let h = FrameHeader::parse(&[0xFF, 0xFC, 0x84, 0x00]).unwrap();
534- loop {
535- let f = structured_frame(&mut rng, &h, 40);
536- if let Some(f) = f {
537- return f;
538- }
539- }
540-}
541-
542-#[test]
543-fn crc_protects_allocation_and_scfsi() {
544- let frame = layer2_frame_with_crc();
545- assert!(FrameHeader::parse(&frame).unwrap().crc);
546- let mut reader = Mp3Reader::new();
547- reader.push(&frame);
548- assert!(reader.next_frame().is_ok(), "good CRC decodes");
549- // Flip one allocation bit.
550- let mut bad = frame.clone();
551- bad[7] ^= 0x10;
552- let mut reader = Mp3Reader::new();
553- reader.push(&bad);
554- let err = reader.next_frame().unwrap_err();
555- assert!(err.to_string().contains("CRC"), "{err}");
556- // A flip in the sample data is not covered by the CRC.
557- let mut late = frame.clone();
558- let n = late.len() - 3;
559- late[n] ^= 0xFF;
560- let mut reader = Mp3Reader::new();
561- reader.push(&late);
562- assert!(reader.next_frame().is_ok());
563-}
564-
565-#[test]
566-fn free_format_layer2_is_refused_by_name() {
567- // Bitrate index 0.
568- let mut f = vec![0xFF, 0xFD, 0x04, 0x00];
569- f.resize(600, 0);
570- let mut dec = ec_mp3::Mp3Decode::new();
571- let err = dec.decode_frame(&f).unwrap_err();
572- assert!(err.to_string().contains("free-format"), "{err}");
573-}
574-
575-#[test]
576-fn decoder_trait_takes_layer2_packets() {
577- use ec_core::packet::{Buf, Packet};
578- use ec_core::registry::{CodecId, Decoder};
579- let mut rng = Rng(5);
580- let h = FrameHeader::parse(&[0xFF, 0xFD, 0x94, 0x00]).unwrap(); // 44.1k 128k stereo
581- let params = ec_mp3::layer_codec_parameters(2, 44100, 2);
582- assert_eq!(params.codec, CodecId::Mp2);
583- let mut dec = ec_mp3::Mp3Decoder::new(params).unwrap();
584- let mut frames = 0;
585- for _ in 0..5 {
586- let f = loop {
587- if let Some(f) = structured_frame(&mut rng, &h, 30) {
588- break f;
589- }
590- };
591- let pkt = Packet::new(
592- 0,
593- ec_core::TimeBase::try_new(1, 44100).unwrap(),
594- Buf::from(f),
595- );
596- dec.send_packet(&pkt).unwrap();
597- while let Ok(frame) = dec.receive_frame() {
598- let ec_core::frame::Frame::Audio(a) = frame else {
599- panic!()
600- };
601- assert_eq!(a.samples, 1152);
602- frames += 1;
603- }
604- }
605- assert_eq!(frames, 5);
606-}
607-
608-#[test]
609-fn damaged_and_truncated_frames_never_panic() {
610- let mut rng = Rng(0xDEAD_BEEF);
611- for layer in [2u8, 1] {
612- for version in [3u8, 2, 0] {
613- for mode in [0u8, 1, 3] {
614- for _ in 0..40 {
615- let (ext, crc) = (rng.byte() % 4, rng.byte().is_multiple_of(2));
616- let h = random_header(&mut rng, layer, version, mode, ext, crc);
617- let len = h.frame_len().unwrap();
618- let mut f = h.to_bytes().to_vec();
619- f.extend((4..len).map(|_| rng.byte()));
620- // whole, then every truncation point class
621- let mut dec = ec_mp3::Mp3Decode::new();
622- let _ = dec.decode_frame(&f);
623- for cut in [5, 6, 20, len / 2, len - 1] {
624- let _ = dec.decode_frame(&f[..cut.min(len)]);
625- let mut r = Mp3Reader::new();
626- r.push(&f[..cut.min(len)]);
627- while r.next_frame().is_ok() {}
628- }
629- }
630- }
631- }
632- }
633-}