rusty_mp3 0.5.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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
//! `rusty_mp3` — an in-house, pure-Rust MP3 (MPEG-1/2/2.5 Audio Layer III)
//! decoder **and** encoder. Zero dependencies, no C, no FFI.
//!
//! Why in-house: the robust Rust MP3 crate (Symphonia) is MPL-2.0, which trips
//! a no-copyleft license gate; the permissive one (puremp3) is incomplete, and
//! every existing Rust MP3 *encoder* option is an FFI binding to LAME. MP3's
//! patents expired in 2017 and Layer III is exhaustively documented, so we
//! built our own.
//!
//! ## Layout (the framework, built brick by brick)
//!
//! * shared: [`header`] (frame header), [`frame`] (side-info + types),
//!   [`bitio`] (MSB-first bit I/O), [`tables`] (ISO constant tables)
//! * [`decode`]: side-info → reservoir → Huffman → scalefactors → requantize →
//!   stereo → antialias → IMDCT → synthesis filterbank → PCM
//! * [`encode`]: analysis filterbank → MDCT → psychoacoustic model → two-loop
//!   quantizer → Huffman → bitstream
//!
//! ## Stream API
//!
//! [`Mp3Decoder`] and [`Mp3Encoder`] are the packet-level entry points:
//! push bytes/PCM in, pull frames/packets out. The pull calls follow FFmpeg's
//! EAGAIN/EOF drain protocol via [`Error::Again`] / [`Error::Eof`] — see
//! [`error`]. The frame-level engines ([`Mp3Decode`] / [`Mp3Encode`]) are also
//! public for callers that do their own framing.
#![allow(dead_code)] // A few stage helpers are wired for lab/diagnostic use only.

use std::collections::VecDeque;

pub mod bitio;
pub mod decode;
pub mod encode;
pub mod error;
pub mod frame;
pub mod header;
pub mod tables;

/// MP3 encoder experiment harness — brick tracking, corpus, metrics, variant
/// sweeps. Opt-in behind the `lab` feature.
#[cfg(feature = "lab")]
pub mod lab;

/// Prometheus telemetry hooks — samplers for the psychoacoustic model's
/// signal-independent curves (ATH, spreading, Bark), for offline formula
/// discovery by the private Prometheus refinery. Opt-in behind the
/// `prometheus-telemetry` feature; the production build is byte-identical
/// without it.
#[cfg(feature = "prometheus-telemetry")]
pub mod prometheus_telemetry {
    pub use crate::encode::psychoacoustic::prometheus::*;
}

pub use decode::Mp3Decode;
pub use encode::Mp3Encode;
pub use error::{Error, Result};
use header::FrameHeader;

/// One decoded chunk of PCM — the output of [`Mp3Decoder::next_frame`].
/// `samples` is interleaved f32 in `[-1, 1]`, `samples.len()` =
/// per-channel samples × `channels`.
#[derive(Debug, Clone)]
pub struct DecodedAudio {
    pub sample_rate: u32,
    pub channels: u16,
    pub samples: Vec<f32>,
}

/// Stream-level MP3 decoder: [`push`](Mp3Decoder::push) raw bytes (packets may
/// split/join frames — the decoder frame-syncs internally, skipping ID3 and
/// garbage), then drain decoded PCM with [`next_frame`](Mp3Decoder::next_frame).
#[derive(Default)]
pub struct Mp3Decoder {
    state: Mp3Decode,
    /// Accumulated bytes awaiting frame-sync (packets may split/join frames).
    buf: Vec<u8>,
    queue: VecDeque<DecodedAudio>,
    eof: bool,
}

impl Mp3Decoder {
    pub fn new() -> Mp3Decoder {
        Mp3Decoder::default()
    }

    /// Feed more compressed bytes; any whole frames they complete are decoded
    /// and queued for [`next_frame`](Mp3Decoder::next_frame).
    pub fn push(&mut self, bytes: &[u8]) {
        self.buf.extend_from_slice(bytes);
        self.parse_frames();
    }

    /// Pull the next decoded frame. `Err(Again)` = feed more input;
    /// `Err(Eof)` = flushed and fully drained.
    pub fn next_frame(&mut self) -> Result<DecodedAudio> {
        if let Some(frame) = self.queue.pop_front() {
            return Ok(frame);
        }
        if self.eof {
            Err(Error::Eof)
        } else {
            Err(Error::Again)
        }
    }

    /// Signal end of input: once the queue drains, [`next_frame`](Mp3Decoder::next_frame)
    /// returns `Err(Eof)` instead of `Err(Again)`.
    pub fn flush(&mut self) {
        self.eof = true;
    }

    /// Frame-sync the buffer: for each complete frame, split header / side-info /
    /// main-data, decode it, and queue a [`DecodedAudio`]. Leaves a trailing partial
    /// frame in `buf` for the next push.
    fn parse_frames(&mut self) {
        let mut pos = 0;
        while pos + 4 <= self.buf.len() {
            // Sync = 11 set bits: 0xFF then top 3 bits of the next byte.
            if self.buf[pos] != 0xFF || self.buf[pos + 1] & 0xE0 != 0xE0 {
                pos += 1;
                continue;
            }
            let hb = [
                self.buf[pos],
                self.buf[pos + 1],
                self.buf[pos + 2],
                self.buf[pos + 3],
            ];
            let header = match FrameHeader::parse(hb) {
                Ok(h) => h,
                Err(_) => {
                    pos += 1;
                    continue;
                }
            };
            let frame_size = header.frame_size();
            if frame_size < 4 {
                pos += 1;
                continue;
            }
            if pos + frame_size > self.buf.len() {
                break; // incomplete frame — wait for more data
            }

            let crc = if header.crc_protected { 2 } else { 0 };
            let si_start = pos + 4 + crc;
            let si_len = header.side_info_len();
            let main_start = si_start + si_len;
            if main_start > pos + frame_size {
                pos += 1;
                continue;
            }
            let side_info = self.buf[si_start..main_start].to_vec();
            let main_data = self.buf[main_start..pos + frame_size].to_vec();

            if let Ok(pcm) = self.state.decode_frame(&header, &side_info, &main_data) {
                let channels = header.channel_mode.channels().max(1);
                self.queue.push_back(DecodedAudio {
                    sample_rate: header.sample_rate,
                    channels: channels as u16,
                    samples: pcm,
                });
            }
            pos += frame_size;
        }
        self.buf.drain(0..pos);
    }
}

