rusty_mp3 0.4.1

Pure-Rust MP3 (MPEG-1/2/2.5 Layer III) decoder + encoder, no C/FFI. Decoder bit-exact vs FFmpeg; the first pure-Rust MP3 encoder (CBR/VBR, joint stereo, bit reservoir).
Documentation
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
//! The brick registry — the canonical, in-code manifest of every encoder brick.
//!
//! This is the single source of truth that [`docs/mp3-encoder-plan.md`] describes
//! in prose. The slice order **is** the execution order, so [`next_unbuilt`]
//! always points at the brick to lay next. Keeping the manifest in typed code
//! means it can't silently drift from the build the way a separate doc would.

use core::fmt;

/// Which floor of the house a brick belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Phase {
    /// Shared primitives & tables (N*).
    Foundation,
    /// Time → frequency: analysis filterbank + forward MDCT (L*).
    Analysis,
    /// Frequency → bits: Huffman + side-info + framing (B*).
    Coding,
    /// The dumb-but-valid controller — first decodable MP3 (C*).
    Controller,
    /// The psychoacoustic quality brain (Q*).
    Quality,
    /// Stereo, rate modes, conformance (R*).
    Roof,
}

impl Phase {
    pub fn name(self) -> &'static str {
        match self {
            Phase::Foundation => "Foundation",
            Phase::Analysis => "Analysis",
            Phase::Coding => "Coding",
            Phase::Controller => "Controller",
            Phase::Quality => "Quality",
            Phase::Roof => "Roof",
        }
    }
}

/// How a brick's data/algorithm is obtained (mirrors the plan's classification).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Class {
    /// Compute from a formula and assert vs known values.
    Gen,
    /// Transcribe a fixed table and validate.
    Tbl,
    /// Transcribe an algorithm and verify.
    Alg,
    /// Wiring/plumbing, no new math.
    Glue,
    /// Already implemented & tested on the decode side (reuse / invert).
    Done,
}

impl Class {
    pub fn tag(self) -> &'static str {
        match self {
            Class::Gen => "[GEN]",
            Class::Tbl => "[TBL]",
            Class::Alg => "[ALG]",
            Class::Glue => "[GLUE]",
            Class::Done => "[done]",
        }
    }
}

/// How a brick is proven correct — the regime it lives in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verify {
    /// Reuses decode-side data/code already proven bit-exact.
    Reuse,
    /// Round-trips bit-exactly through the matching decoder parser.
    RoundTrip,
    /// Time-domain aliasing cancellation: forward→inverse reconstructs the input.
    Tdac,
    /// Compared to an independent float/reference computation.
    Reference,
    /// End-to-end: decodes cleanly in FFmpeg/LAME (a *legal* stream).
    External,
    /// Quality metric under a threshold (the experimental regime — no bit-exact).
    Metric,
}

impl Verify {
    pub fn name(self) -> &'static str {
        match self {
            Verify::Reuse => "reuse",
            Verify::RoundTrip => "round-trip",
            Verify::Tdac => "tdac",
            Verify::Reference => "reference",
            Verify::External => "external",
            Verify::Metric => "metric",
        }
    }

    /// True for the deterministic, provable bricks; false for the experimental
    /// quality bricks where there is no single right answer.
    pub fn is_conformance(self) -> bool {
        !matches!(self, Verify::Metric)
    }
}

/// Build state of a brick.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Status {
    /// Not started.
    Todo,
    /// A stub or lab-only variant exists, not wired into the production pipeline.
    Stub,
    /// Implemented in the pipeline, not yet verified.
    Impl,
    /// Implemented and passing its verification gate.
    Verified,
}

impl Status {
    pub fn symbol(self) -> &'static str {
        match self {
            Status::Todo => "·",
            Status::Stub => "◐",
            Status::Impl => "●",
            Status::Verified => "✓",
        }
    }
    pub fn name(self) -> &'static str {
        match self {
            Status::Todo => "todo",
            Status::Stub => "stub",
            Status::Impl => "impl",
            Status::Verified => "verified",
        }
    }
}

/// Performance posture — where hand-vectorised SIMD earns its keep vs. where safe
/// scalar Rust is fast enough. We won't sacrifice speed for safety on the hot
/// kernels: SIMD/Hybrid bricks get a hand-written path behind a feature flag in an
/// isolated `unsafe` accel boundary (the `rusty_h264-accel` / `rav1e` posture),
/// while the scalar Rust path stays as the default **and** the correctness
/// reference. The lab validates each SIMD path against its scalar twin through the
/// same TDAC/round-trip gate, so acceleration can never silently change output.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Accel {
    /// Safe scalar Rust is sufficient — cold or branchy, no asm warranted.
    Scalar,
    /// Scalar Rust is the default + reference; SIMD optional on the hot inner part.
    Hybrid,
    /// Hot DSP kernel — hand-vectorised SIMD worth it, isolated behind `unsafe`.
    Simd,
}

