mp3rgain 3.7.0

Lossless MP3 volume adjustment - a modern mp3gain replacement written in Rust
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
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
//! ReplayGain analysis module
//!
//! This module implements the ReplayGain 1.0 algorithm for calculating
//! the perceived loudness of audio tracks. The algorithm uses:
//!
//! 1. Equal-loudness filter (ITU-R BS.468 / A-weighting approximation)
//! 2. RMS calculation in 50ms windows
//! 3. 95th percentile statistical analysis
//!
//! Supports both MP3 and AAC/M4A files when compiled with the replaygain feature.
//!
//! Reference: https://wiki.hydrogenaud.io/index.php?title=ReplayGain_specification

use crate::error::{Error, Result};
use std::path::Path;
use std::sync::atomic::AtomicBool;

#[cfg(feature = "replaygain")]
use std::sync::atomic::{AtomicU64, Ordering};
#[cfg(feature = "replaygain")]
use std::sync::Arc;

#[cfg(feature = "replaygain")]
use symphonia::core::audio::{Audio, GenericAudioBufferRef};
#[cfg(feature = "replaygain")]
use symphonia::core::codecs::audio::{AudioDecoderOptions, CODEC_ID_NULL_AUDIO};
#[cfg(feature = "replaygain")]
use symphonia::core::formats::probe::Hint;
#[cfg(feature = "replaygain")]
use symphonia::core::formats::FormatOptions;
#[cfg(feature = "replaygain")]
use symphonia::core::io::{MediaSource, MediaSourceStream};
#[cfg(feature = "replaygain")]
use symphonia::core::meta::MetadataOptions;

/// ReplayGain reference level in dB SPL
/// Original mp3gain uses 89 dB (ReplayGain 1.0)
pub const REPLAYGAIN_REFERENCE_DB: f64 = 89.0;

/// Pink noise reference calibration constant
/// This is the loudness value produced by the ReplayGain algorithm when analyzing
/// the standard -14 dB FS pink noise reference signal. All loudness measurements
/// are compared against this reference to calculate the required gain adjustment.
/// Source: https://replaygain.hydrogenaud.io/calibration.html
const PINK_REF: f64 = 64.82;

/// ReplayGain 2.0 reference level in LUFS. This is the same perceived level
/// as the 89 dB SPL reference of ReplayGain 1.0, expressed on the BS.1770
/// scale — only the measurement algorithm differs between the two modes.
pub const RG2_REFERENCE_LUFS: f64 = -18.0;

/// EBU R128 broadcast target level in LUFS.
pub const R128_REFERENCE_LUFS: f64 = -23.0;

/// Loudness measurement algorithm used for gain calculation (issue #269).
///
/// [`Rg1`](AnalysisMode::Rg1) is the default and reproduces mp3gain's values
/// exactly; the BS.1770-based modes are strictly opt-in.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AnalysisMode {
    /// ReplayGain 1.0 (mp3gain-compatible, 89 dB SPL reference).
    #[default]
    Rg1,
    /// ReplayGain 2.0: BS.1770 integrated loudness, -18 LUFS reference.
    Rg2,
    /// EBU R128: BS.1770 integrated loudness, -23 LUFS target.
    R128,
}

impl AnalysisMode {
    /// Target level in LUFS for the BS.1770-based modes; `None` for RG1.
    pub fn target_lufs(&self) -> Option<f64> {
        match self {
            AnalysisMode::Rg1 => None,
            AnalysisMode::Rg2 => Some(RG2_REFERENCE_LUFS),
            AnalysisMode::R128 => Some(R128_REFERENCE_LUFS),
        }
    }

    /// Unit label for loudness values measured in this mode.
    pub fn unit(&self) -> &'static str {
        if self.target_lufs().is_some() {
            "LUFS"
        } else {
            "dB"
        }
    }

    /// Value for the `REPLAYGAIN_ALGORITHM` tag, or `None` when the mode needs
    /// no tag. Suggested by skamp on the Hydrogenaudio mp3rgain thread.
    ///
    /// [`Rg1`](AnalysisMode::Rg1) writes nothing: every mp3gain-era file in
    /// existence carries untagged classic values, so an absent tag already
    /// means "classic" and adding one would gratuitously diverge from
    /// mp3gain's output. `ITU-R BS.1770` is the string foobar2000 writes for
    /// the RG2 measurement; R128 shares it because the measurement is the
    /// same and only the target level differs.
    pub fn algorithm_tag(&self) -> Option<&'static str> {
        match self {
            AnalysisMode::Rg1 => None,
            AnalysisMode::Rg2 | AnalysisMode::R128 => Some("ITU-R BS.1770"),
        }
    }

    /// Lowercase short name (`"rg1"` / `"rg2"` / `"r128"`) for machine-readable
    /// output, following the [`Channel::name`](crate::Channel::name) convention.
    pub fn name(&self) -> &'static str {
        match self {
            AnalysisMode::Rg1 => "rg1",
            AnalysisMode::Rg2 => "rg2",
            AnalysisMode::R128 => "r128",
        }
    }
}

impl std::fmt::Display for AnalysisMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AnalysisMode::Rg1 => f.write_str("ReplayGain 1.0"),
            AnalysisMode::Rg2 => f.write_str("ReplayGain 2.0"),
            AnalysisMode::R128 => f.write_str("EBU R128"),
        }
    }
}

/// Audio file type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AudioFileType {
    /// MP3 file
    Mp3,
    /// AAC in an MP4/M4A container
    Aac,
    /// Raw ADTS AAC stream, typically `.aac` (issue #330). Same bitstream as
    /// [`Self::Aac`], but with no container to hold metadata, so the tags go
    /// into ID3v2.
    Adts,
}

impl AudioFileType {
    /// Classify `path` by container, matching the dispatch every apply / tag
    /// path uses (AAC for an MP4 carrying AAC audio, ADTS for a raw AAC
    /// stream, MP3 otherwise).
    pub fn from_path(path: &Path) -> Self {
        if crate::mp4meta::is_aac_file(path) {
            return AudioFileType::Aac;
        }
        #[cfg(feature = "aac")]
        if crate::adts::is_adts_file(path) {
            return AudioFileType::Adts;
        }
        AudioFileType::Mp3
    }

    /// Whether the file's audio is AAC, in either container. The bitstream
    /// side (`global_gain` scanning, the saturating apply, no per-channel
    /// gain) is identical for both; only metadata differs.
    pub fn is_aac_bitstream(self) -> bool {
        matches!(self, AudioFileType::Aac | AudioFileType::Adts)
    }
}

impl std::fmt::Display for AudioFileType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AudioFileType::Mp3 => f.write_str("MP3"),
            AudioFileType::Aac => f.write_str("AAC"),
            AudioFileType::Adts => f.write_str("AAC (ADTS)"),
        }
    }
}

/// Result of ReplayGain analysis for a single track
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ReplayGainResult {
    loudness_db: f64,
    gain_db: f64,
    peak: f64,
    sample_rate: u32,
    file_type: AudioFileType,
    #[cfg_attr(feature = "serde", serde(default))]
    analysis_mode: AnalysisMode,
    /// Whether `peak` is a BS.1770-4 Annex 2 true peak rather than the
    /// decoded sample peak (issue #292).
    #[cfg_attr(feature = "serde", serde(default))]
    true_peak: bool,
}

impl ReplayGainResult {
    #[allow(dead_code)]
    pub(crate) fn new(
        loudness_db: f64,
        gain_db: f64,
        peak: f64,
        sample_rate: u32,
        file_type: AudioFileType,
        analysis_mode: AnalysisMode,
    ) -> Self {
        Self {
            loudness_db,
            gain_db,
            peak,
            sample_rate,
            file_type,
            analysis_mode,
            true_peak: false,
        }
    }

    /// Build a result from stored `REPLAYGAIN_*` tags instead of analysis
    /// (`-s R`, issue #298). Loudness is derived from the gain relative to
    /// the mode's target; `sample_rate` is unknown and reported as 0.
    pub fn from_stored_tags(
        gain_db: f64,
        peak: f64,
        file_type: AudioFileType,
        analysis_mode: AnalysisMode,
    ) -> Self {
        let target = analysis_mode
            .target_lufs()
            .unwrap_or(REPLAYGAIN_REFERENCE_DB);
        Self {
            loudness_db: target - gain_db,
            gain_db,
            peak,
            sample_rate: 0,
            file_type,
            analysis_mode,
            true_peak: false,
        }
    }

    /// Measured loudness: the RG1 histogram value in [`AnalysisMode::Rg1`],
    /// or the BS.1770 integrated loudness in LUFS in the other modes.
    pub fn loudness_db(&self) -> f64 {
        self.loudness_db
    }
    pub fn gain_db(&self) -> f64 {
        self.gain_db
    }
    pub fn peak(&self) -> f64 {
        self.peak
    }
    pub fn sample_rate(&self) -> u32 {
        self.sample_rate
    }
    pub fn file_type(&self) -> AudioFileType {
        self.file_type
    }
    pub fn analysis_mode(&self) -> AnalysisMode {
        self.analysis_mode
    }

    /// `true` when [`peak`](Self::peak) is a BS.1770-4 Annex 2 true peak
    /// (measured with [`TrackAnalysisOptions::true_peak`] in a BS.1770
    /// mode) rather than the decoded sample peak (issue #292).
    pub fn is_true_peak(&self) -> bool {
        self.true_peak
    }

    /// Integrated loudness in LUFS when measured with a BS.1770-based mode;
    /// `None` for [`AnalysisMode::Rg1`].
    pub fn loudness_lufs(&self) -> Option<f64> {
        self.analysis_mode.target_lufs().map(|_| self.loudness_db)
    }

    /// Convert gain in dB to MP3 gain steps (1.5 dB per step)
    pub fn gain_steps(&self) -> i32 {
        crate::gain::db_to_steps(self.gain_db)
    }

    /// Return a copy of this result with `peak` overwritten. Used by
    /// frontends that have applied (or undone) gain on the file and
    /// need the cached analysis to reflect the file's new peak for
    /// subsequent clipping checks (issues #171, #172). `gain_db` is
    /// not touched — the caller can decide whether to re-analyze or
    /// keep the original target value.
    pub fn with_peak(mut self, peak: f64) -> Self {
        self.peak = peak;
        self
    }
}

impl std::fmt::Display for ReplayGainResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:+.2} dB (peak: {:.6})", self.gain_db, self.peak)
    }
}

/// Result of album gain analysis
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AlbumGainResult {
    tracks: Vec<ReplayGainResult>,
    album_loudness_db: f64,
    album_gain_db: f64,
    album_peak: f64,
}

impl AlbumGainResult {
    #[allow(dead_code)]
    pub(crate) fn new(
        tracks: Vec<ReplayGainResult>,
        album_loudness_db: f64,
        album_gain_db: f64,
        album_peak: f64,
    ) -> Self {
        Self {
            tracks,
            album_loudness_db,
            album_gain_db,
            album_peak,
        }
    }

    /// Build an album result from stored `REPLAYGAIN_ALBUM_*` tags instead of
    /// analysis (`-s R`, issue #298). See [`ReplayGainResult::from_stored_tags`].
    pub fn from_stored_tags(
        tracks: Vec<ReplayGainResult>,
        album_gain_db: f64,
        album_peak: f64,
        analysis_mode: AnalysisMode,
    ) -> Self {
        let target = analysis_mode
            .target_lufs()
            .unwrap_or(REPLAYGAIN_REFERENCE_DB);
        Self {
            tracks,
            album_loudness_db: target - album_gain_db,
            album_gain_db,
            album_peak,
        }
    }

