| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | use std::hint::black_box; |
| 9 | use std::time::Instant; |
| 10 | |
| 11 | use ec_mp3::{Mp3Encoder, Mp3EncoderConfig}; |
| 12 | |
| 13 | fn encode_once(pcm: &[f32], channels: u16, rate: u32, kbps: u32) -> Vec<u8> { |
| 14 | let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { |
| 15 | bitrate_kbps: kbps, |
| 16 | vbr_quality: None, |
| 17 | }); |
| 18 | encoder.push_pcm_f32(pcm, channels, rate).expect("push"); |
| 19 | encoder.finish(); |
| 20 | let mut out = Vec::new(); |
| 21 | loop { |
| 22 | match encoder.next_packet() { |
| 23 | Ok(frame) => out.extend_from_slice(&frame), |
| 24 | Err(e) if e.is_eof() => break, |
| 25 | Err(e) => panic!("encode: {e}"), |
| 26 | } |
| 27 | } |
| 28 | out |
| 29 | } |
| 30 | |
| 31 | fn main() { |
| 32 | let args: Vec<String> = std::env::args().collect(); |
| 33 | if args.len() < 7 || args[1] != "enc" { |
| 34 | eprintln!("usage: bench enc <in.f32le> <channels> <rate> <kbps> <out.mp3> [reps]"); |
| 35 | std::process::exit(2); |
| 36 | } |
| 37 | let channels: u16 = args[3].parse().expect("channels"); |
| 38 | let rate: u32 = args[4].parse().expect("rate"); |
| 39 | let kbps: u32 = args[5].parse().expect("kbps"); |
| 40 | let reps: usize = args.get(7).map_or(5, |s| s.parse().expect("reps")); |
| 41 | let pcm: Vec<f32> = std::fs::read(&args[2]) |
| 42 | .expect("read input") |
| 43 | .as_chunks::<4>().0.iter() |
| 44 | .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) |
| 45 | .collect(); |
| 46 | let out = encode_once(&pcm, channels, rate, kbps); |
| 47 | let mut best = f64::MAX; |
| 48 | for _ in 0..reps { |
| 49 | let t = Instant::now(); |
| 50 | black_box(encode_once(black_box(&pcm), channels, rate, kbps).len()); |
| 51 | best = best.min(t.elapsed().as_secs_f64()); |
| 52 | } |
| 53 | std::fs::write(&args[6], &out).expect("write output"); |
| 54 | println!( |
| 55 | "bytes={} best_encode_s={best:.4} reps={reps} audio_s={:.3}", |
| 56 | out.len(), |
| 57 | pcm.len() as f64 / f64::from(channels) / f64::from(rate) |
| 58 | ); |
| 59 | } |