impl Accel {
    pub fn tag(self) -> &'static str {
        match self {
            Accel::Scalar => "safe",
            Accel::Hybrid => "hybrid",
            Accel::Simd => "SIMD",
        }
    }
}

/// The performance posture of a brick. The hot set is small and explicit; every
/// brick not listed is fast enough in safe scalar Rust.
///
/// * **SIMD** — `L1`/`L2` (the analysis filterbank + forward MDCT cosine kernels)
///   and `Q2` (the psymodel FFT, the single biggest cycle sink) run inner loops
///   of thousands of MACs per granule and are the classic asm hotspots in LAME.
/// * **Hybrid** — `C2`/`Q6` (the rate/distortion loops: iterative + serial, but
///   their per-call requantize vectorises) and `R1` (per-line M/S stereo).
pub fn accel(id: &str) -> Accel {
    match id {
        "L1" | "L2" | "Q2" => Accel::Simd,
        "C2" | "Q6" | "R1" => Accel::Hybrid,
        _ => Accel::Scalar,
    }
}

/// One brick: a primitive of the encoder, tracked from plan to proof.
#[derive(Debug, Clone, Copy)]
pub struct Brick {
    /// Stable id matching the plan doc (`"N4"`, `"L1"`, …). Runnable lab bricks
    /// dispatch on this.
    pub id: &'static str,
    pub phase: Phase,
    pub class: Class,
    pub verify: Verify,
    pub status: Status,
    /// One-line description.
    pub name: &'static str,
}

impl fmt::Display for Brick {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} {:<3} {:<10} {:<6} {:<10} {:<6} {}",
            self.status.symbol(),
            self.id,
            self.phase.name(),
            self.class.tag(),
            self.verify.name(),
            accel(self.id).tag(),
            self.name,
        )
    }
}