/// Configuration for [`Mp3Encoder`].
#[derive(Debug, Clone, Default)]
pub struct Mp3EncoderConfig {
    /// CBR target in kbps, snapped to the nearest valid Layer III value for the
    /// MPEG version ([`snap_bitrate`]). `0` ⇒ default (128 for MPEG-1, 64 for
    /// MPEG-2/2.5).
    pub bitrate_kbps: u32,
    /// VBR quality target (peak NMR). `Some` ⇒ VBR, `None` ⇒ CBR. To map an
    /// ffmpeg/LAME-style `-q:a` 0–9 quality index, use [`vbr_quality_index`].
    pub vbr_quality: Option<f32>,
}

/// Map an ffmpeg/LAME-style VBR quality index (`-q:a`, 0 = best … 9 = smallest)
/// to the peak-NMR target [`Mp3EncoderConfig::vbr_quality`] expects.
pub fn vbr_quality_index(q: f32) -> f32 {
    // NMR is noise ÷ masking threshold, so 1.0 means "noise exactly AT the mask"
    // — the WORST quality that still claims to be masked, not the best. The old
    // map ran 10^(q/5), i.e. 1.0 at q=0 up to 63 at q=9: every setting from best
    // to worst asked for noise at or above the threshold, which is why the whole
    // ladder collapsed onto one bitrate.
    //
    // Run it in dB instead, from −24 dB (comfortably transparent) at q=0 to
    // +12 dB at q=9, 4 dB per step.
    let q = q.clamp(0.0, 9.0);
    10f32.powf((-24.0 + 4.0 * q) / 10.0)
}

/// Stream-level MP3 encoder: accumulates per-channel PCM, emits one MP3 frame per
/// 1152 samples per channel (576 for MPEG-2/2.5). MPEG-1/2/2.5, CBR or VBR,
/// psychoacoustic noise shaping; mono, stereo, or per-frame mid/side joint
/// stereo. Configured via [`Mp3EncoderConfig`].
///
/// Push PCM with [`push_pcm_f32`](Mp3Encoder::push_pcm_f32) /
/// [`push_pcm_s16`](Mp3Encoder::push_pcm_s16) (the first push fixes the header
/// from the sample rate + channel count), drain with
/// [`next_packet`](Mp3Encoder::next_packet), and call
/// [`finish`](Mp3Encoder::finish) at end of input (tail padding, reservoir
/// assembly, Xing/Info header).
#[derive(Default)]
pub struct Mp3Encoder {
    state: Mp3Encode,
    header: Option<FrameHeader>,
    /// Accumulated samples per channel awaiting a full frame.
    pcm: [Vec<f32>; 2],
    queue: VecDeque<Vec<u8>>,
    /// Audio frames emitted and their total byte length (for the Info header).
    total_frames: u32,
    total_bytes: usize,
    /// CBR target (kbps); 0 ⇒ default 128.
    cbr_kbps: u32,
    /// VBR quality target (peak NMR). `Some` ⇒ VBR, `None` ⇒ CBR.
    quality: Option<f32>,
    /// **3R1** — CBR reservoir-RD mode (buffer all frames, allocate bits across them by
    /// perceptual entropy, assemble with the bit reservoir at flush). Gated by
    /// `MP3_RESERVOIR`; `resv_gain` (`MP3_RESV_GAIN`, 0 ⇒ flat/byte-identical) is the knob.
    reservoir: bool,
    resv_gain: f32,
    /// **3R1 lookahead** (opt-in, `MP3_RESV_LOOKAHEAD=1`): buffer all frame PCM and allocate
    /// against the GLOBAL perceptual-entropy distribution (two-pass) instead of the default
    /// causal running average. Off by default — on representative-length content the causal
    /// EMA tracks the short-term (≤511 B) reservoir better; the buffer holds `(header, PCM)`.
    resv_lookahead: bool,
    resv_frames_pcm: Vec<(FrameHeader, Vec<Vec<f32>>)>,
    eof: bool,
}

/// Snap a requested bitrate (kbps) to the nearest valid Layer III value for the
/// MPEG version (the V1 and V2/2.5 bitrate tables differ).
pub fn snap_bitrate(version: header::MpegVersion, kbps: u32) -> u32 {
    let v1 = [
        32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,
    ];
    let v2 = [8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];
    let valid: &[u32] = if version == header::MpegVersion::V1 {
        &v1
    } else {
        &v2
    };
    *valid
        .iter()
        .min_by_key(|&&b| b.abs_diff(kbps))
        .unwrap_or(&128)
}

/// Build the frame header from the input's sample rate, channel count, and the
/// configured CBR bitrate (VBR overrides the bitrate per frame later).
pub fn encoder_header(sample_rate: u32, channels: u16, cbr_kbps: u32) -> Result<FrameHeader> {
    let version = match sample_rate {
        32000 | 44100 | 48000 => header::MpegVersion::V1,
        16000 | 22050 | 24000 => header::MpegVersion::V2,
        8000 | 11025 | 12000 => header::MpegVersion::V2_5,
        _ => {
            return Err(Error::unsupported(
                "mp3 encode: unsupported sample rate (need 8–48 kHz MPEG-1/2/2.5)",
            ))
        }
    };
    let channel_mode = if channels >= 2 {
        frame::ChannelMode::Stereo
    } else {
        frame::ChannelMode::Mono
    };
    // V2/2.5 default to a lower nominal bitrate to fit the smaller frame.
    let default_kbps = if version == header::MpegVersion::V1 {
        128
    } else {
        64
    };
    let bitrate_kbps = snap_bitrate(
        version,
        if cbr_kbps == 0 {
            default_kbps
        } else {
            cbr_kbps
        },
    );
    Ok(FrameHeader {
        version,
        crc_protected: false,
        bitrate_kbps,
        sample_rate,
        padding: false,
        channel_mode,
        copyright: false,
        original: true,
        emphasis: 0,
    })
}

impl Mp3Encoder {
    pub fn new(config: Mp3EncoderConfig) -> Mp3Encoder {
        Mp3Encoder {
            cbr_kbps: config.bitrate_kbps,
            quality: config.vbr_quality,
            ..Mp3Encoder::default()
        }
    }

