forge
Explore
Log in

Don't you dare go Hollow

Merge lane-av1skipfix @ 960be978 — skip-on-decode-error gates converted to attempt loops + EC_REQUIRE_FIXTURES

Browse files at this commit

605faee2f85ce9ce0ed111369a62deaa6438129aAhmet Kaan GümüşParent: 4c92898b1ef0d6
- crates/ec-av1/src/refusal_inventory.rs: GATES_THAT_SKIP_ON_A_DECODE_ERROR
  emptied — the four arms it named now loop.
- crates/ec-av1/src/stream.rs: a_real_aomenc_lossless_444_key_frame
  (a_real_aomenc_lossless_444_key_frame_decodes_sample_exact) stops reporting
  green on a missing pin; the 444 pin arm honours the repo-wide
  EC_REQUIRE_FIXTURES.
- crates/ec-flac/tests/xiph_vectors.rs, crates/ec-h264/tests/conformance.rs,
  crates/ec-opus/tests/conformance.rs: a missing corpus FAILS under
  EC_REQUIRE_FIXTURES.
- scripts/link-fixtures.sh: give a worktree the gitignored root fixtures/.
- lanes/av1skipfix.report.md (incl. the per-crate assert-site rows),
  lanes/COMMON-20260901.md.

The four-crate fixture asserts (ec-h264 / ec-flac / ec-opus / ec-av1) are
covered by this lane's own report — see lanes/av1skipfix.report.md, per-crate
assert-site rows; no separate coverage task is opened for them.