    pub fn tracks(&self) -> &[ReplayGainResult] {
        &self.tracks
    }
    pub fn album_loudness_db(&self) -> f64 {
        self.album_loudness_db
    }
    pub fn album_gain_db(&self) -> f64 {
        self.album_gain_db
    }
    pub fn album_peak(&self) -> f64 {
        self.album_peak
    }

    /// Convert album gain in dB to MP3 gain steps
    pub fn album_gain_steps(&self) -> i32 {
        crate::gain::db_to_steps(self.album_gain_db)
    }
}

impl std::fmt::Display for AlbumGainResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Album: {:+.2} dB (peak: {:.6}, {} tracks)",
            self.album_gain_db,
            self.album_peak,
            self.tracks.len()
        )
    }
}

/// Report from a "lenient" album analysis that may skip files.
///
/// Returned by `analyze_album_lenient_*` family. `album` is computed from the
/// successfully-analyzed tracks only; `failures` lists `(file_index,
/// error_message)` pairs in input order; `successful_indices` maps
/// `album.tracks()[k]` back to `files[successful_indices[k]]`.
#[derive(Debug, Clone)]
pub struct AlbumAnalysisReport {
    pub album: AlbumGainResult,
    pub failures: Vec<(usize, String)>,
    pub successful_indices: Vec<usize>,
}

// =============================================================================
// Equal-loudness filter coefficients
// =============================================================================

/// Yule-Walker and Butterworth filter coefficients for equal-loudness weighting
/// These are the coefficients used in the original ReplayGain algorithm
/// Supporting all 12 sample rates from the original mp3gain
/// Reference: https://github.com/cpuimage/ReplayGainAnalysis/blob/master/gain_analysis.c
#[cfg(feature = "replaygain")]
mod filter_coeffs {
    // =========================================================================
    // 96000 Hz coefficients (ABYule[0], ABButter[0])
    // =========================================================================
    pub(super) const YULE_A_96000: [f64; 11] = [
        1.0,
        -7.22103125152679,
        24.7034187975904,
        -52.6825833623896,
        77.4825736677539,
        -82.0074753444205,
        63.1566097101925,
        -34.889569769245,
        13.2126852760198,
        -3.09445623301669,
        0.340344741393305,
    ];

    pub(super) const YULE_B_96000: [f64; 11] = [
        0.006471345933032,
        -0.02567678242161,
        0.049805860704367,
        -0.05823001743528,
        0.040611847441914,
        -0.010912036887501,
        -0.00901635868667,
        0.012448886238123,
        -0.007206683749426,
        0.002167156433951,
        -0.000261819276949,
    ];

    pub(super) const BUTTER_A_96000: [f64; 3] = [1.0, -1.98611621154089, 0.986211929160751];

    pub(super) const BUTTER_B_96000: [f64; 3] =
        [0.99308203517541, -1.98616407035082, 0.99308203517541];

    // =========================================================================
    // 88200 Hz coefficients (ABYule[1], ABButter[1])
    // =========================================================================
    pub(super) const YULE_A_88200: [f64; 11] = [
        1.0,
        -7.19001570087017,
        24.4109412087159,
        -51.6306373580801,
        75.3978476863163,
        -79.4164552507386,
        61.0373661948115,
        -33.7446462547014,
        12.8168791146274,
        -3.01332198541437,
        0.223619893831468,
    ];

    pub(super) const YULE_B_88200: [f64; 11] = [
        0.015415414474287,
        -0.07691359399407,
        0.196677418516518,
        -0.338855114128061,
        0.430094579594561,
        -0.415015413747894,
        0.304942508151101,
        -0.166191795926663,
        0.063198189938739,
        -0.015003978694525,
        0.001748085184539,
    ];

    pub(super) const BUTTER_A_88200: [f64; 3] = [1.0, -1.98488843762334, 0.979389350028798];

    pub(super) const BUTTER_B_88200: [f64; 3] =
        [0.992472550461293, -1.98494510092258, 0.992472550461293];

    // =========================================================================
    // 64000 Hz coefficients (ABYule[2], ABButter[2])
    // =========================================================================
    pub(super) const YULE_A_64000: [f64; 11] = [
        1.0,
        -5.74819833657784,
        16.246507961894,
        -29.9691822642542,
        40.027597579378,
        -40.3209196052655,
        30.8542077487718,
        -17.5965138737281,
        7.10690214103873,
        -1.82175564515191,
        0.223619893831468,
    ];

    pub(super) const YULE_B_64000: [f64; 11] = [
        0.021776466467053,
        -0.062376961003801,
        0.107731165328514,
        -0.150994515142316,
        0.170334807313632,
        -0.157984942890531,
        0.121639833268721,
        -0.074094040816409,
        0.031282852041061,
        -0.00755421235941,
        0.00117925454213,
    ];

    pub(super) const BUTTER_A_64000: [f64; 3] = [1.0, -1.97917472731008, 0.979389350028798];

    pub(super) const BUTTER_B_64000: [f64; 3] =
        [0.989641019334721, -1.97928203866944, 0.989641019334721];

    // =========================================================================
    // 48000 Hz coefficients (ABYule[3], ABButter[3])
    // =========================================================================
    pub(super) const YULE_A_48000: [f64; 11] = [
        1.0,
        -3.84664617118067,
        7.81501653005538,
        -11.34170355132042,
        13.05504219327545,
        -12.28759895145294,
        9.48293806319790,
        -5.87257861775999,
        2.75465861874613,
        -0.86984376593551,
        0.13919314567432,
    ];

    pub(super) const YULE_B_48000: [f64; 11] = [
        0.03857599435200,
        -0.02160367184185,
        -0.00123395316851,
        -0.00009291677959,
        -0.01655260341619,
        0.02161526843274,
        -0.02074045215285,
        0.00594298065125,
        0.00306428023191,
        0.00012025322027,
        0.00288463683916,
    ];

    pub(super) const BUTTER_A_48000: [f64; 3] = [1.0, -1.97223372919527, 0.97261396931306];

    pub(super) const BUTTER_B_48000: [f64; 3] =
        [0.98621192462708, -1.97242384925416, 0.98621192462708];

    // =========================================================================
    // 44100 Hz coefficients (ABYule[4], ABButter[4])
    // =========================================================================
    pub(super) const YULE_A_44100: [f64; 11] = [
        1.0,
        -3.47845948550071,
        6.36317777566148,
        -8.54751527471874,
        9.47693607801280,
        -8.81498681370155,
        6.85401540936998,
        -4.39470996079559,
        2.19611684890774,
        -0.75104302451432,
        0.13149317958808,
    ];

    pub(super) const YULE_B_44100: [f64; 11] = [
        0.05418656406430,
        -0.02911007808948,
        -0.00848709379851,
        -0.00851165645469,
        -0.00834990904936,
        0.02245293253339,
        -0.02596338512915,
        0.01624864962975,
        -0.00240879051584,
        0.00674613682247,
        -0.00187763777362,
    ];

    pub(super) const BUTTER_A_44100: [f64; 3] = [1.0, -1.96977855582618, 0.97022847566350];

    pub(super) const BUTTER_B_44100: [f64; 3] =
        [0.98500175787242, -1.97000351574484, 0.98500175787242];

    // =========================================================================
    // 32000 Hz coefficients (ABYule[5], ABButter[5])
    // =========================================================================
    pub(super) const YULE_A_32000: [f64; 11] = [
        1.0,
        -2.37898834973084,
        2.84868151156327,
        -2.64577170229825,
        2.23697657451713,
        -1.67148153367602,
        1.00595954808547,
        -0.45953458054983,
        0.16378164858596,
        -0.05032077717131,
        0.02347897407020,
    ];

    pub(super) const YULE_B_32000: [f64; 11] = [
        0.15457299681924,
        -0.09331049056315,
        -0.06247880153653,
        0.02163541888798,
        -0.05588393329856,
        0.04781476674921,
        0.00222312597743,
        0.03174092540049,
        -0.01390589421898,
        0.00651420667831,
        -0.00881362733839,
    ];

    pub(super) const BUTTER_A_32000: [f64; 3] = [1.0, -1.95835380975398, 0.95920349965459];

    pub(super) const BUTTER_B_32000: [f64; 3] =
        [0.97938932735214, -1.95877865470428, 0.97938932735214];

    // =========================================================================
    // 24000 Hz coefficients (ABYule[6], ABButter[6])
    // =========================================================================
    pub(super) const YULE_A_24000: [f64; 11] = [
        1.0,
        -1.61273165137247,
        1.07977492259970,
        -0.25656257754070,
        -0.16276719120440,
        -0.22638893773906,
        0.39120800788284,
        -0.22138138954925,
        0.04500235387352,
        0.02005851806501,
        0.00302439095741,
    ];

    pub(super) const YULE_B_24000: [f64; 11] = [
        0.30296907319327,
        -0.22613988682123,
        -0.08587323730772,
        0.03282930172664,
        -0.00915702933434,
        -0.02364141202522,
        -0.00584456039913,
        0.06276101321749,
        -0.00000828086748,
        0.00205861885564,
        -0.02950134983287,
    ];

    pub(super) const BUTTER_A_24000: [f64; 3] = [1.0, -1.95002759149878, 0.95124613669835];

    pub(super) const BUTTER_B_24000: [f64; 3] =
        [0.97531843204928, -1.95063686409857, 0.97531843204928];

    // =========================================================================
    // 22050 Hz coefficients (ABYule[7], ABButter[7])
    // =========================================================================
    pub(super) const YULE_A_22050: [f64; 11] = [
        1.0,
        -1.49858979367799,
        0.87350271418188,
        0.12205022308084,
        -0.80774944671438,
        0.47854794562326,
        -0.12453458140019,
        -0.04067510197014,
        0.08333755284107,
        -0.04237348025746,
        0.02977207319925,
    ];

    pub(super) const YULE_B_22050: [f64; 11] = [
        0.33642304856132,
        -0.25572241425570,
        -0.11828570177555,
        0.11921148675203,
        -0.07834489609479,
        -0.00469977914380,
        -0.00589500224440,
        0.05724228140351,
        0.00832043980773,
        -0.01635381384540,
        -0.01760176568150,
    ];

    pub(super) const BUTTER_A_22050: [f64; 3] = [1.0, -1.94561023566527, 0.94705070426118];

    pub(super) const BUTTER_B_22050: [f64; 3] =
        [0.97316523498161, -1.94633046996323, 0.97316523498161];

    // =========================================================================
    // 16000 Hz coefficients (ABYule[8], ABButter[8])
    // =========================================================================
    pub(super) const YULE_A_16000: [f64; 11] = [
        1.0,
        -0.62820619233671,
        0.29661783706366,
        -0.37256372942400,
        0.00213767857124,
        -0.42029820170918,
        0.22199650564824,
        0.00613424350682,
        0.06747620744683,
        0.05784820375801,
        0.03222754072173,
    ];

    pub(super) const YULE_B_16000: [f64; 11] = [
        0.44915256608450,
        -0.14351757464547,
        -0.22784394429749,
        -0.01419140100551,
        0.04078262797139,
        -0.12398163381748,
        0.04078565135648,
        0.10478503600251,
        -0.01863887810927,
        -0.03193428438915,
        0.00541907748707,
    ];

    pub(super) const BUTTER_A_16000: [f64; 3] = [1.0, -1.92783286977036, 0.93034775234268];

    pub(super) const BUTTER_B_16000: [f64; 3] =
        [0.96454515552826, -1.92909031105652, 0.96454515552826];

