forge
Explore
Log in

Don't you dare go Hollow

Commits

Commits on 6c06f1018a6909783f7413dc0c223eb7552f22cb

2026-08-20

fix(opus-enc): look_ahead uses the same mono/20ms predicate dispatch doesAhmet Kaan Gümüş · cbcbe53
fix(opus-enc): look_ahead uses the same mono/20ms predicate dispatch does

look_ahead() consulted only wants_silk() (bitrate/application), not the
frame-size-and-channel check silk_choice()/hybrid_choice() apply before
encode_toc_and_payload actually picks a layer. A Voip/low-bitrate encoder
fed frame sizes other than 20 ms coded CELT but reported SILK's shorter
delay, throwing off the Ogg pre-skip by the difference. look_ahead now
takes the frame size and runs it through silk_choice, matching dispatch
exactly.

Also gives zero_stuff_mono a reusable Encoder-owned scratch buffer instead
of a Vec allocated per SILK/Hybrid frame — the zero-alloc steady-state
claim previously only held on the CELT path.
feat(opus-hybrid): mono 20 ms SWB/FB hybrid packets (SILK 16 kHz + CELT from band 17)Ahmet Kaan Gümüş · a6d0278
feat(opus-hybrid): mono 20 ms SWB/FB hybrid packets (SILK 16 kHz + CELT from band 17)

CeltEncoder::encode takes a start band and mirrors the decoder's start_band
paths (no silence flag mid-stream, no postfilter bit, zeroed x below start,
cleared energy history outside the coded span). SilkEncoder::encode_hybrid
writes the chosen frame into a shared range coder and replay() advances the
mirror from the finished payload. Encoder: Voip 20-40 kbps mono 20 ms ->
config 13/15, reference's SILK rate share, no-redundancy flag under the
decoder's exact presence rule, SILK input delayed 70 samples so both layers
land at CELT's 120 (click-measured LB +121 / HB +120). Decoder gains a
doc(hidden) per-layer mute for the tests.
feat(opus-silk): route Encoder's target bitrate into SILK's rate controlAhmet Kaan Gümüş · c54a10c
feat(opus-silk): route Encoder's target bitrate into SILK's rate control

Merge opus-nsq (NSQ + SilkEncoder::set_bitrate rate control) into
opus-silk. encoder.rs::encode_toc_and_payload now calls
enc.set_bitrate(self.bitrate) every SILK frame, so the public
Encoder's set_bitrate reaches the reservoir-based rate loop instead
of leaving SILK to code at unit excitation RMS. The NB/<=10kbps>WB
threshold in wants_silk/silk_choice is unaffected.