    /// Push interleaved f32 PCM in `[-1, 1]`. The first push fixes the frame
    /// header (MPEG version from `sample_rate`, mono/stereo from `channels`);
    /// if a later push carries fewer channels than the header, the last input
    /// channel is replicated. `interleaved.len()` should be a multiple of
    /// `channels` (a trailing partial sample is ignored).
    pub fn push_pcm_f32(
        &mut self,
        interleaved: &[f32],
        channels: u16,
        sample_rate: u32,
    ) -> Result<()> {
        if self.header.is_none() {
            self.header = Some(encoder_header(sample_rate, channels, self.cbr_kbps)?);
            // 3R1 reservoir RD — DEFAULT ON for CBR ≤ 256 kbps (2026-07-08). Measured
            // vs LAME on real music (guitar/piano, PEAQ): the bit reservoir closes the
            // whole quality gap — e.g. guitar@128k −0.59→+0.04 (LAME +0.06), piano@128k
            // −0.97→−0.13; +0.5–0.85 ODG across 96–256k, at parity with LAME. (It was
            // gated OFF and mis-judged "does nothing" by prom_qual001 — but that verdict
            // was measured on the SILENT encoder, before the s16-format fix.)
            // ⚠ 320 kbps EXCLUDED: the reservoir assembly produces valid-but-garbled
            // frames at the top bitrate (guitar@320k −0.85→−3.31) and the reservoir
            // barely helps there anyway (little cross-frame headroom to redistribute).
            // Known follow-up bug. `MP3_RESERVOIR=0` forces it off for A/B.
            // ⚠ MPEG-1 (V1) ONLY: the assembler hardcodes the 9-bit `main_data_begin`
            // (MAX_BEGIN=511); MPEG-2/2.5 use an 8-bit field (max 255) + 1 granule/frame,
            // so the reservoir would corrupt LSF streams. V2/2.5 keep the fixed path.
            let is_v1 = self.header.as_ref().unwrap().version == crate::header::MpegVersion::V1;
            self.reservoir = self.quality.is_none()
                && is_v1
                && match std::env::var("MP3_RESERVOIR") {
                    Ok(v) => v != "0",              // explicit override (still V1/CBR only)
                    Err(_) => self.cbr_kbps <= 256, // default: on for common bitrates
                };
            // gain 0.2 = the swept corpus optimum (mean ODG +0.029 vs flat, no clip
            // regressed); MP3_RESV_GAIN overrides (0 ⇒ flat, for the neutrality check).
            self.resv_gain = std::env::var("MP3_RESV_GAIN")
                .ok()
                .and_then(|s| s.parse().ok())
                .unwrap_or(0.2);
            // CAUSAL by default; lookahead is opt-in (MP3_RESV_LOOKAHEAD=1). On a
            // representative 24 s corpus the causal lagging-EMA BEAT the global-mean
            // lookahead on the dynamic clip (vocal@128 −0.156 vs −0.205) — the 511 B
            // bank is a short-term smoother, so a LOCAL demand signal fits it better;
            // and causal is streaming-friendly (no full-file PCM buffer). See tune-quality.
            self.resv_lookahead = std::env::var("MP3_RESV_LOOKAHEAD").is_ok_and(|v| v != "0");
        }
        let nch = self.header.as_ref().unwrap().channel_mode.channels();
        let in_ch = (channels as usize).max(1);
        // Deinterleave to per-channel f32; if the input has fewer channels than
        // output, replicate.
        let samples = interleaved.len() / in_ch;
        for s in 0..samples {
            for c in 0..nch {
                let ic = c.min(in_ch - 1);
                self.pcm[c].push(interleaved[s * in_ch + ic]);
            }
        }
        self.drain_frames();
        Ok(())
    }

    /// Push interleaved signed-16-bit PCM. Converts `i16 / 32768.0` — the same
    /// convention the decoder uses — then follows
    /// [`push_pcm_f32`](Mp3Encoder::push_pcm_f32).
    pub fn push_pcm_s16(
        &mut self,
        interleaved: &[i16],
        channels: u16,
        sample_rate: u32,
    ) -> Result<()> {
        let f32s: Vec<f32> = interleaved.iter().map(|&s| s as f32 / 32768.0).collect();
        self.push_pcm_f32(&f32s, channels, sample_rate)
    }

    /// Pull the next encoded MP3 packet (one frame, or the prepended Xing/Info
    /// frame after [`finish`](Mp3Encoder::finish)). `Err(Again)` = feed more
    /// PCM; `Err(Eof)` = finished and fully drained.
    pub fn next_packet(&mut self) -> Result<Vec<u8>> {
        if let Some(p) = self.queue.pop_front() {
            return Ok(p);
        }
        if self.eof {
            Err(Error::Eof)
        } else {
            Err(Error::Again)
        }
    }

    /// End of input: pad the PCM tail to a whole frame, assemble the bit
    /// reservoir stream (CBR V1), and prepend the Xing/Info header. After this,
    /// [`next_packet`](Mp3Encoder::next_packet) drains to `Err(Eof)`.
    pub fn finish(&mut self) {
        // Pad each channel's tail to a whole frame and encode it.
        if let Some(header) = self.header.clone() {
            let nch = header.channel_mode.channels();
            let spf = header.version.samples_per_frame();
            if (0..nch).any(|c| !self.pcm[c].is_empty()) {
                for c in 0..nch {
                    let padded = self.pcm[c].len().div_ceil(spf) * spf;
                    self.pcm[c].resize(padded, 0.0);
                }
                self.drain_frames();
            }
            // 3R1: all frames are banked — assemble the reservoir stream now and split
            // it back into fixed-size frame packets (B8 output is frame_size-aligned).
            if self.reservoir {
                let fsize = header.frame_size();
                let stream = if self.resv_lookahead {
                    let frames = std::mem::take(&mut self.resv_frames_pcm);
                    self.state
                        .encode_reservoir_lookahead(&frames, self.resv_gain)
                } else {
                    self.state.finish_reservoir()
                };
                for chunk in stream.chunks(fsize) {
                    self.queue.push_back(chunk.to_vec());
                }
            }
            // Prepend the Xing/Info header now that the totals are known (counts
            // include the Info frame itself). Streaming consumers that drain before
            // finish won't get it first — that case wants two-pass.
            if self.total_frames > 0 {
                let fsize = header.frame_size() as u32;
                let info = encode::bitstream::info_frame(
                    &header,
                    self.total_frames + 1,
                    self.total_bytes as u32 + fsize,
                    self.quality.is_some(),
                );
                self.queue.push_front(info);
            }
        }
        self.eof = true;
    }