    // =========================================================================
    // 12000 Hz coefficients (ABYule[9], ABButter[9])
    // =========================================================================
    pub(super) const YULE_A_12000: [f64; 11] = [
        1.0,
        -1.04800335126349,
        0.29156311971249,
        -0.26806001042947,
        0.00819999645858,
        0.45054734505008,
        -0.33032403314006,
        0.06739368333110,
        -0.04784254229033,
        0.01639907836189,
        0.01807364323573,
    ];

    pub(super) const YULE_B_12000: [f64; 11] = [
        0.56619470757641,
        -0.75464456939302,
        0.16242137742230,
        0.16744243493672,
        -0.18901604199609,
        0.30931782841830,
        -0.27562961986224,
        0.00647310677246,
        0.08647503780351,
        -0.03788984554840,
        -0.00588215443421,
    ];

    pub(super) const BUTTER_A_12000: [f64; 3] = [1.0, -1.91858953033784, 0.92177618768381];

    pub(super) const BUTTER_B_12000: [f64; 3] =
        [0.96009142950541, -1.92018285901082, 0.96009142950541];

    // =========================================================================
    // 11025 Hz coefficients (ABYule[10], ABButter[10])
    // =========================================================================
    pub(super) const YULE_A_11025: [f64; 11] = [
        1.0,
        -0.51035327095184,
        -0.31863563325245,
        -0.20256413484477,
        0.14728154134330,
        0.38952639978999,
        -0.23313271880868,
        -0.05246019024463,
        -0.02505961724053,
        0.02442357316099,
        0.01818801111503,
    ];

    pub(super) const YULE_B_11025: [f64; 11] = [
        0.58100494960553,
        -0.53174909058578,
        -0.14289799034253,
        0.17520704835522,
        0.02377945217615,
        0.15558449135573,
        -0.25344790059353,
        0.01628462406333,
        0.06920467763959,
        -0.03721611395801,
        -0.00749618797172,
    ];

    pub(super) const BUTTER_A_11025: [f64; 3] = [1.0, -1.91542108074780, 0.91885558323625];

    pub(super) const BUTTER_B_11025: [f64; 3] =
        [0.95856916599601, -1.91713833199203, 0.95856916599601];

    // =========================================================================
    // 8000 Hz coefficients (ABYule[11], ABButter[11])
    // =========================================================================
    pub(super) const YULE_A_8000: [f64; 11] = [
        1.0,
        -0.25049871956020,
        -0.43193942311114,
        -0.03424681017675,
        -0.04678328784242,
        0.26408300200955,
        0.15113130533216,
        -0.17556493366449,
        -0.18823009262115,
        0.05477720428674,
        0.04704409688120,
    ];

    pub(super) const YULE_B_8000: [f64; 11] = [
        0.53648789255105,
        -0.42163034350696,
        -0.00275953611929,
        0.04267842219415,
        -0.10214864179676,
        0.14590772289388,
        -0.02459864859345,
        -0.11202315195388,
        -0.04060034127000,
        0.04788665548180,
        -0.02217936801134,
    ];

    pub(super) const BUTTER_A_8000: [f64; 3] = [1.0, -1.88903307939452, 0.89487434461664];

    pub(super) const BUTTER_B_8000: [f64; 3] =
        [0.94597685600279, -1.89195371200558, 0.94597685600279];
}

/// Small constant to prevent denormal float slowdowns
/// Reference: gain_analysis.c filterYule() uses 1e-10 for this purpose
const DENORMAL_PREVENTION: f64 = 1e-10;

/// Equal-loudness filter state
#[cfg(feature = "replaygain")]
struct EqualLoudnessFilter {
    /// Yule-Walker filter A coefficients
    yule_a: [f64; 11],
    /// Yule-Walker filter B coefficients
    yule_b: [f64; 11],
    /// Butter filter A coefficients
    butter_a: [f64; 3],
    /// Butter filter B coefficients
    butter_b: [f64; 3],
    /// Yule filter state (input history), ring buffer
    yule_x: [f64; 16],
    /// Yule filter state (output history), ring buffer
    yule_y: [f64; 16],
    /// Butter filter state (input history), ring buffer
    butter_x: [f64; 4],
    /// Butter filter state (output history), ring buffer
    butter_y: [f64; 4],
    /// Ring write position; steps backwards (mod 16) per sample so the
    /// value written i samples ago lives at `(pos + i) & 15`. Power-of-two
    /// capacities let the hot loop wrap with a mask instead of shifting
    /// the history arrays every sample (issue #255).
    pos: usize,
}

#[cfg(feature = "replaygain")]
impl EqualLoudnessFilter {
    fn new(sample_rate: u32) -> Option<Self> {
        use filter_coeffs::*;

        let (yule_a, yule_b, butter_a, butter_b) = match sample_rate {
            96000 => (YULE_A_96000, YULE_B_96000, BUTTER_A_96000, BUTTER_B_96000),
            88200 => (YULE_A_88200, YULE_B_88200, BUTTER_A_88200, BUTTER_B_88200),
            64000 => (YULE_A_64000, YULE_B_64000, BUTTER_A_64000, BUTTER_B_64000),
            48000 => (YULE_A_48000, YULE_B_48000, BUTTER_A_48000, BUTTER_B_48000),
            44100 => (YULE_A_44100, YULE_B_44100, BUTTER_A_44100, BUTTER_B_44100),
            32000 => (YULE_A_32000, YULE_B_32000, BUTTER_A_32000, BUTTER_B_32000),
            24000 => (YULE_A_24000, YULE_B_24000, BUTTER_A_24000, BUTTER_B_24000),
            22050 => (YULE_A_22050, YULE_B_22050, BUTTER_A_22050, BUTTER_B_22050),
            16000 => (YULE_A_16000, YULE_B_16000, BUTTER_A_16000, BUTTER_B_16000),
            12000 => (YULE_A_12000, YULE_B_12000, BUTTER_A_12000, BUTTER_B_12000),
            11025 => (YULE_A_11025, YULE_B_11025, BUTTER_A_11025, BUTTER_B_11025),
            8000 => (YULE_A_8000, YULE_B_8000, BUTTER_A_8000, BUTTER_B_8000),
            _ => return None, // Unsupported sample rate
        };

        Some(Self {
            yule_a,
            yule_b,
            butter_a,
            butter_b,
            yule_x: [0.0; 16],
            yule_y: [0.0; 16],
            butter_x: [0.0; 4],
            butter_y: [0.0; 4],
            pos: 0,
        })
    }

    fn process(&mut self, sample: f64) -> f64 {
        // Ring-buffer history: `pos` steps backwards each sample, so the
        // sample from i steps ago sits at `(pos + i) & mask`. This replaces
        // the previous per-sample `copy_within` shifts (issue #255) while
        // performing the exact same arithmetic in the same order, so the
        // output stays bit-identical (guarded by the golden test below).
        // 16 is a multiple of 4, so `pos & 3` decrements consistently for
        // the Butterworth ring as well.
        self.pos = (self.pos + 15) & 15;
        let pos = self.pos;
        self.yule_x[pos] = sample;

        // Apply Yule-Walker filter with denormal prevention.
        // The 1e-10 constant prevents denormal float slowdowns on silent audio
        // (see gain_analysis.c filterYule()). The explicit loop with a fixed
        // upper bound gives the optimizer a better shot at unrolling /
        // vectorizing this hot path than the iterator chain.
        let mut yule_out = DENORMAL_PREVENTION + self.yule_b[0] * sample;
        for i in 1..11 {
            let j = (pos + i) & 15;
            yule_out += self.yule_b[i] * self.yule_x[j] - self.yule_a[i] * self.yule_y[j];
        }
        self.yule_y[pos] = yule_out;

        let bpos = pos & 3;
        self.butter_x[bpos] = yule_out;

        // Apply Butterworth high-pass filter with denormal prevention
        let mut butter_out = DENORMAL_PREVENTION + self.butter_b[0] * yule_out;
        for i in 1..3 {
            let j = (bpos + i) & 3;
            butter_out += self.butter_b[i] * self.butter_x[j] - self.butter_a[i] * self.butter_y[j];
        }
        self.butter_y[bpos] = butter_out;

        butter_out
    }
}

// =============================================================================
// RMS and loudness calculation
// =============================================================================

/// Steps per dB for histogram resolution (matches original mp3gain)
const STEPS_PER_DB: f64 = 100.0;

/// Maximum histogram size (matches the reference gain_analysis.c A[] array)
/// Bin 0 = 0 dB; indices below 0 clamp to bin 0 like the reference, so
/// near-silent content reads 0 dB rather than a negative loudness (issue #236)
/// For 16-bit samples: mean_square peaks around 10*log10(32768²) ≈ 90 dB
const HISTOGRAM_SIZE: usize = 12000;

/// RMS percentile for loudness calculation (95th percentile)
const RMS_PERCENTILE: f64 = 0.95;

/// Histogram data for ReplayGain analysis
/// This can be accumulated across multiple tracks for album gain calculation
#[cfg(feature = "replaygain")]
#[derive(Clone)]
struct LoudnessHistogram {
    /// Histogram of loudness values (RMS windows bucketed by dB)
    data: Vec<u32>,
}

#[cfg(feature = "replaygain")]
impl LoudnessHistogram {
    fn new() -> Self {
        Self {
            data: vec![0; HISTOGRAM_SIZE],
        }
    }

    /// Accumulate another histogram into this one (for album gain calculation)
    fn accumulate(&mut self, other: &LoudnessHistogram) {
        for (a, &b) in self.data.iter_mut().zip(other.data.iter()) {
            *a += b;
        }
    }

    /// Calculate loudness from histogram using 95th percentile
    fn get_loudness(&self) -> f64 {
        let total: u64 = self.data.iter().map(|&x| x as u64).sum();
        if total == 0 {
            return -20.0; // Default for empty histogram
        }

        let threshold = ((total as f64) * (1.0 - RMS_PERCENTILE)).ceil() as u64;
        let mut count = 0u64;

        for i in (0..HISTOGRAM_SIZE).rev() {
            count += self.data[i] as u64;
            if count >= threshold {
                return i as f64 / STEPS_PER_DB;
            }
        }

        -20.0 // Default for lowest values
    }
}

/// Analyzer state for accumulating samples across buffers
#[cfg(feature = "replaygain")]
struct ReplayGainAnalyzer {
    /// Left channel sum of squares for current window
    lsum: f64,
    /// Right channel sum of squares for current window
    rsum: f64,
    /// Number of samples in current window
    totsamp: usize,
    /// Window size in samples (50ms worth)
    window_samples: usize,
    /// Histogram of loudness values
    histogram: LoudnessHistogram,
}

#[cfg(feature = "replaygain")]
impl ReplayGainAnalyzer {
    fn new(sample_rate: u32) -> Self {
        // 50ms window
        let window_samples = (sample_rate as usize * 50) / 1000;
        Self {
            lsum: 0.0,
            rsum: 0.0,
            totsamp: 0,
            window_samples,
            histogram: LoudnessHistogram::new(),
        }
    }

    /// Take ownership of the histogram, consuming the analyzer.
    fn into_histogram(self) -> LoudnessHistogram {
        self.histogram
    }

    /// Add a stereo sample pair (already filtered)
    fn add_sample(&mut self, left: f64, right: f64) {
        self.lsum += left * left;
        self.rsum += right * right;
        self.totsamp += 1;

        if self.totsamp >= self.window_samples {
            self.finish_window();
        }
    }

    /// Add a mono sample (already filtered)
    fn add_mono_sample(&mut self, sample: f64) {
        let sq = sample * sample;
        self.lsum += sq;
        self.rsum += sq;
        self.totsamp += 1;

        if self.totsamp >= self.window_samples {
            self.finish_window();
        }
    }