/// The full manifest, in execution order. Edit a `status` here as bricks land;
/// `cargo run --example mp3lab -- bricks` renders it.
pub static BRICKS: &[Brick] = &[
    // ── Foundation ─────────────────────────────────────────────────────────
    b(
        "N1",
        Phase::Foundation,
        Class::Done,
        Verify::Reuse,
        Status::Verified,
        "Scalefactor-band offsets (reused from decode tables)",
    ),
    b(
        "N2",
        Phase::Foundation,
        Class::Done,
        Verify::Reuse,
        Status::Verified,
        "scalefac_compress → (slen1,slen2); PRETAB (reused)",
    ),
    b(
        "N3",
        Phase::Foundation,
        Class::Done,
        Verify::Reuse,
        Status::Verified,
        "Huffman codebooks (reused; value→code lookup in B1)",
    ),
    b(
        "N4",
        Phase::Foundation,
        Class::Gen,
        Verify::Reference,
        Status::Verified,
        "Forward quantizer power law x^(3/4) / x^(4/3) (round-trips on the lattice)",
    ),
    b(
        "N5",
        Phase::Foundation,
        Class::Gen,
        Verify::Tdac,
        Status::Verified,
        "Analysis polyphase window C[512] (realised in L1, TDAC-verified)",
    ),
    b(
        "N6",
        Phase::Foundation,
        Class::Gen,
        Verify::Tdac,
        Status::Verified,
        "Analysis cosine matrix M[32][64] (realised in L1, TDAC-verified)",
    ),
    b(
        "N7",
        Phase::Foundation,
        Class::Gen,
        Verify::Tdac,
        Status::Verified,
        "Forward-MDCT cosine basis + 4 window shapes (realised in L2)",
    ),
    b(
        "N8",
        Phase::Foundation,
        Class::Tbl,
        Verify::Reuse,
        Status::Verified,
        "linbits per Huffman table (reused from decode PAIR_TABLES)",
    ),
    b(
        "N9",
        Phase::Foundation,
        Class::Gen,
        Verify::RoundTrip,
        Status::Verified,
        "Region-boundary ↔ (region0/1_count) maps",
    ),
    // ── Floor 1: analysis ──────────────────────────────────────────────────
    b(
        "L1",
        Phase::Analysis,
        Class::Alg,
        Verify::Tdac,
        Status::Verified,
        "Analysis filterbank: 18 passes, fold 512→64, cosine matrix",
    ),
    b(
        "L2",
        Phase::Analysis,
        Class::Alg,
        Verify::Tdac,
        Status::Verified,
        "Forward MDCT (36-pt long / 3×12-pt short) + overlap",
    ),
    b(
        "L3",
        Phase::Analysis,
        Class::Alg,
        Verify::Tdac,
        Status::Verified,
        "End-to-end analysis round-trip (PCM→freq→PCM identity)",
    ),
    // ── Floor 2: coding ────────────────────────────────────────────────────
    b(
        "B1",
        Phase::Coding,
        Class::Alg,
        Verify::RoundTrip,
        Status::Verified,
        "Huffman encode-table builder (invert codebooks)",
    ),
    b(
        "B2",
        Phase::Coding,
        Class::Alg,
        Verify::RoundTrip,
        Status::Verified,
        "estimate_bits(region, table) — inner-loop cost oracle",
    ),
    b(
        "B3",
        Phase::Coding,
        Class::Alg,
        Verify::RoundTrip,
        Status::Verified,
        "Huffman spectrum encode (big_values + count1 + linbits)",
    ),
    b(
        "B4",
        Phase::Coding,
        Class::Alg,
        Verify::RoundTrip,
        Status::Verified,
        "Region + table selection (minimise B2 cost)",
    ),
    b(
        "B5",
        Phase::Coding,
        Class::Alg,
        Verify::RoundTrip,
        Status::Verified,
        "Side-info serializer (inverse of decode/sideinfo)",
    ),
    b(
        "B6",
        Phase::Coding,
        Class::Alg,
        Verify::RoundTrip,
        Status::Verified,
        "Scalefactor serializer (band-major, scfsi reuse)",
    ),
    b(
        "B7",
        Phase::Coding,
        Class::Glue,
        Verify::RoundTrip,
        Status::Verified,
        "Frame assembly (reservoir-free; decodes via Mp3Decoder)",
    ),
    b(
        "B8",
        Phase::Coding,
        Class::Alg,
        Verify::RoundTrip,
        Status::Verified,
        "Encoder bit reservoir (stream assembler, borrows + caps at 511)",
    ),
    // ── Floor 3: dumb-but-valid controller ─────────────────────────────────
    b(
        "C1",
        Phase::Controller,
        Class::Alg,
        Verify::Metric,
        Status::Verified,
        "Trivial psymodel: always-long, flat threshold",
    ),
    b(
        "C2",
        Phase::Controller,
        Class::Alg,
        Verify::Metric,
        Status::Verified,
        "Rate-only quantizer (binary-search global_gain, reject clipping)",
    ),
    b(
        "C3",
        Phase::Controller,
        Class::Glue,
        Verify::External,
        Status::Verified,
        "Encoder::send_frame / receive_packet plumbing (mono)",
    ),
    b(
        "C4",
        Phase::Controller,
        Class::Alg,
        Verify::External,
        Status::Verified,
        "Pipeline gate: 81 dB round-trip, FFmpeg-decoded ✓",
    ),
    // ── Floor 4: quality brain ─────────────────────────────────────────────
    b(
        "Q1",
        Phase::Quality,
        Class::Gen,
        Verify::Reference,
        Status::Verified,
        "Psymodel constants from formulas (Terhardt ATH, Zwicker Bark, Schroeder)",
    ),
    b(
        "Q2",
        Phase::Quality,
        Class::Alg,
        Verify::Reference,
        Status::Verified,
        "FFT front-end (in-house radix-2; energy per SFB)",
    ),
    b(
        "Q3",
        Phase::Quality,
        Class::Alg,
        Verify::Metric,
        Status::Verified,
        "Masking threshold + SMR per scalefactor band (spread + ATH)",
    ),
    b(
        "Q4",
        Phase::Quality,
        Class::Alg,
        Verify::Metric,
        Status::Verified,
        "Perceptual entropy → bit demand (reservoir budgeting)",
    ),
    b(
        "Q5",
        Phase::Quality,
        Class::Alg,
        Verify::External,
        Status::Verified,
        "Block switching: short-block coding path + attack FSM (transients→short)",
    ),
    b(
        "Q6",
        Phase::Quality,
        Class::Alg,
        Verify::Metric,
        Status::Verified,
        "Outer distortion loop (shapes noise: 7.4→0.2 dB peak NMR)",
    ),
    // ── Roof: stereo, rate modes, conformance ──────────────────────────────
    b(
        "R1",
        Phase::Roof,
        Class::Alg,
        Verify::RoundTrip,
        Status::Verified,
        "Stereo: independent L/R + mid/side joint stereo (per-frame)",
    ),
    b(
        "R2",
        Phase::Roof,
        Class::Alg,
        Verify::External,
        Status::Verified,
        "Bitrate modes: CBR + VBR (quality target → per-frame bitrate, Xing tag)",
    ),
    b(
        "R3",
        Phase::Roof,
        Class::Tbl,
        Verify::External,
        Status::Verified,
        "Xing/Info header (CBR frame count; FFmpeg reads exact duration)",
    ),
    b(
        "R4",
        Phase::Roof,
        Class::Alg,
        Verify::External,
        Status::Verified,
        "Conformance corpus (8 signals: our-decoder floors + FFmpeg clean)",
    ),
    b(
        "R5",
        Phase::Roof,
        Class::Tbl,
        Verify::External,
        Status::Verified,
        "MPEG-2/2.5 LSF: V2 sfb tables + framing (6 rates, FFmpeg-validated)",
    ),
];

