forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-benchr2': audio-encode, TrueHD and demux bench rows

Browse files at this commit

c71fe36eeb2bec5dabc21fde2aa6b8a5e3df7509Ahmet Kaan GümüşParent: 70502534ef277a
Seventeen new rows over real media through the crates' own decoders;
also fixes ffprobe's literal N/A string silently zeroing a duration
fallback chain. The slowest audio encoder on the board is now visible:
aac at 3.5x realtime.
Cargo.lockmodified+8 -0
@@ -276,14 +276,22 @@ dependencies = [
276 name = "ec-bench"276 name = "ec-bench"
277 version = "0.1.0"277 version = "0.1.0"
278 dependencies = [278 dependencies = [
279+ "ec-aac",
280+ "ec-ac3",
281+ "ec-alac",
279 "ec-av1",282 "ec-av1",
280 "ec-core",283 "ec-core",
284+ "ec-flac",
281 "ec-h264",285 "ec-h264",
282 "ec-h264-syntax",286 "ec-h264-syntax",
283 "ec-h265",287 "ec-h265",
284 "ec-image",288 "ec-image",
285 "ec-inflate",289 "ec-inflate",
290+ "ec-mp3",
291+ "ec-opus",
286 "ec-probe",292 "ec-probe",
293+ "ec-truehd",
294+ "ec-vorbis",
287 ]295 ]
288 296
289 [[package]]297 [[package]]
tools/ec-bench/Cargo.tomlmodified+8 -0
@@ -22,3 +22,11 @@ ec-probe = { workspace = true }
22 ec-h264-syntax = { workspace = true }22 ec-h264-syntax = { workspace = true }
23 ec-image = { workspace = true }23 ec-image = { workspace = true }
24 ec-inflate = { workspace = true }24 ec-inflate = { workspace = true }
25+ec-opus = { workspace = true }
26+ec-vorbis = { workspace = true }
27+ec-aac = { workspace = true }
28+ec-mp3 = { workspace = true }
29+ec-flac = { workspace = true }
30+ec-alac = { workspace = true }
31+ec-ac3 = { workspace = true }
32+ec-truehd = { workspace = true }
tools/ec-bench/src/main.rsmodified+384 -2
@@ -14,8 +14,11 @@ use std::time::Instant;
14 14
15 use ec_av1::encode::Picture as Av1Picture;15 use ec_av1::encode::Picture as Av1Picture;
16 use ec_av1::encoder::{Av1Encoder, Colour, EncoderConfig as Av1Config};16 use ec_av1::encoder::{Av1Encoder, Colour, EncoderConfig as Av1Config};
17-use ec_core::frame::{PixelFormat, Plane, VideoFrame};17+use ec_core::frame::{
18-use ec_core::registry::MediaType;18+ AudioFrame, ChannelLayout, Frame, PixelFormat, Plane, SampleFormat, VideoFrame,
19+};
20+use ec_core::packet::Buf;
21+use ec_core::registry::{Encoder as CoreEncoder, MediaType};
19 use ec_h264::{22 use ec_h264::{
20 Decoder as H264Decoder, Encoder as H264Encoder, EncoderConfig as H264Config, NalOutcome,23 Decoder as H264Decoder, Encoder as H264Encoder, EncoderConfig as H264Config, NalOutcome,
21 PictureView,24 PictureView,
@@ -40,6 +43,9 @@ fn main() {
40 bench_h265_encode(&mut rows);43 bench_h265_encode(&mut rows);
41 bench_av1_encode(&mut rows);44 bench_av1_encode(&mut rows);
42 bench_audio_decode(&mut rows);45 bench_audio_decode(&mut rows);
46+ bench_audio_encode(&mut rows);
47+ bench_truehd(&mut rows);
48+ bench_container_demux(&mut rows);
43 bench_image_decode(&mut rows);49 bench_image_decode(&mut rows);
44 bench_inflate(&mut rows);50 bench_inflate(&mut rows);
45 51
@@ -465,6 +471,382 @@ fn bench_audio_decode(rows: &mut Vec<Row>) {
465 }471 }
466 }472 }
467 473
474+// ---------------------------------------------------------------------------
475+// audio encode: real, decoded PCM (the same WAV fixture the decode rows
476+// already read, run back through `AudioDecoder`'s own PCM path) fed to each
477+// crate's own encoder at its default/representative settings.
478+// ---------------------------------------------------------------------------
479+
480+/// `seconds` of real interleaved `f32` PCM, decoded through `ec-probe`'s own
481+/// `Reader`/`AudioDecoder` route (the same one `bench_audio_decode` drives).
482+fn real_pcm(seconds: f64) -> Option<(Vec<f32>, u32, usize)> {
483+ let path = fixtures().join("audio/wav16-stereo-48000.wav");
484+ let mut reader = Reader::open(&path).ok()?;
485+ let stream = reader.default_stream(MediaType::Audio)?.index;
486+ let mut dec = reader.make_decoder(stream).ok()?;
487+ let channels = dec.channels();
488+ let rate = dec.sample_rate();
489+ let want = (seconds * f64::from(rate)) as usize * channels;
490+ let mut pcm = Vec::new();
491+ let mut out = Vec::new();
492+ while pcm.len() < want {
493+ match reader.next_packet() {
494+ Ok(pkt) if pkt.stream == stream => {
495+ if dec.decode(&pkt, &mut out).is_ok() {
496+ pcm.extend_from_slice(&out);
497+ }
498+ }
499+ Ok(_) => {}
500+ Err(_) => break,
501+ }
502+ }
503+ pcm.truncate(want - want % channels);
504+ (!pcm.is_empty()).then_some((pcm, rate, channels))
505+}
506+
507+fn bench_audio_encode(rows: &mut Vec<Row>) {
508+ let Some((pcm, rate, channels)) = real_pcm(5.0) else {
509+ for name in ["opus", "vorbis", "aac", "mp3", "flac", "alac", "ac3"] {
510+ rows.push(missing(
511+ Box::leak(format!("ec-{name}").into_boxed_str()),
512+ "encode",
513+ ));
514+ }
515+ return;
516+ };
517+ let frames = pcm.len() / channels;
518+ let media_s = frames as f64 / f64::from(rate);
519+ let content = format!("{media_s:.1}s wav16 {channels}ch @ {rate}Hz");
520+
521+ // opus: 20ms frames at the input rate, dropping a short tail frame.
522+ {
523+ let frame_size = rate as usize / 50;
524+ let mut enc = ec_opus::Encoder::new(rate, channels, ec_opus::Application::Audio)
525+ .expect("opus encoder");
526+ let mut out = vec![0u8; 4000];
527+ let start = Instant::now();
528+ for chunk in pcm.chunks_exact(frame_size * channels) {
529+ enc.encode_float(chunk, frame_size, &mut out)
530+ .expect("opus encode");
531+ }
532+ let wall = start.elapsed().as_secs_f64();
533+ rows.push(Row {
534+ component: "ec-opus",
535+ direction: "encode",
536+ content: content.clone(),
537+ media: format!("{media_s:.1}s"),
538+ wall_ms: wall * 1000.0,
539+ rtf: (wall > 0.0).then_some(media_s / wall),
540+ });
541+ }
542+
543+ // vorbis: quality 0.6, the level the oracle tests already encode at.
544+ {
545+ let mut enc = ec_vorbis::VorbisEncoder::new(ec_vorbis::EncoderConfig {
546+ sample_rate: rate,
547+ channels: channels as u16,
548+ bitrate_bps: 0,
549+ quality: 0.6,
550+ })
551+ .expect("vorbis encoder");
552+ let start = Instant::now();
553+ enc.push_interleaved(&pcm).expect("vorbis push");
554+ enc.finish();
555+ let mut n = 0usize;
556+ loop {
557+ match enc.next_packet() {
558+ Ok(p) => n += p.data.len(),
559+ Err(e) if e.is_eof() => break,
560+ Err(e) => panic!("vorbis encode: {e}"),
561+ }
562+ }
563+ let wall = start.elapsed().as_secs_f64();
564+ let _ = n;
565+ rows.push(Row {
566+ component: "ec-vorbis",
567+ direction: "encode",
568+ content: content.clone(),
569+ media: format!("{media_s:.1}s"),
570+ wall_ms: wall * 1000.0,
571+ rtf: (wall > 0.0).then_some(media_s / wall),
572+ });
573+ }
574+
575+ // aac: 128 kbit/s, raw (no ADTS wrap) -- the default config.
576+ {
577+ let mut enc = ec_aac::AacEncoder::new(ec_aac::AacEncoderConfig::default());
578+ let start = Instant::now();
579+ enc.push_pcm(&pcm, channels as u16, rate).expect("aac pcm");
580+ enc.finish();
581+ while enc.next_packet().is_ok() {}
582+ let wall = start.elapsed().as_secs_f64();
583+ rows.push(Row {
584+ component: "ec-aac",
585+ direction: "encode",
586+ content: content.clone(),
587+ media: format!("{media_s:.1}s"),
588+ wall_ms: wall * 1000.0,
589+ rtf: (wall > 0.0).then_some(media_s / wall),
590+ });
591+ }
592+
593+ // mp3: CBR 192 kbit/s, the incumbent-matching default the tests gate on.
594+ {
595+ let mut enc = ec_mp3::Mp3Encoder::new(ec_mp3::Mp3EncoderConfig {
596+ bitrate_kbps: 192,
597+ vbr_quality: None,
598+ });
599+ let start = Instant::now();
600+ enc.push_pcm_f32(&pcm, channels as u16, rate)
601+ .expect("mp3 pcm");
602+ enc.finish();
603+ while enc.next_packet().is_ok() {}
604+ let wall = start.elapsed().as_secs_f64();
605+ rows.push(Row {
606+ component: "ec-mp3",
607+ direction: "encode",
608+ content: content.clone(),
609+ media: format!("{media_s:.1}s"),
610+ wall_ms: wall * 1000.0,
611+ rtf: (wall > 0.0).then_some(media_s / wall),
612+ });
613+ }
614+
615+ // flac: single-shot, default config (4096-sample blocks, LPC-12), 16-bit.
616+ {
617+ let samples: Vec<i32> = pcm
618+ .iter()
619+ .map(|&s| (s.clamp(-1.0, 1.0) * 32767.0) as i32)
620+ .collect();
621+ let cfg = ec_flac::EncoderConfig::default();
622+ let start = Instant::now();
623+ let _ = ec_flac::encode(&cfg, &samples, channels, 16, rate).expect("flac encode");
624+ let wall = start.elapsed().as_secs_f64();
625+ rows.push(Row {
626+ component: "ec-flac",
627+ direction: "encode",
628+ content: content.clone(),
629+ media: format!("{media_s:.1}s"),
630+ wall_ms: wall * 1000.0,
631+ rtf: (wall > 0.0).then_some(media_s / wall),
632+ });
633+ }
634+
635+ // alac: 4096-sample frames, 16-bit -- same shape the round-trip tests use.
636+ {
637+ let samples: Vec<i32> = pcm
638+ .iter()
639+ .map(|&s| (s.clamp(-1.0, 1.0) * 32767.0) as i32)
640+ .collect();
641+ let enc = ec_alac::AlacEncoder::new(rate, channels as u8, 16, 4096).expect("alac encoder");
642+ let per_frame = 4096 * channels;
643+ let start = Instant::now();
644+ for chunk in samples.chunks(per_frame) {
645+ let _ = enc.encode_frame(chunk);
646+ }
647+ let wall = start.elapsed().as_secs_f64();
648+ rows.push(Row {
649+ component: "ec-alac",
650+ direction: "encode",
651+ content: content.clone(),
652+ media: format!("{media_s:.1}s"),
653+ wall_ms: wall * 1000.0,
654+ rtf: (wall > 0.0).then_some(media_s / wall),
655+ });
656+ }
657+
658+ // ac3: 192 kbit/s -- only if the source's channel count is one A/52 codes.
659+ if (1..=6).contains(&channels) && matches!(rate, 48_000 | 44_100 | 32_000) {
660+ let mut enc = ec_ac3::Ac3Encoder::new(ec_ac3::EncoderConfig {
661+ sample_rate: rate,
662+ channels: channels as u16,
663+ bitrate_kbps: 192,
664+ })
665+ .expect("ac3 encoder");
666+ let start = Instant::now();
667+ enc.push_pcm_f32(&pcm).expect("ac3 pcm");
668+ enc.finish();
669+ loop {
670+ match enc.next_packet() {
671+ Ok(_) => {}
672+ Err(e) if e.is_eof() => break,
673+ Err(e) => panic!("ac3 encode: {e}"),
674+ }
675+ }
676+ let wall = start.elapsed().as_secs_f64();
677+ rows.push(Row {
678+ component: "ec-ac3",
679+ direction: "encode",
680+ content,
681+ media: format!("{media_s:.1}s"),
682+ wall_ms: wall * 1000.0,
683+ rtf: (wall > 0.0).then_some(media_s / wall),
684+ });
685+ } else {
686+ rows.push(missing_direction(
687+ "ec-ac3",
688+ "encode",
689+ "source channel/rate combination is not one A/52 codes",
690+ ));
691+ }
692+}
693+
694+// ---------------------------------------------------------------------------
695+// truehd: no fixture stream exists yet, so this round-trips the new encoder
696+// through its own decoder, same shape as ec-h265's own-stream decode row.
697+// ---------------------------------------------------------------------------
698+
699+fn bench_truehd(rows: &mut Vec<Row>) {
700+ let Some((pcm, rate, channels)) = real_pcm(5.0) else {
701+ rows.push(missing("ec-truehd", "encode"));
702+ rows.push(missing("ec-truehd", "decode"));
703+ return;
704+ };
705+ if channels != 2 || !matches!(rate, 48_000 | 44_100 | 96_000 | 88_200 | 192_000 | 176_400) {
706+ rows.push(missing_direction(
707+ "ec-truehd",
708+ "encode",
709+ "this encoder writes 44.1/48 kHz-family stereo only",
710+ ));
711+ rows.push(missing_direction(
712+ "ec-truehd",
713+ "decode",
714+ "this encoder writes 44.1/48 kHz-family stereo only",
715+ ));
716+ return;
717+ }
718+ let n = pcm.len() / channels;
719+ let media_s = n as f64 / f64::from(rate);
720+ let mut bytes = Vec::with_capacity(pcm.len() * 4);
721+ for &s in &pcm {
722+ let sample = (s.clamp(-1.0, 1.0) * 8_388_607.0) as i32;
723+ bytes.extend_from_slice(&(sample << 8).to_le_bytes());
724+ }
725+ let frame = AudioFrame::try_new(
726+ SampleFormat::S32,
727+ false,
728+ ChannelLayout::Stereo,
729+ rate,
730+ n,
731+ vec![Buf::from_vec(bytes)],
732+ )
733+ .expect("audio frame");
734+
735+ let mut enc = ec_truehd::TrueHdEncoder::new(rate).expect("truehd encoder");
736+ let start = Instant::now();
737+ enc.send_frame(&Frame::Audio(frame)).expect("truehd send");
738+ enc.flush().expect("truehd flush");
739+ let mut thd = Vec::new();
740+ while let Ok(pkt) = enc.receive_packet() {
741+ thd.extend_from_slice(&pkt.data);
742+ }
743+ let wall = start.elapsed().as_secs_f64();
744+ rows.push(Row {
745+ component: "ec-truehd",
746+ direction: "encode",
747+ content: format!("{media_s:.1}s wav16 stereo @ {rate}Hz"),
748+ media: format!("{media_s:.1}s"),
749+ wall_ms: wall * 1000.0,
750+ rtf: (wall > 0.0).then_some(media_s / wall),
751+ });
752+
753+ let mut dec = ec_truehd::TrueHdDecoder::new();
754+ let start = Instant::now();
755+ let mut samples = 0u64;
756+ let mut pos = 0usize;
757+ while pos < thd.len() {
758+ let Ok(len) = ec_truehd::frame_length(&thd[pos..]) else {
759+ break;
760+ };
761+ if len == 0 || pos + len > thd.len() {
762+ break;
763+ }
764+ if let Ok(Some(f)) = dec.decode_access_unit(&thd[pos..pos + len]) {
765+ samples += (f.data[0].len() / 4 / channels) as u64;
766+ }
767+ pos += len;
768+ }
769+ let wall = start.elapsed().as_secs_f64();
770+ let media_s = samples as f64 / f64::from(rate);
771+ rows.push(Row {
772+ component: "ec-truehd",
773+ direction: "decode",
774+ content: "own encoded stream, stereo".to_string(),
775+ media: format!("{media_s:.1}s"),
776+ wall_ms: wall * 1000.0,
777+ rtf: (wall > 0.0).then_some(media_s / wall),
778+ });
779+}
780+
781+// ---------------------------------------------------------------------------
782+// container demux: whole-file `ec-matroska`/`ec-mp4` packet reads (through
783+// `ec-probe`'s own container routing) over real muxes already on disk.
784+// ---------------------------------------------------------------------------
785+
786+/// Container-level duration (`format=duration`), for a mux whose per-stream
787+/// packets carry no duration field of their own (some Matroska tracks don't).
788+fn format_duration(path: &Path) -> Option<String> {
789+ let out = Command::new("ffprobe")
790+ .args(["-v", "error", "-show_entries", "format=duration"])
791+ .args(["-of", "default=nw=1:nk=1"])
792+ .arg(path)
793+ .output()
794+ .ok()?;
795+ if !out.status.success() {
796+ return None;
797+ }
798+ let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
799+ (!s.is_empty() && s != "N/A").then_some(s)
800+}
801+
802+fn bench_container_demux(rows: &mut Vec<Row>) {
803+ for (component, ext) in [("ec-matroska", "mkv"), ("ec-mp4", "mp4")] {
804+ let Some(src) = [fixtures().join("video"), home().join("Videos")]
805+ .into_iter()
806+ .filter_map(|d| std::fs::read_dir(d).ok())
807+ .flatten()
808+ .flatten()
809+ .map(|e| e.path())
810+ .filter(|p| p.extension().and_then(|e| e.to_str()) == Some(ext))
811+ .max_by_key(|p| std::fs::metadata(p).map(|m| m.len()).unwrap_or(0))
812+ else {
813+ rows.push(missing(component, "demux"));
814+ continue;
815+ };
816+ let Ok(mut reader) = Reader::open(&src) else {
817+ rows.push(missing(component, "demux"));
818+ continue;
819+ };
820+ let file_mb = std::fs::metadata(&src).map(|m| m.len()).unwrap_or(0) as f64 / 1_000_000.0;
821+ let duration_s = [
822+ ffprobe_field(&src, "v:0", "duration"),
823+ ffprobe_field(&src, "a:0", "duration"),
824+ format_duration(&src),
825+ ]
826+ .into_iter()
827+ .find_map(|s| s.and_then(|s| s.parse::<f64>().ok()))
828+ .unwrap_or(0.0);
829+ let mut packets = 0u64;
830+ let start = Instant::now();
831+ loop {
832+ match reader.next_packet() {
833+ Ok(_) => packets += 1,
834+ Err(_) => break,
835+ }
836+ }
837+ let wall = start.elapsed().as_secs_f64();
838+ let name = src.file_name().unwrap().to_string_lossy().into_owned();
839+ rows.push(Row {
840+ component,
841+ direction: "demux",
842+ content: format!("{name} ({file_mb:.1} MB, {packets} packets)"),
843+ media: format!("{duration_s:.1}s"),
844+ wall_ms: wall * 1000.0,
845+ rtf: (wall > 0.0 && duration_s > 0.0).then_some(duration_s / wall),
846+ });
847+ }
848+}
849+
468 // ---------------------------------------------------------------------------850 // ---------------------------------------------------------------------------
469 // images: one decode entry point (`ec_image::decode`) covers every format851 // images: one decode entry point (`ec_image::decode`) covers every format
470 // the crate sniffs, so every real-library still is a candidate.852 // the crate sniffs, so every real-library still is a candidate.