    /// Finish the current window and add to histogram
    fn finish_window(&mut self) {
        if self.totsamp == 0 {
            return;
        }

        // Calculate mean square value (average of both channels)
        // Original: (lsum + rsum) / totsamp * 0.5
        let mean_square = (self.lsum + self.rsum) / self.totsamp as f64 * 0.5;

        // Convert to histogram index.
        // Original: STEPS_per_dB * 10.0 * log10(mean_square + 1e-37)
        // The reference gain_analysis.c clamps out-of-range indices into the
        // histogram (`if (ival < 0) ival = 0; if (ival >= len) ival = len-1`)
        // so EVERY window is counted. Clamping (not dropping) matters because
        // the 95th-percentile threshold is `ceil(0.05 * total_windows)`:
        // silent windows (very negative `val`) must still be counted, or the
        // total shrinks and sparse material (e.g. acapellas) reads too loud
        // (issue #217). Bin 0 = 0 dB, exactly like the reference: windows
        // below 0 dB mean-square clamp to bin 0 rather than mapping to
        // negative loudness (issue #236).
        let val = STEPS_PER_DB * 10.0 * (mean_square + 1e-37).log10();
        let idx = (val as i32).clamp(0, HISTOGRAM_SIZE as i32 - 1) as usize;
        self.histogram.data[idx] += 1;

        // Reset for next window
        self.lsum = 0.0;
        self.rsum = 0.0;
        self.totsamp = 0;
    }

    /// Calculate the loudness value from the histogram (95th percentile)
    fn get_loudness(&self) -> f64 {
        self.histogram.get_loudness()
    }
}

// =============================================================================
// Main analysis functions
// =============================================================================

/// Detect file type from path
#[cfg(feature = "replaygain")]
fn detect_file_type(file_path: &Path) -> AudioFileType {
    AudioFileType::from_path(file_path)
}

// =============================================================================
// Progress-tracking media source
// =============================================================================

/// Media source wrapper that tracks read position for progress reporting
#[cfg(feature = "replaygain")]
struct ProgressMediaSource {
    inner: std::fs::File,
    position: Arc<AtomicU64>,
    total_size: u64,
}

#[cfg(feature = "replaygain")]
impl std::io::Read for ProgressMediaSource {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let n = self.inner.read(buf)?;
        self.position.fetch_add(n as u64, Ordering::Relaxed);
        Ok(n)
    }
}

#[cfg(feature = "replaygain")]
impl std::io::Seek for ProgressMediaSource {
    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
        let new_pos = self.inner.seek(pos)?;
        self.position.store(new_pos, Ordering::Relaxed);
        Ok(new_pos)
    }
}

#[cfg(feature = "replaygain")]
impl MediaSource for ProgressMediaSource {
    fn is_seekable(&self) -> bool {
        true
    }

    fn byte_len(&self) -> Option<u64> {
        Some(self.total_size)
    }
}

/// Per-track loudness state kept for album accumulation, one variant per
/// measurement algorithm. Modes never mix within one album analysis.
#[cfg(feature = "replaygain")]
enum LoudnessState {
    Rg1(LoudnessHistogram),
    Bs1770(crate::bs1770::BlockEnergies),
}

#[cfg(feature = "replaygain")]
impl LoudnessState {
    fn new(mode: AnalysisMode) -> Self {
        match mode {
            AnalysisMode::Rg1 => LoudnessState::Rg1(LoudnessHistogram::new()),
            _ => LoudnessState::Bs1770(crate::bs1770::BlockEnergies::new()),
        }
    }

    fn accumulate(&mut self, other: &LoudnessState) {
        match (self, other) {
            (LoudnessState::Rg1(a), LoudnessState::Rg1(b)) => a.accumulate(b),
            (LoudnessState::Bs1770(a), LoudnessState::Bs1770(b)) => a.accumulate(b),
            _ => debug_assert!(false, "mixed analysis modes in album accumulation"),
        }
    }

    /// `(loudness, gain_db)` of the accumulated state under `mode`.
    fn loudness_and_gain(&self, mode: AnalysisMode) -> (f64, f64) {
        match self {
            LoudnessState::Rg1(histogram) => {
                let loudness = histogram.get_loudness();
                (loudness, PINK_REF - loudness)
            }
            LoudnessState::Bs1770(blocks) => lufs_loudness_and_gain(blocks.integrated_lufs(), mode),
        }
    }
}

/// Convert integrated LUFS to `(loudness, gain_db)` for the mode's target.
/// Fully-gated input (silence) has no measurable loudness and is treated as
/// already at target: gain 0. Only reachable from BS.1770 branches, so an
/// RG1 mode here is a programming error.
#[cfg(feature = "replaygain")]
fn lufs_loudness_and_gain(lufs: f64, mode: AnalysisMode) -> (f64, f64) {
    let target = mode
        .target_lufs()
        .expect("BS.1770 gain calculation requires an RG2/R128 mode");
    if lufs.is_finite() {
        (lufs, target - lufs)
    } else {
        (target, 0.0)
    }
}

/// Internal result containing both ReplayGainResult and the loudness state
/// for album calculation
#[cfg(feature = "replaygain")]
struct TrackAnalysisInternal {
    result: ReplayGainResult,
    state: LoudnessState,
}

/// Per-track analyzer, selected by [`AnalysisMode`]. The RG1 variant is the
/// original mp3gain algorithm and must stay bit-identical; the BS.1770
/// variant feeds normalized samples of all channels to [`crate::bs1770`].
#[cfg(feature = "replaygain")]
enum TrackAnalyzer {
    Rg1 {
        filters: Vec<EqualLoudnessFilter>,
        analyzer: ReplayGainAnalyzer,
    },
    Bs1770 {
        analyzer: crate::bs1770::Bs1770Analyzer,
    },
}

/// Internal function to analyze a track and return both result and loudness
/// state, with a "this format is unsupported" failure named as such.
///
/// The refinement lives here rather than at each public entry point because
/// this is the single choke point every analysis (single track and album)
/// goes through. Without it an ALAC file fails with symphonia's "unsupported
/// audio codec", which reads as a genuine error and sets the exit code for a
/// whole library scan (issue #330).
#[cfg(feature = "replaygain")]
fn analyze_track_internal(
    file_path: &Path,
    track_index: Option<u32>,
    progress: Option<&dyn Fn(u64, u64)>,
    mode: AnalysisMode,
    true_peak: bool,
) -> Result<TrackAnalysisInternal> {
    analyze_track_decoded(file_path, track_index, progress, mode, true_peak)
        .map_err(|e| e.refine_format(file_path))
}

#[cfg(feature = "replaygain")]
fn analyze_track_decoded(
    file_path: &Path,
    track_index: Option<u32>,
    progress: Option<&dyn Fn(u64, u64)>,
    mode: AnalysisMode,
    true_peak: bool,
) -> Result<TrackAnalysisInternal> {
    // Detect file type
    let file_type = detect_file_type(file_path);

    // Open the media source
    let file = std::fs::File::open(file_path).map_err(|e| Error::io_open(file_path, e))?;
    let file_size = file.metadata().map(|m| m.len()).unwrap_or(0);

    // Create media source with optional position tracking
    let position_tracker = progress.map(|_| Arc::new(AtomicU64::new(0)));

    let mss = if let Some(ref tracker) = position_tracker {
        let source = ProgressMediaSource {
            inner: file,
            position: Arc::clone(tracker),
            total_size: file_size,
        };
        MediaSourceStream::new(Box::new(source), Default::default())
    } else {
        MediaSourceStream::new(Box::new(file), Default::default())
    };

    // Probe the format
    let mut hint = Hint::new();
    if let Some(ext) = file_path.extension().and_then(|e| e.to_str()) {
        hint.with_extension(ext);
    }

    let mut format = symphonia::default::get_probe()
        .probe(
            &hint,
            mss,
            FormatOptions::default(),
            MetadataOptions::default(),
        )
        .map_err(|e| Error::ProbeFailed {
            path: file_path.to_path_buf(),
            source: Box::new(e),
        })?;

    // Find audio tracks
    let audio_tracks: Vec<_> = format
        .tracks()
        .iter()
        .filter(|t| {
            t.codec_params
                .as_ref()
                .and_then(|p| p.audio())
                .is_some_and(|a| a.codec != CODEC_ID_NULL_AUDIO)
        })
        .collect();

    if audio_tracks.is_empty() {
        return Err(Error::NoAudioTrack);
    }

    // Select track by index or default to first
    let track = match track_index {
        Some(idx) => {
            let idx = idx as usize;
            if idx >= audio_tracks.len() {
                return Err(Error::TrackIndexOutOfRange {
                    index: idx as u32,
                    count: audio_tracks.len(),
                });
            }
            audio_tracks[idx]
        }
        None => audio_tracks[0],
    };

    let track_id = track.id;
    let audio_params = track
        .codec_params
        .as_ref()
        .and_then(|p| p.audio())
        .ok_or(Error::NoAudioTrack)?;
    let sample_rate = audio_params
        .sample_rate
        .ok_or(Error::UnsupportedSampleRate(0))?;
    let channels = audio_params
        .channels
        .as_ref()
        .map(|c| c.count())
        .unwrap_or(2);

    // Create decoder
    let mut decoder = symphonia::default::get_codecs()
        .make_audio_decoder(audio_params, &AudioDecoderOptions::default())
        .map_err(|e| Error::Decode(Box::new(e)))?;

    let mut track_analyzer = match mode {
        AnalysisMode::Rg1 => {
            // Create filter for each channel
            let filters: Vec<EqualLoudnessFilter> = (0..channels)
                .map(|_| {
                    EqualLoudnessFilter::new(sample_rate)
                        .ok_or(Error::UnsupportedSampleRate(sample_rate))
                })
                .collect::<Result<Vec<_>>>()?;
            TrackAnalyzer::Rg1 {
                filters,
                analyzer: ReplayGainAnalyzer::new(sample_rate),
            }
        }
        // True peak is only defined for the BS.1770 modes — RG1's peak is
        // mp3gain's MAX_AMPLITUDE semantics and must stay bit-compatible,
        // so the flag is ignored there (issue #292).
        _ if true_peak => TrackAnalyzer::Bs1770 {
            analyzer: crate::bs1770::Bs1770Analyzer::new_with_true_peak(sample_rate, channels),
        },
        _ => TrackAnalyzer::Bs1770 {
            analyzer: crate::bs1770::Bs1770Analyzer::new(sample_rate, channels),
        },
    };
    let mut peak: f64 = 0.0;

    // Process all packets
    loop {
        let packet = match format.next_packet() {
            Ok(Some(p)) => p,
            Ok(None) => break,
            Err(e) => return Err(Error::Decode(Box::new(e))),
        };

        if packet.track_id != track_id {
            continue;
        }

        let decoded = match decoder.decode(&packet) {
            Ok(d) => d,
            Err(symphonia::core::errors::Error::DecodeError(_)) => continue,
            Err(e) => return Err(Error::Decode(Box::new(e))),
        };

        // Process audio buffer
        match &mut track_analyzer {
            TrackAnalyzer::Rg1 { filters, analyzer } => {
                process_audio_buffer(&decoded, filters, analyzer, &mut peak)
            }
            TrackAnalyzer::Bs1770 { analyzer } => {
                process_audio_buffer_bs1770(&decoded, analyzer, &mut peak)
            }
        }

        // Report progress
        if let (Some(cb), Some(ref tracker)) = (progress, &position_tracker) {
            cb(tracker.load(Ordering::Relaxed), file_size);
        }
    }

    // Report completion
    if let Some(cb) = progress {
        cb(file_size, file_size);
    }

    // Finish analysis and calculate loudness and gain
    let mut is_true_peak = false;
    let (loudness_db, gain_db, state) = match track_analyzer {
        TrackAnalyzer::Rg1 { mut analyzer, .. } => {
            // Finish any remaining samples in the last window
            analyzer.finish_window();
            let loudness_db = analyzer.get_loudness();
            (
                loudness_db,
                PINK_REF - loudness_db,
                LoudnessState::Rg1(analyzer.into_histogram()),
            )
        }
        TrackAnalyzer::Bs1770 { analyzer, .. } => {
            // The interpolator's passthrough phase makes the true peak
            // ≥ sample peak by construction; the max() is a guard against
            // rounding at the very margin.
            if let Some(tp) = analyzer.true_peak() {
                peak = peak.max(tp);
                is_true_peak = true;
            }
            let blocks = analyzer.into_blocks();
            let (loudness_db, gain_db) = lufs_loudness_and_gain(blocks.integrated_lufs(), mode);
            (loudness_db, gain_db, LoudnessState::Bs1770(blocks))
        }
    };

    let mut result =
        ReplayGainResult::new(loudness_db, gain_db, peak, sample_rate, file_type, mode);
    result.true_peak = is_true_peak;

    Ok(TrackAnalysisInternal { result, state })
}