CBR-exact vs VBR-± distinction: SILK isn't budgeted against a byte
cap yet (documented at encode_toc_and_payload's doc comment, D2b) --
only the existing reservoir scheme (soft-tracks the target, same as
VBR) is wired; the Encoder's vbr flag doesn't yet branch SILK's mode.

oracle_decodes_our_packets_across_the_rate_table's SILK corner
(8/12/16 kbps) previously ran SILK unconstrained (set_bitrate was
never called from the Encoder path), so its 0.95 floor no longer
holds once the target is honestly rate-limited; lowered to 0.85,
matching the already-established floors in silk_rate_control_tracks_target.

Adds silk_packets_track_encoder_bitrate: drives the public Encoder
(Voip, mono, 8/12/16 kbps) and checks measured kbps within +-20%.

Fixes a merge fallout in oracle_decode (opus_head/write_ogg_opus
call sites diverged pre-skip signatures between the two branches).
fix(ec-probe): rescale a stream's initial_padding into its own time_base before subtracting it from durationAhmet Kaan Gümüş · 28b9982
fix(ec-probe): rescale a stream's initial_padding into its own time_base before subtracting it from duration

Reader::duration() subtracted `initial_padding` (a sample count) straight
off `duration` (time_base ticks). The two units only coincide when the
time base is 1/sample_rate; a Matroska file's TimestampScale usually is
not (commonly milliseconds), so a stream's CodecDelay-derived padding —
1024 samples for AAC — was read as 1024 whole ticks and lopped a third
off the stated length (aac-mka-stereo-48000.mka: 3.021s -> 1.997s).

Root cause: crates/ec-probe/src/lib.rs Reader::duration() (StreamInfo's
own doc comment at crates/ec-core/src/registry.rs:245-249 already says
initial_padding is samples, not time_base ticks). Fixed by rescaling
initial_padding through TimeBase::from_rate(sample_rate) into the
stream's time_base before subtracting. Lacing/BlockGroup handling in
ec-matroska was already correct — not the bug.
doc+test(opus-rs shim): SILK now reachable through the existing Application/bitrate surfaceAhmet Kaan Gümüş · af6881e
doc+test(opus-rs shim): SILK now reachable through the existing Application/bitrate surface

ec-opus's Encoder now dispatches SILK for Voip under 20 kbps mono
20 ms frames, and this shim's OpusEncoder::new/bitrate_bps already
carry both — no new API needed. Correct the stale "CELT-only" doc
claim and add a test proving the shim's own encode() call produces a
SILK TOC config (0..=11) under those conditions.
feat(opus): SILK mode selection in EncoderAhmet Kaan Gümüş · 7f710e5
feat(opus): SILK mode selection in Encoder

Encoder dispatches SILK per frame (mono, 960-sample frames, Voip
application under 20 kbps) via set_mode/wants_silk/silk_choice, with a
click-measured look_ahead split per bandwidth (NB 58, WB 50 samples at
48 kHz) and a zero-alloc scratch buffer for the SILK payload so the
steady-state encode loop stays allocation-free.
chore: untrack the fixtures symlink that 6dc81bf added by mistakeAhmet Kaan Gümüş · 648e800
chore: untrack the fixtures symlink that 6dc81bf added by mistake

fixtures/ is a generated, gitignored directory (scripts/gen-*.sh,
fetch-vectors.sh, scan-real-library.sh). A builder's worktree symlink
got committed in 6dc81bf; merging it into main replaced the real
directory with a self-referential link and every fixture-gated test
silently skipped. Untracked again; the directory is regenerated from
the scripts.
fix(truehd-sync): refuse a 4th substream at parse time, not afterAhmet Kaan Gümüş · 969dce1
fix(truehd-sync): refuse a 4th substream at parse time, not after

The >=4 substream guard sat at the top of the directory loop, checked
against the count from the previous iteration, so it only fired on a
5th entry. A well-formed 4-entry directory (the real object-audio
shape) whose last pointer landed on the AU end broke out of the loop
first, parsing Ok(4); only channel_layout() later caught it, and as a
generic Corrupt rather than naming the 4th substream as Unsupported.

Move the check to after the push, so any 4th entry is refused by name
regardless of whether it also terminates the directory.
feat(opus-silk): noise-shaping quantiser, gain-offset rate control, LTP scale by gainAhmet Kaan Gümüş · ba4dea4
feat(opus-silk): noise-shaping quantiser, gain-offset rate control, LTP scale by gain

Closed-loop NSQ: output error fed back through A(z/0.96)/A(z/0.85)
shaping with harmonic comb and voiced tilt, dead-zone pulse decision,
quant_offset_type by signal type/energy, LTP scale index from the
open-loop LTP gain. set_bitrate(bps): gain-index offset loop (<=3
trials on the range coder's own size) with a 4-frame reservoir; lands
8/12/16/24 kbps within +13%.
docs(ac3-enc): correct three stale claims about the encoderAhmet Kaan Gümüş · f8b6839
docs(ac3-enc): correct three stale claims about the encoder

Module doc still called the encoder a "fixed-allocation skeleton" with a
"constant exponent strategy" -- it now runs transient-driven block
switching, a D15/D25/D45/reuse exponent planner and a binary-searched
rate loop. plan()'s docstring said block-switched blocks send D15; the
code sends D25 there (D15 is LFE-only) because the short transform's
interleaved halves make D15 too expensive per block. Replaced both with
what the code does and the fill ratios actually measured (roughly
93-99.6%, not a flat >97%).
feat(ac3-enc-shim): expose Ac3Encoder on the family's export-facing shapeAhmet Kaan Gümüş · 1466a62
feat(ac3-enc-shim): expose Ac3Encoder on the family's export-facing shape

Ac3Encoder had zero callers outside crates/ec-ac3 -- the shim only wrapped
the decoder. Add new/push_pcm_f32/finish/next_packet/encoder_delay at the
same shape as rusty_aac's AacEncoder, the pattern an export path already
drives, plus a round trip test (encode 1s stereo, decode through this
shim's own decoder, corr >=0.99 past encoder_delay()).
feat(ec-probe,ec-matroska): register the TrueHD decoder in the unified readerAhmet Kaan Gümüş · 4026107
feat(ec-probe,ec-matroska): register the TrueHD decoder in the unified reader

ec-probe's AudioDecoder now carries a TrueHd arm (mirrors Ac3: send_packet/
receive_frame/flush/reset through the generic Decoder trait), so a TrueHD
track decodes through Reader/AudioDecoder like any other codec instead of
only being named in Reader::unsupported. ec-matroska's muxer writes
CodecId::TrueHd back out as A_TRUEHD (demux already read it in); the
symphonia shim needed no change since it wraps ec_probe::AudioDecoder
generically. Library test updated from "TrueHD is listed unsupported" to
"the TrueHD track in his 7.1 remux decodes, 8ch/48kHz, alongside the AC-3
track"; added a demux->mux->demux codec-id round-trip test in ec-matroska.
fix(opus-silk): LPC->NLSF polynomial sign, closed-loop LTP pick, conformance round tripAhmet Kaan Gümüş · 68c7064
fix(opus-silk): LPC->NLSF polynomial sign, closed-loop LTP pick, conformance round trip

lpc_to_nlsf evaluated A(z) = 1 + sum a z^-k for a predictor-convention
lpc (x ~= sum a x[n-k-1]); the decoder's nlsf2a thus got the anti-predictor
and every synthesised frame rang. LTP codebook vectors are now picked per
subframe against the reconstructed (quantised) history so pitch-loop
feedback of quantisation noise cannot run away; the reconstruction keeps
LTP prediction in sample units (g*exc + pred). silk_mono_nb_wb_roundtrip:
synthetic NB 0.975 / WB 0.981, wav16-mono NB 0.9999 / WB 0.9996, range
state equal every packet, ffmpeg decodes the Ogg clean.
feat(truehd): lossless substream decode — 2/6/8-ch presentations bit-exact, 16-ch object substream refusedAhmet Kaan Gümüş · 2f6b7e8
feat(truehd): lossless substream decode — 2/6/8-ch presentations bit-exact, 16-ch object substream refused

Decodes: restart headers (14-bit sync, CRC-8 poly 0x1D verified), decoding
parameters (presence flags, block size, primitive matrices, output shift,
quant step, FIR≤8/IIR≤4 with carried history, Huffman offset/codebook/LSBs),
residuals through the three codebooks (read off an external encoder's mono
output, then oracle-checked), per-substream parity and the lossless-check
byte, rematrixing with both noise generators (23-bit LFSR 2-channel noise for
0x31EA; 256-entry dither table for 0x31EB, every entry solved by constraint
intersection against the external decoder on the real 7.1 track), output
shift, interleaved S32 left-justified 24-bit. TrueHD 7.1 (assignment 0x4F)
lands on FL FR FC LFE BL BR SL SR via [0,1,2,3,6,7,4,5]. MLP major sync's
rate-code offset fixed (data[9], not data[8]).

Refused by name (Error::Unsupported): the 4th / 16-channel object substream,
any substream with more than 8 matrix channels, 8-ch presentations whose
channel assignment is not the standard 7.1 mask, reserved rate codes.
Not validated: the per-substream CRC-8 check byte (generator/span unknown;
parsed and skipped, see corner-cut in decode.rs).

Oracle (tests/oracle.rs, skipped without ffmpeg / the remux): first 60 s of
the real 7.1 remux 23 040 000 / 23 040 000 samples exact, 0 lossless-check,
0 parity, 0 restart-CRC, 0 length failures over 72 000 access units;
externally encoded MLP and TrueHD mono/stereo/5.1 streams all bit-exact.
feat(ac3-enc): block switching, D15/D25/D45/reuse exponent planning and a binary-search rate loopAhmet Kaan Gümüş · 18654e6
feat(ac3-enc): block switching, D15/D25/D45/reuse exponent planning and a binary-search rate loop

Transient detector picks the short transform per block (forward = transpose
of the decoder's short inverse, TDAC-probed at 1/128); exponents are planned
per run of blocks with the decoded set driving allocation; csnroffst then
fsnroffst are binary-searched so frames fill >97% of their size; chbwcod
from the per-channel bit rate; encoder_delay() = 256 and finish() flushes
the overlap tail. Full wav16 fixture matrix round-trips at corr 1.000
through our decoder and the oracle.
fix(alac-enc): wrap predictor residuals to chan_bits the way the decoder doesAhmet Kaan Gümüş · 70bf744
fix(alac-enc): wrap predictor residuals to chan_bits the way the decoder does

A residual of two in-range samples can need one bit more than the samples
(24-bit ramp wrap-around, full-scale alternating at 16 coded bits after a
byte shift); the Golomb escape carries only chan_bits of it, so the value
truncated on the wire and the decoder's clamp() reconstructed the wrong
sample, or lost sync entirely. analyze() now wraps every residual to
chan_bits before zigzag and before the sign-adapt step, matching
decode.rs predict(). Guard AlacEncoder::new to the 16/24-bit depths
actually tested; add ramp/alternating/fuzz round-trip tests.
fix(alac): read a Golomb escape's raw value past the 32-bit prefix peek; drop the mode-1 emission knobAhmet Kaan Gümüş · b8b47ce
fix(alac): read a Golomb escape's raw value past the 32-bit prefix peek; drop the mode-1 emission knob

The adaptive-Golomb escape (9 ones + a raw maxbits value) was decoded from
a single 32-bit peek, so any element whose coded width is 24 or more bits
(24-bit unshifted mono = 24, stereo = 25) lost the raw value's low bit(s)
and desynced the rest of the channel. A smooth 24-bit tone is the first
content whose opening residuals are large enough to escape at that width;
random data goes out as a whole-frame raw escape and 16-bit-derived
24-bit audio codes 16 bits after bytes_shifted, so neither ever hit it.

The encoder's mode-1 (double-difference) path and its EC_ALAC_MODE1 env
knob are gone: no real-world decoder accepts prediction type 1, so a knob
producing such files was a trap. The decoder keeps reading mode 1.
EC_ALAC_NO_SHIFT becomes a hidden AlacEncoder::set_byte_shift setter.
feat(opus-silk): SILK payload writer, mono 20 ms NB/WB, decoder-mirrored stateAhmet Kaan Gümüş · 12e4d27
feat(opus-silk): SILK payload writer, mono 20 ms NB/WB, decoder-mirrored state

Writes every symbol in silk::decode()'s order (VAD/LBRR flags, frame type,
gains, NLSF stage 1/2 + interp, pitch lag/contour + LTP codebook + scale,
seed, rate level, shell-coded pulses with LSB escape, signs) and quantises
the excitation open-loop against the decoder's own reconstruction, with
the encoder replaying each packet through a SilkDecoder so its LTP history
is the real one. Unit test round-trips NB/WB through the decoder including
the LSB escape, range state equal.
feat(ac3-enc): fixed-allocation AC-3 encoder skeleton that round-trips at corr 0.998Ahmet Kaan Gümüş · f663ba5
feat(ac3-enc): fixed-allocation AC-3 encoder skeleton that round-trips at corr 0.998

Adds Ac3Encoder: syncinfo/bsi/6 audblk writer mirroring the parser, D15
exponents on block 0 then reuse, constant bit allocation parameters, a
csnroffst step-down to fit the frame, CRC1/CRC2 patched post-write, MDCT
via ec_dsp::Mdct. Three defects found on the way to a clean round trip:

- forward MDCT gain: ec_dsp's raw sum needs A/52's -2/N (was 0.5, i.e.
  -256x too large, so every loud bin hit exponent 0 and clipped) — pinned
  by a TDAC unit test against transform.rs's IMDCT, both for ec_dsp and an
  O(N^2) direct form of the §7.9.4 formula (worst error < 1e-4)
- grouped mantissas (bap 1/2/4): the decoder reads the group code at the
  group's FIRST member, so the writer must emit it there via lookahead,
  not when the group fills
- exponent envelope: the ±2/bin group coding is fit by a backward+forward
  min-pass that only ever lowers exponents, instead of a one-directional
  walk that raised them on the rising edge of a peak and clipped it

encode_matrix: 1/2/6 ch at 48 kHz and 2 ch at 44.1 kHz decode via
Ac3Decoder at corr >= 0.95; the external oracle accepts the frames with no
error/invalid/crc lines, both stereo channels at corr >= 0.95.
feat(alac-enc): implement bytes_shifted split and mode-1 double-differenceAhmet Kaan Gümüş · d92d8b1
feat(alac-enc): implement bytes_shifted split and mode-1 double-difference

Two documented corner-cuts closed: 24-bit bytes_shifted (0/1, cost-chosen
per element via the existing CostSink) and the mode-1 double-difference
predictor pass (per-channel cost-chosen against mode 0).

Mode 1 is real but gated off by default (EC_ALAC_MODE1 env knob): writing
it broke this crate's own ffmpeg-oracle test with "unknown prediction
type: 1" — real-world ALAC decoders reject any prediction type but 0, even
though this crate's own decode.rs (independently written from the format
description) parses and reconstructs it correctly. Kept selectable for a
dedicated test and any stream known never to cross a third-party decoder.

Also discovered (not fixed, out of scope): a pre-existing bug corrupts
correlated 24-bit content's round trip independent of this change
(reproduces with bytes_shifted forced off too) — logged to the ledger.
feat(opus-silk): SILK encoder analysis front endAhmet Kaan Gümüş · 79db13a
feat(opus-silk): SILK encoder analysis front end

Adds silk_enc.rs: 48k->8/12/16k FIR decimator, simplified VAD, LPC
analysis with unit-circle P/Q NLSF conversion, NLSF VQ search against
the decoder codebooks, pitch estimation and gain quantisation. Decoder
helpers made pub(crate) for reuse; no decoder logic changes.
Merge branch 'hw-10bit'Ahmet Kaan Gümüş · 888f8b1Browse files
feat(truehd): new ec-truehd crate — access-unit framing and major syncAhmet Kaan Gümüş · f77ac31
feat(truehd): new ec-truehd crate — access-unit framing and major sync

frame_length, major sync detection (format id + sample rate) and the
per-substream directory, all calibrated bit-for-bit against a real 7.1
Blu-ray remux (AU count matches ffprobe exactly: 1,270,169). Substream
decode itself is stubbed as Unsupported, named for H2; the 4th
(object/16-ch) substream is out of scope and refused by name.
feat(alac-enc): mono/stereo ALAC encoder (cookie/escape frames + adaptive-Golomb LPC compression)Ahmet Kaan Gümüş · 98a0f6f
feat(alac-enc): mono/stereo ALAC encoder (cookie/escape frames + adaptive-Golomb LPC compression)

Mirrors decode.rs's element walk and Rice/predictor state machine exactly
(same constants, same mean/zero-run adaptation) so encode_frame's output
decodes bit-exact through the existing AlacDecoder. Per-element it picks
the smaller of raw escape vs compressed, and for stereo the smaller of
direct L/R vs a mix_bits=1/mix_res=1 mid-side transform, searching filter
orders {0,4,8,12,16,31} with an always-zero-seeded sign-adapting predictor
(no Levinson-Durbin design step needed since decode's adaptation is
itself the filter).

Corner-cuts (documented in encode.rs): bytes_shifted always 0 (no 24-bit
low-byte split — correctness unaffected, only 24-bit ratio); predictor
mode always 0 (skips the mode!=0 double-difference-pass variant).
feat(hw): expose bit_depth on I420_16 and pin 10-bit readbackAhmet Kaan Gümüş · 54b87cd
feat(hw): expose bit_depth on I420_16 and pin 10-bit readback

I420_16 is the lossless P010 readback, but the value carried nothing to
say so: a 10-bit consumer had only the method name to tell it apart from
the truncating to_i420 path. It now carries bit_depth (always 10),
matching Frame's field.

Adds a unit test that uploads a synthetic P010 surface whose samples
(512, 513, 1023) alias under 8-bit truncation and asserts to_i420_16
preserves them exactly while to_i420 yields the >> 2 values. The crate
doc now states that 10-bit consumers must call to_i420_16.
fix(aac-sbr-ogg): flush the terminal Vorbis block through to Ogg's granule-stated endAhmet Kaan Gümüş · b966d5e
fix(aac-sbr-ogg): flush the terminal Vorbis block through to Ogg's granule-stated end

EOS was never signalled through ec-probe/the symphonia shim, so the last
Vorbis block's un-overlapped tail (and any un-overlapped audio still sitting
in the last decoded packet) never reached the caller: the reader now hands
every audio track one synthetic, empty terminal packet once the container
itself is exhausted, and AudioDecoder::flush() is what answers it.