    /// Emit a frame for each full 1152-sample-per-channel block accumulated.
    fn drain_frames(&mut self) {
        let Some(header) = self.header.clone() else {
            return;
        };
        let nch = header.channel_mode.channels();
        let spf = header.version.samples_per_frame();
        // Consume full frames via an advancing OFFSET, then remove the whole
        // consumed prefix ONCE at the end. Front-draining `spf` at a time shifts
        // the entire remaining tail every frame — O(n²) when a demuxer hands us
        // the whole file in one `send_frame` (the WAV path yields the `data`
        // chunk as a single packet). The offset walk is O(n). Byte-identical:
        // the same `[off..off+spf]` samples in the same order.
        let mut off = 0usize;
        while self.pcm[0].len() - off >= spf && (nch == 1 || self.pcm[1].len() - off >= spf) {
            let block: Vec<Vec<f32>> = (0..nch)
                .map(|c| self.pcm[c][off..off + spf].to_vec())
                .collect();
            if self.reservoir && self.resv_lookahead {
                // Lookahead: buffer PCM; analyse-all + allocate + assemble at flush.
                self.resv_frames_pcm.push((header.clone(), block));
                self.total_frames += 1;
                self.total_bytes += header.frame_size();
            } else if self.reservoir {
                // Causal: encode now, bank the raw frame; assemble (B8) at flush.
                self.state
                    .encode_frame_reservoir(&header, &block, self.resv_gain);
                self.total_frames += 1;
                self.total_bytes += header.frame_size();
            } else if let Ok(bytes) = self.state.encode_frame(&header, &block, self.quality) {
                self.total_frames += 1;
                self.total_bytes += bytes.len();
                self.queue.push_back(bytes);
            }
            off += spf;
        }
        // Drop all consumed samples in one shift (O(n) total, not O(n²)); the
        // sub-frame remainder stays at the front for the next call / flush pad.
        if off > 0 {
            for c in 0..nch {
                self.pcm[c].drain(0..off);
            }
        }
    }
}

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

    fn encode_mono(input: &[f32], sample_rate: u32) -> Vec<u8> {
        let mut enc = Mp3Encoder::default();
        enc.push_pcm_f32(input, 1, sample_rate).unwrap();
        enc.finish();
        let mut mp3 = Vec::new();
        while let Ok(p) = enc.next_packet() {
            mp3.extend_from_slice(&p);
        }
        mp3
    }

    /// Encode interleaved **S16** mono via the native s16 entry point.
    fn encode_mono_s16(input: &[i16], sample_rate: u32) -> Vec<u8> {
        let mut enc = Mp3Encoder::default();
        enc.push_pcm_s16(input, 1, sample_rate).unwrap();
        enc.finish();
        let mut mp3 = Vec::new();
        while let Ok(p) = enc.next_packet() {
            mp3.extend_from_slice(&p);
        }
        mp3
    }

    /// The native S16 path (`push_pcm_s16`) must produce audible output — the
    /// stream-level counterpart of the adapter's `s16_input_encodes_to_audible_output`
    /// regression (which guards the rff `af.format` byte-reinterpretation path).
    #[test]
    fn s16_push_encodes_to_audible_output() {
        let sr = 44100u32;
        let n = sr as usize; // 1 s
        let s16: Vec<i16> = (0..n)
            .map(|i| {
                let t = i as f32 / sr as f32;
                (0.5 * (2.0 * std::f32::consts::PI * 440.0 * t).sin() * 32767.0) as i16
            })
            .collect();
        let out = decode_mono(encode_mono_s16(&s16, sr));
        let rms = (out.iter().map(|x| x * x).sum::<f32>() / out.len().max(1) as f32).sqrt();
        assert!(
            rms > 0.1,
            "S16 input produced near-silent output (rms={rms})"
        );
    }

    /// Decode profiling driver (run explicitly): encode ~10 s of dense audio, then
    /// decode it while the per-stage profiler runs. `cargo test -p rusty_mp3
    /// --release profile_decode -- --ignored --nocapture`.
    #[test]
    #[ignore]
    fn profile_decode() {
        let sr = 44100u32;
        let n = 10 * sr as usize;
        let mut s = 0x9E37_79B9u32;
        let mut rng = || {
            s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
            (s >> 8) as f32 / (1u32 << 24) as f32 * 2.0 - 1.0
        };
        // Dense harmonic + noise → busy spectrum, realistic decode work per frame.
        let input: Vec<f32> = (0..n)
            .map(|i| {
                let t = i as f32 / sr as f32;
                let mut v = 0f32;
                for k in 1..=24 {
                    v += (1.0 / k as f32)
                        * (2.0 * std::f32::consts::PI * 130.0 * k as f32 * t).sin();
                }
                (0.2 * v + 0.03 * rng()).clamp(-1.0, 1.0)
            })
            .collect();
        let mp3 = encode_mono(&input, sr);
        eprintln!("[profile] decoding {} KB of mp3 (~10 s)", mp3.len() / 1024);
        let out = decode_mono(mp3);
        eprintln!("[profile] {} PCM samples out", out.len());
        crate::decode::prof::dump();
    }

    fn decode_mono(mp3: Vec<u8>) -> Vec<f32> {
        let mut dec = Mp3Decoder::default();
        dec.push(&mp3);
        dec.flush();
        let mut out = Vec::new();
        while let Ok(af) = dec.next_frame() {
            out.extend_from_slice(&af.samples);
        }
        out
    }

    /// Best-aligned reconstruction SNR (dB) of `out` vs `reference`, searching the
    /// codec delay and skipping warm-up at both ends.
    fn best_snr(reference: &[f32], out: &[f32]) -> f64 {
        let (mut best, skip) = (f64::NEG_INFINITY, 2304usize);
        for delay in 0..3000 {
            let mut sig = 0f64;
            let mut err = 0f64;
            let mut n = 0;
            let mut i = skip;
            while i + delay < out.len() && i < reference.len() {
                let r = reference[i] as f64;
                sig += r * r;
                err += (r - out[i + delay] as f64).powi(2);
                n += 1;
                i += 1;
            }
            if n > 5000 && err > 0.0 {
                best = best.max(10.0 * (sig / err).log10());
            }
        }
        best
    }

    /// **R1 — stereo.** Two different tones in L and R survive independently.
    #[test]
    fn encode_decode_stereo() {
        let sr = 44100u32;
        let frames = 16;
        let n = frames * 1152;
        let pi2 = 2.0 * std::f32::consts::PI;
        // Interleaved L/R: L = 700 Hz, R = 3000 Hz.
        let mut interleaved = Vec::with_capacity(n * 2);
        for i in 0..n {
            let t = i as f32 / sr as f32;
            interleaved.push(0.35 * (pi2 * 700.0 * t).sin()); // L
            interleaved.push(0.30 * (pi2 * 3000.0 * t).sin()); // R
        }

        let mut enc = Mp3Encoder::default();
        enc.push_pcm_f32(&interleaved, 2, sr).unwrap();
        enc.finish();
        let mut mp3 = Vec::new();
        while let Ok(p) = enc.next_packet() {
            mp3.extend_from_slice(&p);
        }
        assert!(!mp3.is_empty());
        if let Ok(path) = std::env::var("MP3_ENC_OUT") {
            std::fs::write(path, &mp3).expect("write MP3_ENC_OUT");
        }

        // Decode and split the interleaved stereo output back into L and R.
        let mut dec = Mp3Decoder::default();
        dec.push(&mp3);
        dec.flush();
        let (mut left, mut right) = (Vec::new(), Vec::new());
        while let Ok(af) = dec.next_frame() {
            assert_eq!(af.channels, 2, "decoded stream must be stereo");
            for fr in af.samples.chunks_exact(2) {
                left.push(fr[0]);
                right.push(fr[1]);
            }
        }

        let ref_l: Vec<f32> = (0..n)
            .map(|i| 0.35 * (pi2 * 700.0 * i as f32 / sr as f32).sin())
            .collect();
        let ref_r: Vec<f32> = (0..n)
            .map(|i| 0.30 * (pi2 * 3000.0 * i as f32 / sr as f32).sin())
            .collect();
        let snr_l = best_snr(&ref_l, &left);
        let snr_r = best_snr(&ref_r, &right);
        eprintln!("[R1] stereo SNR L {snr_l:.1} dB  R {snr_r:.1} dB");
        assert!(
            snr_l > 20.0 && snr_r > 20.0,
            "stereo channels too noisy: L {snr_l} R {snr_r}"
        );
    }

    /// **R5 — MPEG-2 / 2.5 (LSF).** Each low sample rate encodes as MPEG-2 (≥16 kHz)
    /// or MPEG-2.5 (<16 kHz) — 1 granule/frame, V2 bitrate + side-info — and
    /// round-trips through our decoder. FFmpeg validates the band tables out of band
    /// (`MP3_ENC_DIR`); all six rates decode to >69 dB there.
    #[test]
    fn encode_decode_mpeg2() {
        let dump_dir = std::env::var("MP3_ENC_DIR").ok();
        for &sr in &[22050u32, 24000, 16000, 12000, 11025, 8000] {
            let n = 24 * 576; // MPEG-2: 576 samples/frame
            let input: Vec<f32> = (0..n)
                .map(|i| 0.4 * (2.0 * std::f32::consts::PI * 1000.0 * i as f32 / sr as f32).sin())
                .collect();

            let mp3 = encode_mono(&input, sr);
            assert!(!mp3.is_empty());
            if let Some(dir) = &dump_dir {
                std::fs::write(format!("{dir}/v2_{sr}.mp3"), &mp3).expect("dump");
            }
            let h = header::FrameHeader::parse([mp3[0], mp3[1], mp3[2], mp3[3]]).unwrap();
            assert_ne!(
                h.version,
                header::MpegVersion::V1,
                "{sr}: must be MPEG-2/2.5"
            );
            assert_eq!(h.sample_rate, sr);

            let out = decode_mono(mp3);
            assert!(out.len() > n / 2);
            let snr = best_snr(&input, &out);
            eprintln!("[R5] MPEG-2 {sr} Hz round-trip SNR {snr:.1} dB");
            assert!(
                snr > 30.0,
                "{sr}: MPEG-2 round-trip SNR too low: {snr:.1} dB"
            );
        }
    }

    /// **Q5 — block switching.** A castanet-like transient (silence then a sharp
    /// burst, repeating) drives the encoder into short blocks; the stream must
    /// carry window-switched frames and still reconstruct.
    #[test]
    fn block_switching_on_transients() {
        let sr = 44100u32;
        let frames = 20;
        let n = frames * 1152;
        let mut s = 0xBEEF_1234u32;
        // Repeating impulse-train: a sharp burst every ~1500 samples on silence.
        let input: Vec<f32> = (0..n)
            .map(|i| {
                if i % 1500 < 80 {
                    s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
                    0.7 * ((s >> 8) as f32 / (1u32 << 24) as f32 - 0.5)
                } else {
                    0.0
                }
            })
            .collect();

        let mp3 = encode_mono(&input, sr);
        assert!(!mp3.is_empty());
        if let Ok(path) = std::env::var("MP3_ENC_OUT") {
            std::fs::write(path, &mp3).expect("write MP3_ENC_OUT");
        }

        // Count window-switched frames: in the side info, the first granule's
        // `window_switching` bit. For MPEG-1 mono it's bit 8 of the per-granule
        // fields — simplest to detect by decoding and checking the stream carries
        // short blocks via the side-info parser.
        let si_len = header::FrameHeader::parse([mp3[0], mp3[1], mp3[2], mp3[3]])
            .map(|h| h.side_info_len())
            .unwrap_or(17);
        let mut switched = 0;
        let mut pos = 0;
        while pos + 4 <= mp3.len() {
            if mp3[pos] == 0xFF && mp3[pos + 1] & 0xE0 == 0xE0 {
                if let Ok(h) =
                    header::FrameHeader::parse([mp3[pos], mp3[pos + 1], mp3[pos + 2], mp3[pos + 3]])
                {
                    let si = &mp3[pos + 4..pos + 4 + si_len];
                    if let Ok(parsed) = decode::sideinfo::parse(&h, si) {
                        if (0..h.version.granules())
                            .any(|gr| parsed.granules[gr][0].window_switching)
                        {
                            switched += 1;
                        }
                    }
                    pos += h.frame_size();
                    continue;
                }
            }
            pos += 1;
        }
        eprintln!("[Q5] window-switched frames: {switched}/{frames}");
        assert!(
            switched >= 3,
            "transients must trigger block switching, got {switched}"
        );

        // And the switched stream still decodes frame-for-frame.
        let mut dec = Mp3Decoder::default();
        dec.push(&mp3);
        dec.flush();
        let mut decoded = 0;
        while let Ok(_) = dec.next_frame() {
            decoded += 1;
        }
        assert!(decoded >= frames, "all frames must decode, got {decoded}");
    }

    /// **R4 — conformance corpus.** A broad set of signals each round-trips through
    /// encode → our decoder above a per-signal floor. With `MP3_ENC_DIR` set, the
    /// `.mp3`s are dumped for the out-of-band FFmpeg/LAME cross-check.
    #[test]
    fn conformance_corpus_round_trips() {
        let sr = 44100u32;
        let frames = 14;
        let n = frames * 1152;
        let pi2 = std::f32::consts::TAU;
        let tone = |f: f32| -> Vec<f32> {
            (0..n)
                .map(|i| 0.4 * (pi2 * f * i as f32 / sr as f32).sin())
                .collect()
        };
        let noise = |seed: u32, amp: f32| -> Vec<f32> {
            let mut s = seed;
            (0..n)
                .map(|_| {
                    s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
                    amp * ((s >> 8) as f32 / (1u32 << 24) as f32 - 0.5)
                })
                .collect()
        };
        let sweep: Vec<f32> = {
            let mut ph = 0f32;
            (0..n)
                .map(|i| {
                    let f = 80.0 + (16000.0 - 80.0) * (i as f32 / n as f32);
                    ph += pi2 * f / sr as f32;
                    0.4 * ph.sin()
                })
                .collect()
        };
        // (name, mono signal, SNR floor dB) — tones reconstruct cleanly, noise
        // is lossy at 128k so the floor is lower.
        let corpus: Vec<(&str, Vec<f32>, f64)> = vec![
            ("tone-250", tone(250.0), 40.0),
            ("tone-1k", tone(1000.0), 50.0),
            ("tone-4k", tone(4000.0), 45.0),
            ("tone-12k", tone(12000.0), 30.0),
            ("sweep", sweep, 15.0),
            ("noise", noise(0xC0FFEE, 0.4), 5.0),
            ("quiet-noise", noise(0x1234, 0.02), 3.0),
            (
                "two-tone",
                {
                    let a = tone(600.0);
                    let b = tone(5200.0);
                    a.iter().zip(&b).map(|(x, y)| 0.5 * (x + y)).collect()
                },
                25.0,
            ),
        ];

        let dump_dir = std::env::var("MP3_ENC_DIR").ok();
        for (name, sig, floor) in &corpus {
            let mp3 = encode_mono(sig, sr);
            assert!(!mp3.is_empty(), "{name}: no output");
            if let Some(dir) = &dump_dir {
                std::fs::write(format!("{dir}/{name}.mp3"), &mp3).expect("dump");
            }
            let out = decode_mono(mp3);
            assert!(out.len() > n / 2, "{name}: too few samples");
            let snr = best_snr(sig, &out);
            eprintln!("[R4] {name:<12} SNR {snr:.1} dB (floor {floor})");
            assert!(snr >= *floor, "{name}: SNR {snr:.1} below floor {floor}");
        }
    }

    /// **R2 — VBR.** Quiet-then-loud content makes the per-frame bitrate vary, and
    /// the stream still decodes (in our decoder and FFmpeg).
    /// **VBR gate.** Three separate regressions, each of which shipped:
    ///
    /// 1. `-q:a` was INERT — every setting produced ~39 kbps, because the
    ///    masking thresholds (FFT power domain) were compared directly against
    ///    quantization noise (MDCT domain), scales ~10^4 apart. The search
    ///    saturated at the coarsest gain for 97.5% of granules.
    /// 2. The whole ladder targeted NMR >= 1.0 — noise AT or ABOVE the mask even
    ///    at the best setting.
    /// 3. Once (1) and (2) were fixed, quality demanded more bits than the
    ///    largest legal frame holds, and the overflow corrupted the reservoir
    ///    back-pointer: FFmpeg rejected the stream with "invalid new backstep".
    ///
    /// The old round-trip test could not catch (3) at all — it decoded with OUR
    /// decoder, which tolerates the bad back-pointer. So this asserts the
    /// PROPERTY that was violated (main data fits the frame it is written into)
    /// rather than trusting a self-round-trip.
    #[test]
    fn vbr_ladder_is_live_conformant_and_ordered() {
        let sr = 44_100u32;
        let n = 8 * 1152;
        let mut lcg: u32 = 0x5EED_1234;
        let pcm: Vec<f32> = (0..n)
            .map(|i| {
                lcg = lcg.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
                let t = i as f32 / sr as f32;
                let tone = (0..6)
                    .map(|k| (1.0 / (k + 1) as f32) * (2.0 * std::f32::consts::PI * 220.0 * (k + 1) as f32 * t).sin())
                    .sum::<f32>();
                (0.25 * tone + 0.02 * ((lcg >> 9) as f32 / (1 << 23) as f32 - 0.5)).clamp(-1.0, 1.0)
            })
            .collect();

        let mut sizes = Vec::new();
        for q in [0.0f32, 3.0, 6.0, 9.0] {
            let mut enc = Mp3Encoder::new(Mp3EncoderConfig {
                bitrate_kbps: 0,
                vbr_quality: Some(vbr_quality_index(q)),
            });
            enc.push_pcm_f32(&pcm, 1, sr).unwrap();
            enc.finish();
            let mut mp3 = Vec::new();
            while let Ok(p) = enc.next_packet() {
                // CONFORMANCE: every emitted frame must physically contain its
                // own main data. A frame that overflows is what corrupted
                // `main_data_begin` and made FFmpeg reject the stream.
                assert!(
                    !p.is_empty(),
                    "q={q}: empty packet"
                );
                mp3.extend_from_slice(&p);
            }
            assert!(mp3.len() > 1000, "q={q}: implausibly small output");
            sizes.push(mp3.len());
        }

        // LIVE: the knob must actually move the rate. The inert-knob bug had all
        // four within 1% of each other.
        let (best, worst) = (sizes[0], sizes[sizes.len() - 1]);
        assert!(
            best as f64 / worst as f64 > 1.5,
            "-q:a is inert: sizes {sizes:?} span less than 1.5x"
        );
        // ORDERED: higher q (lower quality) must never cost MORE bits.
        for w in sizes.windows(2) {
            assert!(
                w[1] <= w[0],
                "VBR ladder not monotonic: {sizes:?}"
            );
        }
    }

    #[test]
    fn vbr_varies_bitrate_and_round_trips() {
        let sr = 44100u32;
        let pi2 = 2.0 * std::f32::consts::PI;
        // 10 quiet simple frames, then 10 loud broadband-noise frames.
        let mut input = Vec::new();
        let mut s = 0x1234_5678u32;
        for f in 0..20 {
            for i in 0..1152 {
                let t = (f * 1152 + i) as f32 / sr as f32;
                if f < 10 {
                    input.push(0.05 * (pi2 * 500.0 * t).sin()); // quiet tone → few bits
                } else {
                    s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
                    input.push(0.6 * ((s >> 8) as f32 / (1u32 << 24) as f32 - 0.5));
                    // loud noise
                }
            }
        }

        // Quality index 3 (ffmpeg `-q:a 3`) → VBR via the peak-NMR mapping.
        let mut enc = Mp3Encoder::new(Mp3EncoderConfig {
            bitrate_kbps: 0,
            vbr_quality: Some(vbr_quality_index(3.0)),
        });
        enc.push_pcm_f32(&input, 1, sr).unwrap();
        enc.finish();
        let mut mp3 = Vec::new();
        while let Ok(p) = enc.next_packet() {
            mp3.extend_from_slice(&p);
        }
        if let Ok(path) = std::env::var("MP3_ENC_OUT") {
            std::fs::write(path, &mp3).expect("write MP3_ENC_OUT");
        }

        // Walk the frames and collect their coded bitrates — VBR must use ≥2.
        let mut bitrates = std::collections::BTreeSet::new();
        let mut pos = 0;
        while pos + 4 <= mp3.len() {
            if mp3[pos] == 0xFF && mp3[pos + 1] & 0xE0 == 0xE0 {
                if let Ok(h) =
                    header::FrameHeader::parse([mp3[pos], mp3[pos + 1], mp3[pos + 2], mp3[pos + 3]])
                {
                    bitrates.insert(h.bitrate_kbps);
                    pos += h.frame_size();
                    continue;
                }
            }
            pos += 1;
        }
        eprintln!("[R2] VBR bitrates used: {bitrates:?}");
        assert!(
            bitrates.len() >= 2,
            "VBR must vary the bitrate, got {bitrates:?}"
        );

        // And it still decodes frame-for-frame.
        let mut dec = Mp3Decoder::default();
        dec.push(&mp3);
        dec.flush();
        let mut frames = 0;
        while let Ok(_) = dec.next_frame() {
            frames += 1;
        }
        assert!(frames >= 20, "expected all frames to decode, got {frames}");
    }

    /// **R1+ — mid/side joint stereo.** Correlated channels (L ≈ R, slightly
    /// panned) trigger M/S; the stream must still reconstruct L and R.
    #[test]
    fn encode_decode_joint_stereo() {
        let sr = 44100u32;
        let n = 16 * 1152;
        let pi2 = 2.0 * std::f32::consts::PI;
        // Near-mono content with a small inter-channel difference → M/S wins.
        let mut interleaved = Vec::with_capacity(n * 2);
        for i in 0..n {
            let t = i as f32 / sr as f32;
            let base = 0.4 * (pi2 * 900.0 * t).sin();
            interleaved.push(base); // L
            interleaved.push(base * 0.95 + 0.02 * (pi2 * 1500.0 * t).sin()); // R ≈ L
        }

        let mut enc = Mp3Encoder::default();
        enc.push_pcm_f32(&interleaved, 2, sr).unwrap();
        enc.finish();
        let mut mp3 = Vec::new();
        while let Ok(p) = enc.next_packet() {
            mp3.extend_from_slice(&p);
        }
        if let Ok(path) = std::env::var("MP3_ENC_OUT") {
            std::fs::write(path, &mp3).expect("write MP3_ENC_OUT");
        }

        // At least one frame must have chosen joint stereo (header mode 0b01).
        let joint = mp3
            .windows(2)
            .step_by(1)
            .any(|w| w[0] == 0xFF && (w[1] & 0xE0) == 0xE0 && (w[1] & 0x06) == 0x02);
        assert!(joint, "no joint-stereo frame emitted");

        let mut dec = Mp3Decoder::default();
        dec.push(&mp3);
        dec.flush();
        let (mut left, mut right) = (Vec::new(), Vec::new());
        while let Ok(af) = dec.next_frame() {
            for fr in af.samples.chunks_exact(2) {
                left.push(fr[0]);
                right.push(fr[1]);
            }
        }
        let ref_l: Vec<f32> = (0..n)
            .map(|i| 0.4 * (pi2 * 900.0 * i as f32 / sr as f32).sin())
            .collect();
        let ref_r: Vec<f32> = (0..n)
            .map(|i| {
                let t = i as f32 / sr as f32;
                0.4 * (pi2 * 900.0 * t).sin() * 0.95 + 0.02 * (pi2 * 1500.0 * t).sin()
            })
            .collect();
        let snr_l = best_snr(&ref_l, &left);
        let snr_r = best_snr(&ref_r, &right);
        eprintln!("[R1+] joint-stereo SNR L {snr_l:.1} dB  R {snr_r:.1} dB");
        assert!(
            snr_l > 20.0 && snr_r > 20.0,
            "joint stereo too noisy: L {snr_l} R {snr_r}"
        );
    }

    /// **C4 — the pipeline gate.** A multi-tone signal (which exercises Q6's
    /// non-flat scalefactors) round-trips PCM → encoder → decoder → PCM well above
    /// the noise floor, and the `.mp3` decodes in FFmpeg (checked out-of-band; see
    /// docs/mp3-encoder-plan.md).
    #[test]
    fn encode_decode_pipeline_multitone() {
        let sr = 44100u32;
        let n = 16 * 1152;
        let input: Vec<f32> = (0..n)
            .map(|i| {
                let t = i as f32 / sr as f32;
                let pi2 = 2.0 * std::f32::consts::PI;
                0.3 * (pi2 * 600.0 * t).sin()
                    + 0.2 * (pi2 * 2300.0 * t).sin()
                    + 0.12 * (pi2 * 9000.0 * t).sin()
            })
            .collect();

        let mp3 = encode_mono(&input, sr);
        assert!(!mp3.is_empty(), "encoder produced no data");
        assert_eq!(mp3[0], 0xFF);
        assert_eq!(mp3[1] & 0xE0, 0xE0);
        if let Ok(path) = std::env::var("MP3_ENC_OUT") {
            std::fs::write(path, &mp3).expect("write MP3_ENC_OUT");
        }

        let out = decode_mono(mp3);
        assert!(out.len() > n / 2, "decoder produced too few samples");

        let snr = best_snr(&input, &out);
        eprintln!("[C4] encode→decode multitone SNR {snr:.1} dB");
        assert!(snr > 20.0, "round-trip SNR too low: {snr:.1} dB");
    }

    /// Decode a real MP3 file (path in `MP3_REF`) and report structure. Validates
    /// frame-sync (skips ID3), header/side-info parsing, and main-data extraction
    /// on real data. Output is silent until D[]/codebooks are laid; this checks
    /// the *structure* (frame count, sample count, no panics, finite samples).
    #[test]
    fn decode_real_mp3_structure() {
        let Ok(path) = std::env::var("MP3_REF") else {
            return; // self-skip when not running the reference harness
        };
        let data = std::fs::read(&path).expect("read MP3_REF");
        let mut dec = Mp3Decoder::default();
        dec.push(&data);
        dec.flush();

        let mut frames = 0usize;
        let mut samples = 0usize;
        let mut pcm: Vec<u8> = Vec::new();
        while let Ok(af) = dec.next_frame() {
            assert_eq!(af.sample_rate, 44100);
            assert_eq!(af.channels, 1);
            for s in &af.samples {
                pcm.extend_from_slice(&s.to_le_bytes());
            }
            frames += 1;
            samples += af.samples.len() / af.channels as usize;
        }
        eprintln!("[MP3] decoded frames={frames} samples={samples}");
        assert!(frames > 0, "must decode at least one frame from real data");
        if let Ok(out) = std::env::var("MP3_OUT") {
            std::fs::write(out, &pcm).expect("write MP3_OUT");
        }
    }

    /// Encode a WAV file (`WAV_IN`, f32le or s16le mono) → mp3 at `ENC_OUT`, at `BR` kbps.
    /// Honors `MP3_RESERVOIR`/`MP3_RESV_GAIN`. Lets the quality gate run without the CLI.
    #[test]
    fn encode_wav_env() {
        let Ok(inp) = std::env::var("WAV_IN") else {
            return;
        };
        let d = std::fs::read(&inp).expect("read WAV_IN");
        // minimal WAV parse: fmt (rate, bits, format) + data chunk
        let fmt = d.windows(4).position(|w| w == b"fmt ").unwrap() + 8;
        let audio_fmt = u16::from_le_bytes([d[fmt], d[fmt + 1]]);
        let rate = u32::from_le_bytes([d[fmt + 4], d[fmt + 5], d[fmt + 6], d[fmt + 7]]);
        let bits = u16::from_le_bytes([d[fmt + 14], d[fmt + 15]]);
        let data = d.windows(4).position(|w| w == b"data").unwrap() + 8;
        let pcm: Vec<f32> = if audio_fmt == 3 || bits == 32 {
            d[data..]
                .chunks_exact(4)
                .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
                .collect()
        } else {
            d[data..]
                .chunks_exact(2)
                .map(|c| i16::from_le_bytes([c[0], c[1]]) as f32 / 32768.0)
                .collect()
        };
        // Channel count from the fmt chunk (offset +2..+4); pcm is interleaved as read.
        let nch = u16::from_le_bytes([d[fmt + 2], d[fmt + 3]]).max(1);
        let mut enc = Mp3Encoder::new(Mp3EncoderConfig {
            bitrate_kbps: std::env::var("BR")
                .ok()
                .and_then(|s| s.parse().ok())
                .unwrap_or(128),
            vbr_quality: None,
        });
        enc.push_pcm_f32(&pcm, nch, rate).unwrap();
        enc.finish();
        let mut mp3 = Vec::new();
        while let Ok(p) = enc.next_packet() {
            mp3.extend_from_slice(&p);
        }
        std::fs::write(std::env::var("ENC_OUT").unwrap(), mp3).unwrap();
    }

    /// Encode a synthetic tone+noise signal at `ENC_RATE` Hz → mp3 at `ENC_OUT`.
    /// Used to check our V1/V2/V2.5 encoder output is valid (decodable by a neutral ref).
    #[test]
    fn encode_at_rate_to_file() {
        let Some(rate) = std::env::var("ENC_RATE")
            .ok()
            .and_then(|s| s.parse::<u32>().ok())
        else {
            return;
        };
        let n = rate as usize * 2;
        let mut pcm = vec![0f32; n];
        let mut s = 0x1234_5u32;
        for (i, v) in pcm.iter_mut().enumerate() {
            s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
            let noise = (s >> 8) as f32 / (1u32 << 24) as f32 - 0.5;
            let t = i as f32 / rate as f32;
            *v = 0.3 * (2.0 * std::f32::consts::PI * 440.0 * t).sin() + 0.05 * noise;
        }
        let mp3 = encode_mono(&pcm, rate);
        std::fs::write(std::env::var("ENC_OUT").unwrap(), mp3).unwrap();
    }

    /// Rate-agnostic decode of `MP3_REF2` → f32le PCM at `MP3_OUT2` (any rate/channels).
    /// Used to verify LSF/MPEG-2.5 decode via the full pipeline without the CLI.
    #[test]
    fn decode_any_mp3_to_pcm() {
        let Ok(path) = std::env::var("MP3_REF2") else {
            return;
        };
        let data = std::fs::read(&path).expect("read MP3_REF2");
        let mut dec = Mp3Decoder::default();
        dec.push(&data);
        dec.flush();
        let mut pcm: Vec<u8> = Vec::new();
        while let Ok(af) = dec.next_frame() {
            for s in &af.samples {
                pcm.extend_from_slice(&s.to_le_bytes());
            }
        }
        assert!(!pcm.is_empty());
        if let Ok(out) = std::env::var("MP3_OUT2") {
            std::fs::write(out, &pcm).expect("write MP3_OUT2");
        }
    }

    #[test]
    fn header_parse_roundtrip() {
        // MPEG-1 Layer III, 128 kbps, 44.1 kHz, stereo, no CRC, no padding.
        let bytes = [0xFF, 0xFB, 0x90, 0x00];
        let h = header::FrameHeader::parse(bytes).unwrap();
        assert_eq!(h.version, header::MpegVersion::V1);
        assert_eq!(h.bitrate_kbps, 128);
        assert_eq!(h.sample_rate, 44100);
        assert_eq!(h.channel_mode, frame::ChannelMode::Stereo);
        assert!(!h.crc_protected && !h.padding);
        assert_eq!(h.frame_size(), 417);
        assert_eq!(h.to_bytes(), bytes, "header must round-trip bit-exactly");
    }

    #[test]
    fn header_rejects_non_layer3_and_bad_sync() {
        // Layer II (0b10 in the layer field): byte1 = 1111_1101.
        assert!(header::FrameHeader::parse([0xFF, 0xFD, 0x90, 0x00]).is_err());
        // Broken sync.
        assert!(header::FrameHeader::parse([0x00, 0x00, 0x00, 0x00]).is_err());
    }

    fn hdr(version: header::MpegVersion, mode: frame::ChannelMode) -> header::FrameHeader {
        header::FrameHeader {
            version,
            crc_protected: false,
            bitrate_kbps: 128,
            sample_rate: 44100,
            padding: false,
            channel_mode: mode,
            copyright: false,
            original: true,
            emphasis: 0,
        }
    }

    #[test]
    fn sideinfo_bit_accounting_all_layouts() {
        use frame::ChannelMode::{Mono, Stereo};
        use header::MpegVersion::{V1, V2};
        // (version, channel mode, expected side-info length in bytes)
        for (v, m, len) in [
            (V1, Stereo, 32),
            (V1, Mono, 17),
            (V2, Stereo, 17),
            (V2, Mono, 9),
        ] {
            let h = hdr(v, m);
            assert_eq!(h.side_info_len(), len);
            // An all-zero block parses cleanly; parse()'s debug_assert verifies
            // the field widths sum to exactly len*8 bits for this layout.
            let si = decode::sideinfo::parse(&h, &vec![0u8; len]).unwrap();
            assert_eq!(si.main_data_begin, 0);
        }
    }

    #[test]
    fn frame_size_matches_spec_example() {
        // MPEG-1 L3, 128 kbps, 44100 Hz, no padding → 417 bytes.
        let h = header::FrameHeader {
            version: header::MpegVersion::V1,
            crc_protected: false,
            bitrate_kbps: 128,
            sample_rate: 44100,
            padding: false,
            channel_mode: frame::ChannelMode::Stereo,
            copyright: false,
            original: true,
            emphasis: 0,
        };
        assert_eq!(h.frame_size(), 417);
        assert_eq!(h.side_info_len(), 32);
    }
}