/// Analyze a single track and calculate ReplayGain
#[cfg(feature = "replaygain")]
pub fn analyze_track(file_path: &Path) -> Result<ReplayGainResult> {
    analyze_track_with_index(file_path, None)
}

/// Analyze a single track with optional track index selection
#[cfg(feature = "replaygain")]
pub fn analyze_track_with_index(
    file_path: &Path,
    track_index: Option<u32>,
) -> Result<ReplayGainResult> {
    analyze_track_with_mode(file_path, track_index, AnalysisMode::default(), None)
}

/// Analyze a single track using the given analysis mode (issue #269).
///
/// [`AnalysisMode::Rg1`] is identical to [`analyze_track_with_index`]; the
/// other modes measure BS.1770 integrated loudness and compute the gain
/// against the mode's target level. `on_progress` behaves like
/// [`analyze_track_with_progress`].
#[cfg(feature = "replaygain")]
pub fn analyze_track_with_mode(
    file_path: &Path,
    track_index: Option<u32>,
    mode: AnalysisMode,
    on_progress: Option<&dyn Fn(u64, u64)>,
) -> Result<ReplayGainResult> {
    analyze_track_with_options(
        file_path,
        &TrackAnalysisOptions {
            track_index,
            mode,
            on_progress,
            ..Default::default()
        },
    )
}

/// Options for [`analyze_track_with_options`].
///
/// `Default` is a strict RG1 analysis of the first audio track with no
/// callbacks — the same behavior as [`analyze_track`].
#[derive(Default)]
pub struct TrackAnalysisOptions<'a> {
    /// Which audio track to analyze in multi-track containers (default: first).
    pub track_index: Option<u32>,
    /// Loudness measurement algorithm (issue #269).
    pub mode: AnalysisMode,
    /// Measure BS.1770-4 Annex 2 true peak instead of the decoded sample
    /// peak in the BS.1770 modes (issue #292). True peak estimates
    /// inter-sample peaks by oversampling, so values above 1.0 are expected
    /// and correct. Ignored in [`AnalysisMode::Rg1`], whose peak is
    /// mp3gain's `MAX_AMPLITUDE` semantics and must stay bit-compatible.
    pub true_peak: bool,
    /// Byte-level progress callback, as in [`analyze_track_with_progress`].
    pub on_progress: Option<&'a dyn Fn(u64, u64)>,
}

/// Analyze a single track with the full option set (issue #292). The other
/// `analyze_track_*` functions are conveniences over this one.
#[cfg(feature = "replaygain")]
pub fn analyze_track_with_options(
    file_path: &Path,
    opts: &TrackAnalysisOptions,
) -> Result<ReplayGainResult> {
    let internal = analyze_track_internal(
        file_path,
        opts.track_index,
        opts.on_progress,
        opts.mode,
        opts.true_peak,
    )?;
    Ok(internal.result)
}

/// Analyze a single track with progress reporting
///
/// The callback receives `(bytes_read, total_bytes)` and is called after each
/// decoded packet. Use this to drive a progress bar during analysis.
///
/// Originally requested by @Sappharad in #106 (mp3gain-style byte progress).
#[cfg(feature = "replaygain")]
pub fn analyze_track_with_progress(
    file_path: &Path,
    track_index: Option<u32>,
    on_progress: &dyn Fn(u64, u64),
) -> Result<ReplayGainResult> {
    analyze_track_with_mode(
        file_path,
        track_index,
        AnalysisMode::default(),
        Some(on_progress),
    )
}

/// Scale factor to convert normalized float samples to 16-bit integer range.
/// The original ReplayGain algorithm (and its PINK_REF calibration constant of 64.82)
/// was designed for non-normalized 16-bit integer samples (-32768 to 32767).
/// Symphonia decoders output normalized float samples (-1.0 to 1.0), so we must
/// scale them to match the original algorithm's expected input range.
/// Without this scaling, gain values are off by 20 * log10(32768) ≈ 90.31 dB.
const SAMPLE_SCALE_16BIT: f64 = 32768.0;

/// Scale factor for 32-bit integer samples (2^31).
const SAMPLE_SCALE_32BIT: f64 = 2147483648.0;

/// Process an audio buffer and feed filtered samples to the analyzer
#[cfg(feature = "replaygain")]
fn process_audio_buffer(
    buffer: &GenericAudioBufferRef,
    filters: &mut [EqualLoudnessFilter],
    analyzer: &mut ReplayGainAnalyzer,
    peak: &mut f64,
) {
    // Hoist `plane()` lookups outside the per-sample loop — calling
    // `buf.plane(N).unwrap()` per frame goes through symphonia's Option
    // unwrap on every sample (millions per file).
    match buffer {
        GenericAudioBufferRef::F32(buf) => {
            let channels = buf.num_planes();
            let frames = buf.frames();
            let left_plane = buf.plane(0).unwrap();
            let right_plane = (channels >= 2).then(|| buf.plane(1).unwrap());

            for frame in 0..frames {
                let left_norm = left_plane[frame] as f64;
                *peak = peak.max(left_norm.abs());
                let left_filtered = filters[0].process(left_norm * SAMPLE_SCALE_16BIT);

                if let Some(right_plane) = right_plane {
                    let right_norm = right_plane[frame] as f64;
                    *peak = peak.max(right_norm.abs());
                    let right_filtered = filters[1].process(right_norm * SAMPLE_SCALE_16BIT);
                    analyzer.add_sample(left_filtered, right_filtered);
                } else {
                    analyzer.add_mono_sample(left_filtered);
                }
            }
        }
        GenericAudioBufferRef::S16(buf) => {
            let channels = buf.num_planes();
            let frames = buf.frames();
            let left_plane = buf.plane(0).unwrap();
            let right_plane = (channels >= 2).then(|| buf.plane(1).unwrap());

            for frame in 0..frames {
                // S16 samples are already in the correct range for ReplayGain algorithm
                let left = left_plane[frame] as f64;
                *peak = peak.max((left / SAMPLE_SCALE_16BIT).abs());
                let left_filtered = filters[0].process(left);

                if let Some(right_plane) = right_plane {
                    let right = right_plane[frame] as f64;
                    *peak = peak.max((right / SAMPLE_SCALE_16BIT).abs());
                    let right_filtered = filters[1].process(right);
                    analyzer.add_sample(left_filtered, right_filtered);
                } else {
                    analyzer.add_mono_sample(left_filtered);
                }
            }
        }
        GenericAudioBufferRef::S32(buf) => {
            let channels = buf.num_planes();
            let frames = buf.frames();
            // Scale S32 to 16-bit range: divide by 2^16 to go from 32-bit to 16-bit range
            let scale = SAMPLE_SCALE_16BIT / SAMPLE_SCALE_32BIT;
            let left_plane = buf.plane(0).unwrap();
            let right_plane = (channels >= 2).then(|| buf.plane(1).unwrap());

            for frame in 0..frames {
                let left = left_plane[frame] as f64 * scale;
                *peak = peak.max((left / SAMPLE_SCALE_16BIT).abs());
                let left_filtered = filters[0].process(left);

                if let Some(right_plane) = right_plane {
                    let right = right_plane[frame] as f64 * scale;
                    *peak = peak.max((right / SAMPLE_SCALE_16BIT).abs());
                    let right_filtered = filters[1].process(right);
                    analyzer.add_sample(left_filtered, right_filtered);
                } else {
                    analyzer.add_mono_sample(left_filtered);
                }
            }
        }
        _ => {
            // Unsupported format, skip
        }
    }
}

/// Feed normalized (full scale = 1.0) samples from a decoded buffer to the
/// BS.1770 analyzer. Unlike the RG1 path, all channels are analyzed (the
/// analyzer applies BS.1770 channel weights) and no 16-bit scaling is
/// applied — LUFS is defined relative to digital full scale.
#[cfg(feature = "replaygain")]
fn process_audio_buffer_bs1770(
    buffer: &GenericAudioBufferRef,
    analyzer: &mut crate::bs1770::Bs1770Analyzer,
    peak: &mut f64,
) {
    fn feed<T: Copy>(
        planes: &[&[T]],
        frames: usize,
        conv: impl Fn(T) -> f64,
        analyzer: &mut crate::bs1770::Bs1770Analyzer,
        peak: &mut f64,
    ) {
        // Mono and stereo (all MP3, nearly all AAC) go through fixed-size
        // frames, mirroring the RG1 path's hoisted-plane specialization;
        // rarer multichannel layouts fall back to a per-packet buffer.
        match planes {
            [mono] => {
                for &s in &mono[..frames] {
                    let v = conv(s);
                    *peak = peak.max(v.abs());
                    analyzer.add_frame(&[v]);
                }
            }
            [left, right] => {
                for (&l, &r) in left[..frames].iter().zip(&right[..frames]) {
                    let l = conv(l);
                    let r = conv(r);
                    *peak = peak.max(l.abs()).max(r.abs());
                    analyzer.add_frame(&[l, r]);
                }
            }
            _ => {
                let mut frame_buf = vec![0.0; planes.len()];
                for frame in 0..frames {
                    for (dst, plane) in frame_buf.iter_mut().zip(planes) {
                        let v = conv(plane[frame]);
                        *peak = peak.max(v.abs());
                        *dst = v;
                    }
                    analyzer.add_frame(&frame_buf);
                }
            }
        }
    }

    match buffer {
        GenericAudioBufferRef::F32(buf) => {
            let planes: Vec<&[f32]> = (0..buf.num_planes())
                .map(|i| buf.plane(i).unwrap())
                .collect();
            feed(&planes, buf.frames(), |s| s as f64, analyzer, peak);
        }
        GenericAudioBufferRef::S16(buf) => {
            let planes: Vec<&[i16]> = (0..buf.num_planes())
                .map(|i| buf.plane(i).unwrap())
                .collect();
            feed(
                &planes,
                buf.frames(),
                |s| s as f64 / SAMPLE_SCALE_16BIT,
                analyzer,
                peak,
            );
        }
        GenericAudioBufferRef::S32(buf) => {
            let planes: Vec<&[i32]> = (0..buf.num_planes())
                .map(|i| buf.plane(i).unwrap())
                .collect();
            feed(
                &planes,
                buf.frames(),
                |s| s as f64 / SAMPLE_SCALE_32BIT,
                analyzer,
                peak,
            );
        }
        _ => {
            // Unsupported format, skip
        }
    }
}