/// Const-fn brick constructor, to keep the manifest above terse.
const fn b(
    id: &'static str,
    phase: Phase,
    class: Class,
    verify: Verify,
    status: Status,
    name: &'static str,
) -> Brick {
    Brick {
        id,
        phase,
        class,
        verify,
        status,
        name,
    }
}

/// Look up a brick by its id (`"N4"`).
pub fn by_id(id: &str) -> Option<&'static Brick> {
    BRICKS.iter().find(|b| b.id.eq_ignore_ascii_case(id))
}

/// `[todo, stub, impl, verified]` counts.
pub fn counts() -> [usize; 4] {
    let mut c = [0usize; 4];
    for brick in BRICKS {
        c[match brick.status {
            Status::Todo => 0,
            Status::Stub => 1,
            Status::Impl => 2,
            Status::Verified => 3,
        }] += 1;
    }
    c
}

/// The next brick to lay: first one in execution order not yet built.
pub fn next_unbuilt() -> Option<&'static Brick> {
    BRICKS
        .iter()
        .find(|b| matches!(b.status, Status::Todo | Status::Stub))
}

/// Render the whole manifest as a status table (used by the `mp3lab` CLI).
pub fn table() -> String {
    let mut s = String::new();
    let mut last = None;
    for brick in BRICKS {
        if last != Some(brick.phase) {
            s.push_str(&format!("\n── {} ──\n", brick.phase.name()));
            last = Some(brick.phase);
        }
        s.push_str(&format!("{brick}\n"));
    }
    let [todo, stub, imp, ver] = counts();
    s.push_str(&format!(
        "\n{} bricks — {ver} verified ✓ · {imp} impl ● · {stub} stub ◐ · {todo} todo ·\n",
        BRICKS.len()
    ));
    let simd = BRICKS.iter().filter(|b| accel(b.id) == Accel::Simd).count();
    let hybrid = BRICKS
        .iter()
        .filter(|b| accel(b.id) == Accel::Hybrid)
        .count();
    s.push_str(&format!(
        "accel — {simd} SIMD · {hybrid} hybrid · {} safe scalar Rust\n",
        BRICKS.len() - simd - hybrid
    ));
    s
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ids_are_unique() {
        for (i, a) in BRICKS.iter().enumerate() {
            for b in &BRICKS[i + 1..] {
                assert_ne!(a.id, b.id, "duplicate brick id {}", a.id);
            }
        }
    }

    #[test]
    fn counts_sum_to_total() {
        assert_eq!(counts().iter().sum::<usize>(), BRICKS.len());
    }

    #[test]
    fn every_phase_is_present() {
        for p in [
            Phase::Foundation,
            Phase::Analysis,
            Phase::Coding,
            Phase::Controller,
            Phase::Quality,
            Phase::Roof,
        ] {
            assert!(
                BRICKS.iter().any(|b| b.phase == p),
                "no bricks for {}",
                p.name()
            );
        }
    }

    #[test]
    fn next_unbuilt_is_first_incomplete() {
        // Every brick is built — the house is complete.
        assert_eq!(next_unbuilt().map(|b| b.id), None);
    }

    #[test]
    fn hot_kernels_are_simd_control_stays_scalar() {
        // The transforms + psymodel FFT are the asm hotspots…
        for id in ["L1", "L2", "Q2"] {
            assert_eq!(accel(id), Accel::Simd, "{id} should be SIMD");
        }
        // …while framing/bit-coding stays safe scalar Rust.
        for id in ["B5", "B7", "C3", "R3"] {
            assert_eq!(accel(id), Accel::Scalar, "{id} should be scalar");
        }
    }
}