Trimming to the container's own granule only ever trusts two points: the
very first packet's granule (a real front pre-roll, if the format has one)
and the last one, applied once at flush -- an interior page's granule marks
where the packet finishing on that page ends, not a ceiling every later
page's cumulative output must stay under, so it is never used as one.
Vorbis's last decoded packet is held back one call rather than handed out
immediately, so that final trim can still reach into it.
Merge branch 'sbr-limiter'Ahmet Kaan Gümüş · 73af0e7Browse files
diag+fix(aac-sbr): per-limiter-band LIMDUMP audit + spec-correct Yule-Walker AR(2)Ahmet Kaan Gümüş · 190e8e3
diag+fix(aac-sbr): per-limiter-band LIMDUMP audit + spec-correct Yule-Walker AR(2)

Round-57 audit (ISO/IEC 14496-3 4.6.18.7.5/.7.6), heaac_48000_64k.m4a:

Added EC_AAC_SBR_CELLDUMP-gated per-limiter-band trace (sbr_env.rs `adjust`):
one LIMDUMP line per (envelope, limiter band j) with the exact aggregate
quantities the spec's two equations operate on -- E_orig_mapped[j],
E_curr[j], G_max[j]=limGain*sqrt(ratio), capped_cells/total, E_actual[j],
G_boost[j]. Confirms the ledger's task-3 suspect directly: limiter band
j=1 ([42,59), the patch-width-1 cell's band) has E_curr inflated to
1e10-1e11 against an E_orig_mapped of 1e4-1e6 nearly every frame (not
just the t=18s/24s cliff window) -- capped_cells stays 5/6 and G_boost
pegs at BOOST_MAX (1.584893) almost continuously, meaning that band
structurally never reaches its transmitted target by ~3-10dB. One
outlier cell's astronomically large `cur` poisons the AGGREGATE cap for
every other cell sharing its limiter band (spec-correct aggregate
behavior, applied to a defective per-cell energy estimate).

Root cause traced to `lpc2` (sbr_hf.rs): it solved an unwindowed
covariance-method normal-equation system for the AR(2) whitening/
resynthesis filter, which -- unlike the spec's Levinson-Durbin/
autocorrelation method -- carries no built-in BIBO-stability guarantee.
Replaced it with the Yule-Walker/autocorrelation-method solve (Hermitian
Toeplitz R, always PSD, so the resulting AR(2) poles are unconditionally
inside/on the unit circle by construction) -- this is the exact upgrade
path the module's own `stabilize()` doc comment already named.
`sbr_hf::tests::lpc_recovers_the_poles_of_a_synthetic_ar2_process`'s
tolerance widened 0.05->0.2 to match the (expected, smaller) finite-
window estimation bias this method trades for the stability guarantee;
all sbr_hf/sbr_env lib tests pass.

Measured effect: E_curr for the poisoned limiter band did NOT drop by
orders of magnitude post-fix (still 1e10-1e11) -- the resonance there is
apparently a genuinely near-unity-but-stable pole on real tonal content,
not an actual instability the old covariance solve was mis-estimating,
so this is a real correctness fix (unconditional stability, matching the
spec's own method) but not the cliff's root cause. `EC_AAC_SBR_HF_BYPASS`
A/B confirms the t=18s/24s cliff itself is unrelated to SBR HF content
(corr near-identical with HF zeroed: 0.0546->0.0546, 0.0589->0.0586,
both essentially unchanged after this fix too) -- that cliff's cause is
still open, outside SBR HF/limiter entirely.

Gate (crates/ec-aac, EC_AAC_HEAAC_FIXTURES set):
- sbr_hf::/sbr_env:: lib tests: pass (4+6/4+6)
- sbr_real_library_matches_reference: reeln full 0.9875/0.9866,
  above-5kHz 0.9741/0.9797 (baseline 0.987/0.973-0.980) -- held/slightly
  improved. FMJ full 0.9979/0.9935, below-5kHz 0.99997/0.99993,
  above-5kHz 0.9923/0.9738 -- consistent with prior runs, no regression.
  Test still fails its aspirational 0.999 full-band bar (pre-existing,
  not introduced here).
- sbr_hf_window_band_probe: t=14s corr=0.999944 (unchanged); t=18s/24s
  cliff corr=0.054661/0.058584 (baseline 0.054601/0.058942) -- unchanged,
  confirming the cliff is a separate, still-open defect.
- synthetic_heaac_matrix: 48k HE rows full/below/above 0.988-0.9999 /
  0.994-1.000 / 0.988-0.997, matching prior baseline shape (44.1k rows
  not fully re-measured this round, test run truncated for budget after
  representative 48k family confirmed no regression).
Merge branch 'ogg-tail-granule'Ahmet Kaan Gümüş · 5f3844fBrowse files
fix(vorbis): flush() delivers the terminal block's un-overlapped tailAhmet Kaan Gümüş · 750facc
fix(vorbis): flush() delivers the terminal block's un-overlapped tail

VorbisDecoder::flush() set drained=true and returned without emitting
self.lap, the accumulator holding the last decoded block's samples past
the final centre that had not yet been overlap-added into an output
frame. Per Vorbis I §1.3.2 those samples, up to the stream's final
granule position, are valid output the decoder must deliver — dropping
them left every decode exactly one hop (1024 samples at typical rates)
short of the encoded length at true EOS.

flush() now emits any non-empty self.lap as one final Frame::Audio,
permuted through the same to_ec channel map decode_audio uses, before
marking drained.

Also converts encode.rs's debug_tail_granule_44100_mono from a
panic-driven probe into a real assertion (packets==45, last
granule==44100), and adds oracle.rs::flush_delivers_the_terminal_hop,
a decoder-trait (send_packet/receive_frame/flush) round trip over a
sample count that is deliberately not a multiple of the hop, checking
exact output length and tail correlation against the source.
diag(aac-sbr): quantify heaac_48000_64k HF undershoot at the sweep-crossover cliffAhmet Kaan Gümüş · 217ee44
diag(aac-sbr): quantify heaac_48000_64k HF undershoot at the sweep-crossover cliff

t=18s/24s (bad, per prior lever) vs t=14s (good) QMF-band probe on
heaac_48000_64k.m4a shows our HF bands (kx=27..k2=59) 20-40dB weaker than
the reference at the crossover-straddling sweep window, while
EC_AAC_SBR_HF_BYPASS changes corr by <0.01 (0.054601->0.045626 at t=18s,
0.058942->0.048367 at t=24s) -- our HF content, though nonzero, is too
faint to matter either way; the corr crash is dominated by our overall
PCM being low-band-dominated while the reference's is HF-tone-dominated
at that moment, not by wrong HF phase/placement (per-band dphase across
8 slots is near-zero at t=14s, effectively noise at t=18s/24s where
magnitude is near-floor on both classification axes).

EC_AAC_SBR_CELLDUMP band[28,30) traces show sbr_hf::generate's all-pole
resynthesis producing a raw pre-gain estimate (cur) of 1e7-1e11 against a
~1e4 transmitted target throughout the file (not just the bad window) --
consistent with stabilize()'s documented 0.999 |a1|+|a2| bound permitting
near-unit-circle resonance (~1e6x power gain at r~0.999). Tried tightening
to 0.9: zero measured effect on the cliff or the bypass A/B (raw_gain
cancels cur exactly for non-capped cells), reverted -- see sbr_hf.rs
comment. band[38,40) shows capped=true with boost pegged at BOOST_MAX
throughout, consistent with the shared limiter band's aggregate cap being
chronically starved, but fixing the resonance-gain magnitude alone did not
relieve it, so the starvation's own cause remains open.

New diagnostic: sbr_hf_window_band_probe (tests/sbr_real_library.rs),
reusing qmf_domain_spec (round-46 QMF-domain third witness) for per-band
|X|/phase and narrow_lag_at for a wide +/-8192 lag cross-check (rules out
simple misalignment: t=18s/24s stay near corr~0.05-0.09 at ANY lag in that
window, confirming content divergence, not a sync/drift artifact).

ISO/IEC 14496-3 4.6.18.6 (HF generation), 4.6.18.7 (envelope adjustment,
limiter aggregate).
Merge branch 'sbr-matrix-lag'Ahmet Kaan Gümüş · e5e6247Browse files
fix(aac-sbr-test): matrix lag search adopts the drift probe's top-K refine methodAhmet Kaan Gümüş · fd37ec1
fix(aac-sbr-test): matrix lag search adopts the drift probe's top-K refine method

synthetic_heaac_matrix's mono-derived HE lag used a single coarse-stride
winner, which aliases on this file family's periodic/tonal content (its
own ref-L-vs-ref-R self-check scored coarse lag=-24 corr=0.213 vs the true
fixed-lag 0.873). Switch to sbr441_family_sample_drift_probe's proven
method: keep the top-5 coarse candidates, refine each with a full-
resolution +/-128 search over the first 10s, take the highest-corr
refined candidate, and assert it isn't at the wide search's own edge.
Also reuse that one robust lag for below/above instead of giving the
low-passed band its own independent (and previously unvalidated) search,
and print per-second full-band corr for the 44.1k HE rows so the real
13-27s content-dependent HF dip is visible instead of averaged into one
number.
feat(mux): declare an audio encoder's priming so no-elst/no-CodecDelay means zero delayAhmet Kaan Gümüş · f40e85c
feat(mux): declare an audio encoder's priming so no-elst/no-CodecDelay means zero delay

Root cause: mp4's elst and Matroska's CodecDelay only ever came from a
reordered video track's ctts offset, so an AAC track's encoder priming (one
1024-sample frame, always) was never written. A downstream reader had no way
to distinguish "this file truly has zero delay" from "this file's muxer never
said" and had to guess a fallback -- guessing wrong either trims real audio
from a genuinely delay-free file or leaves an encoder's priming samples in.

ec-mp4: Mp4Muxer::set_audio_delay(stream, priming_samples) folds into the
same elst media_time/segment_duration the video-reorder path already writes
(a shift, never a trim); the demuxer already applied elst generically, so no
demux change was needed there -- verified with a mux+demux round trip.

ec-matroska: the muxer already wrote CodecDelay (set_track_delay), but the
demuxer never read it back. CodecDelay is a decode-but-don't-play priming,
the same contract as StreamInfo::initial_padding (which mp3/Opus already use)
and not a timeline shift, so it is converted ns -> samples and reported there.

ec-aac: AacEncoder::encoder_delay() -> usize accessor (1024, the fixed cost
of the first MDCT window's overlap-add having nothing to overlap yet) for a
muxer caller to pass into the above.

Tests: ec-mp4::aac_priming_round_trips_through_an_elst,
ec-matroska::aac_priming_round_trips_through_codec_delay.
diag(aac-sbr): re-run feed-forward FIR vs all-pole A/B on the normative QMF bankAhmet Kaan Gümüş · 8ec0f40
diag(aac-sbr): re-run feed-forward FIR vs all-pole A/B on the normative QMF bank

Round-48 (commit 8bc305b) shipped the spec's feed-forward 2-tap FIR
extension of sbr_hf::generate; round-50 (ec65451) reverted it to the
all-pole residual resynthesis on measurement, but that A/B ran through the
old fitted-Kaiser QMF bank, not today's normative ISO/IEC 14496-3
4.6.18.4/4.6.18.8.2 analysis/synthesis pair in sbr_qmf.rs. Re-tried the
feed-forward FIR (cherry-picked from 8bc305b, adapted: HfHistory drops the
now-unused y-history half, stabilize's doc updated) against today's
sbr_real_library test suite:

  sbr_real_library_matches_reference (full-band correlation, ch0/ch1):
    reeln:  all-pole 0.986993/0.986238  vs  feed-forward 0.965566/0.965680
    FMJ:        all-pole 0.997880/0.993373  vs  feed-forward 0.994118/0.983006

  synthetic_heaac_matrix, 48k family, above-crossover band:
    32k: 0.9969 -> 0.9951   48k: 0.9882 -> 0.9646
    64k: 0.9864 -> 0.9727   96k: 0.9863 -> 0.9726

  synthetic_heaac_matrix, 44.1k family: unchanged (both already near-zero,
  a separate pre-existing issue this round didn't touch).

Feed-forward loses on every witness again, same direction as round-50, on
the QMF bank that round-50's finding was suspected of being contingent on.
The all-pole structure and its stability bound (BIBO |a1|+|a2|<1, correct
for an IIR recursion; the spec's own |alpha|>=4 -> 0 guard on the FIR
coefficients is not applicable here since that structure isn't in use) are
unchanged from main -- this commit is doc-only, recording the re-measurement
so the next round doesn't re-try this exact experiment from a stale premise.
diag(aac-sbr): 44.1k-family "sample drift" is a narrow-search artifact, not clock driftAhmet Kaan Gümüş · 9f92c74
diag(aac-sbr): 44.1k-family "sample drift" is a narrow-search artifact, not clock drift

sbr441_family_sample_drift_probe (crates/ec-aac/tests/sbr_real_library.rs)
walks lag(t) per-1s window in a NARROW +/-128 search around each fixture's
own true fixed lag (found first via a wide free-search cross-check, since
the earlier -4674/-4617 pair used in coupled_cpe_channel_swap_probe was
itself never independently verified against a wide search on this file).

Findings, all three fixtures (heaac_44100_48k "fail" family,
heaac_48000_48k "control", and reeln.mp4 as a real-content
control):
- lag(t) is FLAT (+/-1-2 samples, fitted slope ~0) across the full 30s for
  every file -- no growing sample-count/clock drift anywhere. The earlier
  "decays 0.998->0.68 by t=9s" reading was the free coarse-then-refine
  search (proven separately unreliable on this file's periodic content)
  chasing a different, wrong lag as it walked forward, not the aligned
  signal actually drifting.
- heaac_44100_48k and heaac_48000_48k -- NOT just the "failing" 44.1k
  family -- both show an IDENTICAL correlation dip-then-recover in the
  file's middle third (t~=13-27s, corr falling to ~0.13-0.5) at their
  otherwise-flat true lag. Since the 48k file shows the same dip, this is
  a property of the synthetic fixture pair's shared source content (both
  built by the same make-heaac-fixtures.sh run), not a 44.1k-vs-48k
  output-rate SBR/rate-family defect.
- Sample counts: our decoder emits exactly au_count*2048 samples/channel
  for both heaac fixtures (no internal drops); ffmpeg's own decode is a
  constant ~5058 samples shorter for BOTH files (encoder priming/padding
  trim ffmpeg applies via edit list that we don't) -- a fixed offset
  already absorbed into the fixed lag, not a growing one. reeln's
  0.366 ours/ffmpeg ratio is purely the test harness's own 1500-AU
  extraction cap (~69.7s) against ffmpeg's full ~190s decode, not a
  decode defect.
- hold_call_count() (new ec_aac::hold_call_count(), sbr_chain.rs
  HOLD_CALLS atomic) is 0 across all three files' full decodes: no
  apply_last/hold fallback is involved at all.

Verdict: the charter's "44.1k-family clock drift" hypothesis is refuted.
Next suspect for the mid-file correlation dip shared by both synthetic
heaac fixtures: their shared source content around t=13-27s (quiet
passage / high-transient section stressing SBR HF reconstruction), not
sample-rate-family-specific code.
Merge branch 'sbr-441-family'Ahmet Kaan Gümüş · 340601eBrowse files
diag(aac-sbr): confirm coupled-CPE swap probe is a lag-drift artifact, not a channel swapAhmet Kaan Gümüş · f7652c7
diag(aac-sbr): confirm coupled-CPE swap probe is a lag-drift artifact, not a channel swap

Adds a fixed-lag correlation matrix (per-pair ch0/ch1 vs ref L/R at four
candidate lags, plus mono-derived lag) to coupled_cpe_channel_swap_probe,
replacing trust in the free lag search (already known unreliable: it
mis-searches ref L vs ref R against each other on this file's periodic
content). A per-1-second sub-window breakdown at the properly-determined
fixed lag shows ch0 starting near-perfect against ref L (0.998) and
drifting down to 0.68 over 10s while its ref R correlation rises 0.90 to
0.99 -- a monotonic crossover consistent with accumulating decode/
reference clock drift, not a step-change channel swap. Adds an assert
gating the swap-shaped signature and updates synthetic_heaac_matrix's HE
rows to derive one lag per stream from the summed (mono) signal instead
of a per-channel free search.
diag(aac): reelh_per_frame prints pns_bands census and full-file RMS/PearsonAhmet Kaan Gümüş · 22effda
diag(aac): reelh_per_frame prints pns_bands census and full-file RMS/Pearson

Used from edith_replica's real-library sweep hunt: confirms this file's raw
ec-aac decode already matches ffmpeg at 0.999999 Pearson over the first 10s
(1/447 AUs below 0.9 sub-window corr, a near-silent PNS frame at the fade-in,
not a real defect) -- the sweep's reported 0.9840 traced to two bugs in the
replica engine/harness instead, not to this decoder.
diag(aac-sbr): isolate the coupled-CPE L/R swap to the bare Analysis/Synthesis QMF pair, not plane/state threadingAhmet Kaan Gümüş · 9631d42
diag(aac-sbr): isolate the coupled-CPE L/R swap to the bare Analysis/Synthesis QMF pair, not plane/state threading

Adds env-gated (EC_AAC_SBR_PREQMF_DUMP) pre-QMF/post-QMF plane dumps in
sbr_chain::apply_data and matching core-only dumps in the test harness,
plus an isolated round-trip probe in coupled_cpe_channel_swap_probe that
runs the already-correctly-directed core-only decode through a bare,
fresh Analysis(32)->zero-stuff-HF->Synthesis(64) pair per channel, with
no sbr_chain, HashMap element lookup, envelope/HF/noise code, or per-AU
state at all.

Findings (see ledger DELTA for the full table): the plane content
entering apply_data is byte-identical to the core-only decode's own
channel content (no pre-QMF swap); the isolated round trip alone
reproduces the swap numbers to ~5 significant figures (kx=20:
ch0 vs ref L corr=-0.089, vs ref R corr=0.980) matching the full-chain
and EC_AAC_SBR_HF_BYPASS=1 numbers almost exactly -- narrowing the bug
to crates/ec-aac/src/sbr_qmf.rs's Analysis/Synthesis pair itself, not
sbr_chain's plane/channel-index threading or sbr_env/sbr_hf. The real
reference L/R content does not invert at any tested lowpass cutoff
(100Hz-12kHz via ffmpeg), ruling out "the source material really does
swap identity in that band". Root cause inside sbr_qmf.rs not found
this round; NOT fixed, gates NOT re-run to passing.
fix(aac-sbr): correct §4.6.18.7.2 coupled-CPE pan-offset/exponent mathAhmet Kaan Gümüş · c1d01e5
fix(aac-sbr): correct §4.6.18.7.2 coupled-CPE pan-offset/exponent math

dequant_pair's ratio exponent was 2*alpha*balance_raw - 12 (doubling
the step at bs_amp_res=1 and using the wrong offset at bs_amp_res=0)
and its left/right naming handed physical channel 0 the env1 shape
and channel 1 the env0 shape. Per ISO/IEC 14496-3 §4.6.18.7.2 the
ratio is 2^(pan - panOffset) with panOffset=24 at bs_amp_res=0 and
12 at bs_amp_res=1, and env0/env1 stay on their own physical channel
(no left/right swap). panOffset must also come from the header's
transmitted bs_amp_res unconditionally, not the per-envelope amp_res
override a single-envelope frame forces to 0 -- the two diverge on
single-envelope coupled frames.

heaac_44100_48k.m4a's live balance raw values cluster at 12 under
bs_amp_res=1, matching a centred pan at panOffset=12 exactly and
confirming the offset direction empirically.

This does NOT fix coupled_cpe_channel_swap_probe's ch0-correlates-
with-ref-R finding: EC_AAC_SBR_HF_BYPASS=1 (which reduces SBR to a
per-channel low-band QMF round trip, running neither this coupling
math nor sbr_hf's HF generation at all) reproduces the identical
swap, ruling out sbr_env.rs and sbr_hf.rs as the swap's cause. Gate
numbers held: coupled_cpe_channel_swap_probe passes as a diagnostic
probe (not an assertion of correctness), synthetic_heaac_matrix ok,
reeln/FMJ real-library correlation unchanged (0.986238 vs the
pre-existing 0.986222 baseline, both below the 0.999 bar this branch
did not touch), ec-aac --lib 45/45 passing.
test(aac-sbr): add coupled-CPE L/R swap probe for the 44.1k implicit-family breakAhmet Kaan Gümüş · 9630027
test(aac-sbr): add coupled-CPE L/R swap probe for the 44.1k implicit-family break

Ledger charter asked why implicit-output-rate-ASC 44.1k HE-AAC fixtures
break the full SBR chain while their core-only decode is fine. Root cause
found, not where the charter expected: heaac_44100_48k.m4a's SBR side info
shows bs_coupling=1 on almost every AU (reeln/FMJ, both passing, show
coupling=false) -- coupling, not the 44.1k rate family, is the actual
discriminant refuted rate-family theories missed.

coupled_cpe_channel_swap_probe decodes both channels and correlates each
against the reference's L and R separately: our ch0 reads 0.98 correlated
with the REFERENCE's RIGHT channel (ch1 with its LEFT) at a fixed lag --
the full chain's stereo output is L/R-swapped for this file. The
core-only (SBR-disabled) decode of the same file is NOT swapped (ch0 vs
ref L 0.83 > ch0 vs ref R 0.72), so the swap is introduced somewhere in
the SBR chain specifically for coupled CPEs, not the AAC-LC core.

Tried and reverted: swapping dequant_pair's left/right assignment in
sbr_env::dequantize_frame's coupling branch (the textbook suspect for a
coupled-CPE channel swap) measurably changed nothing -- rebuilt twice,
identical correlation to 6 decimals -- so the swap site is elsewhere in
the SBR chain (sbr_chain.rs's per-tag/per-ch wiring, or sbr_payload's CPE
channel read order) and is still open. Left as a dead-end + reproducible
instrument rather than shipping an unverified fix.
Merge branch 'sbr-per-au'Ahmet Kaan Gümüş · aadc033Browse files