/// Byte-level progress callback: `(file_index, bytes_read, total_bytes)`.
pub type AlbumProgressFn<'a> = &'a dyn Fn(usize, u64, u64);

/// Per-file completion callback: `(file_index, path)`.
pub type AlbumCompleteFn<'a> = &'a (dyn Fn(usize, &Path) + Sync);

/// Options for [`analyze_album_with_options`] (issue #250).
///
/// `Default` is serial, strict analysis of the first audio track with no
/// callbacks — the same behavior as [`analyze_album`].
#[derive(Default)]
pub struct AlbumAnalysisOptions<'a> {
    /// Which audio track to analyze in multi-track containers (default: first).
    pub track_index: Option<u32>,
    /// Worker threads. `<= 1` (or a single file) analyzes serially; larger
    /// values decode files concurrently on the rayon pool. The album
    /// histogram fold is associative and results are folded in input order,
    /// so the parallel result is numerically identical to the serial one.
    pub threads: usize,
    /// Lenient mode: files that fail to analyze are skipped instead of
    /// aborting the album. Failures land in [`AlbumAnalysisReport::failures`];
    /// it is only an error when every file fails.
    pub skip_errors: bool,
    /// Byte-level progress callback `(file_index, bytes_read, total_bytes)`,
    /// called after each decoded packet (#106). Only driven on the serial
    /// path; ignored when decoding in parallel (use [`Self::on_complete`]
    /// for file-count progress instead).
    pub on_progress: Option<AlbumProgressFn<'a>>,
    /// Per-file completion callback `(file_index, path)`, invoked after each
    /// file finishes (whether it succeeded or failed). On the parallel path
    /// it is called from rayon worker threads, so it must be `Sync`.
    pub on_complete: Option<AlbumCompleteFn<'a>>,
    /// Cooperative cancellation, checked at file boundaries. Once set,
    /// remaining files are not analyzed and [`Error::Cancelled`] is
    /// returned. Files already being decoded run to completion.
    pub cancel: Option<&'a AtomicBool>,
    /// Loudness measurement algorithm (issue #269). Defaults to
    /// [`AnalysisMode::Rg1`], the mp3gain-compatible algorithm.
    pub mode: AnalysisMode,
    /// Measure BS.1770-4 Annex 2 true peak instead of sample peak in the
    /// BS.1770 modes (issue #292); see [`TrackAnalysisOptions::true_peak`].
    /// Ignored in [`AnalysisMode::Rg1`].
    pub true_peak: bool,
}

/// Analyze multiple tracks for album gain (strict, serial, no callbacks).
/// Convenience wrapper over [`analyze_album_with_options`].
#[cfg(feature = "replaygain")]
pub fn analyze_album(files: &[&Path]) -> Result<AlbumGainResult> {
    Ok(analyze_album_with_options(files, &AlbumAnalysisOptions::default())?.album)
}

/// Analyze multiple tracks for album gain.
///
/// This implements the same algorithm as the original mp3gain:
/// - Accumulate all 50ms RMS window values from all tracks into a single histogram
/// - Calculate album loudness from the combined histogram using 95th percentile
/// - This properly weights each track by its duration (more windows = more influence)
///
/// Every knob (track selection, parallelism, lenient error handling,
/// progress / completion callbacks, cancellation) is an
/// [`AlbumAnalysisOptions`] field — see the field docs for semantics.
#[cfg(feature = "replaygain")]
pub fn analyze_album_with_options(
    files: &[&Path],
    opts: &AlbumAnalysisOptions,
) -> Result<AlbumAnalysisReport> {
    if opts.threads <= 1 || files.len() <= 1 {
        analyze_album_serial(files, opts)
    } else {
        analyze_album_parallel_internal(files, opts)
    }
}

#[cfg(feature = "replaygain")]
fn analyze_album_serial(
    files: &[&Path],
    opts: &AlbumAnalysisOptions,
) -> Result<AlbumAnalysisReport> {
    let AlbumAnalysisOptions {
        track_index,
        on_progress,
        on_complete,
        skip_errors,
        cancel,
        mode,
        true_peak,
        ..
    } = *opts;
    let mut track_results = Vec::with_capacity(files.len());
    let mut album_peak: f64 = 0.0;
    // Album state accumulates all track states (like B[] in original mp3gain)
    let mut album_state = LoudnessState::new(mode);
    let mut failures: Vec<(usize, String)> = Vec::new();
    let mut successful_indices: Vec<usize> = Vec::with_capacity(files.len());

    for (i, file) in files.iter().enumerate() {
        if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
            return Err(Error::Cancelled);
        }
        // Create a per-file progress callback that includes the file index
        let file_progress: Option<Box<dyn Fn(u64, u64) + '_>> =
            on_progress.map(|cb| Box::new(move |bytes, total| cb(i, bytes, total)) as _);

        // Analyze each track and get its loudness state
        let track =
            analyze_track_internal(file, track_index, file_progress.as_deref(), mode, true_peak);
        if let Some(cb) = on_complete {
            cb(i, file);
        }
        match track {
            Ok(internal) => {
                album_peak = album_peak.max(internal.result.peak);
                album_state.accumulate(&internal.state);
                track_results.push(internal.result);
                successful_indices.push(i);
            }
            // A file whose *format* mp3rgain cannot process is dropped from
            // the set whether or not `--skip-errors` is on (issue #330): the
            // album gain over the remaining tracks is still correct, and one
            // ALAC track should not fail the whole album.
            Err(e) if skip_errors || e.is_unsupported_format() => {
                failures.push((i, format!("{}", e)));
            }
            Err(e) => return Err(e),
        }
    }

    if track_results.is_empty() && !files.is_empty() {
        return Err(Error::AllFilesFailed { count: files.len() });
    }

    // Calculate album loudness from the combined state
    let (album_loudness_db, album_gain_db) = album_state.loudness_and_gain(mode);

    let album = AlbumGainResult::new(track_results, album_loudness_db, album_gain_db, album_peak);
    Ok(AlbumAnalysisReport {
        album,
        failures,
        successful_indices,
    })
}

#[cfg(feature = "replaygain")]
fn analyze_album_parallel_internal(
    files: &[&Path],
    opts: &AlbumAnalysisOptions,
) -> Result<AlbumAnalysisReport> {
    use rayon::prelude::*;

    let AlbumAnalysisOptions {
        track_index,
        on_complete,
        skip_errors,
        cancel,
        mode,
        true_peak,
        ..
    } = *opts;

    let mut track_results = Vec::with_capacity(files.len());
    let mut album_peak: f64 = 0.0;
    let mut album_state = LoudnessState::new(mode);
    let mut failures: Vec<(usize, String)> = Vec::new();
    let mut successful_indices: Vec<usize> = Vec::with_capacity(files.len());

    // par_iter().collect() preserves input order, which keeps album_peak
    // / album_state folding deterministic and matches the serial path
    // bit-for-bit. Strict mode short-circuits at the first error; lenient
    // collects all outcomes so failures can be reported alongside successes.
    if skip_errors {
        let internals: Vec<Result<TrackAnalysisInternal>> = files
            .par_iter()
            .enumerate()
            .map(|(i, file)| {
                if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
                    return Err(Error::Cancelled);
                }
                let r = analyze_track_internal(file, track_index, None, mode, true_peak);
                if let Some(cb) = on_complete {
                    cb(i, file);
                }
                r
            })
            .collect();
        if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
            return Err(Error::Cancelled);
        }
        for (i, r) in internals.into_iter().enumerate() {
            match r {
                Ok(internal) => {
                    album_peak = album_peak.max(internal.result.peak);
                    album_state.accumulate(&internal.state);
                    track_results.push(internal.result);
                    successful_indices.push(i);
                }
                Err(e) => failures.push((i, format!("{}", e))),
            }
        }
    } else {
        // collect::<Result<Vec<_>>>() short-circuits at the first error,
        // matching the serial path's fail-fast behavior. An unsupported
        // format is not such an error (issue #330), so it rides through as an
        // *inner* Err — the collect keeps going, and it joins `failures`
        // below like a `--skip-errors` skip would.
        let internals: Vec<Result<TrackAnalysisInternal>> = files
            .par_iter()
            .enumerate()
            .map(|(i, file)| {
                if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
                    return Err(Error::Cancelled);
                }
                let r = analyze_track_internal(file, track_index, None, mode, true_peak);
                if let Some(cb) = on_complete {
                    cb(i, file);
                }
                match r {
                    Err(e) if e.is_unsupported_format() => Ok(Err(e)),
                    other => other.map(Ok),
                }
            })
            .collect::<Result<Vec<_>>>()?;
        for (i, r) in internals.into_iter().enumerate() {
            match r {
                Ok(internal) => {
                    album_peak = album_peak.max(internal.result.peak);
                    album_state.accumulate(&internal.state);
                    track_results.push(internal.result);
                    successful_indices.push(i);
                }
                Err(e) => failures.push((i, format!("{}", e))),
            }
        }
    }

    if track_results.is_empty() && !files.is_empty() {
        return Err(Error::AllFilesFailed { count: files.len() });
    }

    let (album_loudness_db, album_gain_db) = album_state.loudness_and_gain(mode);

    let album = AlbumGainResult::new(track_results, album_loudness_db, album_gain_db, album_peak);
    Ok(AlbumAnalysisReport {
        album,
        failures,
        successful_indices,
    })
}

// =============================================================================
// Stub implementations when feature is disabled
// =============================================================================

#[cfg(not(feature = "replaygain"))]
pub fn analyze_track(_file_path: &Path) -> Result<ReplayGainResult> {
    Err(Error::FeatureNotAvailable {
        feature: "ReplayGain analysis",
        feature_flag: "replaygain",
    })
}

#[cfg(not(feature = "replaygain"))]
pub fn analyze_track_with_index(
    _file_path: &Path,
    _track_index: Option<u32>,
) -> Result<ReplayGainResult> {
    Err(Error::FeatureNotAvailable {
        feature: "ReplayGain analysis",
        feature_flag: "replaygain",
    })
}

#[cfg(not(feature = "replaygain"))]
pub fn analyze_track_with_mode(
    _file_path: &Path,
    _track_index: Option<u32>,
    _mode: AnalysisMode,
    _on_progress: Option<&dyn Fn(u64, u64)>,
) -> Result<ReplayGainResult> {
    Err(Error::FeatureNotAvailable {
        feature: "ReplayGain analysis",
        feature_flag: "replaygain",
    })
}

#[cfg(not(feature = "replaygain"))]
pub fn analyze_track_with_options(
    _file_path: &Path,
    _opts: &TrackAnalysisOptions,
) -> Result<ReplayGainResult> {
    Err(Error::FeatureNotAvailable {
        feature: "ReplayGain analysis",
        feature_flag: "replaygain",
    })
}

#[cfg(not(feature = "replaygain"))]
pub fn analyze_track_with_progress(
    _file_path: &Path,
    _track_index: Option<u32>,
    _on_progress: &dyn Fn(u64, u64),
) -> Result<ReplayGainResult> {
    Err(Error::FeatureNotAvailable {
        feature: "ReplayGain analysis",
        feature_flag: "replaygain",
    })
}

#[cfg(not(feature = "replaygain"))]
pub fn analyze_album(_files: &[&Path]) -> Result<AlbumGainResult> {
    Err(Error::FeatureNotAvailable {
        feature: "ReplayGain analysis",
        feature_flag: "replaygain",
    })
}