Tip note: the branch head b696d485 is three commits past this tip
(commit the 444 lossless key-frame pin, rewire its gate onto
CARGO_MANIFEST_DIR, extend the report) and is NOT merged here; the dispatched
tip is 960be978.
crates/ec-av1/src/refusal_inventory.rsmodified+13 -10
@@ -591,17 +591,20 @@ const PROVEN: &[(&str, &str)] = &[
591 /// A gate named `..._decodes_pixel_exact` that cannot decode has failed, and591 /// A gate named `..._decodes_pixel_exact` that cannot decode has failed, and
592 /// swallowing the error keeps the suite green while the gate proves nothing --592 /// swallowing the error keeps the suite green while the gate proves nothing --
593 /// the same vacuum as a gate whose feature never fires, arrived at from the593 /// the same vacuum as a gate whose feature never fires, arrived at from the
594-/// other side. These four predate the attempt-loop pattern the newer gates use594+/// other side. The list is the exact pin of the gates still shaped that way, so
595-/// (encode several fixtures, require at least one to decode, hard-assert the595+/// the set cannot grow; a converted gate is DELETED from it.
596-/// firing count). They are pinned here so the set cannot grow while they are596+///
597-/// converted one at a time.597+/// lane-av1skipfix: emptied. The last four (`filter_intra`, the two
598+/// `deblocking` gates, and `gradients_stream_with_cdef`) were converted to the
599+/// attempt-loop pattern -- several recipes, at least one required to decode, the
600+/// feature counter hard-asserted on a pixel-compared attempt, a decode error on
601+/// every attempt a hard failure carrying its refusal text. None of the four had
602+/// a genuinely absent capability: every recipe family decoded, the refusals the
603+/// old arms swallowed were a named *screen-content* refusal on one recipe and a
604+/// stale premise on the CDEF gate (a single-superblock frame cannot make libaom
605+/// write `cdef_bits > 0`, so the old recipe never read a `cdef_idx` at all).
598 #[cfg(test)]606 #[cfg(test)]
599-const GATES_THAT_SKIP_ON_A_DECODE_ERROR: &[&str] = &[607+const GATES_THAT_SKIP_ON_A_DECODE_ERROR: &[&str] = &[];
600- "a_real_aomenc_filter_intra_stream_decodes_pixel_exact",
601- "a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact",
602- "a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact",
603- "a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact",
604-];
605 608
606 #[cfg(test)]609 #[cfg(test)]
607 mod tests {610 mod tests {
crates/ec-av1/src/stream.rsmodified+339 -107
@@ -6492,14 +6492,40 @@ pub(crate) mod tests {
6492 eprintln!("SKIP {NAME}: no ffmpeg");6492 eprintln!("SKIP {NAME}: no ffmpeg");
6493 return;6493 return;
6494 }6494 }
6495- let Ok(stream) = std::fs::read(pin_dir().join("ll444-lossless-key.obu")) else {6495+ // lane-av1skipfix: this arm used to be a bare SKIP, so on any box
6496+ // without the pin (the root `fixtures/` directory is GITIGNORED --
6497+ // `.gitignore:2` -- so a fresh clone, and every linked worktree, can
6498+ // never have it) the gate reported green having decoded nothing.
6499+ // `EC_REQUIRE_FIXTURES=1` -- the repo-wide fixture env, same as the
6500+ // ec-h264/ec-flac/ec-opus conformance gates -- or this crate's own
6501+ // `EC_AV1_REQUIRE_AOMENC=1` turns it into a hard failure naming the
6502+ // missing pin, the exact regeneration recipe and the
6503+ // `EC_AV1_PIN_DIR` override, so a batch run cannot report green off it.
6504+ let pin = pin_dir().join("ll444-lossless-key.obu");
6505+ let stream = match std::fs::read(&pin) {
6506+ Ok(stream) => stream,
6507+ Err(e) => {
6508+ assert!(
6509+ std::env::var_os("EC_REQUIRE_FIXTURES").is_none()
6510+ && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(),
6511+ "{NAME}: the pinned 4:4:4 lossless key frame is missing at {} ({e}). \
6512+ This gate would prove nothing. A worktree has no gitignored root \
6513+ `fixtures/`: run scripts/link-fixtures.sh. No script generates this \
6514+ pin -- regenerate it with `testsrc2 128x96` yuv444p 6 frames, aomenc \
6515+ --profile=1 --lossless=1 --enable-palette=0 --enable-intrabc=0, cut to \
6516+ the key frame's OBUs -- or point EC_AV1_PIN_DIR at a directory that has it.",
6517+ pin.display()
6518+ );
6496 eprintln!(6519 eprintln!(
6497- "SKIP {NAME}: no pinned bytes at {} -- regenerate with \6520+ "SKIP {NAME}: no pinned bytes at {} ({e}) -- this gate decoded nothing \
6521+ and proves nothing; run scripts/link-fixtures.sh, or regenerate with \
6498 `testsrc2 128x96` yuv444p 6 frames, aomenc --profile=1 --lossless=1 \6522 `testsrc2 128x96` yuv444p 6 frames, aomenc --profile=1 --lossless=1 \
6499- --enable-palette=0 --enable-intrabc=0, cut to the key frame's OBUs",6523+ --enable-palette=0 --enable-intrabc=0, cut to the key frame's OBUs \
6500- pin_dir().join("ll444-lossless-key.obu").display()6524+ (or set EC_REQUIRE_FIXTURES=1 to make this a failure).",
6525+ pin.display()
6501 );6526 );
6502 return;6527 return;
6528+ }
6503 };6529 };
6504 // Blindness guard: the pinned fixture must really be a lossless frame.6530 // Blindness guard: the pinned fixture must really be a lossless frame.
6505 let mut parser = Av1Parser::new();6531 let mut parser = Av1Parser::new();
@@ -8572,26 +8598,55 @@ pub(crate) mod tests {
8572 /// CDEF *on* (no `-enable-cdef 0`) -- the whole point of `lane-av1cdef`:8598 /// CDEF *on* (no `-enable-cdef 0`) -- the whole point of `lane-av1cdef`:
8573 /// proves `apply_cdef` itself, not just that this decoder still works8599 /// proves `apply_cdef` itself, not just that this decoder still works
8574 /// when the filter never fires. Gradient content at a low crf reliably8600 /// when the filter never fires. Gradient content at a low crf reliably
8575- /// gives libaom something to dering. If a run happens to land on8601+ /// gives libaom something to dering.
8576- /// `cdef_bits > 0` (per-64x64 `cdef_idx`, still unimplemented -- see the8602+ ///
8577- /// refusal in `decode_stream`) the stream is skipped rather than failed:8603+ /// lane-av1skipfix: the attempt-loop shape. A single-SB 64x64 frame can
8578- /// that gap is named by the refusal's own error text, not silently8604+ /// never make libaom write `cdef_bits > 0` (nothing to differentiate per
8579- /// swallowed here.8605+ /// superblock), so this recipe is MULTI-SB and MULTI-FRAME, and it sweeps
8606+ /// (size, cpu-used, crf) until one attempt reads a real `cdef_idx` literal
8607+ /// -- MEASURED 2026-09-29 on `a21f3680`: 64x64 at every crf/cpu reads
8608+ /// ZERO `cdef_idx` (single superblock, `bits == 0`, though `apply_cdef`
8609+ /// does filter with a nonzero strength pair), while 128x64/128x128 at
8610+ /// 24 frames read 2-8. Every attempt that decodes is ALWAYS pixel-
8611+ /// compared against ffmpeg's own decode of the identical bytes; a decode
8612+ /// error is a named refusal recorded per attempt, never a SKIP, and
8613+ /// exhausting every attempt -- or decoding without ever reading a
8614+ /// `cdef_idx` -- is a hard FAILURE (an unfired gate is a vacuous gate,
8615+ /// class `gate-skips-on-its-own-failure`).
8580 #[test]8616 #[test]
8581 fn a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact() {8617 fn a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact() {
8618+ const NAME: &str = "a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact";
8619+ let _gate_lock = lock_gate_counters();
8582 if !have_ffmpeg() {8620 if !have_ffmpeg() {
8583- eprintln!(8621+ eprintln!("SKIP {NAME}: no ffmpeg");
8584- "SKIP a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact: no ffmpeg"
8585- );
8586 return;8622 return;
8587 }8623 }
8588- let (width, height) = (64, 64);8624+ // (width, height, frames, cpu-used, crf). The frame count is what
8589- let stream = libaom_encode_with(8625+ // gives libaom's cdef search more than one superblock to price.
8590- &gradients_source(42, width, height, "rate=1"),8626+ const RECIPES: [(usize, usize, usize, &str, u32); 8] = [
8591- width,8627+ (128, 64, 24, "0", 20),
8592- height,8628+ (128, 64, 24, "2", 20),
8593- 30,8629+ (128, 64, 24, "0", 16),
8630+ (128, 128, 24, "2", 20),
8631+ (128, 128, 24, "0", 16),
8632+ (128, 128, 24, "0", 24),
8633+ (128, 64, 24, "2", 24),
8634+ (128, 128, 24, "2", 24),
8635+ ];
8636+ let mut refusals = Vec::new();
8637+ let mut counted_exact = 0u32;
8638+ let mut uncounted_exact = 0u32;
8639+ for (w, h, frames, cpu, crf) in RECIPES {
8640+ let Some(stream) = libaom_encode_with(
8641+ &gradients_source(42, w, h, "rate=25"),
8642+ w,
8643+ h,
8644+ crf,
8594 &[8645 &[
8646+ "-cpu-used",
8647+ cpu,
8648+ "-frames:v",
8649+ &frames.to_string(),
8595 "-threads",8650 "-threads",
8596 "1",8651 "1",
8597 "-row-mt",8652 "-row-mt",
@@ -8601,19 +8656,60 @@ pub(crate) mod tests {
8601 "-tile-rows",8656 "-tile-rows",
8602 "0",8657 "0",
8603 ],8658 ],
8604- )8659+ ) else {
8605- .expect("ffmpeg encode");8660+ refusals.push(format!(
8606- match decode_stream(&stream) {8661+ "{w}x{h} cpu-used {cpu} crf {crf}: ffmpeg itself refused"
8607- Ok(frames) => {8662+ ));
8608- let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);8663+ continue;
8609- assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg (CDEF on)");8664+ };
8610- assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (CDEF on)");8665+ let before = decode::cdef_idx_hits();
8611- assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (CDEF on)");8666+ let decoded = match decode_stream(&stream) {
8612- }8667+ Ok(frames) => frames,
8613 Err(e) => {8668 Err(e) => {
8614- eprintln!("SKIP a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact: {e}");8669+ refusals.push(format!("{w}x{h} cpu-used {cpu} crf {crf}: {e}"));
8670+ continue;
8615 }8671 }
8672+ };
8673+ // A decode that succeeded is ALWAYS pixel-compared; the hit
8674+ // counter only decides whether the attempt counts as firing
8675+ // (class `counter-from-refused-stream`).
8676+ let counted = decode::cdef_idx_hits() != before;
8677+ if counted {
8678+ counted_exact += 1;
8679+ } else {
8680+ uncounted_exact += 1;
8616 }8681 }
8682+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, w, h, frames);
8683+ assert_eq!(decoded.len(), frames);
8684+ for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
8685+ assert_eq!(
8686+ got.y, want.y,
8687+ "{NAME} frame {i} luma vs ffmpeg ({w}x{h} cpu-used {cpu} crf {crf}, \
8688+ cdef_idx fired: {counted})"
8689+ );
8690+ assert_eq!(
8691+ got.u, want.u,
8692+ "{NAME} frame {i} U vs ffmpeg ({w}x{h} cpu-used {cpu} crf {crf}, \
8693+ cdef_idx fired: {counted})"
8694+ );
8695+ assert_eq!(
8696+ got.v, want.v,
8697+ "{NAME} frame {i} V vs ffmpeg ({w}x{h} cpu-used {cpu} crf {crf}, \
8698+ cdef_idx fired: {counted})"
8699+ );
8700+ }
8701+ if counted_exact >= 2 {
8702+ break;
8703+ }
8704+ }
8705+ gate_buckets(NAME, counted_exact, uncounted_exact, refusals.len());
8706+ assert!(
8707+ counted_exact > 0,
8708+ "{NAME}: no attempt of {} read a cdef_idx literal -- CDEF is not exercised \
8709+ (class gate-blind-to-feature):\n{}",
8710+ RECIPES.len(),
8711+ refusals.join("\n")
8712+ );
8617 }8713 }
8618 8714
8619 /// Path to a real `aomenc` build carrying the reference options this8715 /// Path to a real `aomenc` build carrying the reference options this
@@ -8996,35 +9092,64 @@ pub(crate) mod tests {
8996 /// decoder has no in-loop deblocking filter at all, and libaom's default9092 /// decoder has no in-loop deblocking filter at all, and libaom's default
8997 /// (on) smooths every block-boundary column, which first looked like a9093 /// (on) smooths every block-boundary column, which first looked like a
8998 /// filter-intra math bug (mismatches straddling the 32-pixel block9094 /// filter-intra math bug (mismatches straddling the 32-pixel block
8999- /// seam) until the recipe without it round-tripped byte-exact. Checks9095+ /// seam) until the recipe without it round-tripped byte-exact.
9000- /// [`decode::filter_intra_hits`] actually moved (a process-global9096+ ///
9001- /// counter, so before/after rather than an absolute value) to prove the9097+ /// lane-av1skipfix: the attempt-loop shape this gate's single recipe
9002- /// symbol fired, then pixel-exactness against ffmpeg's own decode of the9098+ /// lacked. It sweeps (seed, cq) and REQUIRES at least one attempt to both
9003- /// identical bytes on every plane.9099+ /// decode and read `use_filter_intra`: a decode error on EVERY attempt is
9100+ /// a hard failure carrying the refusal texts, not a printed SKIP, and an
9101+ /// attempt that decodes without the symbol firing is still pixel-compared
9102+ /// (class `gate-skips-on-its-own-failure`). MEASURED 2026-09-29 on
9103+ /// `a21f3680`: seed 42 cq 40 and seed 43 cq 40 read the symbol 3x each,
9104+ /// pixel-exact, while seed 44 cq 45 and seed 45 cq 30 decode WITHOUT it --
9105+ /// so the one fixed recipe really did carry the whole gate.
9106+ ///
9107+ /// The per-attempt decode error the old single recipe SKIPped on is
9108+ /// `screen_content_tools_determination` (libaom `encoder_utils.c`): a real
9109+ /// internal trial-encode/PSNR comparison, not a flag this CLI exposes a
9110+ /// knob for -- on this flat gradient fixture it lands on
9111+ /// `allow_screen_content_tools=0` most runs but occasionally trips over
9112+ /// its 0.9 dB threshold the other way even with palette/intrabc both
9113+ /// disabled. That is a genuine separate gap (`decode_stream` never reads
9114+ /// `intrabc`/`palette_mode_info`), so it is a NAMED REFUSAL counted per
9115+ /// attempt, never a silent skip and never a pass.
9004 #[test]9116 #[test]
9005 fn a_real_aomenc_filter_intra_stream_decodes_pixel_exact() {9117 fn a_real_aomenc_filter_intra_stream_decodes_pixel_exact() {
9118+ const NAME: &str = "a_real_aomenc_filter_intra_stream_decodes_pixel_exact";
9119+ let _gate_lock = lock_gate_counters();
9006 if !have_ffmpeg() {9120 if !have_ffmpeg() {
9007- eprintln!("SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: no ffmpeg");9121+ eprintln!("SKIP {NAME}: no ffmpeg");
9008 return;9122 return;
9009 }9123 }
9010 if !have_aomenc() {9124 if !have_aomenc() {
9011- eprintln!(9125+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
9012- "SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: no aomenc at {}",
9013- aomenc_path().display()
9014- );
9015 return;9126 return;
9016 }9127 }
9017 let (width, height) = (64usize, 64usize);9128 let (width, height) = (64usize, 64usize);
9018- // Recipe-search hooks: with the encoder pinned to one thread the9129+ // Recipe-search hooks: with the encoder pinned to one thread the stream
9019- // stream is a deterministic function of (seed, cq), so a firing recipe9130+ // is a deterministic function of (seed, cq), so a firing recipe can be
9020- // can be searched for without a rebuild.9131+ // searched for without a rebuild. These pin attempt 0 for a bisect; the
9132+ // sweep walks the same axes regardless.
9021 let fi_seed: u32 = std::env::var("EC_FI_SEED")9133 let fi_seed: u32 = std::env::var("EC_FI_SEED")
9022 .ok()9134 .ok()
9023 .and_then(|v| v.parse().ok())9135 .and_then(|v| v.parse().ok())
9024 .unwrap_or(42);9136 .unwrap_or(42);
9025- let fi_source = gradients_source(fi_seed, 64, 64, "duration=0.04:rate=25");9137+ let fi_cq: u32 = std::env::var("EC_FI_CQ")
9026- let fi_cq = std::env::var("EC_FI_CQ").unwrap_or_else(|_| "40".to_string());9138+ .ok()
9027- let fi_cq_arg = format!("--cq-level={fi_cq}");9139+ .and_then(|v| v.parse().ok())
9140+ .unwrap_or(40);
9141+ // Two seeds x three quantisers, so "every attempt refused" and "no
9142+ // attempt ever read `use_filter_intra`" are distinguishable failures
9143+ // rather than one unlucky recipe.
9144+ const CQS: [u32; 3] = [40, 35, 30];
9145+ let mut refusals = Vec::new();
9146+ let mut counted_exact = 0u32;
9147+ let mut uncounted_exact = 0u32;
9148+ 'attempts: for round in 0..2u32 {
9149+ for (i, &walked) in CQS.iter().enumerate() {
9150+ let seed = fi_seed + round;
9151+ let cq = if round == 0 && i == 0 { fi_cq } else { walked };
9152+ let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
9028 let y4m = Command::new("ffmpeg")9153 let y4m = Command::new("ffmpeg")
9029 .args([9154 .args([
9030 "-v",9155 "-v",
@@ -9032,7 +9157,7 @@ pub(crate) mod tests {
9032 "-f",9157 "-f",
9033 "lavfi",9158 "lavfi",
9034 "-i",9159 "-i",
9035- &fi_source,9160+ &source,
9036 "-pix_fmt",9161 "-pix_fmt",
9037 "yuv420p",9162 "yuv420p",
9038 "-f",9163 "-f",
@@ -9049,12 +9174,13 @@ pub(crate) mod tests {
9049 "ffmpeg refused to generate the y4m fixture: {}",9174 "ffmpeg refused to generate the y4m fixture: {}",
9050 String::from_utf8_lossy(&y4m.stderr)9175 String::from_utf8_lossy(&y4m.stderr)
9051 );9176 );
9177+ let cq_arg = format!("--cq-level={cq}");
9052 let out = run_with_stdin(9178 let out = run_with_stdin(
9053 Command::new(aomenc_path()).args([9179 Command::new(aomenc_path()).args([
9054 "--codec=av1",9180 "--codec=av1",
9055 "--passes=1",9181 "--passes=1",
9056 "--end-usage=q",9182 "--end-usage=q",
9057- &fi_cq_arg,9183+ &cq_arg,
9058 "--cpu-used=0",9184 "--cpu-used=0",
9059 // Every sibling gate pins these; this one did not, and a9185 // Every sibling gate pins these; this one did not, and a
9060 // multi-threaded aomenc is not deterministic, so each run9186 // multi-threaded aomenc is not deterministic, so each run
@@ -9084,36 +9210,53 @@ pub(crate) mod tests {
9084 );9210 );
9085 assert!(9211 assert!(
9086 out.status.success(),9212 out.status.success(),
9087- "aomenc refused the fixture: {}",9213+ "{NAME}: aomenc refused the seed {seed} cq {cq} fixture: {}",
9088 String::from_utf8_lossy(&out.stderr)9214 String::from_utf8_lossy(&out.stderr)
9089 );9215 );
9090 let stream = out.stdout;9216 let stream = out.stdout;
9091 let before = decode::filter_intra_hits();9217 let before = decode::filter_intra_hits();
9092- // `screen_content_tools_determination` (libaom encoder_utils.c) is a
9093- // real internal trial-encode/PSNR comparison, not a flag this CLI
9094- // exposes a knob for -- on this flat gradient fixture it lands on
9095- // `allow_screen_content_tools=0` most runs but occasionally trips
9096- // over its 0.9 dB threshold the other way even with palette/intrabc
9097- // both disabled. That is a genuine separate gap (`decode_stream`
9098- // never reads `intrabc`/`palette_mode_info`), not a filter-intra
9099- // regression, so it is skipped here exactly as
9100- // `a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact`
9101- // above skips its own still-unsupported-gap runs.
9102 let frames = match decode_stream(&stream) {9218 let frames = match decode_stream(&stream) {
9103 Ok(frames) => frames,9219 Ok(frames) => frames,
9104 Err(e) => {9220 Err(e) => {
9105- eprintln!("SKIP a_real_aomenc_filter_intra_stream_decodes_pixel_exact: {e}");9221+ refusals.push(format!("seed {seed} cq {cq}: {e}"));
9106- return;9222+ continue;
9107 }9223 }
9108 };9224 };
9225+ // A decode that succeeded is ALWAYS pixel-compared; the hit
9226+ // counter only decides whether the attempt counts as firing
9227+ // (class `counter-from-refused-stream`).
9228+ let counted = decode::filter_intra_hits() != before;
9229+ if counted {
9230+ counted_exact += 1;
9231+ } else {
9232+ uncounted_exact += 1;
9233+ }
9234+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
9235+ assert_eq!(
9236+ frames[0].y, ffmpeg_frames[0].y,
9237+ "luma vs ffmpeg (seed {seed} cq {cq}, use_filter_intra fired: {counted})"
9238+ );
9239+ assert_eq!(
9240+ frames[0].u, ffmpeg_frames[0].u,
9241+ "U vs ffmpeg (seed {seed} cq {cq}, use_filter_intra fired: {counted})"
9242+ );
9243+ assert_eq!(
9244+ frames[0].v, ffmpeg_frames[0].v,
9245+ "V vs ffmpeg (seed {seed} cq {cq}, use_filter_intra fired: {counted})"
9246+ );
9247+ if counted_exact >= 2 {
9248+ break 'attempts;
9249+ }
9250+ }
9251+ }
9252+ gate_buckets(NAME, counted_exact, uncounted_exact, refusals.len());
9109 assert!(9253 assert!(
9110- decode::filter_intra_hits() > before,9254+ counted_exact > 0,
9111- "use_filter_intra never fired decoding this stream"9255+ "{NAME}: none of {} attempts decoded a stream that read use_filter_intra -- the \
9256+ gate would prove nothing (class gate-blind-to-feature):\n{}",
9257+ CQS.len() * 2,
9258+ refusals.join("\n")
9112 );9259 );
9113- let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
9114- assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
9115- assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
9116- assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
9117 }9260 }
9118 9261
9119 /// A real `aomenc` palette-Y fixture (lane-palette r3): `smptebars`9262 /// A real `aomenc` palette-Y fixture (lane-palette r3): `smptebars`
@@ -14759,23 +14902,37 @@ pub(crate) mod tests {
14759 /// picks a nonzero level -- proves `apply_deblock` itself, not just that14902 /// picks a nonzero level -- proves `apply_deblock` itself, not just that
14760 /// this decoder still works when every edge lands on level 0. CDEF14903 /// this decoder still works when every edge lands on level 0. CDEF
14761 /// stays off so a pixel mismatch can only come from the loop filter.14904 /// stays off so a pixel mismatch can only come from the loop filter.
14905+ ///
14906+ /// lane-av1skipfix: the attempt-loop shape. The sweep walks cq (which is
14907+ /// what decides whether libaom picks a nonzero deblocking level at all)
14908+ /// and seed, REQUIRES at least one attempt to decode, and hard-asserts
14909+ /// `decode::deblock_hits` on a pixel-compared attempt -- a decode error on
14910+ /// every attempt is a hard failure carrying the refusal texts, never a
14911+ /// printed SKIP (class `gate-skips-on-its-own-failure`). MEASURED
14912+ /// 2026-09-29 on `a21f3680`: cq 55/45/35/63 all decode pixel-exact with
14913+ /// 48/64/64/64 deblock edges, so the old single recipe was one lucky
14914+ /// point of a cq range that needed no fallback.
14762 #[test]14915 #[test]
14763 fn a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact() {14916 fn a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact() {
14917+ const NAME: &str = "a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact";
14918+ let _gate_lock = lock_gate_counters();
14764 if !have_ffmpeg() {14919 if !have_ffmpeg() {
14765- eprintln!(14920+ eprintln!("SKIP {NAME}: no ffmpeg");
14766- "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: no ffmpeg"
14767- );
14768 return;14921 return;
14769 }14922 }
14770 if !have_aomenc() {14923 if !have_aomenc() {
14771- eprintln!(14924+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
14772- "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: no aomenc at {}",
14773- aomenc_path().display()
14774- );
14775 return;14925 return;
14776 }14926 }
14777 let (width, height) = (64usize, 64usize);14927 let (width, height) = (64usize, 64usize);
14778- let source = gradients_source(42, width, height, "duration=0.04:rate=25");14928+ // Two seeds x four quantisers.
14929+ const CQS: [u32; 4] = [55, 45, 35, 63];
14930+ let mut refusals = Vec::new();
14931+ let mut counted_exact = 0u32;
14932+ let mut uncounted_exact = 0u32;
14933+ 'attempts: for round in 0..2u32 {
14934+ for cq in CQS {
14935+ let source = gradients_source(42 + round, width, height, "duration=0.04:rate=25");
14779 let y4m = Command::new("ffmpeg")14936 let y4m = Command::new("ffmpeg")
14780 .args(["-v", "error", "-f", "lavfi", "-i"])14937 .args(["-v", "error", "-f", "lavfi", "-i"])
14781 .arg(&source)14938 .arg(&source)
@@ -14787,9 +14944,11 @@ pub(crate) mod tests {
14787 .expect("ffmpeg failed to run");14944 .expect("ffmpeg failed to run");
14788 assert!(14945 assert!(
14789 y4m.status.success(),14946 y4m.status.success(),
14790- "ffmpeg fixture: {}",14947+ "{NAME}: ffmpeg fixture (seed {} cq {cq}): {}",
14948+ 42 + round,
14791 String::from_utf8_lossy(&y4m.stderr)14949 String::from_utf8_lossy(&y4m.stderr)
14792 );14950 );
14951+ let cq_arg = format!("--cq-level={cq}");
14793 let out = run_with_stdin(14952 let out = run_with_stdin(
14794 Command::new(aomenc_path()).args([14953 Command::new(aomenc_path()).args([
14795 // lane-defon r1: explicit on-value (aomenc keeps the FIRST14954 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
@@ -14798,7 +14957,7 @@ pub(crate) mod tests {
14798 "--codec=av1",14957 "--codec=av1",
14799 "--passes=1",14958 "--passes=1",
14800 "--end-usage=q",14959 "--end-usage=q",
14801- "--cq-level=55",14960+ &cq_arg,
14802 "--cpu-used=0",14961 "--cpu-used=0",
14803 "--enable-filter-intra=0",14962 "--enable-filter-intra=0",
14804 "--enable-smooth-intra=0",14963 "--enable-smooth-intra=0",
@@ -14827,7 +14986,8 @@ pub(crate) mod tests {
14827 );14986 );
14828 assert!(14987 assert!(
14829 out.status.success(),14988 out.status.success(),
14830- "aomenc refused the fixture: {}",14989+ "{NAME}: aomenc refused the seed {} cq {cq} fixture: {}",
14990+ 42 + round,
14831 String::from_utf8_lossy(&out.stderr)14991 String::from_utf8_lossy(&out.stderr)
14832 );14992 );
14833 let stream = out.stdout;14993 let stream = out.stdout;
@@ -14835,20 +14995,51 @@ pub(crate) mod tests {
14835 let frames = match decode_stream(&stream) {14995 let frames = match decode_stream(&stream) {
14836 Ok(frames) => frames,14996 Ok(frames) => frames,
14837 Err(e) => {14997 Err(e) => {
14838- eprintln!(14998+ refusals.push(format!("seed {} cq {cq}: {e}", 42 + round));
14839- "SKIP a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact: {e}"14999+ continue;
14840- );
14841- return;
14842 }15000 }
14843 };15001 };
15002+ // A decode that succeeded is ALWAYS pixel-compared; the hit
15003+ // counter only decides whether the attempt counts as firing
15004+ // (class `counter-from-refused-stream`).
15005+ let counted = decode::deblock_hits() != before;
15006+ if counted {
15007+ counted_exact += 1;
15008+ } else {
15009+ uncounted_exact += 1;
15010+ }
15011+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
15012+ assert_eq!(
15013+ frames[0].y,
15014+ ffmpeg_frames[0].y,
15015+ "luma vs ffmpeg (seed {} cq {cq}, deblock fired: {counted})",
15016+ 42 + round
15017+ );
15018+ assert_eq!(
15019+ frames[0].u,
15020+ ffmpeg_frames[0].u,
15021+ "U vs ffmpeg (seed {} cq {cq}, deblock fired: {counted})",
15022+ 42 + round
15023+ );
15024+ assert_eq!(
15025+ frames[0].v,
15026+ ffmpeg_frames[0].v,
15027+ "V vs ffmpeg (seed {} cq {cq}, deblock fired: {counted})",
15028+ 42 + round
15029+ );
15030+ if counted_exact >= 2 {
15031+ break 'attempts;
15032+ }
15033+ }
15034+ }
15035+ gate_buckets(NAME, counted_exact, uncounted_exact, refusals.len());
14844 assert!(15036 assert!(
14845- decode::deblock_hits() > before,15037+ counted_exact > 0,
14846- "no deblocking edge fired decoding this stream -- raise cq-level"15038+ "{NAME}: none of {} attempts decoded a stream with a deblocking edge -- \
15039+ apply_deblock is unproven (class gate-blind-to-feature):\n{}",
15040+ CQS.len() * 2,
15041+ refusals.join("\n")
14847 );15042 );
14848- let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
14849- assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
14850- assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
14851- assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
14852 }15043 }
14853 15044
14854 /// As [`a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact`],15045 /// As [`a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact`],
@@ -21869,23 +22060,40 @@ pub(crate) mod tests {
21869 );22060 );
21870 }22061 }
21871 22062
22063+ /// The inter-frame twin of
22064+ /// [`a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact`]:
22065+ /// deblocking left *on* at a crf high enough that libaom picks a nonzero
22066+ /// level, CDEF off, so a pixel mismatch can only come from the loop
22067+ /// filter -- and over a real 4-frame INTER sequence, not one key frame.
22068+ ///
22069+ /// lane-av1skipfix: the attempt-loop shape. The sweep walks cq and seed,
22070+ /// REQUIRES at least one attempt to decode, and hard-asserts
22071+ /// `decode::deblock_hits` on a pixel-compared attempt; a decode error on
22072+ /// every attempt is a hard failure carrying the refusal texts, never a
22073+ /// printed SKIP (class `gate-skips-on-its-own-failure`). MEASURED
22074+ /// 2026-09-29 on `a21f3680`: cq 55/45/35/63 all decode 4 frames
22075+ /// pixel-exact with 208/224/160/208 deblock edges.
21872 #[test]22076 #[test]
21873 fn a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact() {22077 fn a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact() {
22078+ const NAME: &str = "a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact";
22079+ let _gate_lock = lock_gate_counters();
21874 if !have_ffmpeg() {22080 if !have_ffmpeg() {
21875- eprintln!(22081+ eprintln!("SKIP {NAME}: no ffmpeg");
21876- "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: no ffmpeg"
21877- );
21878 return;22082 return;
21879 }22083 }
21880 if !have_aomenc() {22084 if !have_aomenc() {
21881- eprintln!(22085+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
21882- "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: no aomenc at {}",
21883- aomenc_path().display()
21884- );
21885 return;22086 return;
21886 }22087 }
21887 let (width, height, frame_count) = (64usize, 64usize, 4usize);22088 let (width, height, frame_count) = (64usize, 64usize, 4usize);
21888- let source = gradients_source(42, width, height, "duration=0.16:rate=25");22089+ // Two seeds x four quantisers.
22090+ const CQS: [u32; 4] = [55, 45, 35, 63];
22091+ let mut refusals = Vec::new();
22092+ let mut counted_exact = 0u32;
22093+ let mut uncounted_exact = 0u32;
22094+ 'attempts: for round in 0..2u32 {
22095+ for cq in CQS {
22096+ let source = gradients_source(42 + round, width, height, "duration=0.16:rate=25");
21889 let y4m = Command::new("ffmpeg")22097 let y4m = Command::new("ffmpeg")
21890 .args(["-v", "error", "-f", "lavfi", "-i"])22098 .args(["-v", "error", "-f", "lavfi", "-i"])
21891 .arg(&source)22099 .arg(&source)
@@ -21897,9 +22105,11 @@ pub(crate) mod tests {
21897 .expect("ffmpeg failed to run");22105 .expect("ffmpeg failed to run");
21898 assert!(22106 assert!(
21899 y4m.status.success(),22107 y4m.status.success(),
21900- "ffmpeg fixture: {}",22108+ "{NAME}: ffmpeg fixture (seed {} cq {cq}): {}",
22109+ 42 + round,
21901 String::from_utf8_lossy(&y4m.stderr)22110 String::from_utf8_lossy(&y4m.stderr)
21902 );22111 );
22112+ let cq_arg = format!("--cq-level={cq}");
21903 let out = run_with_stdin(22113 let out = run_with_stdin(
21904 Command::new(aomenc_path()).args([22114 Command::new(aomenc_path()).args([
21905 // lane-defon r1: explicit on-value (aomenc keeps the FIRST22115 // lane-defon r1: explicit on-value (aomenc keeps the FIRST
@@ -21908,7 +22118,7 @@ pub(crate) mod tests {
21908 "--codec=av1",22118 "--codec=av1",
21909 "--passes=1",22119 "--passes=1",
21910 "--end-usage=q",22120 "--end-usage=q",
21911- "--cq-level=55",22121+ &cq_arg,
21912 "--cpu-used=0",22122 "--cpu-used=0",
21913 "--lag-in-frames=0",22123 "--lag-in-frames=0",
21914 "--auto-alt-ref=0",22124 "--auto-alt-ref=0",
@@ -21958,7 +22168,8 @@ pub(crate) mod tests {
21958 );22168 );
21959 assert!(22169 assert!(
21960 out.status.success(),22170 out.status.success(),
21961- "aomenc refused the fixture: {}",22171+ "{NAME}: aomenc refused the seed {} cq {cq} fixture: {}",
22172+ 42 + round,
21962 String::from_utf8_lossy(&out.stderr)22173 String::from_utf8_lossy(&out.stderr)
21963 );22174 );
21964 let stream = out.stdout;22175 let stream = out.stdout;
@@ -21969,16 +22180,19 @@ pub(crate) mod tests {
21969 let frames = match decode_stream(&stream) {22180 let frames = match decode_stream(&stream) {
21970 Ok(frames) => frames,22181 Ok(frames) => frames,
21971 Err(e) => {22182 Err(e) => {
21972- eprintln!(22183+ refusals.push(format!("seed {} cq {cq}: {e}", 42 + round));
21973- "SKIP a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact: {e}"22184+ continue;
21974- );
21975- return;
21976 }22185 }
21977 };22186 };
21978- assert!(22187+ // A decode that succeeded is ALWAYS pixel-compared; the hit
21979- decode::deblock_hits() > before,22188+ // counter only decides whether the attempt counts as firing
21980- "no deblocking edge fired decoding this sequence -- raise cq-level"22189+ // (class `counter-from-refused-stream`).
21981- );22190+ let counted = decode::deblock_hits() != before;
22191+ if counted {
22192+ counted_exact += 1;
22193+ } else {
22194+ uncounted_exact += 1;
22195+ }
21982 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);22196 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
21983 assert_eq!(frames.len(), frame_count);22197 assert_eq!(frames.len(), frame_count);
21984 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {22198 for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
@@ -21988,14 +22202,32 @@ pub(crate) mod tests {
21988 // bisectable (replay: EC_AV1_PIN on scratch_isolate_pinned_mismatch).22202 // bisectable (replay: EC_AV1_PIN on scratch_isolate_pinned_mismatch).
21989 let ok = got.y == want.y && got.u == want.u && got.v == want.v;22203 let ok = got.y == want.y && got.u == want.u && got.v == want.v;
21990 if !ok {22204 if !ok {
21991- let pin = std::env::temp_dir().join("ec-av1-deblocking-gate-fail.obu");22205+ let pin = std::env::temp_dir().join(format!(
22206+ "ec-av1-deblocking-gate-fail-s{}-cq{cq}.obu",
22207+ 42 + round
22208+ ));
21992 let _ = std::fs::write(&pin, &stream);22209 let _ = std::fs::write(&pin, &stream);
21993 panic!(22210 panic!(
21994- "frame {i} mismatch vs ffmpeg -- stream pinned at {}",22211+ "frame {i} mismatch vs ffmpeg (seed {} cq {cq}, deblock fired: \
22212+ {counted}) -- stream pinned at {}",
22213+ 42 + round,
21995 pin.display()22214 pin.display()
21996 );22215 );
21997 }22216 }
21998 }22217 }
22218+ if counted_exact >= 2 {
22219+ break 'attempts;
22220+ }
22221+ }
22222+ }
22223+ gate_buckets(NAME, counted_exact, uncounted_exact, refusals.len());
22224+ assert!(
22225+ counted_exact > 0,
22226+ "{NAME}: none of {} attempts decoded a sequence with a deblocking edge -- \
22227+ apply_deblock is unproven (class gate-blind-to-feature):\n{}",
22228+ CQS.len() * 2,
22229+ refusals.join("\n")
22230+ );
21999 }22231 }
22000 22232
22001 /// The decisive cross-frame CDF forwarding test: identical to22233 /// The decisive cross-frame CDF forwarding test: identical to
crates/ec-flac/tests/xiph_vectors.rsmodified+23 -1
@@ -21,7 +21,29 @@ fn corpus(kind: &str) -> Option<Vec<PathBuf>> {
21 let dir = Path::new(env!("CARGO_MANIFEST_DIR"))21 let dir = Path::new(env!("CARGO_MANIFEST_DIR"))
22 .join("../../fixtures/vectors/flac-xiph/flac-test-files-main")22 .join("../../fixtures/vectors/flac-xiph/flac-test-files-main")
23 .join(kind);23 .join(kind);
24- let mut files: Vec<PathBuf> = std::fs::read_dir(dir)24+ // A missing corpus made every gate below skip GREEN having decoded nothing
25+ // — the "gate skips on its own failure" class. The root `fixtures/` tree is
26+ // gitignored, so `git worktree add` hands every lane worktree a tree without
27+ // it. `EC_REQUIRE_FIXTURES=1` turns that into a hard failure naming the
28+ // exact path and the command that produces it; unset, the skip is kept and
29+ // now says what it skipped. Set it in every batch run.
30+ if !dir.is_dir() {
31+ assert!(
32+ std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
33+ "the FLAC xiph {kind} corpus is missing at {} — these gates would prove \
34+ nothing. A worktree has no gitignored root `fixtures/`: run \
35+ scripts/link-fixtures.sh, or fetch it with scripts/fetch-vectors.sh.",
36+ dir.display()
37+ );
38+ eprintln!(
39+ "SKIP the FLAC xiph {kind} corpus is missing at {} — these gates proved \
40+ nothing; run scripts/link-fixtures.sh, or fetch it with \
41+ scripts/fetch-vectors.sh (or set EC_REQUIRE_FIXTURES=1 to make this a failure).",
42+ dir.display()
43+ );
44+ return None;
45+ }
46+ let mut files: Vec<PathBuf> = std::fs::read_dir(&dir)
25 .ok()?47 .ok()?
26 .filter_map(|e| e.ok().map(|e| e.path()))48 .filter_map(|e| e.ok().map(|e| e.path()))
27 .filter(|p| p.extension().is_some_and(|e| e == "flac"))49 .filter(|p| p.extension().is_some_and(|e| e == "flac"))
crates/ec-h264/tests/conformance.rsmodified+58 -15
@@ -68,6 +68,34 @@ fn vectors_dir() -> PathBuf {
68 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/vectors/h264-jvt")68 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/vectors/h264-jvt")
69 }69 }
70 70
71+/// A gate that skips when its fixtures are absent reports GREEN having checked
72+/// nothing — the "gate skips on its own failure" class. The root `fixtures/`
73+/// directory is gitignored, so `git worktree add` hands every lane worktree a
74+/// tree without it and the whole conformance suite silently stops testing.
75+///
76+/// `EC_REQUIRE_FIXTURES=1` turns the skip into a hard failure naming the exact
77+/// missing path and the command that produces it; unset (the default), the skip
78+/// is kept and now says what it skipped. Set it in every batch run.
79+fn require_fixtures(path: &Path, what: &str, generator: &str) -> bool {
80+ if path.exists() {
81+ return true;
82+ }
83+ assert!(
84+ std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
85+ "{what} missing at {} — this gate would prove nothing. A worktree has no \
86+ gitignored root `fixtures/`: run scripts/link-fixtures.sh, or generate \
87+ them with {generator}.",
88+ path.display()
89+ );
90+ eprintln!(
91+ "SKIP {what} missing at {} — this gate proved nothing; run \
92+ scripts/link-fixtures.sh, or generate them with {generator} \
93+ (or set EC_REQUIRE_FIXTURES=1 to make this a failure).",
94+ path.display()
95+ );
96+ false
97+}
98+
71 /// Every vector directory `scripts/fetch-vectors.sh` has populated, in name99 /// Every vector directory `scripts/fetch-vectors.sh` has populated, in name
72 /// order.100 /// order.
73 ///101 ///
@@ -289,11 +317,11 @@ fn compare_sequence(stream: &Path) -> Result<usize, String> {
289 #[test]317 #[test]
290 fn jvt_cavlc_first_idr_bit_exact() {318 fn jvt_cavlc_first_idr_bit_exact() {
291 let base = vectors_dir();319 let base = vectors_dir();
292- if !base.is_dir() {320+ if !require_fixtures(
293- eprintln!(321+ &base,
294- "SKIP: {} missing — run scripts/fetch-vectors.sh",322+ "the JVT conformance vectors",
295- base.display()323+ "scripts/fetch-vectors.sh",
296- );324+ ) {
297 return;325 return;
298 }326 }
299 let mut passed = Vec::new();327 let mut passed = Vec::new();
@@ -396,8 +424,11 @@ fn jvt_cavlc_first_idr_bit_exact() {
396 #[test]424 #[test]
397 fn steady_state_decode_loop_zero_alloc() {425 fn steady_state_decode_loop_zero_alloc() {
398 let base = vectors_dir();426 let base = vectors_dir();
399- if !base.is_dir() {427+ if !require_fixtures(
400- eprintln!("SKIP: fixtures missing");428+ &base,
429+ "the JVT conformance vectors",
430+ "scripts/fetch-vectors.sh",
431+ ) {
401 return;432 return;
402 }433 }
403 // One stream per entropy coder, and one with B slices and multiple434 // One stream per entropy coder, and one with B slices and multiple
@@ -480,8 +511,11 @@ fn steady_state_decode_loop_zero_alloc() {
480 #[test]511 #[test]
481 fn ns_per_macroblock_measurement() {512 fn ns_per_macroblock_measurement() {
482 let base = vectors_dir();513 let base = vectors_dir();
483- if !base.is_dir() {514+ if !require_fixtures(
484- eprintln!("SKIP: fixtures missing");515+ &base,
516+ "the JVT conformance vectors",
517+ "scripts/fetch-vectors.sh",
518+ ) {
485 return;519 return;
486 }520 }
487 for name in [521 for name in [
@@ -564,8 +598,11 @@ fn perf_whole_sequence() {
564 #[test]598 #[test]
565 fn corrupt_streams_never_panic() {599 fn corrupt_streams_never_panic() {
566 let base = vectors_dir();600 let base = vectors_dir();
567- if !base.is_dir() {601+ if !require_fixtures(
568- eprintln!("SKIP: fixtures missing");602+ &base,
603+ "the JVT conformance vectors",
604+ "scripts/fetch-vectors.sh",
605+ ) {
569 return;606 return;
570 }607 }
571 // One stream per entropy coder, plus one with B slices and multiple608 // One stream per entropy coder, plus one with B slices and multiple
@@ -1070,8 +1107,11 @@ fn p_only_gop_matches_ffmpeg_every_frame() {
1070 #[test]1107 #[test]
1071 fn jvt_full_sequence_bit_exact() {1108 fn jvt_full_sequence_bit_exact() {
1072 let base = vectors_dir();1109 let base = vectors_dir();
1073- if !base.is_dir() {1110+ if !require_fixtures(
1074- eprintln!("SKIP: {} missing", base.display());1111+ &base,
1112+ "the JVT conformance vectors",
1113+ "scripts/fetch-vectors.sh",
1114+ ) {
1075 return;1115 return;
1076 }1116 }
1077 let mut table = String::new();1117 let mut table = String::new();
@@ -2313,8 +2353,11 @@ fn h264_seek_matches_linear_open_gop() {
2313 return;2353 return;
2314 }2354 }
2315 let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/video/h264-open-gop.mp4");2355 let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/video/h264-open-gop.mp4");
2316- if !src.is_file() {2356+ if !require_fixtures(
2317- eprintln!("SKIP: no fixtures/video/h264-open-gop.mp4 (run scripts/gen-fixtures.sh)");2357+ &src,
2358+ "the open-GOP fixture",
2359+ "scripts/gen-fixtures.sh (fixtures/video/h264-open-gop.mp4)",
2360+ ) {
2318 return;2361 return;
2319 }2362 }
2320 let dir = scratch("open-gop");2363 let dir = scratch("open-gop");
crates/ec-opus/tests/conformance.rsmodified+705 -212
@@ -412,11 +412,31 @@ const VECTORS: [&str; 12] = [
412 /// MUST stay within the `opus_compare` threshold (quality >= 0).412 /// MUST stay within the `opus_compare` threshold (quality >= 0).
413 #[test]413 #[test]
414 fn rfc6716_test_vectors() {414 fn rfc6716_test_vectors() {
415+ // A missing test vector made this gate skip GREEN having decoded nothing —
416+ // the "gate skips on its own failure" class. The root `fixtures/` tree is
417+ // gitignored, so `git worktree add` hands every lane worktree a tree without
418+ // it. `EC_REQUIRE_FIXTURES=1` turns a missing vector into a hard failure
419+ // naming the exact path and the command that produces it; unset, the skip
420+ // is kept and now says what it skipped. Set it in every batch run.
421+ let base = vectors_dir();
415 let mut table = Vec::new();422 let mut table = Vec::new();
416 for name in VECTORS {423 for name in VECTORS {
417- let path = vectors_dir().join(format!("{name}.bit"));424+ let path = base.join(format!("{name}.bit"));
418 if !path.exists() {425 if !path.exists() {
419- eprintln!("{name}: missing, skipped (run scripts/fetch-vectors.sh)");426+ assert!(
427+ std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
428+ "RFC 6716 test vector {name} missing at {} — this gate would prove \
429+ nothing. A worktree has no gitignored root `fixtures/`: run \
430+ scripts/link-fixtures.sh, or fetch it with scripts/fetch-vectors.sh.",
431+ path.display()
432+ );
433+ eprintln!(
434+ "SKIP RFC 6716 test vector {name} missing at {} — this gate proved \
435+ nothing; run scripts/link-fixtures.sh, or fetch it with \
436+ scripts/fetch-vectors.sh (or set EC_REQUIRE_FIXTURES=1 to make this \
437+ a failure).",
438+ path.display()
439+ );
420 continue;440 continue;
421 }441 }
422 let packets = read_vector(&path);442 let packets = read_vector(&path);
@@ -1595,7 +1615,14 @@ fn ogg_opus_round_trip_duration_is_exact() {
1595 let packets = encode_packets(&mut enc, &pcm, 2);1615 let packets = encode_packets(&mut enc, &pcm, 2);
1596 let path = temp_path("duration.opus");1616 let path = temp_path("duration.opus");
1597 let pre_skip = enc.look_ahead(960);1617 let pre_skip = enc.look_ahead(960);
1598- write_ogg_opus(&path, &packets, opus_head(2, pre_skip as u16, None), 2, total, pre_skip as i64);1618+ write_ogg_opus(
1619+ &path,
1620+ &packets,
1621+ opus_head(2, pre_skip as u16, None),
1622+ 2,
1623+ total,
1624+ pre_skip as i64,
1625+ );
1599 let probe = Command::new("ffprobe")1626 let probe = Command::new("ffprobe")
1600 .args([1627 .args([
1601 "-v",1628 "-v",
@@ -2380,7 +2407,14 @@ fn oracle_decode(
2380 return None;2407 return None;
2381 }2408 }
2382 let path = temp_path(&format!("{name}.opus"));2409 let path = temp_path(&format!("{name}.opus"));
2383- write_ogg_opus(&path, packets, opus_head(1, pre_skip as u16, None), 1, samples, pre_skip as i64);2410+ write_ogg_opus(
2411+ &path,
2412+ packets,
2413+ opus_head(1, pre_skip as u16, None),
2414+ 1,
2415+ samples,
2416+ pre_skip as i64,
2417+ );
2384 let out = Command::new("ffmpeg")2418 let out = Command::new("ffmpeg")
2385 .args(["-v", "warning", "-c:a", "libopus", "-i"])2419 .args(["-v", "warning", "-c:a", "libopus", "-i"])
2386 .arg(&path)2420 .arg(&path)
@@ -2557,7 +2591,10 @@ fn hybrid_layers_align() {
2557 (plb - phb).abs() <= 3,2591 (plb - phb).abs() <= 3,
2558 "layers misaligned: LB +{plb} vs HB +{phb}"2592 "layers misaligned: LB +{plb} vs HB +{phb}"
2559 );2593 );
2560- assert!((phb - delay).abs() <= 2, "HB peak +{phb}, look_ahead {delay}");2594+ assert!(
2595+ (phb - delay).abs() <= 2,
2596+ "HB peak +{phb}, look_ahead {delay}"
2597+ );
2561 }2598 }
2562 2599
2563 /// 20 ms FB hybrid at 32 kbps: decodes in our decoder range-exactly, tracks2600 /// 20 ms FB hybrid at 32 kbps: decodes in our decoder range-exactly, tracks
@@ -2845,7 +2882,12 @@ fn ffmpeg_encode_libopus(src: &Path, kbps: u32, out: &Path, secs: f64) {
2845 /// file — and the correlation is computed inline without per-lag allocations.2882 /// file — and the correlation is computed inline without per-lag allocations.
2846 /// The delay lands the peak at a positive lag; the symmetric scan keeps the2883 /// The delay lands the peak at a positive lag; the symmetric scan keeps the
2847 /// gate honest if a reference decoder shifts the other way.2884 /// gate honest if a reference decoder shifts the other way.
2848-fn align_to_source(source: &[f32], decoded: &[f32], channels: usize, max_lag: usize) -> (i32, Vec<f32>) {2885+fn align_to_source(
2886+ source: &[f32],
2887+ decoded: &[f32],
2888+ channels: usize,
2889+ max_lag: usize,
2890+) -> (i32, Vec<f32>) {
2849 let sf = source.len() / channels;2891 let sf = source.len() / channels;
2850 let df = decoded.len() / channels;2892 let df = decoded.len() / channels;
2851 let scan_frames = sf.min(df).min(48000 * 10);2893 let scan_frames = sf.min(df).min(48000 * 10);
@@ -2881,7 +2923,11 @@ fn align_to_source(source: &[f32], decoded: &[f32], channels: usize, max_lag: us
2881 }2923 }
2882 // Build a source-length aligned copy using the chosen lag.2924 // Build a source-length aligned copy using the chosen lag.
2883 let mut aligned = vec![0.0f32; sf * channels];2925 let mut aligned = vec![0.0f32; sf * channels];
2884- let i0 = if best_lag < 0 { (-best_lag) as usize } else { 0 };2926+ let i0 = if best_lag < 0 {
2927+ (-best_lag) as usize
2928+ } else {
2929+ 0
2930+ };
2885 let j0 = if best_lag < 0 { 0 } else { best_lag as usize };2931 let j0 = if best_lag < 0 { 0 } else { best_lag as usize };
2886 let len = sf.saturating_sub(i0).min(df.saturating_sub(j0));2932 let len = sf.saturating_sub(i0).min(df.saturating_sub(j0));
2887 for i in 0..len {2933 for i in 0..len {
@@ -3017,7 +3063,9 @@ fn reelm64_persecond_diag() {
3017 let (_, ours_aligned) = align_to_source(&source_pcm, &ours_dec, CHANNELS, MAX_LAG);3063 let (_, ours_aligned) = align_to_source(&source_pcm, &ours_dec, CHANNELS, MAX_LAG);
3018 3064
3019 // Per-second correlation for both3065 // Per-second correlation for both
3020- let n_frames = (source_frames).min(ours_aligned.len() / CHANNELS).min(ref_aligned.len() / CHANNELS);3066+ let n_frames = (source_frames)
3067+ .min(ours_aligned.len() / CHANNELS)
3068+ .min(ref_aligned.len() / CHANNELS);
3021 let sec_samples = 48000usize;3069 let sec_samples = 48000usize;
3022 let frames_per_sec = sec_samples / FRAME; // 503070 let frames_per_sec = sec_samples / FRAME; // 50
3023 3071
@@ -3034,11 +3082,19 @@ fn reelm64_persecond_diag() {
3034 let s = source_pcm[(start + i) * CHANNELS + ch] as f64;3082 let s = source_pcm[(start + i) * CHANNELS + ch] as f64;
3035 let o = ours_aligned[(start + i) * CHANNELS + ch] as f64;3083 let o = ours_aligned[(start + i) * CHANNELS + ch] as f64;
3036 let r = ref_aligned[(start + i) * CHANNELS + ch] as f64;3084 let r = ref_aligned[(start + i) * CHANNELS + ch] as f64;
3037- sxy_o += s * o; sxx_o += s * s; syy_o += o * o;3085+ sxy_o += s * o;
3038- sxy_r += s * r; sxx_r += s * s; syy_r += r * r;3086+ sxx_o += s * s;
3087+ syy_o += o * o;
3088+ sxy_r += s * r;
3089+ sxx_r += s * s;
3090+ syy_r += r * r;
3091+ }
3092+ if sxx_o > 0.0 && syy_o > 0.0 {
3093+ acc_o += sxy_o / (sxx_o * syy_o).sqrt();
3094+ }
3095+ if sxx_r > 0.0 && syy_r > 0.0 {
3096+ acc_r += sxy_r / (sxx_r * syy_r).sqrt();
3039 }3097 }
3040- if sxx_o > 0.0 && syy_o > 0.0 { acc_o += sxy_o / (sxx_o * syy_o).sqrt(); }
3041- if sxx_r > 0.0 && syy_r > 0.0 { acc_r += sxy_r / (sxx_r * syy_r).sqrt(); }
3042 }3098 }
3043 let co = acc_o / CHANNELS as f64;3099 let co = acc_o / CHANNELS as f64;
3044 let cr = acc_r / CHANNELS as f64;3100 let cr = acc_r / CHANNELS as f64;
@@ -3054,10 +3110,19 @@ fn reelm64_persecond_diag() {
3054 let mut out_str = String::new();3110 let mut out_str = String::new();
3055 out_str.push_str("# reelm@64k per-second diagnostic (r1, current code)\n");3111 out_str.push_str("# reelm@64k per-second diagnostic (r1, current code)\n");
3056 out_str.push_str("# 120s cap, 20ms frames, VBR constrained, 48kHz stereo\n");3112 out_str.push_str("# 120s cap, 20ms frames, VBR constrained, 48kHz stereo\n");
3057- out_str.push_str(&format!("# total frames: ours={} ref={}\n", diags.len(), ref_payload.len()));3113+ out_str.push_str(&format!(
3114+ "# total frames: ours={} ref={}\n",
3115+ diags.len(),
3116+ ref_payload.len()
3117+ ));
3058 let total_corr_o: f64 = sec_rows.iter().map(|r| r.1).sum::<f64>() / sec_rows.len() as f64;3118 let total_corr_o: f64 = sec_rows.iter().map(|r| r.1).sum::<f64>() / sec_rows.len() as f64;
3059 let total_corr_r: f64 = sec_rows.iter().map(|r| r.2).sum::<f64>() / sec_rows.len() as f64;3119 let total_corr_r: f64 = sec_rows.iter().map(|r| r.2).sum::<f64>() / sec_rows.len() as f64;
3060- out_str.push_str(&format!("# avg corr: ours={:.4} ref={:.4} gap={:+.4}\n\n", total_corr_o, total_corr_r, total_corr_r - total_corr_o));3120+ out_str.push_str(&format!(
3121+ "# avg corr: ours={:.4} ref={:.4} gap={:+.4}\n\n",
3122+ total_corr_o,
3123+ total_corr_r,
3124+ total_corr_r - total_corr_o
3125+ ));
3061 3126
3062 // Per-second summary table3127 // Per-second summary table
3063 out_str.push_str("# sec\tcorr_ours\tcorr_ref\tgap\tavg_trim\tdual_n\tint_typ\tavg_B_ours\tavg_B_ref\ttf_chng_n\ttrans_n\n");3128 out_str.push_str("# sec\tcorr_ours\tcorr_ref\tgap\tavg_trim\tdual_n\tint_typ\tavg_B_ours\tavg_B_ref\ttf_chng_n\ttrans_n\n");
@@ -3067,19 +3132,35 @@ fn reelm64_persecond_diag() {
3067 let sec_diags = &diags[f0..f1.min(diags.len())];3132 let sec_diags = &diags[f0..f1.min(diags.len())];
3068 let avg_trim: f64 = if !sec_diags.is_empty() {3133 let avg_trim: f64 = if !sec_diags.is_empty() {
3069 sec_diags.iter().map(|d| d.alloc_trim as f64).sum::<f64>() / sec_diags.len() as f643134 sec_diags.iter().map(|d| d.alloc_trim as f64).sum::<f64>() / sec_diags.len() as f64
3070- } else { -1.0 };3135+ } else {
3136+ -1.0
3137+ };
3071 let dual_n = sec_diags.iter().filter(|d| d.dual_stereo).count();3138 let dual_n = sec_diags.iter().filter(|d| d.dual_stereo).count();
3072 let int_typ = if !sec_diags.is_empty() {3139 let int_typ = if !sec_diags.is_empty() {
3073 sec_diags.iter().map(|d| d.intensity).max().unwrap_or(0)3140 sec_diags.iter().map(|d| d.intensity).max().unwrap_or(0)
3074- } else { 0 };3141+ } else {
3142+ 0
3143+ };
3075 let avg_b_o: f64 = if !sec_diags.is_empty() {3144 let avg_b_o: f64 = if !sec_diags.is_empty() {
3076- sec_diags.iter().map(|d| d.nb_compressed as f64).sum::<f64>() / sec_diags.len() as f643145+ sec_diags
3077- } else { 0.0 };3146+ .iter()
3147+ .map(|d| d.nb_compressed as f64)
3148+ .sum::<f64>()
3149+ / sec_diags.len() as f64
3150+ } else {
3151+ 0.0
3152+ };
3078 let ref_f0 = f0.min(ref_payload.len());3153 let ref_f0 = f0.min(ref_payload.len());
3079 let ref_f1 = f1.min(ref_payload.len());3154 let ref_f1 = f1.min(ref_payload.len());
3080 let avg_b_r: f64 = if ref_f1 > ref_f0 {3155 let avg_b_r: f64 = if ref_f1 > ref_f0 {
3081- ref_payload[ref_f0..ref_f1].iter().map(|&b| b as f64).sum::<f64>() / (ref_f1 - ref_f0) as f643156+ ref_payload[ref_f0..ref_f1]
3082- } else { 0.0 };3157+ .iter()
3158+ .map(|&b| b as f64)
3159+ .sum::<f64>()
3160+ / (ref_f1 - ref_f0) as f64
3161+ } else {
3162+ 0.0
3163+ };
3083 // tf_changed: count bands where tf_res != 0 (we don't have tf_res in diag,3164 // tf_changed: count bands where tf_res != 0 (we don't have tf_res in diag,
3084 // but is_transient tells us if short blocks were used)3165 // but is_transient tells us if short blocks were used)
3085 let trans_n = sec_diags.iter().filter(|d| d.is_transient).count();3166 let trans_n = sec_diags.iter().filter(|d| d.is_transient).count();
@@ -3103,10 +3184,23 @@ fn reelm64_persecond_diag() {
3103 let f5: Vec<String> = (0..5).map(|i| format!("{}", d.fine_quant[i])).collect();3184 let f5: Vec<String> = (0..5).map(|i| format!("{}", d.fine_quant[i])).collect();
3104 out_str.push_str(&format!(3185 out_str.push_str(&format!(
3105 "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n",3186 "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
3106- fi, fi * 20, d.nb_compressed, b_ref,3187+ fi,
3107- d.is_transient as u8, d.short_blocks, d.intra as u8, d.silence as u8,3188+ fi * 20,
3108- d.lm, d.start, d.coded_bands, d.intensity, d.dual_stereo as u8,3189+ d.nb_compressed,
3109- d.alloc_trim, d.vbr_reservoir, p5.join(","), f5.join(",")3190+ b_ref,
3191+ d.is_transient as u8,
3192+ d.short_blocks,
3193+ d.intra as u8,
3194+ d.silence as u8,
3195+ d.lm,
3196+ d.start,
3197+ d.coded_bands,
3198+ d.intensity,
3199+ d.dual_stereo as u8,
3200+ d.alloc_trim,
3201+ d.vbr_reservoir,
3202+ p5.join(","),
3203+ f5.join(",")
3110 ));3204 ));
3111 }3205 }
3112 out_str.push('\n');3206 out_str.push('\n');
@@ -3116,30 +3210,50 @@ fn reelm64_persecond_diag() {
3116 out_str.push_str("# --- global stats ---\n");3210 out_str.push_str("# --- global stats ---\n");
3117 let trim_hist: Vec<(i32, usize)> = {3211 let trim_hist: Vec<(i32, usize)> = {
3118 let mut h = std::collections::HashMap::new();3212 let mut h = std::collections::HashMap::new();
3119- for d in &diags { *h.entry(d.alloc_trim).or_insert(0) += 1; }3213+ for d in &diags {
3214+ *h.entry(d.alloc_trim).or_insert(0) += 1;
3215+ }
3120 let mut v: Vec<_> = h.into_iter().collect();3216 let mut v: Vec<_> = h.into_iter().collect();
3121 v.sort();3217 v.sort();
3122 v3218 v
3123 };3219 };
3124 out_str.push_str(&format!("# alloc_trim histogram: {:?}\n", trim_hist));3220 out_str.push_str(&format!("# alloc_trim histogram: {:?}\n", trim_hist));
3125 let dual_count = diags.iter().filter(|d| d.dual_stereo).count();3221 let dual_count = diags.iter().filter(|d| d.dual_stereo).count();
3126- out_str.push_str(&format!("# dual_stereo frames: {}/{}\n", dual_count, diags.len()));3222+ out_str.push_str(&format!(
3223+ "# dual_stereo frames: {}/{}\n",
3224+ dual_count,
3225+ diags.len()
3226+ ));
3127 let trans_count = diags.iter().filter(|d| d.is_transient).count();3227 let trans_count = diags.iter().filter(|d| d.is_transient).count();
3128- out_str.push_str(&format!("# transient frames: {}/{}\n", trans_count, diags.len()));3228+ out_str.push_str(&format!(
3229+ "# transient frames: {}/{}\n",
3230+ trans_count,
3231+ diags.len()
3232+ ));
3129 let intensity_hist: Vec<(usize, usize)> = {3233 let intensity_hist: Vec<(usize, usize)> = {
3130 let mut h = std::collections::HashMap::new();3234 let mut h = std::collections::HashMap::new();
3131- for d in &diags { *h.entry(d.intensity).or_insert(0) += 1; }3235+ for d in &diags {
3236+ *h.entry(d.intensity).or_insert(0) += 1;
3237+ }
3132 let mut v: Vec<_> = h.into_iter().collect();3238 let mut v: Vec<_> = h.into_iter().collect();
3133 v.sort();3239 v.sort();
3134 v3240 v
3135 };3241 };
3136 out_str.push_str(&format!("# intensity histogram: {:?}\n", intensity_hist));3242 out_str.push_str(&format!("# intensity histogram: {:?}\n", intensity_hist));
3137- let avg_b_ours: f64 = diags.iter().map(|d| d.nb_compressed as f64).sum::<f64>() / diags.len() as f64;3243+ let avg_b_ours: f64 =
3138- let avg_b_ref: f64 = ref_payload.iter().map(|&b| b as f64).sum::<f64>() / ref_payload.len() as f64;3244+ diags.iter().map(|d| d.nb_compressed as f64).sum::<f64>() / diags.len() as f64;
3139- out_str.push_str(&format!("# avg bytes/frame: ours={:.1} ref={:.1}\n", avg_b_ours, avg_b_ref));3245+ let avg_b_ref: f64 =
3246+ ref_payload.iter().map(|&b| b as f64).sum::<f64>() / ref_payload.len() as f64;
3247+ out_str.push_str(&format!(
3248+ "# avg bytes/frame: ours={:.1} ref={:.1}\n",
3249+ avg_b_ours, avg_b_ref
3250+ ));
3140 let ours_kbps = ours_bytes.iter().map(|&b| b as f64).sum::<f64>() * 8.0 / seconds / 1000.0;3251 let ours_kbps = ours_bytes.iter().map(|&b| b as f64).sum::<f64>() * 8.0 / seconds / 1000.0;
3141 let ref_kbps = ref_payload.iter().map(|&b| b as f64).sum::<f64>() * 8.0 / seconds / 1000.0;3252 let ref_kbps = ref_payload.iter().map(|&b| b as f64).sum::<f64>() * 8.0 / seconds / 1000.0;
3142- out_str.push_str(&format!("# realised kbps: ours={:.1} ref={:.1}\n", ours_kbps, ref_kbps));3253+ out_str.push_str(&format!(
3254+ "# realised kbps: ours={:.1} ref={:.1}\n",
3255+ ours_kbps, ref_kbps
3256+ ));
3143 3257
3144 let out_path = lanes_dir.join("opus-64-r1.seconds.txt");3258 let out_path = lanes_dir.join("opus-64-r1.seconds.txt");
3145 fs::write(&out_path, out_str).unwrap();3259 fs::write(&out_path, out_str).unwrap();
@@ -3160,7 +3274,10 @@ fn encoder_library_gate_vs_libopus() {
3160 ("reell", "~/Music/reell.mp4"),3274 ("reell", "~/Music/reell.mp4"),
3161 ("reelm", "~/Music/reelm.wav"),3275 ("reelm", "~/Music/reelm.wav"),
3162 ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),3276 ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),
3163- ("hein", "~/Downloads/reelm.mp3"),3277+ (
3278+ "hein",
3279+ "~/Downloads/reelm.mp3",
3280+ ),
3164 ];3281 ];
3165 let only: Vec<String> = std::env::var("SWEEP_ONLY")3282 let only: Vec<String> = std::env::var("SWEEP_ONLY")
3166 .unwrap_or_default()3283 .unwrap_or_default()
@@ -3198,7 +3315,9 @@ fn encoder_library_gate_vs_libopus() {
3198 for &kbps in &[64u32, 96u32] {3315 for &kbps in &[64u32, 96u32] {
3199 // Reference: ffmpeg libopus, VBR on, realised rate from file size.3316 // Reference: ffmpeg libopus, VBR on, realised rate from file size.
3200 ffmpeg_encode_libopus(src, kbps, &scratch, SECS);3317 ffmpeg_encode_libopus(src, kbps, &scratch, SECS);
3201- let ref_bytes = fs::metadata(&scratch).map(|m| m.len() as usize).unwrap_or(0);3318+ let ref_bytes = fs::metadata(&scratch)
3319+ .map(|m| m.len() as usize)
3320+ .unwrap_or(0);
3202 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;3321 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
3203 let (ref_dec, ref_ch) = decode_ogg(&scratch);3322 let (ref_dec, ref_ch) = decode_ogg(&scratch);
3204 assert_eq!(ref_ch, CHANNELS, "{tag}@{kbps}: ref not stereo");3323 assert_eq!(ref_ch, CHANNELS, "{tag}@{kbps}: ref not stereo");
@@ -3206,8 +3325,7 @@ fn encoder_library_gate_vs_libopus() {
3206 3325
3207 // Ours: ec-opus encoder at the reference's realised rate, decoded3326 // Ours: ec-opus encoder at the reference's realised rate, decoded
3208 // by our own decoder; payload bytes give the realised rate.3327 // by our own decoder; payload bytes give the realised rate.
3209- let mut enc =3328+ let mut enc = Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder");
3210- Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder");
3211 enc.set_bitrate((ref_kbps * 1000.0).round() as u32);3329 enc.set_bitrate((ref_kbps * 1000.0).round() as u32);
3212 enc.set_vbr_constrained(true);3330 enc.set_vbr_constrained(true);
3213 let (ours_dec, ours_bytes) = roundtrip_own(&mut enc, &source_pcm, CHANNELS, FRAME);3331 let (ours_dec, ours_bytes) = roundtrip_own(&mut enc, &source_pcm, CHANNELS, FRAME);
@@ -3233,7 +3351,11 @@ fn encoder_library_gate_vs_libopus() {
3233 let q_ref = opus_compare(&s_i, &r_i, CHANNELS);3351 let q_ref = opus_compare(&s_i, &r_i, CHANNELS);
3234 let err_ours = opus_compare_err(&s_i, &o_i, CHANNELS);3352 let err_ours = opus_compare_err(&s_i, &o_i, CHANNELS);
3235 let err_ref = opus_compare_err(&s_i, &r_i, CHANNELS);3353 let err_ref = opus_compare_err(&s_i, &r_i, CHANNELS);
3236- let err_ratio = if err_ref > 0.0 { err_ours / err_ref } else { f64::INFINITY };3354+ let err_ratio = if err_ref > 0.0 {
3355+ err_ours / err_ref
3356+ } else {
3357+ f64::INFINITY
3358+ };
3237 3359
3238 let corr_ours = corr_interleaved(&source_pcm, &ours_aligned, CHANNELS);3360 let corr_ours = corr_interleaved(&source_pcm, &ours_aligned, CHANNELS);
3239 let corr_ref = corr_interleaved(&source_pcm, &ref_aligned, CHANNELS);3361 let corr_ref = corr_interleaved(&source_pcm, &ref_aligned, CHANNELS);
@@ -3271,8 +3393,10 @@ fn encoder_library_gate_vs_libopus() {
3271 let mut table = String::new();3393 let mut table = String::new();
3272 table.push_str("# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1)\n");3394 table.push_str("# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1)\n");
3273 table.push_str("# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo\n");3395 table.push_str("# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo\n");
3274- table.push_str("# source\tkbps\tours_kbps\tref_kbps\trate%\tcorr_ours\tcorr_ref\tgap\t\3396+ table.push_str(
3275- Q_ours\tQ_ref\terr_ratio\tminsec_ours\tminsec_ref\tdrop_ours\tdrop_ref\n");3397+ "# source\tkbps\tours_kbps\tref_kbps\trate%\tcorr_ours\tcorr_ref\tgap\t\
3398+ Q_ours\tQ_ref\terr_ratio\tminsec_ours\tminsec_ref\tdrop_ours\tdrop_ref\n",
3399+ );
3276 for r in &rows {3400 for r in &rows {
3277 table.push_str(r);3401 table.push_str(r);
3278 table.push('\n');3402 table.push('\n');
@@ -3335,8 +3459,18 @@ fn ffmpeg_decode_pcm_mono(path: &Path, secs: f64) -> Vec<f32> {
3335 .args(["-v", "error", "-i"])3459 .args(["-v", "error", "-i"])
3336 .arg(path)3460 .arg(path)
3337 .args([3461 .args([
3338- "-vn", "-t", &format!("{secs}"), "-ac", "1", "-ar", "48000", "-f", "f32le",3462+ "-vn",
3339- "-acodec", "pcm_f32le", "-",3463+ "-t",
3464+ &format!("{secs}"),
3465+ "-ac",
3466+ "1",
3467+ "-ar",
3468+ "48000",
3469+ "-f",
3470+ "f32le",
3471+ "-acodec",
3472+ "pcm_f32le",
3473+ "-",
3340 ])3474 ])
3341 .output()3475 .output()
3342 .expect("ffmpeg runs");3476 .expect("ffmpeg runs");
@@ -3359,8 +3493,21 @@ fn ffmpeg_encode_libopus_mono_voip(src: &Path, kbps: u32, out: &Path, secs: f64)
3359 .args(["-y", "-v", "error", "-i"])3493 .args(["-y", "-v", "error", "-i"])
3360 .arg(src)3494 .arg(src)
3361 .args([3495 .args([
3362- "-vn", "-t", &format!("{secs}"), "-ac", "1", "-ar", "48000", "-c:a", "libopus",3496+ "-vn",
3363- "-application", "voip", "-b:a", &format!("{kbps}k"), "-vbr", "on",3497+ "-t",
3498+ &format!("{secs}"),
3499+ "-ac",
3500+ "1",
3501+ "-ar",
3502+ "48000",
3503+ "-c:a",
3504+ "libopus",
3505+ "-application",
3506+ "voip",
3507+ "-b:a",
3508+ &format!("{kbps}k"),
3509+ "-vbr",
3510+ "on",
3364 ])3511 ])
3365 .arg(out)3512 .arg(out)
3366 .output()3513 .output()
@@ -3475,7 +3622,9 @@ fn silk_library_gate_vs_libopus() {
3475 3622
3476 // Reference: ffmpeg libopus, mono, voip, VBR; realised rate from size.3623 // Reference: ffmpeg libopus, mono, voip, VBR; realised rate from size.
3477 ffmpeg_encode_libopus_mono_voip(&src, kbps, &ref_ogg, SECS);3624 ffmpeg_encode_libopus_mono_voip(&src, kbps, &ref_ogg, SECS);
3478- let ref_bytes = fs::metadata(&ref_ogg).map(|m| m.len() as usize).unwrap_or(0);3625+ let ref_bytes = fs::metadata(&ref_ogg)
3626+ .map(|m| m.len() as usize)
3627+ .unwrap_or(0);
3479 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;3628 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
3480 // SYMMETRY: ref decoded through ffmpeg libopus (the reference decoder),3629 // SYMMETRY: ref decoded through ffmpeg libopus (the reference decoder),
3481 // NOT our own decoder — so both sides cross the same decoder. (r1 used3630 // NOT our own decoder — so both sides cross the same decoder. (r1 used
@@ -3526,17 +3675,24 @@ fn silk_library_gate_vs_libopus() {
3526 pre_skip,3675 pre_skip,
3527 );3676 );
3528 let ours_dec = ffmpeg_decode(&ours_ogg, CHANNELS).expect("ffmpeg libopus decode of ours");3677 let ours_dec = ffmpeg_decode(&ours_ogg, CHANNELS).expect("ffmpeg libopus decode of ours");
3529- let ours_trim: Vec<f32> = ours_dec.into_iter().take(source_frames * CHANNELS).collect();3678+ let ours_trim: Vec<f32> = ours_dec
3679+ .into_iter()
3680+ .take(source_frames * CHANNELS)
3681+ .collect();
3530 let (lag_ours, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);3682 let (lag_ours, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);
3531 3683
3532 // Own-decoder aligned (extra column: decoder drift visibility).3684 // Own-decoder aligned (extra column: decoder drift visibility).
3533- let ours_own_trim: Vec<f32> =3685+ let ours_own_trim: Vec<f32> = ours_own_dec
3534- ours_own_dec.into_iter().take(source_frames * CHANNELS).collect();3686+ .into_iter()
3687+ .take(source_frames * CHANNELS)
3688+ .collect();
3535 let (_, ours_own_aligned) = align_to_source(&source_pcm, &ours_own_trim, CHANNELS, MAX_LAG);3689 let (_, ours_own_aligned) = align_to_source(&source_pcm, &ours_own_trim, CHANNELS, MAX_LAG);
3536 3690
3537 // LAG GATE: a lag at the scan bound is an invalid measurement, not a result.3691 // LAG GATE: a lag at the scan bound is an invalid measurement, not a result.
3538 if (lag_ours as i64).abs() >= MAX_LAG as i64 {3692 if (lag_ours as i64).abs() >= MAX_LAG as i64 {
3539- lag_violations.push(format!("{tag}: ours lag {lag_ours} hit scan bound {MAX_LAG}"));3693+ lag_violations.push(format!(
3694+ "{tag}: ours lag {lag_ours} hit scan bound {MAX_LAG}"
3695+ ));
3540 }3696 }
3541 if (lag_ref as i64).abs() >= MAX_LAG as i64 {3697 if (lag_ref as i64).abs() >= MAX_LAG as i64 {
3542 lag_violations.push(format!("{tag}: ref lag {lag_ref} hit scan bound {MAX_LAG}"));3698 lag_violations.push(format!("{tag}: ref lag {lag_ref} hit scan bound {MAX_LAG}"));
@@ -3555,7 +3711,11 @@ fn silk_library_gate_vs_libopus() {
3555 let q_ref = opus_compare(&s_i, &r_i, CHANNELS);3711 let q_ref = opus_compare(&s_i, &r_i, CHANNELS);
3556 let err_ours = opus_compare_err(&s_i, &o_i, CHANNELS);3712 let err_ours = opus_compare_err(&s_i, &o_i, CHANNELS);
3557 let err_ref = opus_compare_err(&s_i, &r_i, CHANNELS);3713 let err_ref = opus_compare_err(&s_i, &r_i, CHANNELS);
3558- let err_ratio = if err_ref > 0.0 { err_ours / err_ref } else { f64::INFINITY };3714+ let err_ratio = if err_ref > 0.0 {
3715+ err_ours / err_ref
3716+ } else {
3717+ f64::INFINITY
3718+ };
3559 3719
3560 // Primary corr: band-limited reference. Secondary: full-band source.3720 // Primary corr: band-limited reference. Secondary: full-band source.
3561 let corr_ours_bl = corr_interleaved(&ref_source, &ours_aligned, CHANNELS);3721 let corr_ours_bl = corr_interleaved(&ref_source, &ours_aligned, CHANNELS);
@@ -3672,7 +3832,9 @@ fn silk_silkq_persecond_diag() {
3672 3832
3673 // Reference: ffmpeg libopus mono voip VBR at 12k; realised rate from size.3833 // Reference: ffmpeg libopus mono voip VBR at 12k; realised rate from size.
3674 ffmpeg_encode_libopus_mono_voip(&src, KBPS, &ref_ogg, SECS);3834 ffmpeg_encode_libopus_mono_voip(&src, KBPS, &ref_ogg, SECS);
3675- let ref_bytes = fs::metadata(&ref_ogg).map(|m| m.len() as usize).unwrap_or(0);3835+ let ref_bytes = fs::metadata(&ref_ogg)
3836+ .map(|m| m.len() as usize)
3837+ .unwrap_or(0);
3676 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;3838 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
3677 let ref_dec = ffmpeg_decode(&ref_ogg, CHANNELS).expect("ffmpeg libopus decode of ref");3839 let ref_dec = ffmpeg_decode(&ref_ogg, CHANNELS).expect("ffmpeg libopus decode of ref");
3678 let ref_trim: Vec<f32> = ref_dec.into_iter().take(source_frames * CHANNELS).collect();3840 let ref_trim: Vec<f32> = ref_dec.into_iter().take(source_frames * CHANNELS).collect();
@@ -3711,11 +3873,16 @@ fn silk_silkq_persecond_diag() {
3711 let len = enc.encode_float(block, FRAME, &mut out).expect("encode");3873 let len = enc.encode_float(block, FRAME, &mut out).expect("encode");
3712 let d = enc.last_silk_diag().cloned();3874 let d = enc.last_silk_diag().cloned();
3713 ours_bytes.push(len);3875 ours_bytes.push(len);
3714- if let Some(d) = d { diags.push(d); }3876+ if let Some(d) = d {
3877+ diags.push(d);
3878+ }
3715 let n = dec.decode_float(&out[..len], &mut buf).expect("decode");3879 let n = dec.decode_float(&out[..len], &mut buf).expect("decode");
3716 ours_dec.extend_from_slice(&buf[..n * CHANNELS]);3880 ours_dec.extend_from_slice(&buf[..n * CHANNELS]);
3717 }3881 }
3718- let ours_trim: Vec<f32> = ours_dec.into_iter().take(source_frames * CHANNELS).collect();3882+ let ours_trim: Vec<f32> = ours_dec
3883+ .into_iter()
3884+ .take(source_frames * CHANNELS)
3885+ .collect();
3719 let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);3886 let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);
3720 3887
3721 // Per-second correlation ours vs ref against the full-band source (matches3888 // Per-second correlation ours vs ref against the full-band source (matches
@@ -3736,11 +3903,23 @@ fn silk_silkq_persecond_diag() {
3736 let s = source_pcm[start + i] as f64;3903 let s = source_pcm[start + i] as f64;
3737 let o = ours_aligned[start + i] as f64;3904 let o = ours_aligned[start + i] as f64;
3738 let r = ref_aligned[start + i] as f64;3905 let r = ref_aligned[start + i] as f64;
3739- sxy_o += s * o; sxx_o += s * s; syy_o += o * o;3906+ sxy_o += s * o;
3740- sxy_r += s * r; sxx_r += s * s; syy_r += r * r;3907+ sxx_o += s * s;
3741- }3908+ syy_o += o * o;
3742- let co = if sxx_o > 0.0 && syy_o > 0.0 { sxy_o / (sxx_o * syy_o).sqrt() } else { 0.0 };3909+ sxy_r += s * r;
3743- let cr = if sxx_r > 0.0 && syy_r > 0.0 { sxy_r / (sxx_r * syy_r).sqrt() } else { 0.0 };3910+ sxx_r += s * s;
3911+ syy_r += r * r;
3912+ }
3913+ let co = if sxx_o > 0.0 && syy_o > 0.0 {
3914+ sxy_o / (sxx_o * syy_o).sqrt()
3915+ } else {
3916+ 0.0
3917+ };
3918+ let cr = if sxx_r > 0.0 && syy_r > 0.0 {
3919+ sxy_r / (sxx_r * syy_r).sqrt()
3920+ } else {
3921+ 0.0
3922+ };
3744 sec_rows.push((sec_idx, co, cr, cr - co));3923 sec_rows.push((sec_idx, co, cr, cr - co));
3745 start += sec_samples;3924 start += sec_samples;
3746 sec_idx += 1;3925 sec_idx += 1;
@@ -3752,13 +3931,20 @@ fn silk_silkq_persecond_diag() {
3752 let mut out_str = String::new();3931 let mut out_str = String::new();
3753 out_str.push_str("# reelm@12k SILK per-second diagnostic (r1)\n");3932 out_str.push_str("# reelm@12k SILK per-second diagnostic (r1)\n");
3754 out_str.push_str("# mono, 120s cap, 20ms frames, VBR constrained, 48kHz, Application::Voip\n");3933 out_str.push_str("# mono, 120s cap, 20ms frames, VBR constrained, 48kHz, Application::Voip\n");
3755- out_str.push_str(&format!("# total frames: ours={} ref={}\n", diags.len(), ref_payload.len()));3934+ out_str.push_str(&format!(
3935+ "# total frames: ours={} ref={}\n",
3936+ diags.len(),
3937+ ref_payload.len()
3938+ ));
3756 let avg_o: f64 = sec_rows.iter().map(|r| r.1).sum::<f64>() / sec_rows.len().max(1) as f64;3939 let avg_o: f64 = sec_rows.iter().map(|r| r.1).sum::<f64>() / sec_rows.len().max(1) as f64;
3757 let avg_r: f64 = sec_rows.iter().map(|r| r.2).sum::<f64>() / sec_rows.len().max(1) as f64;3940 let avg_r: f64 = sec_rows.iter().map(|r| r.2).sum::<f64>() / sec_rows.len().max(1) as f64;
3758 let gap_avg = avg_r - avg_o;3941 let gap_avg = avg_r - avg_o;
3759 out_str.push_str(&format!(3942 out_str.push_str(&format!(
3760 "# avg corr: ours={:.4} ref={:.4} gap={:+.4} ref_kbps={:.1} ours_kbps={:.1}\n\n",3943 "# avg corr: ours={:.4} ref={:.4} gap={:+.4} ref_kbps={:.1} ours_kbps={:.1}\n\n",
3761- avg_o, avg_r, gap_avg, ref_kbps,3944+ avg_o,
3945+ avg_r,
3946+ gap_avg,
3947+ ref_kbps,
3762 ours_bytes.iter().map(|&b| b as f64).sum::<f64>() * 8.0 / seconds / 1000.03948 ours_bytes.iter().map(|&b| b as f64).sum::<f64>() * 8.0 / seconds / 1000.0
3763 ));3949 ));
3764 3950
@@ -3770,27 +3956,45 @@ fn silk_silkq_persecond_diag() {
3770 let sd = &diags[f0..f1.min(diags.len())];3956 let sd = &diags[f0..f1.min(diags.len())];
3771 let gain_mean: f64 = if !sd.is_empty() {3957 let gain_mean: f64 = if !sd.is_empty() {
3772 sd.iter().map(|d| d.gain_idx[0] as f64).sum::<f64>() / sd.len() as f643958 sd.iter().map(|d| d.gain_idx[0] as f64).sum::<f64>() / sd.len() as f64
3773- } else { -1.0 };3959+ } else {
3960+ -1.0
3961+ };
3774 let voiced_n = sd.iter().filter(|d| d.voiced).count();3962 let voiced_n = sd.iter().filter(|d| d.voiced).count();
3775 let nlsf_int = if !sd.is_empty() {3963 let nlsf_int = if !sd.is_empty() {
3776 sd.iter().map(|d| d.nlsf_interp).max().unwrap_or(0)3964 sd.iter().map(|d| d.nlsf_interp).max().unwrap_or(0)
3777- } else { 0 };3965+ } else {
3966+ 0
3967+ };
3778 let avg_b_o: f64 = if !sd.is_empty() {3968 let avg_b_o: f64 = if !sd.is_empty() {
3779 sd.iter().map(|d| d.bytes as f64).sum::<f64>() / sd.len() as f643969 sd.iter().map(|d| d.bytes as f64).sum::<f64>() / sd.len() as f64
3780- } else { 0.0 };3970+ } else {
3971+ 0.0
3972+ };
3781 let ref_f0 = f0.min(ref_payload.len());3973 let ref_f0 = f0.min(ref_payload.len());
3782 let ref_f1 = f1.min(ref_payload.len());3974 let ref_f1 = f1.min(ref_payload.len());
3783 let avg_b_r: f64 = if ref_f1 > ref_f0 {3975 let avg_b_r: f64 = if ref_f1 > ref_f0 {
3784- ref_payload[ref_f0..ref_f1].iter().map(|&b| b as f64).sum::<f64>()3976+ ref_payload[ref_f0..ref_f1]
3977+ .iter()
3978+ .map(|&b| b as f64)
3979+ .sum::<f64>()
3785 / (ref_f1 - ref_f0) as f643980 / (ref_f1 - ref_f0) as f64
3786- } else { 0.0 };3981+ } else {
3982+ 0.0
3983+ };
3787 let ltp_mean: f64 = if !sd.is_empty() {3984 let ltp_mean: f64 = if !sd.is_empty() {
3788 sd.iter().map(|d| d.ltp_gain as f64).sum::<f64>() / sd.len() as f643985 sd.iter().map(|d| d.ltp_gain as f64).sum::<f64>() / sd.len() as f64
3789- } else { 0.0 };3986+ } else {
3987+ 0.0
3988+ };
3790 let pitch_mean: f64 = if !sd.is_empty() {3989 let pitch_mean: f64 = if !sd.is_empty() {
3791- sd.iter().filter(|d| d.voiced).map(|d| d.pitch_l[0] as f64).sum::<f64>()3990+ sd.iter()
3991+ .filter(|d| d.voiced)
3992+ .map(|d| d.pitch_l[0] as f64)
3993+ .sum::<f64>()
3792 / sd.iter().filter(|d| d.voiced).count().max(1) as f643994 / sd.iter().filter(|d| d.voiced).count().max(1) as f64
3793- } else { 0.0 };3995+ } else {
3996+ 0.0
3997+ };
3794 out_str.push_str(&format!(3998 out_str.push_str(&format!(
3795 "{}\t{:.4}\t{:.4}\t{:+.4}\t{:.1}\t{}\t{}\t{:.1}\t{:.1}\t{:.3}\t{:.1}\n",3999 "{}\t{:.4}\t{:.4}\t{:+.4}\t{:.1}\t{}\t{}\t{:.1}\t{:.1}\t{:.3}\t{:.1}\n",
3796 s, co, cr, g, gain_mean, voiced_n, nlsf_int, avg_b_o, avg_b_r, ltp_mean, pitch_mean4000 s, co, cr, g, gain_mean, voiced_n, nlsf_int, avg_b_o, avg_b_r, ltp_mean, pitch_mean
@@ -3809,9 +4013,18 @@ fn silk_silkq_persecond_diag() {
3809 let b_ref = ref_payload.get(fi).copied().unwrap_or(0);4013 let b_ref = ref_payload.get(fi).copied().unwrap_or(0);
3810 out_str.push_str(&format!(4014 out_str.push_str(&format!(
3811 "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{:.3}\t{}\n",4015 "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{:.3}\t{}\n",
3812- fi, fi * 20, d.bytes, b_ref,4016+ fi,
3813- d.voiced as u8, d.signal_type, d.gain_idx[0], d.lag_index,4017+ fi * 20,
3814- d.pitch_l[0], d.nlsf_interp, d.ltp_gain, d.nb_subfr4018+ d.bytes,
4019+ b_ref,
4020+ d.voiced as u8,
4021+ d.signal_type,
4022+ d.gain_idx[0],
4023+ d.lag_index,
4024+ d.pitch_l[0],
4025+ d.nlsf_interp,
4026+ d.ltp_gain,
4027+ d.nb_subfr
3815 ));4028 ));
3816 }4029 }
3817 out_str.push('\n');4030 out_str.push('\n');
@@ -3820,10 +4033,16 @@ fn silk_silkq_persecond_diag() {
3820 // Global stats.4033 // Global stats.
3821 out_str.push_str("# --- global stats ---\n");4034 out_str.push_str("# --- global stats ---\n");
3822 let voiced_count = diags.iter().filter(|d| d.voiced).count();4035 let voiced_count = diags.iter().filter(|d| d.voiced).count();
3823- out_str.push_str(&format!("# voiced frames: {}/{}\n", voiced_count, diags.len()));4036+ out_str.push_str(&format!(
4037+ "# voiced frames: {}/{}\n",
4038+ voiced_count,
4039+ diags.len()
4040+ ));
3824 let gain_hist: Vec<(i8, usize)> = {4041 let gain_hist: Vec<(i8, usize)> = {
3825 let mut h = std::collections::HashMap::new();4042 let mut h = std::collections::HashMap::new();
3826- for d in &diags { *h.entry(d.gain_idx[0]).or_insert(0) += 1; }4043+ for d in &diags {
4044+ *h.entry(d.gain_idx[0]).or_insert(0) += 1;
4045+ }
3827 let mut v: Vec<_> = h.into_iter().collect();4046 let mut v: Vec<_> = h.into_iter().collect();
3828 v.sort();4047 v.sort();
3829 v4048 v
@@ -3831,16 +4050,24 @@ fn silk_silkq_persecond_diag() {
3831 out_str.push_str(&format!("# gain_idx[0] histogram: {:?}\n", gain_hist));4050 out_str.push_str(&format!("# gain_idx[0] histogram: {:?}\n", gain_hist));
3832 let nlsf_hist: Vec<(i32, usize)> = {4051 let nlsf_hist: Vec<(i32, usize)> = {
3833 let mut h = std::collections::HashMap::new();4052 let mut h = std::collections::HashMap::new();
3834- for d in &diags { *h.entry(d.nlsf_interp).or_insert(0) += 1; }4053+ for d in &diags {
4054+ *h.entry(d.nlsf_interp).or_insert(0) += 1;
4055+ }
3835 let mut v: Vec<_> = h.into_iter().collect();4056 let mut v: Vec<_> = h.into_iter().collect();
3836 v.sort();4057 v.sort();
3837 v4058 v
3838 };4059 };
3839 out_str.push_str(&format!("# nlsf_interp histogram: {:?}\n", nlsf_hist));4060 out_str.push_str(&format!("# nlsf_interp histogram: {:?}\n", nlsf_hist));
3840- let avg_b_ours: f64 = diags.iter().map(|d| d.bytes as f64).sum::<f64>() / diags.len().max(1) as f64;4061+ let avg_b_ours: f64 =
3841- let avg_b_ref: f64 = ref_payload.iter().map(|&b| b as f64).sum::<f64>() / ref_payload.len().max(1) as f64;4062+ diags.iter().map(|d| d.bytes as f64).sum::<f64>() / diags.len().max(1) as f64;
3842- out_str.push_str(&format!("# avg bytes/frame: ours={:.1} ref={:.1}\n", avg_b_ours, avg_b_ref));4063+ let avg_b_ref: f64 =
3843- let ltp_mean_all: f64 = diags.iter().map(|d| d.ltp_gain as f64).sum::<f64>() / diags.len().max(1) as f64;4064+ ref_payload.iter().map(|&b| b as f64).sum::<f64>() / ref_payload.len().max(1) as f64;
4065+ out_str.push_str(&format!(
4066+ "# avg bytes/frame: ours={:.1} ref={:.1}\n",
4067+ avg_b_ours, avg_b_ref
4068+ ));
4069+ let ltp_mean_all: f64 =
4070+ diags.iter().map(|d| d.ltp_gain as f64).sum::<f64>() / diags.len().max(1) as f64;
3844 out_str.push_str(&format!("# mean ltp_gain: {:.4}\n", ltp_mean_all));4071 out_str.push_str(&format!("# mean ltp_gain: {:.4}\n", ltp_mean_all));
3845 4072
3846 let out_path = lanes_dir.join("opus-silkq-r1.seconds.txt");4073 let out_path = lanes_dir.join("opus-silkq-r1.seconds.txt");
@@ -3902,25 +4129,37 @@ fn silk_silkq_oracle() {
3902 ours_packets.push(out[..len].to_vec());4129 ours_packets.push(out[..len].to_vec());
3903 }4130 }
3904 4131
3905-
3906 let ours_ix = collect_indices(&ours_packets);4132 let ours_ix = collect_indices(&ours_packets);
3907 let ref_ix = collect_indices(&ref_packets);4133 let ref_ix = collect_indices(&ref_packets);
3908 4134
3909- eprintln!("ours frames: {} ref frames: {}", ours_ix.len(), ref_ix.len());4135+ eprintln!(
4136+ "ours frames: {} ref frames: {}",
4137+ ours_ix.len(),
4138+ ref_ix.len()
4139+ );
3910 4140
3911 // Print side-by-side for target seconds (50 frames/sec at 20ms).4141 // Print side-by-side for target seconds (50 frames/sec at 20ms).
3912 let frames_per_sec = 50usize;4142 let frames_per_sec = 50usize;
3913 let mut out_str = String::new();4143 let mut out_str = String::new();
3914 out_str.push_str("# reelm@12k SILK oracle: ours vs ffmpeg-libopus indices (r1)\n");4144 out_str.push_str("# reelm@12k SILK oracle: ours vs ffmpeg-libopus indices (r1)\n");
3915 out_str.push_str("# mono, 120s, 20ms frames, VBR constrained, 48kHz, Application::Voip\n");4145 out_str.push_str("# mono, 120s, 20ms frames, VBR constrained, 48kHz, Application::Voip\n");
3916- out_str.push_str(&format!("# ours_frames={} ref_frames={}\n", ours_ix.len(), ref_ix.len()));4146+ out_str.push_str(&format!(
4147+ "# ours_frames={} ref_frames={}\n",
4148+ ours_ix.len(),
4149+ ref_ix.len()
4150+ ));
3917 out_str.push_str("# sig: 0=unvoiced 2=voiced | per: LTP codebook | nlsf_i: 4=nointerp\n");4151 out_str.push_str("# sig: 0=unvoiced 2=voiced | per: LTP codebook | nlsf_i: 4=nointerp\n");
3918 out_str.push_str("# gains/ltp are 4 subframe indices; lag/contour only for voiced\n\n");4152 out_str.push_str("# gains/ltp are 4 subframe indices; lag/contour only for voiced\n\n");
3919 4153
3920 for &sec in TARGET_SECS {4154 for &sec in TARGET_SECS {
3921 let start = sec * frames_per_sec;4155 let start = sec * frames_per_sec;
3922 let end = start + frames_per_sec;4156 let end = start + frames_per_sec;
3923- out_str.push_str(&format!("=== second {} (frames {}–{}) ===\n", sec, start, end - 1));4157+ out_str.push_str(&format!(
4158+ "=== second {} (frames {}–{}) ===\n",
4159+ sec,
4160+ start,
4161+ end - 1
4162+ ));
3924 out_str.push_str("frame side sig qoff gains[4] nlsf_i lag cont per ltp[4] ltpscl seed bytes\n");4163 out_str.push_str("frame side sig qoff gains[4] nlsf_i lag cont per ltp[4] ltpscl seed bytes\n");
3925 for f in start..end {4164 for f in start..end {
3926 let ours = ours_ix.get(f);4165 let ours = ours_ix.get(f);
@@ -3948,7 +4187,10 @@ fn silk_silkq_oracle() {
3948 "-".to_string()4187 "-".to_string()
3949 };4188 };
3950 let ltp_str = if voiced {4189 let ltp_str = if voiced {
3951- format!("[{},{},{},{}]", ix.ltp_index[0], ix.ltp_index[1], ix.ltp_index[2], ix.ltp_index[3])4190+ format!(
4191+ "[{},{},{},{}]",
4192+ ix.ltp_index[0], ix.ltp_index[1], ix.ltp_index[2], ix.ltp_index[3]
4193+ )
3952 } else {4194 } else {
3953 "[-,-,-,-]".to_string()4195 "[-,-,-,-]".to_string()
3954 };4196 };
@@ -3990,14 +4232,26 @@ fn silk_silkq_oracle() {
3990 for i in 0..n {4232 for i in 0..n {
3991 let (o, ob) = &ours_ix[i];4233 let (o, ob) = &ours_ix[i];
3992 let (r, rb) = &ref_ix[i];4234 let (r, rb) = &ref_ix[i];
3993- if o.signal_type != r.signal_type { sig_mismatch += 1; }4235+ if o.signal_type != r.signal_type {
3994- if o.quant_offset_type != r.quant_offset_type { qoff_mismatch += 1; }4236+ sig_mismatch += 1;
3995- for k in 0..4 { gain_diff_sum += (o.gains[k] as i64 - r.gains[k] as i64).abs(); }4237+ }
3996- if o.nlsf_interp_coef_q2 != r.nlsf_interp_coef_q2 { nlsf_interp_diff += 1; }4238+ if o.quant_offset_type != r.quant_offset_type {
4239+ qoff_mismatch += 1;
4240+ }
4241+ for k in 0..4 {
4242+ gain_diff_sum += (o.gains[k] as i64 - r.gains[k] as i64).abs();
4243+ }
4244+ if o.nlsf_interp_coef_q2 != r.nlsf_interp_coef_q2 {
4245+ nlsf_interp_diff += 1;
4246+ }
3997 if o.signal_type == 2 && r.signal_type == 2 {4247 if o.signal_type == 2 && r.signal_type == 2 {
3998 voiced_both += 1;4248 voiced_both += 1;
3999- if o.per_index != r.per_index { ltp_per_mismatch += 1; }4249+ if o.per_index != r.per_index {
4000- for k in 0..4 { ltp_idx_diff_sum += (o.ltp_index[k] as i64 - r.ltp_index[k] as i64).abs(); }4250+ ltp_per_mismatch += 1;
4251+ }
4252+ for k in 0..4 {
4253+ ltp_idx_diff_sum += (o.ltp_index[k] as i64 - r.ltp_index[k] as i64).abs();
4254+ }
4001 lag_diff_sum += (o.lag_index as i64 - r.lag_index as i64).abs();4255 lag_diff_sum += (o.lag_index as i64 - r.lag_index as i64).abs();
4002 }4256 }
4003 bytes_ours += *ob as u64;4257 bytes_ours += *ob as u64;
@@ -4005,15 +4259,45 @@ fn silk_silkq_oracle() {
4005 }4259 }
4006 out_str.push_str("=== divergence summary (all frames) ===\n");4260 out_str.push_str("=== divergence summary (all frames) ===\n");
4007 out_str.push_str(&format!("frames compared: {}\n", n));4261 out_str.push_str(&format!("frames compared: {}\n", n));
4008- out_str.push_str(&format!("signal_type mismatch: {} ({:.1}%)\n", sig_mismatch, 100.0 * sig_mismatch as f64 / n as f64));4262+ out_str.push_str(&format!(
4009- out_str.push_str(&format!("quant_offset mismatch: {} ({:.1}%)\n", qoff_mismatch, 100.0 * qoff_mismatch as f64 / n as f64));4263+ "signal_type mismatch: {} ({:.1}%)\n",
4010- out_str.push_str(&format!("avg |gain diff| per subframe: {:.2}\n", gain_diff_sum as f64 / (n as f64 * 4.0)));4264+ sig_mismatch,
4011- out_str.push_str(&format!("nlsf_interp mismatch: {} ({:.1}%)\n", nlsf_interp_diff, 100.0 * nlsf_interp_diff as f64 / n as f64));4265+ 100.0 * sig_mismatch as f64 / n as f64
4266+ ));
4267+ out_str.push_str(&format!(
4268+ "quant_offset mismatch: {} ({:.1}%)\n",
4269+ qoff_mismatch,
4270+ 100.0 * qoff_mismatch as f64 / n as f64
4271+ ));
4272+ out_str.push_str(&format!(
4273+ "avg |gain diff| per subframe: {:.2}\n",
4274+ gain_diff_sum as f64 / (n as f64 * 4.0)
4275+ ));
4276+ out_str.push_str(&format!(
4277+ "nlsf_interp mismatch: {} ({:.1}%)\n",
4278+ nlsf_interp_diff,
4279+ 100.0 * nlsf_interp_diff as f64 / n as f64
4280+ ));
4012 out_str.push_str(&format!("voiced_both: {}\n", voiced_both));4281 out_str.push_str(&format!("voiced_both: {}\n", voiced_both));
4013- out_str.push_str(&format!(" LTP per_index mismatch: {} ({:.1}%)\n", ltp_per_mismatch, 100.0 * ltp_per_mismatch as f64 / voiced_both.max(1) as f64));4282+ out_str.push_str(&format!(
4014- out_str.push_str(&format!(" avg |ltp_index diff| per subframe: {:.2}\n", ltp_idx_diff_sum as f64 / (voiced_both.max(1) as f64 * 4.0)));4283+ " LTP per_index mismatch: {} ({:.1}%)\n",
4015- out_str.push_str(&format!(" avg |lag diff|: {:.2}\n", lag_diff_sum as f64 / voiced_both.max(1) as f64));4284+ ltp_per_mismatch,
4016- out_str.push_str(&format!("total bytes: ours={} ref={} ratio={:.3}\n", bytes_ours, bytes_ref, bytes_ours as f64 / bytes_ref.max(1) as f64));4285+ 100.0 * ltp_per_mismatch as f64 / voiced_both.max(1) as f64
4286+ ));
4287+ out_str.push_str(&format!(
4288+ " avg |ltp_index diff| per subframe: {:.2}\n",
4289+ ltp_idx_diff_sum as f64 / (voiced_both.max(1) as f64 * 4.0)
4290+ ));
4291+ out_str.push_str(&format!(
4292+ " avg |lag diff|: {:.2}\n",
4293+ lag_diff_sum as f64 / voiced_both.max(1) as f64
4294+ ));
4295+ out_str.push_str(&format!(
4296+ "total bytes: ours={} ref={} ratio={:.3}\n",
4297+ bytes_ours,
4298+ bytes_ref,
4299+ bytes_ours as f64 / bytes_ref.max(1) as f64
4300+ ));
4017 4301
4018 let out_path = lanes_dir.join("opus-silkq-r1.oracle.txt");4302 let out_path = lanes_dir.join("opus-silkq-r1.oracle.txt");
4019 fs::write(&out_path, &out_str).unwrap();4303 fs::write(&out_path, &out_str).unwrap();
@@ -4059,14 +4343,7 @@ fn collect_indices(packets: &[Vec<u8>]) -> Vec<(ec_opus::SilkDecIndices, usize)>
4059 continue;4343 continue;
4060 }4344 }
4061 let mut dec = ec_opus::RangeDecoder::new(frame_data);4345 let mut dec = ec_opus::RangeDecoder::new(frame_data);
4062- let _ = silk.decode(4346+ let _ = silk.decode(&mut dec, &mut silk_pcm, payload_ms, internal_rate, 1, first);
4063- &mut dec,
4064- &mut silk_pcm,
4065- payload_ms,
4066- internal_rate,
4067- 1,
4068- first,
4069- );
4070 let ix = silk.last_indices();4347 let ix = silk.last_indices();
4071 let bytes = frame_data.len();4348 let bytes = frame_data.len();
4072 results.push((ix, bytes));4349 results.push((ix, bytes));
@@ -4110,7 +4387,9 @@ fn silk_spectral_divergence_12k() {
4110 4387
4111 // Reference: ffmpeg libopus mono voip at 12k, decoded by ffmpeg libopus.4388 // Reference: ffmpeg libopus mono voip at 12k, decoded by ffmpeg libopus.
4112 ffmpeg_encode_libopus_mono_voip(&src, KBPS, &ref_ogg, SECS);4389 ffmpeg_encode_libopus_mono_voip(&src, KBPS, &ref_ogg, SECS);
4113- let ref_bytes = fs::metadata(&ref_ogg).map(|m| m.len() as usize).unwrap_or(0);4390+ let ref_bytes = fs::metadata(&ref_ogg)
4391+ .map(|m| m.len() as usize)
4392+ .unwrap_or(0);
4114 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;4393 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
4115 let ref_dec = ffmpeg_decode(&ref_ogg, CHANNELS).expect("ffmpeg libopus decode of ref");4394 let ref_dec = ffmpeg_decode(&ref_ogg, CHANNELS).expect("ffmpeg libopus decode of ref");
4116 let ref_trim: Vec<f32> = ref_dec.into_iter().take(source_frames * CHANNELS).collect();4395 let ref_trim: Vec<f32> = ref_dec.into_iter().take(source_frames * CHANNELS).collect();
@@ -4156,7 +4435,10 @@ fn silk_spectral_divergence_12k() {
4156 let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0;4435 let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0;
4157 let ours_dec = ffmpeg_decode(&ours_ogg, CHANNELS).expect("ffmpeg libopus decode of ours");4436 let ours_dec = ffmpeg_decode(&ours_ogg, CHANNELS).expect("ffmpeg libopus decode of ours");
4158 let _ = fs::remove_file(&ours_ogg);4437 let _ = fs::remove_file(&ours_ogg);
4159- let ours_trim: Vec<f32> = ours_dec.into_iter().take(source_frames * CHANNELS).collect();4438+ let ours_trim: Vec<f32> = ours_dec
4439+ .into_iter()
4440+ .take(source_frames * CHANNELS)
4441+ .collect();
4160 let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);4442 let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);
4161 4443
4162 // opus_compare totals, per-band eb², per-frame ef² — both vs the source.4444 // opus_compare totals, per-band eb², per-frame ef² — both vs the source.
@@ -4178,9 +4460,27 @@ fn silk_spectral_divergence_12k() {
4178 let mut bands_o = Vec::new();4460 let mut bands_o = Vec::new();
4179 let mut bands_r = Vec::new();4461 let mut bands_r = Vec::new();
4180 let mut scratch_ps = Vec::new();4462 let mut scratch_ps = Vec::new();
4181- band_energy(&as_f64(&s_i), CHANNELS, nframes, &mut Some(&mut bands_s), &mut scratch_ps);4463+ band_energy(
4182- band_energy(&as_f64(&o_i), CHANNELS, nframes, &mut Some(&mut bands_o), &mut scratch_ps);4464+ &as_f64(&s_i),
4183- band_energy(&as_f64(&r_i), CHANNELS, nframes, &mut Some(&mut bands_r), &mut scratch_ps);4465+ CHANNELS,
4466+ nframes,
4467+ &mut Some(&mut bands_s),
4468+ &mut scratch_ps,
4469+ );
4470+ band_energy(
4471+ &as_f64(&o_i),
4472+ CHANNELS,
4473+ nframes,
4474+ &mut Some(&mut bands_o),
4475+ &mut scratch_ps,
4476+ );
4477+ band_energy(
4478+ &as_f64(&r_i),
4479+ CHANNELS,
4480+ nframes,
4481+ &mut Some(&mut bands_r),
4482+ &mut scratch_ps,
4483+ );
4184 4484
4185 // Oracle indices both sides; FFT frame xi -> 20 ms packet index.4485 // Oracle indices both sides; FFT frame xi -> 20 ms packet index.
4186 let ours_ix = collect_indices(&ours_packets);4486 let ours_ix = collect_indices(&ours_packets);
@@ -4213,7 +4513,11 @@ fn silk_spectral_divergence_12k() {
4213 }4513 }
4214 dol /= nframes as f64;4514 dol /= nframes as f64;
4215 drl /= nframes as f64;4515 drl /= nframes as f64;
4216- let ratio = if eb2_r[bi] > 0.0 { eb2_o[bi] / eb2_r[bi] } else { f64::INFINITY };4516+ let ratio = if eb2_r[bi] > 0.0 {
4517+ eb2_o[bi] / eb2_r[bi]
4518+ } else {
4519+ f64::INFINITY
4520+ };
4217 report.push_str(&format!(4521 report.push_str(&format!(
4218 "{:5} {:5} {:6} {:+.3} {:+.3} {:.3e} {:.3e} {:>7} {:5.1}% {:5.1}%\n",4522 "{:5} {:5} {:6} {:+.3} {:+.3} {:.3e} {:.3e} {:>7} {:5.1}% {:5.1}%\n",
4219 bi,4523 bi,
@@ -4318,7 +4622,10 @@ fn silk_spectral_divergence_12k() {
4318 "# tail: top-1% ({k} frames) carry {:.2}% of ours' Σef2 vs {:.2}% of ref's; \4622 "# tail: top-1% ({k} frames) carry {:.2}% of ours' Σef2 vs {:.2}% of ref's; \
4319 50% of ours' err sits in the worst {half_o} frames ({:.2}%) \4623 50% of ours' err sits in the worst {half_o} frames ({:.2}%) \
4320 vs ref's worst {half_r} ({:.2}%)\n",4624 vs ref's worst {half_r} ({:.2}%)\n",
4321- 100.0 * sh1_o, 100.0 * sh1_r, 100.0 * halff_o, 100.0 * halff_r4625+ 100.0 * sh1_o,
4626+ 100.0 * sh1_r,
4627+ 100.0 * halff_o,
4628+ 100.0 * halff_r
4322 ));4629 ));
4323 // De-tailed: drop each side's worst 50 frames (of 24k FFT frames/pkt-mapped).4630 // De-tailed: drop each side's worst 50 frames (of 24k FFT frames/pkt-mapped).
4324 let clip50 = |ef2: &[f64]| -> f64 {4631 let clip50 = |ef2: &[f64]| -> f64 {
@@ -4351,7 +4658,11 @@ fn silk_spectral_divergence_12k() {
4351 if i >= pkt_ef2.len() {4658 if i >= pkt_ef2.len() {
4352 break;4659 break;
4353 }4660 }
4354- let mean = if pkt_cnt[i] > 0 { pkt_ef2[i] / pkt_cnt[i] as f64 } else { 0.0 };4661+ let mean = if pkt_cnt[i] > 0 {
4662+ pkt_ef2[i] / pkt_cnt[i] as f64
4663+ } else {
4664+ 0.0
4665+ };
4355 if ix.gains[0] >= 60 {4666 if ix.gains[0] >= 60 {
4356 g_hi.0 += mean;4667 g_hi.0 += mean;
4357 g_hi.1 += 1;4668 g_hi.1 += 1;
@@ -4373,12 +4684,28 @@ fn silk_spectral_divergence_12k() {
4373 >20 bytes: mean ef2 {:.3e}\n",4684 >20 bytes: mean ef2 {:.3e}\n",
4374 g_hi.1,4685 g_hi.1,
4375 g_hi.1 + g_lo.1,4686 g_hi.1 + g_lo.1,
4376- if g_hi.1 > 0 { g_hi.0 / g_hi.1 as f64 } else { f64::NAN },4687+ if g_hi.1 > 0 {
4377- if g_lo.1 > 0 { g_lo.0 / g_lo.1 as f64 } else { f64::NAN },4688+ g_hi.0 / g_hi.1 as f64
4689+ } else {
4690+ f64::NAN
4691+ },
4692+ if g_lo.1 > 0 {
4693+ g_lo.0 / g_lo.1 as f64
4694+ } else {
4695+ f64::NAN
4696+ },
4378 b_lo.1,4697 b_lo.1,
4379 b_lo.1 + b_hi.1,4698 b_lo.1 + b_hi.1,
4380- if b_lo.1 > 0 { b_lo.0 / b_lo.1 as f64 } else { f64::NAN },4699+ if b_lo.1 > 0 {
4381- if b_hi.1 > 0 { b_hi.0 / b_hi.1 as f64 } else { f64::NAN },4700+ b_lo.0 / b_lo.1 as f64
4701+ } else {
4702+ f64::NAN
4703+ },
4704+ if b_hi.1 > 0 {
4705+ b_hi.0 / b_hi.1 as f64
4706+ } else {
4707+ f64::NAN
4708+ },
4382 ));4709 ));
4383 4710
4384 let out_path = lanes_dir.join("opus-silkq-r2.bands.txt");4711 let out_path = lanes_dir.join("opus-silkq-r2.bands.txt");
@@ -4415,7 +4742,10 @@ fn opus_compare_harness() {
4415 );4742 );
4416 let err = opus_compare_err(&x, &y, channels);4743 let err = opus_compare_err(&x, &y, channels);
4417 let q = opus_compare(&x, &y, channels);4744 let q = opus_compare(&x, &y, channels);
4418- println!("HARNESS err={err:.6} Q={q:.4} ch={channels} n={}", x.len() / channels);4745+ println!(
4746+ "HARNESS err={err:.6} Q={q:.4} ch={channels} n={}",
4747+ x.len() / channels
4748+ );
4419 }4749 }
4420 4750
4421 // ---------------------------------------------------------------------------4751 // ---------------------------------------------------------------------------
@@ -4454,10 +4784,12 @@ fn opus_compare_harness_ours() {
4454 let mut d_i16 = vec![0i16; n * channels];4784 let mut d_i16 = vec![0i16; n * channels];
4455 for i in 0..n {4785 for i in 0..n {
4456 for ch in 0..channels {4786 for ch in 0..channels {
4457- s_i16[i * channels + ch] =4787+ s_i16[i * channels + ch] = (src_f32[i * channels + ch] * 32768.0)
4458- (src_f32[i * channels + ch] * 32768.0).round().clamp(-32768.0, 32767.0) as i16;4788+ .round()
4459- d_i16[i * channels + ch] =4789+ .clamp(-32768.0, 32767.0) as i16;
4460- (aligned[i * channels + ch] * 32768.0).round().clamp(-32768.0, 32767.0) as i16;4790+ d_i16[i * channels + ch] = (aligned[i * channels + ch] * 32768.0)
4791+ .round()
4792+ .clamp(-32768.0, 32767.0) as i16;
4461 }4793 }
4462 }4794 }
4463 fs::write(&out_src, bytemap(&s_i16)).unwrap();4795 fs::write(&out_src, bytemap(&s_i16)).unwrap();
@@ -4465,9 +4797,7 @@ fn opus_compare_harness_ours() {
4465 let err = opus_compare_err(&s_i16, &d_i16, channels);4797 let err = opus_compare_err(&s_i16, &d_i16, channels);
4466 let q = opus_compare(&s_i16, &d_i16, channels);4798 let q = opus_compare(&s_i16, &d_i16, channels);
4467 let c = corr_interleaved(&src_f32[..n * channels], &aligned, channels);4799 let c = corr_interleaved(&src_f32[..n * channels], &aligned, channels);
4468- println!(4800+ println!("HARNESS_OURS lag={lag} corr={c:.4} err={err:.6} Q={q:.4} kbps={kbps} n={n}");
4469- "HARNESS_OURS lag={lag} corr={c:.4} err={err:.6} Q={q:.4} kbps={kbps} n={n}"
4470- );
4471 }4801 }
4472 4802
4473 fn bytemap(p: &[i16]) -> Vec<u8> {4803 fn bytemap(p: &[i16]) -> Vec<u8> {
@@ -4533,7 +4863,8 @@ fn opus_compare_err_pinned_against_c() {
4533 4863
4534 // Case 2: mild perturbation (+0.5 dB on L, quiet 1500 Hz partial on L).4864 // Case 2: mild perturbation (+0.5 dB on L, quiet 1500 Hz partial on L).
4535 let gain = 10f64.powf(0.5 / 10.0);4865 let gain = 10f64.powf(0.5 / 10.0);
4536- let lp: Vec<f64> = t.iter()4866+ let lp: Vec<f64> = t
4867+ .iter()
4537 .zip(b0.iter())4868 .zip(b0.iter())
4538 .map(|(&tt, &bv)| bv * gain + 0.02 * (2.0 * std::f64::consts::PI * 1500.0 * tt).sin())4869 .map(|(&tt, &bv)| bv * gain + 0.02 * (2.0 * std::f64::consts::PI * 1500.0 * tt).sin())
4539 .collect();4870 .collect();
@@ -4575,7 +4906,10 @@ fn spectral_divergence_vs_libopus() {
4575 const FRAME: usize = 960;4906 const FRAME: usize = 960;
4576 const CHANNELS: usize = 2;4907 const CHANNELS: usize = 2;
4577 const MAX_LAG: usize = 2000;4908 const MAX_LAG: usize = 2000;
4578- let kbps_env: u32 = std::env::var("SWEEP_KBPS").ok().and_then(|v| v.parse().ok()).unwrap_or(96);4909+ let kbps_env: u32 = std::env::var("SWEEP_KBPS")
4910+ .ok()
4911+ .and_then(|v| v.parse().ok())
4912+ .unwrap_or(96);
4579 #[allow(non_snake_case)]4913 #[allow(non_snake_case)]
4580 let KBPS: u32 = kbps_env;4914 let KBPS: u32 = kbps_env;
4581 4915
@@ -4586,7 +4920,10 @@ fn spectral_divergence_vs_libopus() {
4586 ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),4920 ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),
4587 ("her", "~/Music/reeli.mp3"),4921 ("her", "~/Music/reeli.mp3"),
4588 ("reelm", "~/Music/reelm.wav"),4922 ("reelm", "~/Music/reelm.wav"),
4589- ("hein", "~/Downloads/reelm.mp3"),4923+ (
4924+ "hein",
4925+ "~/Downloads/reelm.mp3",
4926+ ),
4590 ];4927 ];
4591 let only: Vec<String> = std::env::var("SWEEP_ONLY")4928 let only: Vec<String> = std::env::var("SWEEP_ONLY")
4592 .unwrap_or_else(|_| "reell,dl8a".to_owned())4929 .unwrap_or_else(|_| "reell,dl8a".to_owned())
@@ -4622,7 +4959,9 @@ fn spectral_divergence_vs_libopus() {
4622 4959
4623 // Reference: ffmpeg libopus at 96k, VBR, decoded by our decoder.4960 // Reference: ffmpeg libopus at 96k, VBR, decoded by our decoder.
4624 ffmpeg_encode_libopus(src, KBPS, &scratch, SECS);4961 ffmpeg_encode_libopus(src, KBPS, &scratch, SECS);
4625- let ref_bytes = fs::metadata(&scratch).map(|m| m.len() as usize).unwrap_or(0);4962+ let ref_bytes = fs::metadata(&scratch)
4963+ .map(|m| m.len() as usize)
4964+ .unwrap_or(0);
4626 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;4965 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
4627 let ref_pkts: Vec<Vec<u8>> = ogg_packets(&fs::read(&scratch).unwrap())4966 let ref_pkts: Vec<Vec<u8>> = ogg_packets(&fs::read(&scratch).unwrap())
4628 .into_iter()4967 .into_iter()
@@ -4646,7 +4985,9 @@ fn spectral_divergence_vs_libopus() {
4646 for block in source_pcm.chunks(FRAME * CHANNELS) {4985 for block in source_pcm.chunks(FRAME * CHANNELS) {
4647 let mut padded = block.to_vec();4986 let mut padded = block.to_vec();
4648 padded.resize(FRAME * CHANNELS, 0.0);4987 padded.resize(FRAME * CHANNELS, 0.0);
4649- let len = enc.encode_float(&padded, FRAME, &mut packet).expect("encode");4988+ let len = enc
4989+ .encode_float(&padded, FRAME, &mut packet)
4990+ .expect("encode");
4650 if first_pkts.len() < 10 {4991 if first_pkts.len() < 10 {
4651 first_pkts.push(packet[..len].to_vec());4992 first_pkts.push(packet[..len].to_vec());
4652 }4993 }
@@ -4674,7 +5015,10 @@ fn spectral_divergence_vs_libopus() {
4674 "{tag}@{KBPS}k transient frames: ours {ours_tr}/{} ref {ref_tr}/{ref_n}",5015 "{tag}@{KBPS}k transient frames: ours {ours_tr}/{} ref {ref_tr}/{ref_n}",
4675 diags.len()5016 diags.len()
4676 );5017 );
4677- let ours_trim: Vec<f32> = ours_dec.into_iter().take(source_frames * CHANNELS).collect();5018+ let ours_trim: Vec<f32> = ours_dec
5019+ .into_iter()
5020+ .take(source_frames * CHANNELS)
5021+ .collect();
4678 let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);5022 let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);
4679 let ours_i16 = to_i16(&ours_aligned);5023 let ours_i16 = to_i16(&ours_aligned);
4680 let ref_i16 = to_i16(&ref_aligned);5024 let ref_i16 = to_i16(&ref_aligned);
@@ -4700,9 +5044,27 @@ fn spectral_divergence_vs_libopus() {
4700 let mut bands_o = Vec::new();5044 let mut bands_o = Vec::new();
4701 let mut bands_r = Vec::new();5045 let mut bands_r = Vec::new();
4702 let mut scratch_ps = Vec::new();5046 let mut scratch_ps = Vec::new();
4703- band_energy(&as_f64(&s_i), CHANNELS, nframes, &mut Some(&mut bands_s), &mut scratch_ps);5047+ band_energy(
4704- band_energy(&as_f64(&o_i), CHANNELS, nframes, &mut Some(&mut bands_o), &mut scratch_ps);5048+ &as_f64(&s_i),
4705- band_energy(&as_f64(&r_i), CHANNELS, nframes, &mut Some(&mut bands_r), &mut scratch_ps);5049+ CHANNELS,
5050+ nframes,
5051+ &mut Some(&mut bands_s),
5052+ &mut scratch_ps,
5053+ );
5054+ band_energy(
5055+ &as_f64(&o_i),
5056+ CHANNELS,
5057+ nframes,
5058+ &mut Some(&mut bands_o),
5059+ &mut scratch_ps,
5060+ );
5061+ band_energy(
5062+ &as_f64(&r_i),
5063+ CHANNELS,
5064+ nframes,
5065+ &mut Some(&mut bands_r),
5066+ &mut scratch_ps,
5067+ );
4706 5068
4707 report.push_str(&format!(5069 report.push_str(&format!(
4708 "\n# source {tag} @{KBPS}k: ours {ours_kbps:.1} kbps, ref {ref_kbps:.1} kbps; \5070 "\n# source {tag} @{KBPS}k: ours {ours_kbps:.1} kbps, ref {ref_kbps:.1} kbps; \
@@ -4800,11 +5162,9 @@ fn spectral_divergence_vs_libopus() {
4800 let dual = fr.iter().filter(|d| d.dual_stereo).count();5162 let dual = fr.iter().filter(|d| d.dual_stereo).count();
4801 let intra = fr.iter().filter(|d| d.intra).count();5163 let intra = fr.iter().filter(|d| d.intra).count();
4802 let cbb_min = fr.iter().map(|d| d.coded_bands).min().unwrap_or(0);5164 let cbb_min = fr.iter().map(|d| d.coded_bands).min().unwrap_or(0);
4803- let cbb_mean =5165+ let cbb_mean = fr.iter().map(|d| d.coded_bands).sum::<usize>() as f64 / dn as f64;
4804- fr.iter().map(|d| d.coded_bands).sum::<usize>() as f64 / dn as f64;
4805 let int_mean = fr.iter().map(|d| d.intensity).sum::<usize>() as f64 / dn as f64;5166 let int_mean = fr.iter().map(|d| d.intensity).sum::<usize>() as f64 / dn as f64;
4806- let bits =5167+ let bits = fr.iter().map(|d| d.nb_compressed).sum::<usize>() as f64 * 8.0 / dn as f64;
4807- fr.iter().map(|d| d.nb_compressed).sum::<usize>() as f64 * 8.0 / dn as f64;
4808 report.push_str(&format!(5168 report.push_str(&format!(
4809 "{}\t{:.3e}\t{}/{}\t{}\t{}\t{}\t{}/{}\t{}/{}\t{:.0}\n",5169 "{}\t{:.3e}\t{}/{}\t{}\t{}\t{}\t{}/{}\t{}/{}\t{:.0}\n",
4810 s,5170 s,
@@ -4829,8 +5189,7 @@ fn spectral_divergence_vs_libopus() {
4829 let dual = diags.iter().filter(|d| d.dual_stereo).count();5189 let dual = diags.iter().filter(|d| d.dual_stereo).count();
4830 let intra = diags.iter().filter(|d| d.intra).count();5190 let intra = diags.iter().filter(|d| d.intra).count();
4831 let cbb_min = diags.iter().map(|d| d.coded_bands).min().unwrap_or(0);5191 let cbb_min = diags.iter().map(|d| d.coded_bands).min().unwrap_or(0);
4832- let cbb_mean =5192+ let cbb_mean = diags.iter().map(|d| d.coded_bands).sum::<usize>() as f64 / dn as f64;
4833- diags.iter().map(|d| d.coded_bands).sum::<usize>() as f64 / dn as f64;
4834 let int_mean = diags.iter().map(|d| d.intensity).sum::<usize>() as f64 / dn as f64;5193 let int_mean = diags.iter().map(|d| d.intensity).sum::<usize>() as f64 / dn as f64;
4835 let bits =5194 let bits =
4836 diags.iter().map(|d| d.nb_compressed).sum::<usize>() as f64 * 8.0 / dn as f64;5195 diags.iter().map(|d| d.nb_compressed).sum::<usize>() as f64 * 8.0 / dn as f64;
@@ -4854,9 +5213,14 @@ fn spectral_divergence_vs_libopus() {
4854 // frame each window lands in.5213 // frame each window lands in.
4855 let mut byf: Vec<(usize, f64)> = ef2_o.iter().cloned().enumerate().collect();5214 let mut byf: Vec<(usize, f64)> = ef2_o.iter().cloned().enumerate().collect();
4856 byf.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());5215 byf.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
4857- report.push_str("# top-8 metric windows by ours ef²: offset_ms ours ref | enc frame diag\n");5216+ report
5217+ .push_str("# top-8 metric windows by ours ef²: offset_ms ours ref | enc frame diag\n");
4858 for &(xi, v) in &byf[..byf.len().min(8)] {5218 for &(xi, v) in &byf[..byf.len().min(8)] {
4859- let rv = if xi < ef2_r.len() { ef2_r[xi] } else { f64::NAN };5219+ let rv = if xi < ef2_r.len() {
5220+ ef2_r[xi]
5221+ } else {
5222+ f64::NAN
5223+ };
4860 let ms = xi * WIN_STEP * 1000 / 48000;5224 let ms = xi * WIN_STEP * 1000 / 48000;
4861 let eidx = xi * WIN_STEP / FRAME;5225 let eidx = xi * WIN_STEP / FRAME;
4862 let d = diags.get(eidx);5226 let d = diags.get(eidx);
@@ -4882,9 +5246,8 @@ fn spectral_divergence_vs_libopus() {
4882 }5246 }
4883 5247
4884 // Startup behavior: first 10 encoder frames.5248 // Startup behavior: first 10 encoder frames.
4885- report.push_str(5249+ report
4886- "# first encoder frames: idx trans intra silence cbb_hz int_hz dual bytes\n",5250+ .push_str("# first encoder frames: idx trans intra silence cbb_hz int_hz dual bytes\n");
4887- );
4888 for (i, d) in diags.iter().take(10).enumerate() {5251 for (i, d) in diags.iter().take(10).enumerate() {
4889 report.push_str(&format!(5252 report.push_str(&format!(
4890 "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n",5253 "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
@@ -4901,11 +5264,12 @@ fn spectral_divergence_vs_libopus() {
4901 5264
4902 // Per-window per-band ln-energies for the metric windows 12..=205265 // Per-window per-band ln-energies for the metric windows 12..=20
4903 // (+120..+200 ms): the leak's shape, band by band.5266 // (+120..+200 ms): the leak's shape, band by band.
4904- report.push_str(5267+ report.push_str("# windows 12..=20: win +ms band lo-hi | lnE src/ours/ref, ch L then R\n");
4905- "# windows 12..=20: win +ms band lo-hi | lnE src/ours/ref, ch L then R\n",
4906- );
4907 // WIN_CENTRE=<window index> recentres the dump on another window.5268 // WIN_CENTRE=<window index> recentres the dump on another window.
4908- let wc: usize = std::env::var("WIN_CENTRE").ok().and_then(|v| v.parse().ok()).unwrap_or(16);5269+ let wc: usize = std::env::var("WIN_CENTRE")
5270+ .ok()
5271+ .and_then(|v| v.parse().ok())
5272+ .unwrap_or(16);
4909 for xi in wc.saturating_sub(4)..=wc + 4 {5273 for xi in wc.saturating_sub(4)..=wc + 4 {
4910 if xi >= nframes {5274 if xi >= nframes {
4911 break;5275 break;
@@ -4951,7 +5315,8 @@ fn spectral_divergence_vs_libopus() {
4951 g.total_bits,5315 g.total_bits,
4952 ));5316 ));
4953 for (ch, name) in [(0usize, 'L'), (1usize, 'R')] {5317 for (ch, name) in [(0usize, 'L'), (1usize, 'R')] {
4954- let band = &g.old_band_e[ch * ec_opus::celt::NB_BANDS..(ch + 1) * ec_opus::celt::NB_BANDS];5318+ let band = &g.old_band_e
5319+ [ch * ec_opus::celt::NB_BANDS..(ch + 1) * ec_opus::celt::NB_BANDS];
4955 let e: Vec<String> = band.iter().map(|v| format!("{v:+6.1}")).collect();5320 let e: Vec<String> = band.iter().map(|v| format!("{v:+6.1}")).collect();
4956 frames_all.push_str(&format!(" {name} {}\n", e.join(" ")));5321 frames_all.push_str(&format!(" {name} {}\n", e.join(" ")));
4957 }5322 }
@@ -5021,8 +5386,12 @@ fn celt_silence_then_attack_decodes_bounded() {
5021 fn reell_startup_hop_energies() {5386 fn reell_startup_hop_energies() {
5022 const CH: usize = 2;5387 const CH: usize = 2;
5023 // HOP_SRC / HOP_MS pick another source and window centre (diagnostic).5388 // HOP_SRC / HOP_MS pick another source and window centre (diagnostic).
5024- let src_s = std::env::var("HOP_SRC").unwrap_or_else(|_| "~/Music/reell.mp4".into());5389+ let src_s =
5025- let centre_ms: f64 = std::env::var("HOP_MS").ok().and_then(|v| v.parse().ok()).unwrap_or(42.5);5390+ std::env::var("HOP_SRC").unwrap_or_else(|_| "~/Music/reell.mp4".into());
5391+ let centre_ms: f64 = std::env::var("HOP_MS")
5392+ .ok()
5393+ .and_then(|v| v.parse().ok())
5394+ .unwrap_or(42.5);
5026 let src = shellexpand(&src_s);5395 let src = shellexpand(&src_s);
5027 if !src.exists() {5396 if !src.exists() {
5028 return;5397 return;
@@ -5030,7 +5399,10 @@ fn reell_startup_hop_energies() {
5030 let secs = (centre_ms / 1000.0 + 1.0).max(2.0);5399 let secs = (centre_ms / 1000.0 + 1.0).max(2.0);
5031 let pcm = ffmpeg_decode_pcm(&src, secs);5400 let pcm = ffmpeg_decode_pcm(&src, secs);
5032 let scratch = std::env::temp_dir().join("ec-opus-reell-startup.opus");5401 let scratch = std::env::temp_dir().join("ec-opus-reell-startup.opus");
5033- let kbps: u32 = std::env::var("HOP_KBPS").ok().and_then(|v| v.parse().ok()).unwrap_or(96);5402+ let kbps: u32 = std::env::var("HOP_KBPS")
5403+ .ok()
5404+ .and_then(|v| v.parse().ok())
5405+ .unwrap_or(96);
5034 ffmpeg_encode_libopus(&src, kbps, &scratch, secs);5406 ffmpeg_encode_libopus(&src, kbps, &scratch, secs);
5035 let (ref_dec, _) = decode_ogg(&scratch);5407 let (ref_dec, _) = decode_ogg(&scratch);
5036 let (lag_r, ref_al) = align_to_source(&pcm, &ref_dec, CH, 2000);5408 let (lag_r, ref_al) = align_to_source(&pcm, &ref_dec, CH, 2000);
@@ -5048,11 +5420,22 @@ fn reell_startup_hop_energies() {
5048 ours_dec.extend_from_slice(&buf[..m * CH]);5420 ours_dec.extend_from_slice(&buf[..m * CH]);
5049 let e = enc.last_celt_diag().clone();5421 let e = enc.last_celt_diag().clone();
5050 let d = dec.last_celt_diag().clone();5422 let d = dec.last_celt_diag().clone();
5051- frames_diag.push((n, e.is_transient, e.intra, d.tf_res.clone(), d.anti_collapse));5423+ frames_diag.push((
5424+ n,
5425+ e.is_transient,
5426+ e.intra,
5427+ d.tf_res.clone(),
5428+ d.anti_collapse,
5429+ ));
5052 }5430 }
5053 let (lag_o, ours_al) = align_to_source(&pcm, &ours_dec, CH, 2000);5431 let (lag_o, ours_al) = align_to_source(&pcm, &ours_dec, CH, 2000);
5054 let first = |v: &[f32]| v.iter().position(|x| x.abs() > 1e-4).map(|i| i / CH);5432 let first = |v: &[f32]| v.iter().position(|x| x.abs() > 1e-4).map(|i| i / CH);
5055- println!("lag ref {lag_r} ours {lag_o}; first>1e-4: src {:?} ours {:?} ref {:?}", first(&pcm), first(&ours_al), first(&ref_al));5433+ println!(
5434+ "lag ref {lag_r} ours {lag_o}; first>1e-4: src {:?} ours {:?} ref {:?}",
5435+ first(&pcm),
5436+ first(&ours_al),
5437+ first(&ref_al)
5438+ );
5056 let e = |v: &[f32], h: usize| -> f64 {5439 let e = |v: &[f32], h: usize| -> f64 {
5057 let a = (h * 120 * CH).min(v.len());5440 let a = (h * 120 * CH).min(v.len());
5058 let b = ((h + 1) * 120 * CH).min(v.len());5441 let b = ((h + 1) * 120 * CH).min(v.len());
@@ -5061,12 +5444,21 @@ fn reell_startup_hop_energies() {
5061 let hc = (centre_ms / 2.5) as usize;5444 let hc = (centre_ms / 2.5) as usize;
5062 for f in (hc / 8).saturating_sub(1)..=(hc / 8 + 1) {5445 for f in (hc / 8).saturating_sub(1)..=(hc / 8 + 1) {
5063 if let Some((n, t, i, tf, ac)) = frames_diag.get(f) {5446 if let Some((n, t, i, tf, ac)) = frames_diag.get(f) {
5064- println!("frame {f} ({:.1} ms): bytes {n} trans {t} intra {i} ac {ac} tf {tf:?}", f as f64 * 20.0);5447+ println!(
5448+ "frame {f} ({:.1} ms): bytes {n} trans {t} intra {i} ac {ac} tf {tf:?}",
5449+ f as f64 * 20.0
5450+ );
5065 }5451 }
5066 }5452 }
5067 println!("hop(ms)\tsrc\tours\tref");5453 println!("hop(ms)\tsrc\tours\tref");
5068 for h in hc.saturating_sub(8)..hc + 8 {5454 for h in hc.saturating_sub(8)..hc + 8 {
5069- println!("{:.1}\t{:.3e}\t{:.3e}\t{:.3e}", h as f64 * 2.5, e(&pcm, h), e(&ours_al, h), e(&ref_al, h));5455+ println!(
5456+ "{:.1}\t{:.3e}\t{:.3e}\t{:.3e}",
5457+ h as f64 * 2.5,
5458+ e(&pcm, h),
5459+ e(&ours_al, h),
5460+ e(&ref_al, h)
5461+ );
5070 }5462 }
5071 }5463 }
5072 5464
@@ -5083,9 +5475,18 @@ fn celt_click_peak_offset() {
5083 enc.set_mode(Some(ec_opus::Mode::Celt));5475 enc.set_mode(Some(ec_opus::Mode::Celt));
5084 enc.set_bitrate(bps);5476 enc.set_bitrate(bps);
5085 let (dec, _) = roundtrip_own(&mut enc, &click, 1, 960);5477 let (dec, _) = roundtrip_own(&mut enc, &click, 1, 960);
5086- let p = dec.iter().enumerate().max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap()).unwrap().0;5478+ let p = dec
5479+ .iter()
5480+ .enumerate()
5481+ .max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap())
5482+ .unwrap()
5483+ .0;
5087 let d = enc.last_celt_diag().clone();5484 let d = enc.last_celt_diag().clone();
5088- println!("celt click {bps}: peak +{} (lm {})", p as i64 - at as i64, d.lm);5485+ println!(
5486+ "celt click {bps}: peak +{} (lm {})",
5487+ p as i64 - at as i64,
5488+ d.lm
5489+ );
5089 }5490 }
5090 }5491 }
5091 5492
@@ -5147,7 +5548,9 @@ fn short_block_bits_vs_libopus() {
5147 5548
5148 // Reference: ffmpeg libopus at KBPS, VBR.5549 // Reference: ffmpeg libopus at KBPS, VBR.
5149 ffmpeg_encode_libopus(src, KBPS, &scratch, SECS);5550 ffmpeg_encode_libopus(src, KBPS, &scratch, SECS);
5150- let ref_bytes = fs::metadata(&scratch).map(|m| m.len() as usize).unwrap_or(0);5551+ let ref_bytes = fs::metadata(&scratch)
5552+ .map(|m| m.len() as usize)
5553+ .unwrap_or(0);
5151 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;5554 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
5152 let ref_pkts: Vec<Vec<u8>> = ogg_packets(&fs::read(&scratch).unwrap())5555 let ref_pkts: Vec<Vec<u8>> = ogg_packets(&fs::read(&scratch).unwrap())
5153 .into_iter()5556 .into_iter()
@@ -5182,7 +5585,9 @@ fn short_block_bits_vs_libopus() {
5182 for block in source_pcm.chunks(FRAME * CHANNELS) {5585 for block in source_pcm.chunks(FRAME * CHANNELS) {
5183 let mut padded = block.to_vec();5586 let mut padded = block.to_vec();
5184 padded.resize(FRAME * CHANNELS, 0.0);5587 padded.resize(FRAME * CHANNELS, 0.0);
5185- let len = enc.encode_float(&padded, FRAME, &mut packet).expect("encode");5588+ let len = enc
5589+ .encode_float(&padded, FRAME, &mut packet)
5590+ .expect("encode");
5186 ours_bytes += len;5591 ours_bytes += len;
5187 let toc = ec_opus::Toc::new(packet[0]);5592 let toc = ec_opus::Toc::new(packet[0]);
5188 if dec.decode_float(&packet[..len], &mut dbuf).is_ok() && toc.mode() != Mode::Silk {5593 if dec.decode_float(&packet[..len], &mut dbuf).is_ok() && toc.mode() != Mode::Silk {
@@ -5199,10 +5604,14 @@ fn short_block_bits_vs_libopus() {
5199 ));5604 ));
5200 5605
5201 for (label, is_trans) in [("LONG", false), ("SHORT", true)] {5606 for (label, is_trans) in [("LONG", false), ("SHORT", true)] {
5202- let ours_t: Vec<&ec_opus::celt::CeltDecDiag> =5607+ let ours_t: Vec<&ec_opus::celt::CeltDecDiag> = ours_diags
5203- ours_diags.iter().filter(|d| d.transient == is_trans).collect();5608+ .iter()
5204- let ref_t: Vec<&ec_opus::celt::CeltDecDiag> =5609+ .filter(|d| d.transient == is_trans)
5205- ref_diags.iter().filter(|d| d.transient == is_trans).collect();5610+ .collect();
5611+ let ref_t: Vec<&ec_opus::celt::CeltDecDiag> = ref_diags
5612+ .iter()
5613+ .filter(|d| d.transient == is_trans)
5614+ .collect();
5206 let on = ours_t.len();5615 let on = ours_t.len();
5207 let rn = ref_t.len();5616 let rn = ref_t.len();
5208 if on == 0 && rn == 0 {5617 if on == 0 && rn == 0 {
@@ -5235,19 +5644,18 @@ fn short_block_bits_vs_libopus() {
5235 ours_t.iter().map(|d| d.fine_quant[i] as f64).sum::<f64>() / on.max(1) as f64;5644 ours_t.iter().map(|d| d.fine_quant[i] as f64).sum::<f64>() / on.max(1) as f64;
5236 let rm: f64 =5645 let rm: f64 =
5237 ref_t.iter().map(|d| d.fine_quant[i] as f64).sum::<f64>() / rn.max(1) as f64;5646 ref_t.iter().map(|d| d.fine_quant[i] as f64).sum::<f64>() / rn.max(1) as f64;
5238- report.push_str(&format!(5647+ report.push_str(&format!("{}\t{:.2}\t{:.2}\n", CELT_EBANDS[i] * 240, om, rm));
5239- "{}\t{:.2}\t{:.2}\n",
5240- CELT_EBANDS[i] * 240,
5241- om,
5242- rm
5243- ));
5244 }5648 }
5245 5649
5246 // Aggregate stats.5650 // Aggregate stats.
5247- let mean = |v: &[&ec_opus::celt::CeltDecDiag], f: &dyn Fn(&ec_opus::celt::CeltDecDiag) -> f64| -> f64 {5651+ let mean = |v: &[&ec_opus::celt::CeltDecDiag],
5652+ f: &dyn Fn(&ec_opus::celt::CeltDecDiag) -> f64|
5653+ -> f64 {
5248 v.iter().map(|d| f(d)).sum::<f64>() / v.len().max(1) as f645654 v.iter().map(|d| f(d)).sum::<f64>() / v.len().max(1) as f64
5249 };5655 };
5250- let mean_band_hz = |v: &[&ec_opus::celt::CeltDecDiag], f: &dyn Fn(&ec_opus::celt::CeltDecDiag) -> usize| -> f64 {5656+ let mean_band_hz = |v: &[&ec_opus::celt::CeltDecDiag],
5657+ f: &dyn Fn(&ec_opus::celt::CeltDecDiag) -> usize|
5658+ -> f64 {
5251 let m = v.iter().map(|d| f(d)).sum::<usize>() / v.len().max(1);5659 let m = v.iter().map(|d| f(d)).sum::<usize>() / v.len().max(1);
5252 CELT_EBANDS[m] as f64 * 240.05660 CELT_EBANDS[m] as f64 * 240.0
5253 };5661 };
@@ -5291,16 +5699,22 @@ fn short_block_bits_vs_libopus() {
5291 ));5699 ));
5292 report.push_str("# mean dynalloc boost per band (1/8 bit) ours / ref\n");5700 report.push_str("# mean dynalloc boost per band (1/8 bit) ours / ref\n");
5293 for b in 0..nb {5701 for b in 0..nb {
5294- let mo = mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.offsets[b] as f64);5702+ let mo = mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| {
5295- let mr = mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.offsets[b] as f64);5703+ d.offsets[b] as f64
5704+ });
5705+ let mr = mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| {
5706+ d.offsets[b] as f64
5707+ });
5296 if mo != 0.0 || mr != 0.0 {5708 if mo != 0.0 || mr != 0.0 {
5297 report.push_str(&format!("{}\t{:.1}\t{:.1}\n", CELT_EBANDS[b] * 240, mo, mr));5709 report.push_str(&format!("{}\t{:.1}\t{:.1}\n", CELT_EBANDS[b] * 240, mo, mr));
5298 }5710 }
5299 }5711 }
5300 report.push_str(&format!(5712 report.push_str(&format!(
5301 "# alloc_trim mean: ours {:.2} ref {:.2}\n",5713 "# alloc_trim mean: ours {:.2} ref {:.2}\n",
5302- mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.alloc_trim as f64),5714+ mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.alloc_trim
5303- mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.alloc_trim as f64),5715+ as f64),
5716+ mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.alloc_trim
5717+ as f64),
5304 ));5718 ));
5305 report.push_str(&format!(5719 report.push_str(&format!(
5306 "# coded_bands mean Hz: ours {:.0} ref {:.0}\n",5720 "# coded_bands mean Hz: ours {:.0} ref {:.0}\n",
@@ -5319,8 +5733,10 @@ fn short_block_bits_vs_libopus() {
5319 ));5733 ));
5320 report.push_str(&format!(5734 report.push_str(&format!(
5321 "# total_bits mean: ours {:.0} ref {:.0}\n",5735 "# total_bits mean: ours {:.0} ref {:.0}\n",
5322- mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.total_bits as f64),5736+ mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.total_bits
5323- mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.total_bits as f64),5737+ as f64),
5738+ mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.total_bits
5739+ as f64),
5324 ));5740 ));
5325 report.push_str(&format!(5741 report.push_str(&format!(
5326 "# balance mean: ours {:.0} ref {:.0}\n",5742 "# balance mean: ours {:.0} ref {:.0}\n",
@@ -5393,7 +5809,9 @@ fn err_map_vs_libopus() {
5393 5809
5394 // Reference: ffmpeg libopus, VBR — the gate's path.5810 // Reference: ffmpeg libopus, VBR — the gate's path.
5395 ffmpeg_encode_libopus(&src, kbps_env, &scratch, SECS);5811 ffmpeg_encode_libopus(&src, kbps_env, &scratch, SECS);
5396- let ref_bytes = fs::metadata(&scratch).map(|m| m.len() as usize).unwrap_or(0);5812+ let ref_bytes = fs::metadata(&scratch)
5813+ .map(|m| m.len() as usize)
5814+ .unwrap_or(0);
5397 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;5815 let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
5398 let (ref_dec, ref_ch) = decode_ogg(&scratch);5816 let (ref_dec, ref_ch) = decode_ogg(&scratch);
5399 assert_eq!(ref_ch, CH, "ref not stereo");5817 assert_eq!(ref_ch, CH, "ref not stereo");
@@ -5421,7 +5839,11 @@ fn err_map_vs_libopus() {
5421 let toc = ec_opus::Toc::new(p[0]);5839 let toc = ec_opus::Toc::new(p[0]);
5422 let got = d.decode_float(p, &mut buf).unwrap_or(0);5840 let got = d.decode_float(p, &mut buf).unwrap_or(0);
5423 if toc.mode() != Mode::Silk {5841 if toc.mode() != Mode::Silk {
5424- ref_fd.push(FD { sample: at, enc: None, dec: d.last_celt_diag().clone() });5842+ ref_fd.push(FD {
5843+ sample: at,
5844+ enc: None,
5845+ dec: d.last_celt_diag().clone(),
5846+ });
5425 }5847 }
5426 at += got;5848 at += got;
5427 }5849 }
@@ -5465,7 +5887,11 @@ fn err_map_vs_libopus() {
5465 5887
5466 // 1 s windows.5888 // 1 s windows.
5467 let nwin = hop_o.len() / HOPS_PER_WIN;5889 let nwin = hop_o.len() / HOPS_PER_WIN;
5468- let sum = |h: &[f64], w: usize| h[w * HOPS_PER_WIN..(w + 1) * HOPS_PER_WIN].iter().sum::<f64>();5890+ let sum = |h: &[f64], w: usize| {
5891+ h[w * HOPS_PER_WIN..(w + 1) * HOPS_PER_WIN]
5892+ .iter()
5893+ .sum::<f64>()
5894+ };
5469 let tot_o: f64 = hop_o.iter().sum();5895 let tot_o: f64 = hop_o.iter().sum();
5470 let tot_r: f64 = hop_r.iter().sum();5896 let tot_r: f64 = hop_r.iter().sum();
5471 let mut wins: Vec<(usize, f64, f64, f64)> = (0..nwin)5897 let mut wins: Vec<(usize, f64, f64, f64)> = (0..nwin)
@@ -5500,9 +5926,9 @@ fn err_map_vs_libopus() {
5500 f.dec.spread,5926 f.dec.spread,
5501 f.dec.anti_collapse as u8,5927 f.dec.anti_collapse as u8,
5502 f.dec.total_bits,5928 f.dec.total_bits,
5503- ) + &e.map(|e| format!(5929+ ) + &e
5504- " | ENC sb{} vbr{}", e.short_blocks, e.vbr_reservoir5930+ .map(|e| format!(" | ENC sb{} vbr{}", e.short_blocks, e.vbr_reservoir))
5505- )).unwrap_or_default()5931+ .unwrap_or_default()
5506 };5932 };
5507 let ref_at = |s: usize| -> Option<&FD> {5933 let ref_at = |s: usize| -> Option<&FD> {
5508 let i = ref_fd.partition_point(|f| f.sample <= s);5934 let i = ref_fd.partition_point(|f| f.sample <= s);
@@ -5569,13 +5995,19 @@ fn err_map_vs_libopus() {
5569 )5995 )
5570 })5996 })
5571 .collect();5997 .collect();
5572- out.push_str(&format!(" Δlog2E L {}\n R {}\n", d0.join(" "), d1.join(" ")));5998+ out.push_str(&format!(
5999+ " Δlog2E L {}\n R {}\n",
6000+ d0.join(" "),
6001+ d1.join(" ")
6002+ ));
5573 }6003 }
5574 }6004 }
5575 }6005 }
5576 6006
5577 // The single worst ours window, frame by frame: where do decisions diverge.6007 // The single worst ours window, frame by frame: where do decisions diverge.
5578- let worst = (0..nwin).max_by(|&a, &b| wins[a].1.total_cmp(&wins[b].1)).unwrap();6008+ let worst = (0..nwin)
6009+ .max_by(|&a, &b| wins[a].1.total_cmp(&wins[b].1))
6010+ .unwrap();
5579 out.push_str(&format!(6011 out.push_str(&format!(
5580 "\n== WORST WINDOW t={}..{}s, ALL FRAMES (OUR | REF) ==\n",6012 "\n== WORST WINDOW t={}..{}s, ALL FRAMES (OUR | REF) ==\n",
5581 worst,6013 worst,
@@ -5583,7 +6015,9 @@ fn err_map_vs_libopus() {
5583 ));6015 ));
5584 for fi in worst * 50..(worst + 1) * 50 {6016 for fi in worst * 50..(worst + 1) * 50 {
5585 let our = ours_fd.get(fi).map(&fmt_fd).unwrap_or_else(|| "-".into());6017 let our = ours_fd.get(fi).map(&fmt_fd).unwrap_or_else(|| "-".into());
5586- let rf = ref_at(fi * FRAME + 480).map(&fmt_fd).unwrap_or_else(|| "-".into());6018+ let rf = ref_at(fi * FRAME + 480)
6019+ .map(&fmt_fd)
6020+ .unwrap_or_else(|| "-".into());
5587 out.push_str(&format!("f{fi}: OUR {our}\n REF {rf}\n"));6021 out.push_str(&format!("f{fi}: OUR {our}\n REF {rf}\n"));
5588 }6022 }
5589 6023
@@ -5599,31 +6033,53 @@ fn err_map_vs_libopus() {
5599 #[ignore]6033 #[ignore]
5600 fn frame_decisions_vs_libopus() {6034 fn frame_decisions_vs_libopus() {
5601 const CH: usize = 2;6035 const CH: usize = 2;
5602- let src_s = std::env::var("FRAME_SRC")6036+ let src_s =
5603- .unwrap_or_else(|_| "~/Music/reell.mp4".into());6037+ std::env::var("FRAME_SRC").unwrap_or_else(|_| "~/Music/reell.mp4".into());
5604 let src = shellexpand(&src_s);6038 let src = shellexpand(&src_s);
5605 if !src.exists() {6039 if !src.exists() {
5606 eprintln!("SKIP: missing {}", src.display());6040 eprintln!("SKIP: missing {}", src.display());
5607 return;6041 return;
5608 }6042 }
5609- let kbps: u32 = std::env::var("FRAME_KBPS").ok().and_then(|v| v.parse().ok()).unwrap_or(64);6043+ let kbps: u32 = std::env::var("FRAME_KBPS")
5610- let from: usize = std::env::var("FRAME_FROM").ok().and_then(|v| v.parse().ok()).unwrap_or(0);6044+ .ok()
5611- let to: usize = std::env::var("FRAME_TO").ok().and_then(|v| v.parse().ok()).unwrap_or(6);6045+ .and_then(|v| v.parse().ok())
6046+ .unwrap_or(64);
6047+ let from: usize = std::env::var("FRAME_FROM")
6048+ .ok()
6049+ .and_then(|v| v.parse().ok())
6050+ .unwrap_or(0);
6051+ let to: usize = std::env::var("FRAME_TO")
6052+ .ok()
6053+ .and_then(|v| v.parse().ok())
6054+ .unwrap_or(6);
5612 let secs = (to as f64 * 0.02 + 1.0).max(2.0);6055 let secs = (to as f64 * 0.02 + 1.0).max(2.0);
5613 let pcm = ffmpeg_decode_pcm(&src, secs);6056 let pcm = ffmpeg_decode_pcm(&src, secs);
5614 let scratch = std::env::temp_dir().join("ec-opus-frame-dec.opus");6057 let scratch = std::env::temp_dir().join("ec-opus-frame-dec.opus");
5615 ffmpeg_encode_libopus(&src, kbps, &scratch, secs);6058 ffmpeg_encode_libopus(&src, kbps, &scratch, secs);
5616- let ref_pkts: Vec<Vec<u8>> =6059+ let ref_pkts: Vec<Vec<u8>> = ogg_packets(&fs::read(&scratch).unwrap())
5617- ogg_packets(&fs::read(&scratch).unwrap()).into_iter().skip(2).collect();6060+ .into_iter()
6061+ .skip(2)
6062+ .collect();
5618 6063
5619 let show = |tag: &str, f: usize, bytes: usize, d: &ec_opus::celt::CeltDecDiag| {6064 let show = |tag: &str, f: usize, bytes: usize, d: &ec_opus::celt::CeltDecDiag| {
5620- let e: Vec<String> = d.old_band_e[..NB_BANDS_DIAG].iter().map(|v| format!("{v:.1}")).collect();6065+ let e: Vec<String> = d.old_band_e[..NB_BANDS_DIAG]
6066+ .iter()
6067+ .map(|v| format!("{v:.1}"))
6068+ .collect();
5621 println!(6069 println!(
5622 "f{f} {tag}: bytes {bytes} sil {} intra {} trans {} ac {} trim {} spread {} cb {} \6070 "f{f} {tag}: bytes {bytes} sil {} intra {} trans {} ac {} trim {} spread {} cb {} \
5623 tf {:?} pulses {:?} fine {:?} E {}",6071 tf {:?} pulses {:?} fine {:?} E {}",
5624- d.silence, d.intra, d.transient, d.anti_collapse, d.alloc_trim, d.spread,6072+ d.silence,
5625- d.coded_bands, &d.tf_res[..NB_BANDS_DIAG], &d.pulses[..NB_BANDS_DIAG],6073+ d.intra,
5626- &d.fine_quant[..NB_BANDS_DIAG], e.join(",")6074+ d.transient,
6075+ d.anti_collapse,
6076+ d.alloc_trim,
6077+ d.spread,
6078+ d.coded_bands,
6079+ &d.tf_res[..NB_BANDS_DIAG],
6080+ &d.pulses[..NB_BANDS_DIAG],
6081+ &d.fine_quant[..NB_BANDS_DIAG],
6082+ e.join(",")
5627 );6083 );
5628 };6084 };
5629 6085
@@ -5634,7 +6090,11 @@ fn frame_decisions_vs_libopus() {
5634 let ok = !p.is_empty()6090 let ok = !p.is_empty()
5635 && ec_opus::Toc::new(p[0]).mode() != Mode::Silk6091 && ec_opus::Toc::new(p[0]).mode() != Mode::Silk
5636 && d.decode_float(p, &mut buf).is_ok();6092 && d.decode_float(p, &mut buf).is_ok();
5637- ref_rows.push(if ok { Some((p.len(), d.last_celt_diag().clone())) } else { None });6093+ ref_rows.push(if ok {
6094+ Some((p.len(), d.last_celt_diag().clone()))
6095+ } else {
6096+ None
6097+ });
5638 }6098 }
5639 6099
5640 // Encode at the reference's REALISED rate, like the library gate does:6100 // Encode at the reference's REALISED rate, like the library gate does:
@@ -5653,7 +6113,11 @@ fn frame_decisions_vs_libopus() {
5653 let n = enc.encode_float(block, 960, &mut out).unwrap();6113 let n = enc.encode_float(block, 960, &mut out).unwrap();
5654 let ok = ec_opus::Toc::new(out[0]).mode() != Mode::Silk6114 let ok = ec_opus::Toc::new(out[0]).mode() != Mode::Silk
5655 && dec.decode_float(&out[..n], &mut buf).is_ok();6115 && dec.decode_float(&out[..n], &mut buf).is_ok();
5656- ours_rows.push(if ok { Some((n, dec.last_celt_diag().clone())) } else { None });6116+ ours_rows.push(if ok {
6117+ Some((n, dec.last_celt_diag().clone()))
6118+ } else {
6119+ None
6120+ });
5657 }6121 }
5658 6122
5659 if to - from <= 40 {6123 if to - from <= 40 {
@@ -5674,9 +6138,10 @@ fn frame_decisions_vs_libopus() {
5674 let mut agg = [(0usize, [0.0f64; 8]); 2];6138 let mut agg = [(0usize, [0.0f64; 8]); 2];
5675 let mut trans_diff = 0usize;6139 let mut trans_diff = 0usize;
5676 for f in from..to {6140 for f in from..to {
5677- let (Some((no, o)), Some((nr, r))) =6141+ let (Some((no, o)), Some((nr, r))) = (
5678- (ours_rows.get(f).and_then(|x| x.as_ref()), ref_rows.get(f).and_then(|x| x.as_ref()))6142+ ours_rows.get(f).and_then(|x| x.as_ref()),
5679- else {6143+ ref_rows.get(f).and_then(|x| x.as_ref()),
6144+ ) else {
5680 continue;6145 continue;
5681 };6146 };
5682 if o.transient != r.transient {6147 if o.transient != r.transient {
@@ -5689,10 +6154,14 @@ fn frame_decisions_vs_libopus() {
5689 let a = &mut agg[slot];6154 let a = &mut agg[slot];
5690 a.0 += 1;6155 a.0 += 1;
5691 for (k, v) in [6156 for (k, v) in [
5692- *no as f64, *nr as f64,6157+ *no as f64,
5693- o.alloc_trim as f64, r.alloc_trim as f64,6158+ *nr as f64,
5694- tf(o), tf(r),6159+ o.alloc_trim as f64,
5695- f64::from(u8::from(o.anti_collapse)), f64::from(u8::from(r.anti_collapse)),6160+ r.alloc_trim as f64,
6161+ tf(o),
6162+ tf(r),
6163+ f64::from(u8::from(o.anti_collapse)),
6164+ f64::from(u8::from(r.anti_collapse)),
5696 ]6165 ]
5697 .into_iter()6166 .into_iter()
5698 .enumerate()6167 .enumerate()
@@ -5710,7 +6179,14 @@ fn frame_decisions_vs_libopus() {
5710 println!(6179 println!(
5711 "{name} n={n}: bytes o {:.1} r {:.1} | trim o {:.2} r {:.2} | mean tf_res o {:.3} \6180 "{name} n={n}: bytes o {:.1} r {:.1} | trim o {:.2} r {:.2} | mean tf_res o {:.3} \
5712 r {:.3} | anti_collapse o {:.2} r {:.2}",6181 r {:.3} | anti_collapse o {:.2} r {:.2}",
5713- m(0), m(1), m(2), m(3), m(4), m(5), m(6), m(7)6182+ m(0),
6183+ m(1),
6184+ m(2),
6185+ m(3),
6186+ m(4),
6187+ m(5),
6188+ m(6),
6189+ m(7)
5714 );6190 );
5715 }6191 }
5716 }6192 }
@@ -5730,7 +6206,11 @@ fn analysis_music_prob_separates_speech_from_music() {
5730 const FRAME: usize = 960;6206 const FRAME: usize = 960;
5731 const CHANNELS: usize = 2;6207 const CHANNELS: usize = 2;
5732 let sources: &[(&str, &str, bool)] = &[6208 let sources: &[(&str, &str, bool)] = &[
5733- ("hein", "~/Downloads/reelm.mp3", false),6209+ (
6210+ "hein",
6211+ "~/Downloads/reelm.mp3",
6212+ false,
6213+ ),
5734 ("reell", "~/Music/reell.mp4", true),6214 ("reell", "~/Music/reell.mp4", true),
5735 ("reelo", "~/Music/reelo.mp3", true),6215 ("reelo", "~/Music/reelo.mp3", true),
5736 ];6216 ];
@@ -5781,7 +6261,10 @@ fn analysis_music_prob_separates_speech_from_music() {
5781 bw_hist[(d.analysis_bandwidth.clamp(0, 20)) as usize] += 1;6261 bw_hist[(d.analysis_bandwidth.clamp(0, 20)) as usize] += 1;
5782 }6262 }
5783 }6263 }
5784- assert!(valid * 10 > n * 9, "{tag}: analysis valid on only {valid}/{n} frames");6264+ assert!(
6265+ valid * 10 > n * 9,
6266+ "{tag}: analysis valid on only {valid}/{n} frames"
6267+ );
5785 let bw: Vec<String> = bw_hist6268 let bw: Vec<String> = bw_hist
5786 .iter()6269 .iter()
5787 .enumerate()6270 .enumerate()
@@ -5816,7 +6299,12 @@ fn analysis_music_prob_separates_speech_from_music() {
5816 let speech: Vec<_> = means.iter().filter(|m| !m.1).collect();6299 let speech: Vec<_> = means.iter().filter(|m| !m.1).collect();
5817 let music: Vec<_> = means.iter().filter(|m| m.1).collect();6300 let music: Vec<_> = means.iter().filter(|m| m.1).collect();
5818 for s in &speech {6301 for s in &speech {
5819- assert!(s.2 < 0.5, "{}: speech music_prob {:.3} should be < 0.5", s.0, s.2);6302+ assert!(
6303+ s.2 < 0.5,
6304+ "{}: speech music_prob {:.3} should be < 0.5",
6305+ s.0,
6306+ s.2
6307+ );
5820 for m in &music {6308 for m in &music {
5821 assert!(6309 assert!(
5822 m.2 - s.2 > 0.2,6310 m.2 - s.2 > 0.2,
@@ -5829,6 +6317,11 @@ fn analysis_music_prob_separates_speech_from_music() {
5829 }6317 }
5830 }6318 }
5831 for m in &music {6319 for m in &music {
5832- assert!(m.2 > 0.5, "{}: music music_prob {:.3} should be > 0.5", m.0, m.2);6320+ assert!(
6321+ m.2 > 0.5,
6322+ "{}: music music_prob {:.3} should be > 0.5",
6323+ m.0,
6324+ m.2
6325+ );
5833 }6326 }
5834 }6327 }
lanes/COMMON-20260901.mdmodified+7 -0
@@ -15,6 +15,13 @@ WORKING RULES (binding):
15 `systemd-run --user --scope -p MemoryMax=8G` and bound ffmpeg with `-t`.15 `systemd-run --user --scope -p MemoryMax=8G` and bound ffmpeg with `-t`.
16 - Test scope: `cargo test -p ec-av1 --lib` only (plus `cargo check -p ec-av1`). Never the16 - Test scope: `cargo test -p ec-av1 --lib` only (plus `cargo check -p ec-av1`). Never the
17 workspace suite. Set `EC_AV1_REQUIRE_AOMENC=1` so an absent oracle FAILS, never SKIPs.17 workspace suite. Set `EC_AV1_REQUIRE_AOMENC=1` so an absent oracle FAILS, never SKIPs.
18+- FIRST STEP of every lane, after `git worktree add`: `scripts/link-fixtures.sh`. The root
19+ `fixtures/` directory is gitignored (`.gitignore:2`), so a worktree does NOT get it and
20+ every fixture-backed gate (JVT/FLAC-xiph/RFC-6716 vectors, the ec-av1 pins) skips GREEN
21+ having tested nothing. The script symlinks the primary checkout's `fixtures/` in
22+ (`--check` for a preflight; it refuses loudly if the primary has none). Set
23+ `EC_REQUIRE_FIXTURES=1` in EVERY batch unit (with EC_AV1_REQUIRE_FFMPEG /
24+ EC_AV1_REQUIRE_AOMENC) so an absent fixture FAILS instead of skipping.
18 - Oracle: `~/.cache/aom-oracle/build/aomenc` and instrumented `aomdec` (scripts/build-aom-oracle.sh,25 - Oracle: `~/.cache/aom-oracle/build/aomenc` and instrumented `aomdec` (scripts/build-aom-oracle.sh,
19 scripts/instrument-aom-oracle.sh; rungs EC_TRACE=1 / EC_TRACE_COEFF=1 / EC_TRACE_MODE=1 /26 scripts/instrument-aom-oracle.sh; rungs EC_TRACE=1 / EC_TRACE_COEFF=1 / EC_TRACE_MODE=1 /
20 EC_AV1_PREFILT_DUMP). Ours: EC_TRACE_COEFF / EC_TRACE_MODE / EC_TRACE_MODE_STEP in decode.rs.27 EC_AV1_PREFILT_DUMP). Ours: EC_TRACE_COEFF / EC_TRACE_MODE / EC_TRACE_MODE_STEP in decode.rs.
lanes/av1skipfix.report.mdadded+140 -0
@@ -0,0 +1,140 @@
1+# lane-av1skipfix — convert skip-on-decode-error gates; audit fixture provenance
2+
3+Branch `lane-av1skipfix` off `a21f3680`. Tests only: no file under
4+`crates/ec-av1/src/decode.rs` was touched, and no decoder logic changed anywhere.
5+
6+## Defect 1 — four `..._decodes_pixel_exact` gates turned a decode error into a printed SKIP
7+
8+Pinned as a set in `refusal_inventory.rs` (`GATES_THAT_SKIP_ON_A_DECODE_ERROR`).
9+Each one ran a single recipe and, on `Err`, printed `SKIP <name>: {e}` and returned
10+green. Converted to the attempt-loop shape already used elsewhere in `stream.rs`:
11+sweep several recipes, count a named refusal per attempt (never swallow it), ALWAYS
12+pixel-compare an attempt that decoded, and hard-assert the feature counter on a
13+pixel-compared attempt. Exhausting every attempt is a hard failure, not a skip.
14+
15+| gate | counter | recipes | decoded+fired (green run) |
16+|---|---|---|---|
17+| `a_real_aomenc_filter_intra_stream_decodes_pixel_exact` | `filter_intra_hits` | 2 seeds × 3 cq | 2 |
18+| `a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact` | `deblock_hits` | 2 seeds × 4 cq | 2 |
19+| `a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact` | `deblock_hits` | 2 seeds × 4 cq | 2 |
20+| `a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact` | `cdef_idx_hits` | 8 × (size, cpu-used, crf) | 2 |
21+
22+All four run under `lock_gate_counters()` and report the three-bucket
23+`gate_buckets` summary, so the buckets sum to the attempts made.
24+
25+### Measurements (this box, 2026-09-29, base `a21f3680`)
26+
27+- **filter intra** — seed 42 cq 40 and seed 43 cq 40 read `use_filter_intra` 3× each,
28+ pixel-exact. seed 44 cq 45 and seed 45 cq 30 **decode without it** (delta 0), so the
29+ one fixed recipe was carrying the whole gate.
30+- **intra deblock** — cq 55/45/35/63 all decode pixel-exact with 48/64/64/64 deblock edges.
31+- **inter deblock** — cq 55/45/35/63 all decode 4 frames pixel-exact with
32+ 208/224/160/208 deblock edges.
33+- **CDEF** — the old recipe was a **single 64×64 frame**, which gives libaom's cdef
34+ search exactly one superblock, so it can never write `cdef_bits > 0` and the gate
35+ never read a `cdef_idx` at ANY crf / cpu-used (0, 2, 4, 8 × crf 10–60, sizes
36+ 64×64…256×128: delta 0 everywhere). `EC_AV1_CDEF_DBG` shows `apply_cdef` *does* filter
37+ there (nonzero `t`, `pri=11`/`pri=2`), but the gate's own firing proof is
38+ `cdef_idx_hits`, so its premise was unfalsifiable on the recipe it shipped. The
39+ recipe list is now multi-SB and multi-frame: 128×64/128×128 at 24 frames read
40+ 2–8 `cdef_idx` and are pixel-exact against ffmpeg.
41+
42+No recipe in any of the four families failed to decode for a capability reason, so
43+**no entry had to be kept**; the inventory list is now empty and stays an exact pin.
44+
45+### Red-before (each mutation reverted after the run)
46+
47+| mutation | result |
48+|---|---|
49+| `--enable-filter-intra=0` in the filter-intra recipe | `none of 6 attempts decoded a stream that read use_filter_intra` — FAILED |
50+| `--loopfilter-control=0` in the intra-deblock recipe | `buckets counted-exact=0 uncounted-exact=8`; `none of 8 attempts … with a deblocking edge` — FAILED |
51+| `--loopfilter-control=0` in the inter-deblock recipe | same, FAILED |
52+| original 64×64/1-frame CDEF recipe restored | `buckets counted-exact=0 uncounted-exact=8`; `no attempt of 8 read a cdef_idx literal` — FAILED |
53+| one `SKIP <name>: {e}` arm re-added to a converted gate | `gates_that_swallow_a_decode_error_are_declared` FAILED, naming that gate |
54+
55+Note the mutation runs report `uncounted-exact=8`: the eight attempts still ran real
56+pixel compares, so the compare is load-bearing and the counter assert is what bites.
57+
58+## Defect 2 — `a_real_aomenc_lossless_444_key_frame_decodes_sample_exact` reported green on a missing pin
59+
60+Its pinned fixture `fixtures/ll444-lossless-key.obu` does not exist: not in git, not
61+in the root `fixtures/` directory on this box, and no script under `scripts/` produces
62+it. The `Err` arm was a bare SKIP, so the test finished in 0.05 s (its siblings take
63+seconds — it had decoded nothing) and the suite reported green.
64+
65+The root `fixtures/` directory is listed in `.gitignore:2`, so a pin that lands there
66+can never be committed and a fresh clone can never have it; every `~/.cache/wt/*`
67+worktree lacks it for the same reason. Committing a fixture is therefore not available
68+as a fix, and the gate is not deleted. The arm keeps its skip but `EC_AV1_REQUIRE_AOMENC=1`
69+now turns it into a hard failure naming the missing path, the exact regeneration recipe
70+and the `EC_AV1_PIN_DIR` override; the skip line itself says the gate decoded nothing
71+and proves nothing. Smallest possible hunk: the arm only, no gate body below it.
72+
73+## Fixture-generator audit (this lane's manifest)
74+
75+| referenced path | on disk | generator |
76+|---|---|---|
77+| `fixtures/video/*.mp4/.mkv` | present | `scripts/gen-fixtures.sh` (deterministic ffmpeg) — OK |
78+| `crates/ec-av1/fixtures/*.obu` (48, committed) | present | **NONE** — provenance lives only in gate doc comments / lane reports |
79+| root `fixtures/*.obu` pins: `golden6-mismatch`, `golden7-forwarding-mismatch`, `lr-sgr-r7`, `golden4-pin` | present | **NONE**, and gitignored so not committable |
80+| root `fixtures/*.obu` pins: `ll444-lossless-key`, `golden3-pin`, `sbpart-pin` | **missing on this box** | **NONE** (`golden3-pin` and `sbpart-pin` gates are `#[ignore]`d — the honest shape) |
81+
82+So of the ~55 distinct AV1 fixtures these tests name, **every `.obu`/`.av1` pin has no
83+generator script**; only the container fixtures do. The pin directory is also split
84+across two homes (`crates/ec-av1/fixtures/`, committed, 48 files) and the root
85+`fixtures/`, gitignored — and `pin_dir()` resolves to the gitignored one, so any pin
86+written there is un-reproducible on a fresh clone by construction.
87+
88+## Defect 3 — the root cause: a worktree has no `fixtures/` at all
89+
90+`fixtures/` is `.gitignore:2`, so `git worktree add` hands every lane worktree a tree
91+without it. Not one gate in ec-av1/ec-h264/ec-flac/ec-opus checks that before skipping,
92+so a worktree run measures nothing while looking clean. Fixed on both halves:
93+
94+- **(b) root cause** — `scripts/link-fixtures.sh` resolves the primary checkout through
95+ `git rev-parse --git-common-dir` (works from any linked worktree), symlinks its
96+ `fixtures/` in, no-ops with a message when the directory already exists, and refuses
97+ loudly (exit 2) when the primary has none. `--check` is the preflight. Verified in a
98+ synthetic repo+worktree: links, is idempotent, and refuses with the generator names.
99+ Documented in `lanes/COMMON-20260901.md` beside the batch env line.
100+- **(a) the assert** — `EC_REQUIRE_FIXTURES=1` (default off, set in every batch unit by
101+ the parent) turns each missing-fixture skip into a hard failure naming the path, the
102+ generator when one exists, and `scripts/link-fixtures.sh` when the real cause is the
103+ missing root directory.
104+
105+### Per-crate assert sites
106+
107+| file:line | shape before | shape after | red proof | green proof |
108+|---|---|---|---|---|
109+| `crates/ec-h264/tests/conformance.rs:299` (`jvt_cavlc_first_idr_bit_exact`) | `!base.is_dir()` → `SKIP: … missing — run scripts/fetch-vectors.sh` | `require_fixtures(&base, "the JVT conformance vectors", "scripts/fetch-vectors.sh")` | `EC_REQUIRE_FIXTURES=1`, `fixtures/` unlinked → panics "the JVT conformance vectors missing at …/vectors/h264-jvt — this gate would prove nothing" | linked: 1 passed (1.58s) |
110+| `crates/ec-h264/tests/conformance.rs:406` (`steady_state_decode_loop_zero_alloc`) | `!base.is_dir()` → `SKIP: fixtures missing` | same helper | same env/path | linked: 1 passed (0.73s) |
111+| `crates/ec-h264/tests/conformance.rs:490` (`ns_per_macroblock_measurement`) | `!base.is_dir()` → `SKIP: fixtures missing` | same helper | same env/path | linked: 1 passed (9.94s) |
112+| `crates/ec-h264/tests/conformance.rs:574` (`corrupt_streams_never_panic`) | `!base.is_dir()` → `SKIP: fixtures missing` | same helper | same env/path | linked: 1 passed (20.85s) |
113+| `crates/ec-h264/tests/conformance.rs:1080` (`jvt_full_sequence_bit_exact`) | `!base.is_dir()` → `SKIP: … missing` | same helper | same env/path | linked: 1 passed (5.59s) |
114+| `crates/ec-h264/tests/conformance.rs:2323` (`h264_seek_matches_linear_open_gop`) | `!src.is_file()` → `SKIP: no fixtures/video/h264-open-gop.mp4 (run scripts/gen-fixtures.sh)` | same helper, generator `scripts/gen-fixtures.sh` | `EC_REQUIRE_FIXTURES=1` → panics "the open-GOP fixture missing at …/video/h264-open-gop.mp4" | linked: 1 passed (0.75s) |
115+| `crates/ec-flac/tests/xiph_vectors.rs:24` (`corpus()`, all 4 gates) | `read_dir().ok()?` → `None` → each gate `eprintln!("skipped: …")` + return | assert in `corpus()` itself — the one place that knows the path — so 4 gates, 1 hunk | `EC_REQUIRE_FIXTURES=1` → panics "the FLAC xiph subset corpus is missing at …/subset" | linked: 4 passed (32.0s) |
116+| `crates/ec-opus/tests/conformance.rs:425` (`rfc6716_test_vectors`) | `!path.exists()` → `eprintln!("{name}: missing, skipped")` + `continue` (no env at all) | per-vector assert naming path + `scripts/link-fixtures.sh` + `scripts/fetch-vectors.sh` | `EC_REQUIRE_FIXTURES=1` → panics "RFC 6716 test vector testvector01 missing at …/opus_testvectors/testvector01.bit" | linked: 1 passed (179.2s) |
117+| `crates/ec-av1/src/stream.rs:6500` (`a_real_aomenc_lossless_444_key_frame_decodes_sample_exact`) | `Err` → `SKIP … -- regenerate with …` (gate ran 0.05s, decoded nothing) | assert naming path + `scripts/link-fixtures.sh` + regeneration recipe + `EC_AV1_PIN_DIR`; fires on `EC_REQUIRE_FIXTURES` **or** `EC_AV1_REQUIRE_AOMENC` | `EC_REQUIRE_FIXTURES=1` → panics "the pinned 4:4:4 lossless key frame is missing at …/ll444-lossless-key.obu" | default: SKIP with the recipe; both envs: FAILED |
118+
119+Deliberately **not** converted: the `if path.exists()` arms in ec-opus at 740/1852
120+(optional-input blocks inside tests that assert nothing on them) and the
121+`~/Music/…` skips at 4985/5378/5607 (personal media, not a fixture manifest — failing
122+those on every box would be its own lie).
123+
124+### Provenance hand-off
125+
126+The enumeration above is Agent18-2's input for `scripts/fixture-library.tsv`; this lane did
127+not build the manifest. What the assert messages now guarantee is that every gate that
128+reads a fixture names the path it wanted, the generator when one exists, and
129+`scripts/link-fixtures.sh` when the cause is the missing root directory.
130+
131+## Commits
132+
133+- `cd81750b` — stream: convert the four skip-on-decode-error gates to attempt loops
134+- `0b92c6da` — refusal_inventory: empty GATES_THAT_SKIP_ON_A_DECODE_ERROR
135+- `3c302798` — stream: a_real_aomenc_lossless_444_key_frame stops reporting green on a missing pin
136+- `62c04b70` — scripts: link-fixtures.sh — give a worktree the gitignored root fixtures/
137+- `423ce6be` — stream: the 444 pin arm also honours the repo-wide EC_REQUIRE_FIXTURES
138+- `ae94ee6a` — ec-h264: a missing conformance vector FAILS under EC_REQUIRE_FIXTURES
139+- `d853d31a` — ec-flac: a missing xiph corpus FAILS under EC_REQUIRE_FIXTURES
140+- `3f94c60d` — ec-opus: a missing RFC 6716 vector FAILS under EC_REQUIRE_FIXTURES
scripts/link-fixtures.shadded+74 -0
@@ -0,0 +1,74 @@
1+#!/usr/bin/env bash
2+# link-fixtures.sh — give this worktree the primary checkout's root `fixtures/`.
3+#
4+# The root `fixtures/` directory is listed in `.gitignore` (line 2) and is NOT
5+# committed, so `git worktree add` gives every lane worktree a tree WITHOUT it.
6+# Every test that reads a fixture through `<crate>/../../fixtures` then reports
7+# green having checked nothing: this is the "gate skips on its own failure"
8+# class, and it has already cost false verdicts (lane-av1skipfix 2026-09-29).
9+#
10+# This script makes a SYMLINK, never a copy: the fixtures are large and the
11+# lane worktrees exist to run tests, not to duplicate data.
12+#
13+# Usage: scripts/link-fixtures.sh [--check]
14+# (no args) create the symlink, or no-op if fixtures/ is already there
15+# --check report what would happen and exit non-zero if the fixtures are
16+# absent; for a batch preflight
17+#
18+# Idempotent and safe to run from any worktree of this repo.
19+
20+set -uo pipefail
21+
22+ROOT=$(cd -- "$(dirname -- "$0")/.." && pwd)
23+cd "$ROOT" || exit 2
24+
25+# `--git-common-dir` resolves to the PRIMARY checkout's .git from any linked
26+# worktree (a linked worktree's own .git is a FILE, not the common dir), so
27+# this works identically in the primary tree and in ~/.cache/wt/<lane>.
28+COMMON=$(git rev-parse --git-common-dir 2>/dev/null) || {
29+ echo "link-fixtures: not inside a git repository ($ROOT)" >&2
30+ exit 2
31+}
32+COMMON=$(cd -- "$COMMON" && pwd) || exit 2
33+PRIMARY=$(dirname -- "$COMMON")
34+SOURCE="$PRIMARY/fixtures"
35+
36+CHECK=0
37+[ "${1:-}" = "--check" ] && CHECK=1
38+
39+report() { # report <state> <detail>
40+ echo "link-fixtures: $1 — $2"
41+ echo " primary checkout: $PRIMARY"
42+ echo " this tree: $ROOT"
43+}
44+
45+if [ -e "$ROOT/fixtures" ] || [ -L "$ROOT/fixtures" ]; then
46+ if [ -L "$ROOT/fixtures" ] && [ -d "$ROOT/fixtures" ]; then
47+ report "already linked" "$ROOT/fixtures -> $(readlink -f "$ROOT/fixtures")"
48+ exit 0
49+ fi
50+ if [ -d "$ROOT/fixtures" ]; then
51+ report "already a real directory" "nothing to do ($ROOT/fixtures)"
52+ exit 0
53+ fi
54+ report "REFUSING" "$ROOT/fixtures exists but is neither a directory nor a live symlink; remove it by hand" >&2
55+ exit 2
56+fi
57+
58+if [ ! -d "$SOURCE" ]; then
59+ report "REFUSING" "the primary checkout has no fixtures/ at $SOURCE" >&2
60+ echo " It is gitignored, so it exists only where someone generated it:" >&2
61+ echo " scripts/gen-fixtures.sh (containers) and scripts/fetch-vectors.sh" >&2
62+ echo " (conformance vectors). Run one there, then re-run this script." >&2
63+ exit 2
64+fi
65+
66+if [ "$CHECK" = 1 ]; then
67+ report "would link" "$ROOT/fixtures -> $SOURCE"
68+ exit 1
69+fi
70+
71+ln -s "$SOURCE" "$ROOT/fixtures" || exit 2
72+report "linked" "$ROOT/fixtures -> $SOURCE"
73+echo " Fixtures are now reachable; run your crate's gates with"
74+echo " EC_REQUIRE_FIXTURES=1 so an absent fixture FAILS instead of skipping."