1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! # oxideav-opus
//!
//! **Status:** orphan-rebuild scaffold (post 2026-05-20 audit).
//!
//! The prior implementation was retired under the workspace clean-room
//! policy. The crate is being re-implemented from scratch against
//! RFC 6716 + RFC 8251 + RFC 7587 + RFC 7845 using only material under
//! `docs/` and black-box validator binaries (`opusdec` / `opusenc`).
//!
//! ## Current surface
//!
//! * Round 1 lands the [`OpusTocByte`] parser per RFC 6716 §3.1
//! (Table 2, Table 3, Table 4 — the 32-config × stereo-flag ×
//! frame-count-code triple that prefixes every well-formed Opus
//! packet).
//! * Round 2 lands the [`OpusPacket`] §3.2 frame-packing parser for
//! all four `c` codes (code 0 single frame; code 1 two equal-size;
//! code 2 two unequal with §3.2.1 length encoding; code 3 signalled
//! frame count with optional VBR per-frame lengths and Opus
//! padding). The returned slices borrow from the input packet, so
//! the SILK / CELT decoders can be hooked up against them in a
//! subsequent round without copying.
//! * Round 3 lands the [`RangeDecoder`] RFC 6716 §4.1 range coder —
//! the shared entropy primitive consumed by both the SILK and CELT
//! layers. The sibling `oxideav-celt` crate owns an independent
//! clean-room copy of the same primitive; both crates carry their
//! own copy until a shared low-level primitives crate exists.
//! * Round 4 lands the [`SilkFrameHeader`] decoder for RFC 6716
//! §4.2.7.1 (stereo prediction weights), §4.2.7.2 (mid-only flag),
//! §4.2.7.3 (frame type / quantization-offset type), and §4.2.7.5.1
//! (normalized LSF stage-1 codebook index `I1`). These are the four
//! structural decisions that gate every subsequent SILK stage
//! (gains, LSF stage-2, LTP, excitation). Implemented as
//! inverse-CDF reads against the range decoder, with the PDFs
//! transcribed from Tables 6, 8, 9, and 14.
//! * Round 5 lands the [`SubframeGains`] decoder for RFC 6716
//! §4.2.7.4 — per-subframe quantization gains for the two- or
//! four-subframe SILK frame. The first subframe is **independently**
//! coded (Table 11 signal-type-conditioned MSB PDF + Table 12
//! uniform LSB PDF + the `max(gain_index, previous_log_gain - 16)`
//! clamp from §4.2.7.4) when the §4.2.7.4 enumeration triggers;
//! otherwise it's coded as a 41-symbol delta (Table 13) against
//! the previous coded subframe gain via the `clamp(0,
//! max(2*delta - 16, prev + delta - 4), 63)` rule. All subsequent
//! subframes in the frame use the delta path. Output is integer
//! `log_gain` in `0..=63`; the §4.2.7.4 tail-end `gain_Q16`
//! conversion (`silk_log2lin`) is part of the excitation stage
//! and not wired up yet.
//!
//! * Round 6 lands the [`LsfStage2`] decoder for RFC 6716 §4.2.7.5.2 —
//! the per-coefficient stage-2 residual indices `I2[k] ∈ [-10, 10]`
//! plus the backwards-prediction-undone `res_Q10[k]`. Tables 15
//! (NB/MB) and 16 (WB) are the eight signal-shape codebooks; Tables
//! 17 (NB/MB) and 18 (WB) map `(I1, k)` → codebook letter; Table 19
//! is the 7-cell extension PDF for the `|I2| == 4` saturation case;
//! Table 20 holds the four prediction-weight lists (A/B for NB/MB,
//! C/D for WB); Tables 21 (NB/MB) and 22 (WB) map `(I1, k)` →
//! weight-list. Output stops at `res_Q10[]`.
//!
//! * Round 7 lands the [`NlsfReconstructed`] decoder for RFC 6716
//! §4.2.7.5.3 — the stage-1 codebook lookup (Tables 23 NB/MB and
//! 24 WB carrying `cb1_Q8[]` for each `I1 ∈ 0..32`), the
//! low-complexity Inverse Harmonic Mean Weighting (IHMW) derivation
//! of `w_Q9[k]` from `cb1_Q8[]` via
//! `w2_Q18[k] = (1024/(cb1_Q8[k]-cb1_Q8[k-1]) + 1024/(cb1_Q8[k+1]-cb1_Q8[k])) << 16`
//! reduced through the spec's square-root approximation, and the
//! final reconstructed
//! `NLSF_Q15[k] = clamp(0, (cb1_Q8[k]<<7) + (res_Q10[k]<<14)/w_Q9[k], 32767)`.
//! The §4.2.7.5.5 interpolation step that consumes the stabilized
//! `NLSF_Q15[]` is deferred to a later round.
//!
//! * Round 8 lands the [`NlsfStabilized`] decoder for RFC 6716
//! §4.2.7.5.4 — the normalized-LSF stabilization that enforces the
//! Table 25 minimum spacing between consecutive `NLSF_Q15[]` entries.
//! Up to 20 distortion-minimizing re-centring passes run first
//! (finding the smallest-spacing pair, then the `min_center` /
//! `max_center` / `center_freq` re-centring, with special handling
//! for the implicit `NLSF_Q15[-1] = 0` and `NLSF_Q15[d_LPC] = 32768`
//! edges), falling back after the 20th pass to a guaranteed sort +
//! forward-`max` + backward-`min` sweep. The fallback's forward sweep
//! uses 16-bit saturating addition per the RFC 8251 §7 erratum.
//!
//! * Round 9 lands the [`LsfInterpolated`] decoder for RFC 6716
//! §4.2.7.5.5 — the normalized-LSF interpolation that produces the
//! first-half coefficients of a 20 ms SILK frame. A Q2 factor
//! `w_Q2 ∈ 0..=4` is decoded from the Table 26 PDF and
//! `n1_Q15[k] = n0_Q15[k] + (w_Q2*(n2_Q15[k] - n0_Q15[k]) >> 2)` blends
//! the prior coded frame's NLSF vector (`n0`) with the current
//! stabilized one (`n2`). After a decoder reset or an uncoded regular
//! side-channel SILK frame the factor is still decoded (to keep the
//! range coder in sync) but discarded and `4` is used instead; for a
//! 10 ms SILK frame no factor is present at all.
//!
//! * Round 10 lands the [`LpcQ17`] core converter for RFC 6716
//! §4.2.7.5.6 — the NLSF → LPC reconstruction (`silk_NLSF2A`). The
//! Table 28 Q12 cosine table with linear interpolation produces the
//! re-ordered Q17 cosine vector `c_Q17[]` per Table 27, the
//! `silk_NLSF2A_find_poly` P/Q recurrence runs in i64 to absorb the
//! "up to 48 bits of intermediate precision" the spec calls out, and
//! the last-row sum/difference assembly produces the 32-bit
//! `a32_Q17[]`.
//!
//! * Round 11 lands the §4.2.7.5.7 range-limiting bandwidth expansion
//! ([`LpcQ17::range_limited`]) — up to 10 rounds of `silk_bwexpander_32`
//! chirping (`maxabs_Q12 = min((maxabs_Q17 + 16) >> 5, 163838)`, chirp
//! factor `sc_Q16[0] = 65470 - ((maxabs_Q12 - 32767) << 14) /
//! ((maxabs_Q12 * (k+1)) >> 2)`) that shrink the raw `a32_Q17[]` until
//! it fits a signed 16-bit Q12 value, followed by the documented
//! post-loop Q12 saturation `clamp(-32768, (a + 16) >> 5, 32767) << 5`.
//! The result is held in the Q17 domain for the §4.2.7.5.8
//! prediction-gain limiting that follows.
//!
//! * Round 12 lands the §4.2.7.5.8 prediction-gain limiting
//! ([`LpcQ17::prediction_gain_limited`] → [`LpcQ12`]) — the
//! `silk_LPC_inverse_pred_gain_QA()` stability test (DC-response check
//! plus the fixed-point Levinson recurrence on the Q24-widened Q12
//! coefficients, with the `abs(a32_Q24[k][k]) > 16773022` and
//! `inv_gain_Q30[k] < 107374` instability bounds) driving up to 16
//! rounds of bandwidth expansion with `sc_Q16[0] = 65536 - (2<<i)`.
//! The result is the final stable Q12 filter `a_Q12[k]` consumed by the
//! §4.2.7.9.2 LPC synthesis.
//!
//! * Round 13 lands the §4.2.7.6 Long-Term Prediction parameters
//! ([`LtpParameters`]) — the primary pitch lag (§4.2.7.6.1; absolute via
//! Table 29 high part + Table 30 bandwidth-conditioned low part, or
//! relative via the Table 31 delta with a zero-delta fallback to
//! absolute), the pitch-contour VQ index (Table 32 PDF; Tables 33–36
//! codebooks) that refines the primary lag into per-subframe pitch lags
//! clamped to `[lag_min, lag_max]`, the §4.2.7.6.2 periodicity index
//! (Table 37) and per-subframe 5-tap Q7 LTP filter taps (Table 38 PDFs;
//! Tables 39–41 codebooks), and the §4.2.7.6.3 optional Q14 LTP scaling
//! factor (Table 42 → `{15565, 12288, 8192}`; default `15565` when not
//! coded). Non-voiced frames consume no LTP bits.
//!
//! * Round 14 lands the §4.2.7.7 LCG seed ([`decode_lcg_seed`]) and the
//! §4.2.7.8 SILK excitation decoder ([`Excitation`] / [`ExcitationConfig`]).
//! The excitation is decoded in six substeps: §4.2.7.8.1 rate level
//! (Table 45 PDFs, one symbol per SILK frame), §4.2.7.8.2 per-shell-block
//! pulse count (Table 46 PDFs at one of 11 rate levels; the "extra LSB"
//! value 17 chains into rate level 9, then 10), §4.2.7.8.3 recursive
//! pulse-location partition (16 → 8 → 4 → 2 → 1; Tables 47–50 select
//! the split PDF by partition size + remaining pulse count),
//! §4.2.7.8.4 per-coefficient LSB decoding (Table 51), §4.2.7.8.5
//! sign decoding (Table 52, picked by signal type × quantization
//! offset type × pulse count bin with 6+ saturating), and §4.2.7.8.6
//! reconstruction with the LCG `seed' = 196314165*seed + 907633515
//! mod 2^32` plus the Table 53 Q23 quantization offset. The result is
//! the final Q23 excitation `e_Q23[]` consumed by the §4.2.7.9 LTP
//! and LPC synthesis filters.
//!
//! * Round 15 lands the §4.2.7.9.2 SILK LPC synthesis filter
//! ([`lpc_synthesis_subframe`] / [`lpc_synthesis_frame`] /
//! [`LpcSynthState`]). The short-term predictor combines the §4.2.7.4
//! Q16 gain, the §4.2.7.9.1 residual `res[i]`, and the §4.2.7.5.8 Q12
//! stabilised filter `a_Q12[k]` into the unclamped `lpc[i]` and its
//! clamped output `out[i] = clamp(-1.0, lpc[i], 1.0)`; the per-subframe
//! `d_LPC` unclamped history is carried across subframes via the
//! stateful [`LpcSynthState`] (cleared to zero on a decoder reset).
//!
//! * Round 16 lands the §4.2.7.9.1 SILK LTP synthesis filter
//! ([`ltp_synthesis_subframe`] / [`ltp_synth_commit_subframe`] /
//! [`LtpSynthState`]). Unvoiced subframes produce `res[i] = e_Q23[i] /
//! 2^23` (a normalised excitation copy). Voiced subframes go through the
//! §4.2.7.6 5-tap Q7 LTP convolution `res[i] = e_Q23[i]/2^23 + Σ
//! res[i - pitch_lag + 2 - k] * b_Q7[k]/128`, with the prior-subframe
//! `out[]` history rewhitened via `4*LTP_scale_Q14/gain_Q16 *
//! clamp(out[i] - Σ out[i-k-1] * a_Q12[k]/4096, -1, 1)` (region A) and
//! the prior-subframe unclamped `lpc[]` rewhitened via `65536/gain_Q16 *
//! (lpc[i] - Σ lpc[i-k-1] * a_Q12[k]/4096)` (region B). `out_end` and
//! the effective `LTP_scale_Q14` (= 16384 fresh-LPC override) follow the
//! §4.2.7.9.1 third/fourth-subframe LSF-interpolation-split branch. The
//! stateful [`LtpSynthState`] carries 306 samples of out[] and 256
//! samples of lpc[] history (the spec-stated WB worst cases) across
//! subframes and across SILK frame boundaries, cleared to zero on a
//! decoder reset per §4.5.2.
//!
//! * Round 17 lands the §4.2.8 SILK stereo unmixing
//! ([`stereo_ms_to_lr`] / [`StereoUnmixState`] / [`StereoWeightsQ13`] /
//! [`StereoFrame`]) — the `silk_stereo_MS_to_LR` conversion that turns
//! the decoded mid/side `out[]` signals into left/right. The side
//! channel is predicted from a low-passed mid term
//! (`p0 = (mid[i-2] + 2*mid[i-1] + mid[i]) / 4`) and the unfiltered
//! one-sample-delayed mid (`mid[i-1]`) via the §4.2.7.1 Q13 weights:
//! `left[i] = clamp(-1, (1+w1)*mid[i-1] + side[i-1] + w0*p0, 1)` and
//! `right[i] = clamp(-1, (1-w1)*mid[i-1] - side[i-1] - w0*p0, 1)`. The
//! first `n1` samples (64 NB / 96 MB / 128 WB) interpolate the weights
//! from the previous frame's `(prev_w0_Q13, prev_w1_Q13)` to the
//! current frame's; the remainder use the current weights. An uncoded
//! side channel (§4.2.7.2) is treated as all-zero. The two trailing
//! mid samples, one trailing side sample, and previous-frame weights
//! carry across the frame boundary via [`StereoUnmixState`], cleared
//! to zero on a decoder reset per §4.2.8.
//!
//! * Round 19 lands the §4.2.9 SILK resampler delay budget and the
//! internal-vs-output sample-rate accounting ([`silk_resampler_delay_ms`] /
//! [`silk_resampler_delay_samples_at`] / [`silk_internal_rate_hz`] /
//! [`silk_frame_samples_internal`] / [`silk_frame_samples_at_output`] /
//! [`is_supported_output_rate`] / [`SUPPORTED_OUTPUT_RATES_HZ`]).
//! The §4.2.9 resampler itself is non-normative ("a decoder can use
//! any method it wants"); what IS normative is the Table 54 maximum
//! delay allocation (NB = 0.538 ms, MB = 0.692 ms, WB = 0.706 ms) so
//! the encoder can apply a matching pre-delay to keep SILK and CELT
//! aligned across a §4.5 mode switch. This module owns Table 54 plus
//! the implied SILK internal rates (NB = 8000 Hz, MB = 12000 Hz,
//! WB = 16000 Hz) and the §4.2.9 supported output rates (8 / 12 / 16 /
//! 24 / 48 kHz). SWB and FB never reach the §4.2.9 SILK stage and are
//! rejected with `None`.
//!
//! * Round 18 lands the §4.2.3 SILK packet-level header bits and the
//! §4.2.4 per-frame LBRR flags ([`SilkHeaderBits`] / [`silk_frame_count`]).
//! For each channel (mono: 1; stereo: 2), the decoder reads N uniform
//! `dec_bit_logp(1)` VAD bits (N = SILK-frame count from §4.2.2: 1 for
//! 10/20 ms Opus frames, 2 for 40 ms, 3 for 60 ms) followed by a single
//! global LBRR flag. For Opus frames longer than 20 ms, each channel
//! whose global LBRR flag is set then contributes one Table 4 symbol
//! (`{0, 53, 53, 150}/256` for 40 ms / `{0, 41, 20, 29, 41, 15, 28,
//! 82}/256` for 60 ms) carrying a per-SILK-frame LBRR bitmap, packed
//! LSB-to-MSB. For 10/20 ms Opus frames the global LBRR flag itself
//! implies a single LBRR frame. Output is a [`SilkHeaderBits`]
//! carrying the per-channel VAD bitmap, global LBRR flag, and the
//! fully expanded per-channel × per-SILK-frame [`PerFrameLbrr`]
//! bitmap consumed by the downstream §4.2.5 LBRR / §4.2.6 regular
//! SILK frame loop.
//!
//! * Round 20 lands the first CELT-layer fragment ([`CeltHeaderPrefix`] /
//! [`CeltPostFilter`]) — the §4.3, Table 56 pre-band header symbols
//! that every CELT-bearing Opus frame opens with: `silence`
//! (`{32767, 1}/32768`), the §4.3.7.1 pitch post-filter parameter
//! group (logp=1 enable bit, then `octave` uniform[0,6), `period =
//! (16<<octave) + fine_pitch - 1` from `4+octave` raw bits bounded
//! to `15..=1022`, `gain` 3 raw bits ⇒ `G = 3*(gain_index+1)/32`,
//! `tapset` `{2,1,1}/4`), the §4.3.1 `transient` (`{7,1}/8`), and
//! the §4.3.2.1 `intra` (`{7,1}/8`) flag. When `silence` is set,
//! the rest of the prefix is force-defaulted per the §4.3
//! shortcut. This is the only Table-56 segment that fits between
//! the SILK pipeline already wired up and the §4.3.2.1 coarse
//! energy (#936, blocked on the Laplace decoder + `e_prob_model`
//! table) / §4.3.3 bit allocation (#943, blocked on `cache_caps50`
//! + `LOG2_FRAC_TABLE`) sub-pieces.
//!
//! * Round 21 lands the §3.1 / §4.2 framing dispatch ([`OpusFrameRouting`]
//! / [`OperatingMode`] / [`SilkBandwidth`]) — the single
//! pure-function lookup that turns an [`OpusTocByte`] into the
//! per-Opus-frame routing decision a §4 decoder needs *before* it
//! touches the range coder: which layer(s) are present (SILK-only /
//! Hybrid / CELT-only), the SILK internal bandwidth (pinned to WB
//! for Hybrid per §4.2 even when the TOC bandwidth is SWB / FB), the
//! §4.2.2 SILK-frame count per channel (1 for 10/20 ms, 2 for 40 ms,
//! 3 for 60 ms), the §4.2.4 per-frame LBRR-flag presence gate
//! (duration > 20 ms), and the channel-count multiplier for stereo.
//! Codifies the dispatch decision so downstream decoders consume one
//! `OpusFrameRouting` instead of open-coding the
//! `(mode, bandwidth, frame_size)` switch each time.
//!
//! * Round 23 lands the §4.2.7.4 SILK gain dequantization tail
//! ([`silk_log2lin`] / [`silk_gains_dequant`] /
//! [`SubframeGains::dequant_q16`](crate::silk_gains::SubframeGains::dequant_q16))
//! — the piecewise-linear approximation of `2^(inLog_Q7/128)` and the
//! composed `log_gain ∈ 0..=63 → gain_Q16 ∈ [81920, 1_686_110_208]`
//! mapping that the §4.2.7.9.1 LTP and §4.2.7.9.2 LPC synthesis
//! filters consume. The two §4.2.7.4 endpoints (`log_gain = 0`
//! ⇒ `81920` = 1.25× linear; `log_gain = 63` ⇒ `1_686_110_208` ≈
//! 25 728× linear) are pinned to the RFC text. The §4.2.7.5 NLSF
//! stages had been deferred since round 5; this round closes that gap.
//!
//! * Round 24 lands the §4.3 CELT MDCT-band layout
//! ([`celt_band_layout`]: [`CeltFrameSize`] + Table 55
//! `bins_per_channel` lookups via [`celt_band_bins_per_channel`] +
//! [`celt_band_start_hz`] / [`celt_band_stop_hz`] band-edge
//! accessors + [`celt_band_at_hz`] reverse lookup + the §4.3
//! "first 17 bands not coded in Hybrid mode" rule baked into
//! [`celt_first_coded_band`] / [`HYBRID_FIRST_CODED_BAND`] + the
//! [`celt_total_bins_per_channel`] column-sum helper). The standard
//! non-Custom CELT layer's [`CELT_NUM_BANDS`] = 21 bands and the
//! per-band MDCT bin counts at the four CELT frame sizes (2.5 / 5
//! / 10 / 20 ms) are the lookup every §4.3.2 coarse-energy decoder,
//! §4.3.3 bit allocator, §4.3.4 PVQ shape decoder, §4.3.6
//! denormaliser, and §4.3.7 inverse-MDCT pass needs before any
//! band-loop iteration can start.
//!
//! The rest of the CELT layer is not yet wired up; the [`Decoder`]
//! / [`Encoder`] entry points still return [`Error::NotImplemented`].
use RuntimeContext;
/// Crate-local error type.
pub use ;
pub use ;
pub use ;
pub use ;
pub use RangeDecoder;
pub use ;
pub use ;
pub use ;
pub use ;
pub use decode_lcg_seed;
pub use ;
pub use ;
pub use ;
pub use ;
pub use NlsfStabilized;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
/// No-op codec registration — the orphan-rebuild scaffold registers
/// nothing into the runtime context until decode / encode paths are
/// wired up.
register!;