#[cfg(not(feature = "replaygain"))]
pub fn analyze_album_with_options(
    _files: &[&Path],
    _opts: &AlbumAnalysisOptions,
) -> Result<AlbumAnalysisReport> {
    Err(Error::FeatureNotAvailable {
        feature: "ReplayGain analysis",
        feature_flag: "replaygain",
    })
}

/// Check if ReplayGain feature is available
pub fn is_available() -> bool {
    cfg!(feature = "replaygain")
}

/// Result of peak amplitude analysis
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PeakAmplitudeResult {
    peak: f64,
    peak_pcm: f64,
    sample_rate: u32,
}

impl PeakAmplitudeResult {
    #[allow(dead_code)]
    pub(crate) fn new(peak: f64, peak_pcm: f64, sample_rate: u32) -> Self {
        Self {
            peak,
            peak_pcm,
            sample_rate,
        }
    }

    pub fn peak(&self) -> f64 {
        self.peak
    }
    pub fn peak_pcm(&self) -> f64 {
        self.peak_pcm
    }
    pub fn sample_rate(&self) -> u32 {
        self.sample_rate
    }
}

impl std::fmt::Display for PeakAmplitudeResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "peak: {:.6} ({:.1} PCM)", self.peak, self.peak_pcm)
    }
}

/// Find the peak amplitude of an audio file by decoding the audio.
/// This properly decodes the audio to measure actual PCM sample values,
/// unlike the old method that estimated from global_gain fields.
///
/// Returns peak amplitude that can exceed 1.0 for clipping audio.
#[cfg(feature = "replaygain")]
pub fn find_peak_amplitude(file_path: &Path) -> Result<PeakAmplitudeResult> {
    let file = std::fs::File::open(file_path).map_err(|e| Error::io_open(file_path, e))?;
    find_peak_amplitude_from_source(file_path, Box::new(file))
}

/// [`find_peak_amplitude`] over bytes already in memory, for callers that
/// read the file for another scan and shouldn't pay a second disk read.
/// `file_path` is only used for the format hint and error messages.
#[cfg(feature = "replaygain")]
pub fn find_peak_amplitude_in_data(file_path: &Path, data: Vec<u8>) -> Result<PeakAmplitudeResult> {
    find_peak_amplitude_from_source(file_path, Box::new(std::io::Cursor::new(data)))
}

#[cfg(feature = "replaygain")]
fn find_peak_amplitude_from_source(
    file_path: &Path,
    source: Box<dyn MediaSource>,
) -> Result<PeakAmplitudeResult> {
    let mss = MediaSourceStream::new(source, Default::default());

    let mut hint = Hint::new();
    if let Some(ext) = file_path.extension().and_then(|e| e.to_str()) {
        hint.with_extension(ext);
    }

    let mut format = symphonia::default::get_probe()
        .probe(
            &hint,
            mss,
            FormatOptions::default(),
            MetadataOptions::default(),
        )
        .map_err(|e| Error::ProbeFailed {
            path: file_path.to_path_buf(),
            source: Box::new(e),
        })?;

    let track = format
        .tracks()
        .iter()
        .find(|t| {
            t.codec_params
                .as_ref()
                .and_then(|p| p.audio())
                .is_some_and(|a| a.codec != CODEC_ID_NULL_AUDIO)
        })
        .ok_or(Error::NoAudioTrack)?;

    let track_id = track.id;
    let audio_params = track
        .codec_params
        .as_ref()
        .and_then(|p| p.audio())
        .ok_or(Error::NoAudioTrack)?;
    let sample_rate = audio_params
        .sample_rate
        .ok_or(Error::UnsupportedSampleRate(0))?;

    let mut decoder = symphonia::default::get_codecs()
        .make_audio_decoder(audio_params, &AudioDecoderOptions::default())
        .map_err(|e| Error::Decode(Box::new(e)))?;

    let mut max_peak: f64 = 0.0;

    loop {
        let packet = match format.next_packet() {
            Ok(Some(p)) => p,
            Ok(None) => break,
            Err(e) => return Err(Error::Decode(Box::new(e))),
        };

        if packet.track_id != track_id {
            continue;
        }

        let decoded = match decoder.decode(&packet) {
            Ok(d) => d,
            Err(symphonia::core::errors::Error::DecodeError(_)) => continue,
            Err(e) => return Err(Error::Decode(Box::new(e))),
        };

        // Process each sample format and track peak
        // Symphonia's MP3 decoder outputs F32 samples in the range [-1.0, 1.0]
        // However, the decoder internally clips samples that exceed this range.
        // For accurate peak detection of potentially clipping audio, we need to
        // access the raw decoded values before normalization.
        //
        // The F32 buffer from Symphonia is already normalized and clipped.
        // To detect clipping, we check if the peak is exactly 1.0 (or very close),
        // which indicates the audio may have been clipped by the decoder.
        // Iterate plane-major so `plane(ch).unwrap()` happens once per channel
        // rather than once per sample.
        match &decoded {
            GenericAudioBufferRef::F32(buf) => {
                for ch in 0..buf.num_planes() {
                    for &sample in buf.plane(ch).unwrap() {
                        max_peak = max_peak.max((sample as f64).abs());
                    }
                }
            }
            GenericAudioBufferRef::S16(buf) => {
                for ch in 0..buf.num_planes() {
                    for &sample in buf.plane(ch).unwrap() {
                        // S16 samples: convert to normalized range
                        // This can exceed 1.0 if sample is at max (32767/32768 ≈ 0.99997)
                        let s = (sample as f64).abs() / SAMPLE_SCALE_16BIT;
                        max_peak = max_peak.max(s);
                    }
                }
            }
            GenericAudioBufferRef::S32(buf) => {
                for ch in 0..buf.num_planes() {
                    for &sample in buf.plane(ch).unwrap() {
                        let s = (sample as f64).abs() / SAMPLE_SCALE_32BIT;
                        max_peak = max_peak.max(s);
                    }
                }
            }
            _ => {}
        }
    }

    Ok(PeakAmplitudeResult::new(
        max_peak,
        crate::gain::peak_to_pcm_sample(max_peak),
        sample_rate,
    ))
}

#[cfg(not(feature = "replaygain"))]
pub fn find_peak_amplitude(_file_path: &Path) -> Result<PeakAmplitudeResult> {
    Err(Error::FeatureNotAvailable {
        feature: "Peak amplitude analysis",
        feature_flag: "replaygain",
    })
}

#[cfg(not(feature = "replaygain"))]
pub fn find_peak_amplitude_in_data(
    _file_path: &Path,
    _data: Vec<u8>,
) -> Result<PeakAmplitudeResult> {
    Err(Error::FeatureNotAvailable {
        feature: "Peak amplitude analysis",
        feature_flag: "replaygain",
    })
}

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

    #[test]
    fn test_replaygain_availability() {
        // This test just verifies the stub functions compile
        let available = is_available();
        #[cfg(feature = "replaygain")]
        assert!(available);
        #[cfg(not(feature = "replaygain"))]
        assert!(!available);
    }

    #[test]
    fn with_peak_replaces_peak_and_preserves_other_fields() {
        let original = ReplayGainResult::new(
            -15.0,
            6.0,
            0.5,
            44_100,
            AudioFileType::Mp3,
            AnalysisMode::Rg1,
        );
        let updated = original.clone().with_peak(0.8);
        assert_eq!(updated.peak(), 0.8);
        assert_eq!(updated.gain_db(), original.gain_db());
        assert_eq!(updated.loudness_db(), original.loudness_db());
        assert_eq!(updated.sample_rate(), original.sample_rate());
        assert_eq!(updated.file_type(), original.file_type());
    }

    #[cfg(feature = "replaygain")]
    #[test]
    fn test_filter_creation() {
        // Test all supported sample rates
        let supported_rates = [
            96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000,
        ];
        for rate in supported_rates {
            let filter = EqualLoudnessFilter::new(rate);
            assert!(filter.is_some(), "Sample rate {} should be supported", rate);
            let filter = filter.unwrap();
            assert_eq!(filter.yule_a.len(), 11);
            assert_eq!(filter.butter_a.len(), 3);
        }

        // Test unsupported sample rate
        let unsupported = EqualLoudnessFilter::new(99999);
        assert!(
            unsupported.is_none(),
            "Unsupported sample rate should return None"
        );
    }

    #[cfg(feature = "replaygain")]
    #[test]
    fn test_rms_calculation() {
        // Test that the analyzer correctly processes samples through the full filter chain
        let sample_rate = 44100u32;
        let mut filter = EqualLoudnessFilter::new(sample_rate).unwrap();
        let mut analyzer = ReplayGainAnalyzer::new(sample_rate);

        // Create a simple sine wave at 1kHz
        // Note: ReplayGain algorithm expects 16-bit range samples (-32768 to 32767)
        let frequency = 1000.0;
        let amplitude_normalized = 0.5; // Normalized amplitude (0.0 to 1.0)
        let amplitude = amplitude_normalized * SAMPLE_SCALE_16BIT; // Scale to 16-bit range
        let duration_samples = sample_rate as usize; // 1 second

        for i in 0..duration_samples {
            let t = i as f64 / sample_rate as f64;
            let sample = amplitude * (2.0 * std::f64::consts::PI * frequency * t).sin();
            let filtered = filter.process(sample);
            analyzer.add_mono_sample(filtered);
        }

        // Should have processed multiple windows (1 second = 20 windows at 50ms each)
        let loudness = analyzer.get_loudness();
        // Loudness should be a reasonable positive dB value for 16-bit range samples
        // After equal-loudness filtering, the value will vary based on frequency response
        assert!(
            loudness > 50.0,
            "Loudness should be above 50 dB: {}",
            loudness
        );
        assert!(
            loudness < 100.0,
            "Loudness should be below 100 dB: {}",
            loudness
        );
    }

    #[cfg(feature = "replaygain")]
    #[test]
    fn lenient_album_skips_failed_files() {
        // Issue #144: --skip-errors should let album analysis continue when a
        // single file fails to probe. Mix one good fixture with one bogus path.
        let good = std::path::PathBuf::from("tests/fixtures/test_stereo.mp3");
        let bad = std::path::PathBuf::from("tests/fixtures/this-file-does-not-exist.mp3");
        let files = vec![good.as_path(), bad.as_path()];

        let strict = analyze_album(&files);
        assert!(
            strict.is_err(),
            "strict mode must fail when any file is unreadable"
        );

        let lenient = AlbumAnalysisOptions {
            skip_errors: true,
            ..Default::default()
        };
        let report =
            analyze_album_with_options(&files, &lenient).expect("lenient must skip the bad file");
        assert_eq!(report.album.tracks().len(), 1);
        assert_eq!(report.successful_indices, vec![0]);
        assert_eq!(report.failures.len(), 1);
        assert_eq!(report.failures[0].0, 1);
    }

    #[cfg(feature = "replaygain")]
    #[test]
    fn lenient_album_errors_when_all_fail() {
        let bad1 = std::path::PathBuf::from("tests/fixtures/missing-1.mp3");
        let bad2 = std::path::PathBuf::from("tests/fixtures/missing-2.mp3");
        let files = vec![bad1.as_path(), bad2.as_path()];

        let lenient = AlbumAnalysisOptions {
            skip_errors: true,
            ..Default::default()
        };
        let result = analyze_album_with_options(&files, &lenient);
        assert!(matches!(result, Err(Error::AllFilesFailed { count: 2 })));
    }

    #[cfg(feature = "replaygain")]
    #[test]
    fn test_loudness_calculation() {
        // Test analyzer with known amplitude using a 1kHz sine wave
        // (DC is filtered out by the equal-loudness filter)
        let sample_rate = 44100u32;
        let mut filter = EqualLoudnessFilter::new(sample_rate).unwrap();
        let mut analyzer = ReplayGainAnalyzer::new(sample_rate);

        // Feed a 1kHz sine wave at 0.1 normalized amplitude
        // Note: ReplayGain algorithm expects 16-bit range samples
        let frequency = 1000.0;
        let amplitude_normalized = 0.1; // Normalized amplitude
        let amplitude = amplitude_normalized * SAMPLE_SCALE_16BIT; // Scale to 16-bit range (3276.8)
        let duration_samples = sample_rate as usize; // 1 second

        for i in 0..duration_samples {
            let t = i as f64 / sample_rate as f64;
            let sample = amplitude * (2.0 * std::f64::consts::PI * frequency * t).sin();
            let filtered = filter.process(sample);
            analyzer.add_mono_sample(filtered);
        }

        let loudness = analyzer.get_loudness();
        // For a sine wave at 3276.8 amplitude, after filtering the loudness
        // should be in a reasonable range for 16-bit audio
        assert!(
            loudness > 50.0 && loudness < 80.0,
            "Loudness {} should be between 50 and 80 dB for a 0.1 amplitude 1kHz sine",
            loudness
        );
    }

    /// Issue #236: a fully silent file must read 0 dB loudness (all windows
    /// clamp into bin 0, which the reference gain_analysis.c defines as 0 dB),
    /// giving a suggested gain of exactly PINK_REF = +64.82 dB — matching
    /// mp3gain, not the previous −20 dB / +84.82 dB.
    #[cfg(feature = "replaygain")]
    #[test]
    fn silent_file_matches_reference_zero_db() {
        let sample_rate = 44100u32;
        let mut filter = EqualLoudnessFilter::new(sample_rate).unwrap();
        let mut analyzer = ReplayGainAnalyzer::new(sample_rate);

        // 20 full 50ms windows of digital silence
        for _ in 0..sample_rate {
            let filtered = filter.process(0.0);
            analyzer.add_mono_sample(filtered);
        }

        let loudness = analyzer.get_loudness();
        assert_eq!(loudness, 0.0, "silent file loudness must clamp to 0 dB");
        assert!(
            (PINK_REF - loudness - 64.82).abs() < 1e-12,
            "silent file gain must be +64.82 dB (mp3gain reference)"
        );
    }

    /// Issue #236: when ≥95% of windows are silent, the 95th percentile falls
    /// in bin 0 and the reference reports 0 dB — not a negative loudness.
    #[cfg(feature = "replaygain")]
    #[test]
    fn near_silent_file_matches_reference_zero_db() {
        let sample_rate = 44100u32;
        let window = (sample_rate as usize * 50) / 1000;
        let mut filter = EqualLoudnessFilter::new(sample_rate).unwrap();
        let mut analyzer = ReplayGainAnalyzer::new(sample_rate);

        // 100 windows: 96 silent, 4 loud (1kHz sine at half scale).
        // threshold = ceil(0.05 * 100) = 5 > 4 loud windows, so the
        // percentile lands in bin 0 → 0 dB, exactly like gain_analysis.c.
        let frequency = 1000.0;
        let amplitude = 0.5 * SAMPLE_SCALE_16BIT;
        for i in 0..(window * 100) {
            let sample = if i < window * 96 {
                0.0
            } else {
                let t = i as f64 / sample_rate as f64;
                amplitude * (2.0 * std::f64::consts::PI * frequency * t).sin()
            };
            let filtered = filter.process(sample);
            analyzer.add_mono_sample(filtered);
        }

        let loudness = analyzer.get_loudness();
        assert_eq!(
            loudness, 0.0,
            "96%-silent file loudness must clamp to 0 dB, got {}",
            loudness
        );
        assert!(
            (PINK_REF - loudness - 64.82).abs() < 1e-12,
            "96%-silent file gain must be +64.82 dB (mp3gain reference)"
        );
    }

    // =========================================================================
    // Issue #201: cross-check the ReplayGain *analysis* against the reference C
    // `gain_analysis.c` by feeding both the identical PCM. The decoder
    // (symphonia) is deliberately kept out of the loop, so any difference here
    // is the analysis and nothing else — isolating it from the ~0.05 dB
    // decoder-vs-decoder gap seen end-to-end against mp3gain.
    // =========================================================================

    #[cfg(feature = "replaygain")]
    const GOLDEN_PCM_SAMPLE_RATE: u32 = 44_100;

    /// 80 full 50 ms windows (44100 * 0.05 = 2205 samples each). An exact
    /// multiple of the window leaves no trailing partial window — the reference
    /// gain_analysis.c only counts a window when it fills, while mp3rgain's
    /// final `finish_window()` would flush a partial one. Matching the window
    /// boundary removes that as a variable.
    #[cfg(feature = "replaygain")]
    const GOLDEN_PCM_FRAMES: usize = 2205 * 80;

    /// Deterministic stereo PCM (normalized to [-1, 1]) used by both the
    /// reference C harness in `tests/reference/` and the test below.
    ///
    /// Layout (80 windows of 50 ms): the first 50 are **silent**, the last 30
    /// are broadband white noise on a distinct-amplitude staircase. The silent
    /// windows are the #217 regression: they must be counted in the
    /// 95th-percentile denominator (clamped to bin 0), not dropped — dropping
    /// them shrinks the total and the staircase makes the resulting percentile
    /// land on a different (louder) bin, so this signal fails without the
    /// `finish_window` clamp. White noise (flat spectrum) also exercises every
    /// filter tap, and the staircase keeps the loud windows on well-separated
    /// bins (no near-ties at the percentile).
    ///
    /// Deliberately uses no transcendentals: a fixed-seed integer LCG, integer
    /// rounding, and division by a power of two (exact in f64). The result is
    /// therefore bit-identical on every platform, so the golden value captured
    /// on one machine is valid for the CI runner too.
    #[cfg(feature = "replaygain")]
    fn golden_pcm() -> (Vec<f64>, Vec<f64>) {
        let win = (GOLDEN_PCM_SAMPLE_RATE as usize * 50) / 1000; // 2205 @ 44.1k
        let n = GOLDEN_PCM_FRAMES;
        let mut left = Vec::with_capacity(n);
        let mut right = Vec::with_capacity(n);
        let mut ls: u64 = 0x1234_5678_9abc_def0;
        let mut rs: u64 = 0x0fed_cba9_8765_4321;
        // 64-bit LCG (Knuth MMIX constants) mapped to [-1, 1) — no rand dep.
        let lcg = |s: &mut u64| -> f64 {
            *s = s
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            ((*s >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0
        };
        for i in 0..n {
            let w = i / win;
            // First 50 windows silent; last 30 a distinct-amplitude staircase.
            let amp = if w < 50 {
                0.0
            } else {
                0.06 + 0.01 * (w - 50) as f64
            };
            let l = (lcg(&mut ls) * amp * 30000.0).round() as i32;
            let r = (lcg(&mut rs) * amp * 30000.0).round() as i32;
            left.push(l as f64 / SAMPLE_SCALE_16BIT);
            right.push(r as f64 / SAMPLE_SCALE_16BIT);
        }
        (left, right)
    }

    /// One-time helper: dump `golden_pcm()` to a binary file the reference C
    /// harness reads. Header is `[u32 sample_rate][u32 frames]` (LE) followed by
    /// `frames` f64 left samples then `frames` f64 right samples. Run with:
    ///   `cargo test --lib dump_golden_pcm -- --ignored --nocapture`
    /// then see `tests/reference/README.md` to produce the golden value.
    #[cfg(feature = "replaygain")]
    #[test]
    #[ignore = "one-time: regenerates the PCM dump for the reference C harness (#201)"]
    fn dump_golden_pcm() {
        let path =
            std::env::var("RG_PCM_DUMP").unwrap_or_else(|_| "/tmp/rg_golden_pcm.bin".to_string());
        let (left, right) = golden_pcm();
        let mut buf = Vec::with_capacity(8 + left.len() * 16);
        buf.extend_from_slice(&GOLDEN_PCM_SAMPLE_RATE.to_le_bytes());
        buf.extend_from_slice(&(left.len() as u32).to_le_bytes());
        // Write the exact values the filter sees: normalized × 16-bit scale.
        // The reference harness feeds these straight into AnalyzeSamples, so
        // both implementations filter identical numbers.
        for &x in &left {
            buf.extend_from_slice(&(x * SAMPLE_SCALE_16BIT).to_le_bytes());
        }
        for &x in &right {
            buf.extend_from_slice(&(x * SAMPLE_SCALE_16BIT).to_le_bytes());
        }
        std::fs::write(&path, &buf).expect("write PCM dump");
        eprintln!(
            "wrote {} frames ({} bytes) to {}",
            left.len(),
            buf.len(),
            path
        );
    }

    /// #201 / #217: the isolated unit test. Feed `golden_pcm()` through
    /// mp3rgain's exact production analysis path (per-channel equal-loudness
    /// filter → windowed RMS → 95th-percentile histogram → gain) and assert it
    /// matches `GetTitleGain()` from the reference C `gain_analysis.c` to
    /// floating-point precision.
    ///
    /// `golden_pcm()` is half silence, which makes this double as the #217
    /// regression test: silent windows must be counted (clamped to bin 0), not
    /// dropped. Without the `finish_window` clamp, mp3rgain reads −1.50 dB here
    /// vs the reference −0.83 dB; with it, they agree to the last ULP.
    ///
    /// `GOLDEN_GAIN_DB` was captured by running the reference harness in
    /// `tests/reference/` on the exact bytes `golden_pcm()` emits — same
    /// lineage mp3gain uses (Glen Sawyer's gain_analysis.c), compiled with
    /// `Float_t = double` to match mp3gain's original precision and mp3rgain's
    /// f64. See `tests/reference/README.md` to reproduce.
    #[cfg(feature = "replaygain")]
    #[test]
    fn analysis_matches_reference_c_to_float_precision() {
        // GetTitleGain() from tests/reference/ on golden_pcm() (44100 Hz, stereo),
        // captured with `./tests/reference/run.sh`. mp3rgain reproduces this to
        // the last ULP (Δ < 1e-15 dB) — the analysis is bit-faithful, including
        // the silent-window histogram clamp (#217).
        const GOLDEN_GAIN_DB: f64 = -0.83000000000001251;

        let (left, right) = golden_pcm();
        let sr = GOLDEN_PCM_SAMPLE_RATE;
        let mut filter_l = EqualLoudnessFilter::new(sr).unwrap();
        let mut filter_r = EqualLoudnessFilter::new(sr).unwrap();
        let mut analyzer = ReplayGainAnalyzer::new(sr);

        // Identical to process_audio_buffer's F32 path: normalized samples are
        // scaled to 16-bit range before filtering, then squared per window.
        for (&l, &r) in left.iter().zip(right.iter()) {
            let lf = filter_l.process(l * SAMPLE_SCALE_16BIT);
            let rf = filter_r.process(r * SAMPLE_SCALE_16BIT);
            analyzer.add_sample(lf, rf);
        }
        analyzer.finish_window(); // no-op: GOLDEN_PCM_FRAMES is a window multiple
        let gain = PINK_REF - analyzer.get_loudness();

        let delta = (gain - GOLDEN_GAIN_DB).abs();
        assert!(
            delta < 1e-6,
            "ReplayGain analysis diverged from reference gain_analysis.c: \
             mp3rgain {gain:.12} dB vs reference {GOLDEN_GAIN_DB:.12} dB (Δ {delta:.3e} dB)"
        );
    }
}