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
//\! Single-speaker EQ optimization
//\!
//\! This module handles optimization of individual speakers with a single measurement.
//\! Includes support for Schroeder split, multi-measurement strategies, and target curve matching.
use super::spectral_align;
use crate::Curve;
use crate::error::{AutoeqError, Result};
use crate::read as load;
use crate::response;
use log::{debug, info, warn};
use math_audio_dsp::analysis::compute_average_response;
use math_audio_iir_fir::Biquad;
use ndarray::Array1;
use std::path::Path;
use super::eq;
use super::excursion;
use super::fir;
use super::output;
use super::target_tilt;
use super::types::{
ChannelDspChain, MeasurementSource, OptimizerConfig, ProcessingMode, RoomConfig, TargetShape,
TiltType,
};
// Import from optimize and group_processing modules
use super::group_processing::process_mixed_mode_crossover;
use super::optimize::{detect_passband_and_mean, extract_wav_path};
// Type aliases from optimize module
pub(super) type MixedModeResult = (
ChannelDspChain,
f64,
f64,
Curve,
Curve,
Vec<Biquad>,
f64,
Option<f64>,
Option<Vec<f64>>,
);
pub(super) fn optimize_eq_maybe_multi(
source: &MeasurementSource,
optimization_curve: &Curve,
optimizer_config: &OptimizerConfig,
target_config: Option<&super::types::TargetCurveConfig>,
sample_rate: f64,
channel_name: &str,
callback: Option<crate::optim::OptimProgressCallback>,
target_tilt_curve: Option<&Curve>,
) -> Result<(Vec<Biquad>, f64)> {
use super::types::MultiMeasurementStrategy;
let use_multi = matches!(
source,
MeasurementSource::Multiple(_) | MeasurementSource::InMemoryMultiple(_)
) && optimizer_config
.multi_measurement
.as_ref()
.is_some_and(|mc| mc.strategy != MultiMeasurementStrategy::Average);
if use_multi {
let multi_config = optimizer_config.multi_measurement.as_ref().unwrap();
let raw_curves =
load::load_source_individual(source).map_err(|e| AutoeqError::InvalidMeasurement {
message: format!(
"Failed to load individual measurements for channel {}: {}",
channel_name, e
),
})?;
// Apply target tilt to each individual curve (same as single-measurement path).
// Without this, multi-measurement optimization sees untilted curves while the
// averaged curve was tilted, causing variance to increase instead of decrease.
let curves: Vec<Curve> = if let Some(tilt) = target_tilt_curve {
raw_curves
.iter()
.map(|c| Curve {
freq: c.freq.clone(),
spl: &c.spl - &tilt.spl,
phase: c.phase.clone(),
})
.collect()
} else {
raw_curves
};
info!(
" Multi-measurement optimization ({:?}) with {} curves{}",
multi_config.strategy,
curves.len(),
if target_tilt_curve.is_some() { " (tilt applied)" } else { "" },
);
if let Some(cb) = callback {
eq::optimize_channel_eq_multi_with_callback(
&curves,
optimizer_config,
multi_config,
target_config,
sample_rate,
cb,
)
} else {
eq::optimize_channel_eq_multi(
&curves,
optimizer_config,
multi_config,
target_config,
sample_rate,
)
}
.map_err(|e| AutoeqError::OptimizationFailed {
message: format!(
"Multi-measurement EQ optimization failed for channel {}: {}",
channel_name, e
),
})
} else {
if let Some(cb) = callback {
eq::optimize_channel_eq_with_callback(
optimization_curve,
optimizer_config,
target_config,
sample_rate,
cb,
)
} else {
eq::optimize_channel_eq(
optimization_curve,
optimizer_config,
target_config,
sample_rate,
)
}
.map_err(|e| AutoeqError::OptimizationFailed {
message: format!("EQ optimization failed for channel {}: {}", channel_name, e),
})
}
}
/// Process a simple speaker with a single measurement
///
/// Returns: (DSP chain, pre_score, post_score, initial_curve, final_curve, biquads, mean_spl, arrival_time_ms)
///
/// `shared_mean_spl` — when `Some`, the target level is this shared average
/// instead of the channel's own mean. Reduces inter-channel deviation at the
/// source by making all channels optimize toward the same reference level.
pub(super) fn process_single_speaker(
channel_name: &str,
source: &MeasurementSource,
room_config: &RoomConfig,
sample_rate: f64,
output_dir: &Path,
mut callback: Option<crate::optim::OptimProgressCallback>,
probe_arrival_ms: Option<f64>,
shared_mean_spl: Option<f64>,
) -> Result<MixedModeResult> {
// Load measurement
let curve = load::load_source(source).map_err(|e| AutoeqError::InvalidMeasurement {
message: format!(
"Failed to load measurement for channel {}: {}",
channel_name, e
),
})?;
debug!(
" Loaded measurement: {:.1} Hz - {:.1} Hz",
curve.freq[0],
curve.freq[curve.freq.len() - 1]
);
// Use probe-based arrival time if available (more accurate), else fall back to WAV onset
let arrival_time_ms: Option<f64> = if let Some(probe_ms) = probe_arrival_ms {
debug!(
" Using probe-based arrival time for '{}': {:.2} ms",
channel_name, probe_ms
);
Some(probe_ms)
} else {
extract_wav_path(source).and_then(|wav_path| {
let path = std::path::Path::new(&wav_path);
if path.exists() {
match super::time_align::find_arrival_time(path, None) {
Ok(result) => {
debug!(
" Arrival time for '{}': {:.2} ms (peak at sample {})",
channel_name, result.arrival_ms, result.arrival_samples
);
Some(result.arrival_ms)
}
Err(e) => {
debug!(
" Could not determine arrival time for '{}': {}",
channel_name, e
);
None
}
}
} else {
debug!(" WAV file not found for '{}': {:?}", channel_name, path);
None
}
})
};
// ========================================================================
// Build target curve with tilt (if configured)
// ========================================================================
// Build the unified target curve from target_response (or migrated legacy fields).
// This curve is the single source of truth for both broadband pre-correction
// and EQ optimization, eliminating double-tilt bugs.
//
// When 3-pass CEA2034 correction is active, user preferences (bass/treble shelves)
// are emitted as Pass 3 filters rather than being baked into the target curve.
let cea2034_active = room_config
.optimizer
.cea2034_correction
.as_ref()
.is_some_and(|c| c.enabled);
let target_tilt_curve = if let Some(ref target_resp) = room_config.optimizer.target_response {
// When 3-pass is active, strip preferences from the target
// (they become Pass 3 output filters instead)
let effective_target = if cea2034_active {
let mut stripped = target_resp.clone();
stripped.preference = super::types::UserPreference::default();
stripped
} else {
target_resp.clone()
};
if effective_target.shape != TargetShape::Flat
|| effective_target.preference.bass_shelf_db.abs() > 1e-6
|| effective_target.preference.treble_shelf_db.abs() > 1e-6
{
info!(
" Building target curve: shape={:?}, slope={:.2} dB/oct, bass={:+.1}dB, treble={:+.1}dB{}",
effective_target.shape,
match effective_target.shape {
TargetShape::Harman => -0.8,
TargetShape::Custom => effective_target.slope_db_per_octave,
_ => 0.0,
},
effective_target.preference.bass_shelf_db,
effective_target.preference.treble_shelf_db,
if cea2034_active {
" (preferences extracted to Pass 3)"
} else {
""
},
);
Some(target_tilt::build_complete_target_curve(
&curve.freq,
&effective_target,
))
} else {
None
}
} else if let Some(tilt_config) = &room_config.optimizer.target_tilt {
// Legacy path: target_tilt without migration (shouldn't happen after migrate_target_config)
if tilt_config.tilt_type != TiltType::Flat {
info!(
" Building target curve with legacy {:?} tilt ({:.2} dB/octave)",
tilt_config.tilt_type, tilt_config.slope_db_per_octave
);
Some(target_tilt::build_target_curve_with_tilt(
&curve.freq,
tilt_config,
))
} else {
None
}
} else {
None
};
// When target curve is active, it is baked into the measurement before optimization.
// Passing target_curve on top would double-apply.
if target_tilt_curve.is_some() && room_config.target_curve.is_some() {
warn!(
" Both target_curve and target_response are configured for '{}'. \
target_response is baked into the measurement; target_curve will be \
ignored to avoid double-application.",
channel_name
);
}
// ========================================================================
// Excursion Protection (detect F3, generate HPF)
// ========================================================================
let excursion_filters: Vec<Biquad> =
if let Some(exc_config) = &room_config.optimizer.excursion_protection {
if exc_config.enabled {
info!(" Applying excursion protection...");
match excursion::generate_excursion_protection(&curve, exc_config, sample_rate) {
Ok(result) => {
info!(
" Excursion protection: F3={:.1}Hz, HPF={:.1}Hz ({} filters)",
result.f3_hz,
result.hpf_frequency,
result.filters.len()
);
result.filters
}
Err(e) => {
warn!(
" Excursion protection failed: {}. Continuing without protection.",
e
);
Vec::new()
}
}
} else {
Vec::new()
}
} else {
Vec::new()
};
// Simulate excursion HPF on the curve so the EQ optimizer sees the measurement
// as it will be after the HPF. Without this, the optimizer doesn't know about the
// HPF cuts and stacks additional cuts on top, double-cutting the bass.
// Keep `curve_raw` for final display (all_filters applied to raw measurement).
let curve_raw = curve.clone();
let curve = if !excursion_filters.is_empty() {
let hpf_resp =
response::compute_peq_complex_response(&excursion_filters, &curve.freq, sample_rate);
let adjusted = response::apply_complex_response(&curve, &hpf_resp);
info!(
" Simulating excursion HPF on optimization curve ({} filters)",
excursion_filters.len()
);
adjusted
} else {
curve
};
// ========================================================================
// Pass 1: CEA2034 Speaker Correction (above Schroeder frequency)
// ========================================================================
let (curve, cea2034_filters, cea2034_plugins) = if let Some(cea_config) =
&room_config.optimizer.cea2034_correction
{
if cea_config.enabled {
// Resolve speaker name: config override > MeasurementSource
let speaker_name = cea_config
.speaker_name
.as_deref()
.or_else(|| source.speaker_name());
if let Some(name) = speaker_name {
// Look up pre-fetched CEA2034 data
let cea_data = room_config
.cea2034_cache
.as_ref()
.and_then(|cache| cache.get(name));
if let Some(data) = cea_data {
// Determine Schroeder frequency
let schroeder_freq = cea_config.min_freq.unwrap_or_else(|| {
room_config
.optimizer
.schroeder_split
.as_ref()
.filter(|s| s.enabled)
.map(|s| s.schroeder_freq)
.unwrap_or(300.0)
});
match super::cea2034_correction::compute_speaker_correction(
data,
cea_config,
&curve,
schroeder_freq,
arrival_time_ms,
sample_rate,
) {
Ok((filters, corrected_curve)) => {
info!(
" Pass 1 CEA2034 correction: {} filters above {:.0} Hz for '{}'",
filters.len(),
schroeder_freq,
name
);
let plugin = output::create_labeled_eq_plugin(
&filters,
"cea2034_speaker_correction",
);
(corrected_curve, filters, vec![plugin])
}
Err(e) => {
warn!(
" CEA2034 correction failed for '{}': {}. Skipping Pass 1.",
name, e
);
(curve, vec![], vec![])
}
}
} else {
warn!(
" No CEA2034 data in cache for speaker '{}'. Skipping Pass 1.",
name
);
(curve, vec![], vec![])
}
} else {
debug!(" No speaker_name configured. Skipping CEA2034 correction.");
(curve, vec![], vec![])
}
} else {
(curve, vec![], vec![])
}
} else {
(curve, vec![], vec![])
};
// Compute pre-score (within EQ range)
let mut min_freq = room_config.optimizer.min_freq;
let max_freq = room_config.optimizer.max_freq;
// Detect passband for display metadata only
let (norm_range, _passband_mean) = detect_passband_and_mean(&curve);
if let Some((f_low, f_high)) = norm_range {
info!(
" Detected passband for '{}': {:.1} Hz - {:.1} Hz",
channel_name, f_low, f_high
);
}
// When target tilt is active, clamp min_freq to the speaker's F3 rolloff.
// Without this, the tilt creates a massive target deficit below the speaker's
// capability (e.g. +4.5dB at 20Hz on a speaker that rolls off at 60Hz).
// The optimizer wastes filters on impossible bass boost, and the broad filter
// skirts cause collateral damage in the midrange.
if target_tilt_curve.is_some() {
match excursion::detect_f3(&curve, None) {
Ok(f3_result) => {
// Only clamp if F3 is above the configured min_freq but still
// well below max_freq. A very high "F3" (e.g., on a tilted curve
// with no real rolloff) would invalidate the frequency range.
if f3_result.f3_hz > min_freq && f3_result.f3_hz < max_freq * 0.5 {
info!(
" Tilt active: clamping min_freq from {:.1}Hz to F3={:.1}Hz \
to prevent bass over-boost below rolloff",
min_freq, f3_result.f3_hz
);
min_freq = f3_result.f3_hz;
}
}
Err(e) => {
debug!(
" F3 detection failed for tilt clamping: {}. Using configured min_freq.",
e
);
}
}
}
// Use range-based mean (same as optimizer) for consistent pre/post scoring
let pre_freqs_f32: Vec<f32> = curve.freq.iter().map(|&f| f as f32).collect();
let pre_spl_f32: Vec<f32> = curve.spl.iter().map(|&s| s as f32).collect();
let pre_mean = compute_average_response(
&pre_freqs_f32,
&pre_spl_f32,
Some((min_freq as f32, max_freq as f32)),
) as f64;
let normalized_spl = &curve.spl - pre_mean;
let pre_score = crate::loss::flat_loss(&curve.freq, &normalized_spl, min_freq, max_freq);
// Level alignment: use mean SPL within the EQ optimization range.
// Passband mean (-3 dB from peak) is too narrow for resonant room data;
// full-range mean is misleading for bandpass speakers (subwoofers).
// The optimizer range gives a consistent reference across channel types.
let freqs_f32: Vec<f32> = curve.freq.iter().map(|&f| f as f32).collect();
let spl_f32: Vec<f32> = curve.spl.iter().map(|&s| s as f32).collect();
let channel_mean_spl = compute_average_response(
&freqs_f32,
&spl_f32,
Some((min_freq as f32, max_freq as f32)),
) as f64;
// When a shared average level is provided (multi-channel pre-pass), use it
// as the target level instead of this channel's own mean. This makes all
// channels optimize toward the same reference, reducing ICD at the source.
let mean_spl = if let Some(shared) = shared_mean_spl {
debug!(
" Using shared target level {:.1} dB (channel mean was {:.1} dB, delta {:.1} dB)",
shared,
channel_mean_spl,
shared - channel_mean_spl
);
shared
} else {
channel_mean_spl
};
// ========================================================================
// Broadband Pre-Correction
// ========================================================================
// Fit shelves/gain to the complete target curve (including tilt + preference)
// within the speaker's passband, establishing a balanced baseline before
// fine-grained EQ optimization. Both broadband and optimizer share the SAME
// target curve, so there is no double-application of tilt.
let broadband_enabled = room_config
.optimizer
.target_response
.as_ref()
.map(|tr| tr.broadband_precorrection)
.unwrap_or(false)
|| room_config
.optimizer
.broadband_target_matching
.as_ref()
.map(|bb| bb.enabled)
.unwrap_or(false);
let (curve_for_optim, broadband_plugins, broadband_biquads, bb_mean_shift) =
if broadband_enabled {
info!(" Broadband pre-correction enabled...");
// Detect F3 to avoid shelf-correcting below the speaker's rolloff.
let detected_f3 = match excursion::detect_f3(&curve, None) {
Ok(f3_result) if f3_result.f3_hz > min_freq && f3_result.f3_hz < max_freq * 0.5 => {
info!(" Broadband: detected speaker F3={:.1}Hz", f3_result.f3_hz);
Some(f3_result.f3_hz)
}
_ => None,
};
let bb_min_freq = detected_f3.unwrap_or(min_freq);
// Construct target at the measurement's mean level, INCLUDING the
// target shape (tilt + preference). This ensures broadband and
// optimizer pull toward the same goal — no double-tilt.
let target = if let Some(ref tilt_curve) = target_tilt_curve {
Curve {
freq: curve.freq.clone(),
spl: &tilt_curve.spl + mean_spl,
phase: None,
}
} else {
Curve {
freq: curve.freq.clone(),
spl: Array1::from_elem(curve.freq.len(), mean_spl),
phase: None,
}
};
// 2. Compute alignment within the speaker's passband (F3 to 20kHz).
// The target is flat at mean_spl, so the alignment fits gentle
// shelves + gain to correct the measurement's broadband shape.
if let Some(mut result) = spectral_align::compute_target_alignment(
&curve,
&target,
bb_min_freq,
20000.0,
sample_rate,
) {
// Suppress the low-shelf when a rolloff is detected below the
// shelf frequency: the shelf response extends to DC and would
// partially boost the rolloff region, creating a worse shape
// than leaving it uncorrected.
if let Some(f3) = detected_f3
&& f3 < spectral_align::LOWSHELF_FREQ
{
info!(
" Broadband: suppressing low-shelf (F3={:.1}Hz < shelf={:.1}Hz)",
f3,
spectral_align::LOWSHELF_FREQ
);
result.lowshelf_gain_db = 0.0;
}
info!(
" Broadband correction: LS={:+.2}dB, HS={:+.2}dB, Gain={:+.2}dB",
result.lowshelf_gain_db, result.highshelf_gain_db, result.flat_gain_db
);
// 3. Create plugins
let (eq_plugin, gain_plugin) =
spectral_align::create_alignment_plugins(&result, sample_rate);
let mut plugins = Vec::new();
if let Some(g) = gain_plugin {
plugins.push(g);
}
if let Some(eq) = eq_plugin {
plugins.push(eq);
}
// Simulate the broadband correction on the curve
use math_audio_iir_fir::{Biquad, BiquadFilterType, DEFAULT_Q_HIGH_LOW_SHELF};
let mut filters = Vec::new();
if result.lowshelf_gain_db.abs() > 1e-3 {
filters.push(Biquad::new(
BiquadFilterType::Lowshelf,
spectral_align::LOWSHELF_FREQ,
sample_rate,
DEFAULT_Q_HIGH_LOW_SHELF,
result.lowshelf_gain_db,
));
}
if result.highshelf_gain_db.abs() > 1e-3 {
filters.push(Biquad::new(
BiquadFilterType::Highshelf,
spectral_align::HIGHSHELF_FREQ,
sample_rate,
DEFAULT_Q_HIGH_LOW_SHELF,
result.highshelf_gain_db,
));
}
// 1. Gain
let mut temp_curve = curve.clone();
temp_curve.spl += result.flat_gain_db;
// 2. Filters
let corrected_curve = if !filters.is_empty() {
let resp =
response::compute_peq_complex_response(&filters, &curve.freq, sample_rate);
response::apply_complex_response(&temp_curve, &resp)
} else {
temp_curve
};
// 3. Validate: reject broadband correction if it makes things worse.
// Measure deviation from the tilted target — broadband should move
// us CLOSER to the target, not further away. When combined with
// excursion HPF + room modes, the shelf fitting can produce bad
// results that then compound with the optimizer's tilt subtraction.
let target_spl = &target.spl; // mean_spl + tilt (or just mean_spl if flat)
let pre_bb_dev = &curve.spl - target_spl;
let pre_bb_score =
crate::loss::flat_loss(&curve.freq, &pre_bb_dev, min_freq, max_freq);
let post_bb_dev = &corrected_curve.spl - target_spl;
let post_bb_score =
crate::loss::flat_loss(&corrected_curve.freq, &post_bb_dev, min_freq, max_freq);
if post_bb_score > pre_bb_score * 1.5 {
warn!(
" Broadband correction rejected: deviation from target {:.4} -> {:.4} \
(worse by {:.0}%). Shelf fit likely confused by room modes or HPF rolloff.",
pre_bb_score,
post_bb_score,
(post_bb_score / pre_bb_score - 1.0) * 100.0,
);
(curve.clone(), Vec::new(), Vec::new(), 0.0)
} else {
(corrected_curve, plugins, filters, result.flat_gain_db)
}
} else {
(curve.clone(), Vec::new(), Vec::new(), 0.0)
}
} else {
(curve.clone(), Vec::new(), Vec::new(), 0.0)
};
// We must update the mean_spl because the broadband gain shifted it
let mean_spl = mean_spl + bb_mean_shift;
// Build optimizer config with the clamped min_freq so the optimizer
// doesn't place filters below the speaker's rolloff when tilt is active.
// Also inject the WAV path for SSIR analysis if available.
let wav_path_for_ssir = extract_wav_path(source).and_then(|wp| {
let p = std::path::PathBuf::from(&wp);
if p.exists() { Some(p) } else { None }
});
// Detect whether this is a subwoofer/LFE channel
let is_sub_channel = if let Some(sys) = &room_config.system {
if let Some(subs) = &sys.subwoofers {
// v2.1: check if this channel is in the subwoofer mapping
sys.speakers
.get(channel_name)
.is_some_and(|meas_key| subs.mapping.contains_key(meas_key))
} else {
false
}
} else {
// Legacy: name-based detection
channel_name.eq_ignore_ascii_case("lfe") || channel_name.to_lowercase().starts_with("sub")
};
let clamped_optimizer = {
let mut opt = room_config.optimizer.clone();
if min_freq != room_config.optimizer.min_freq {
opt.min_freq = min_freq;
}
opt.ssir_wav_path = wav_path_for_ssir;
// Apply subwoofer-specific optimizer overrides
if is_sub_channel && let Some(sub_cfg) = &room_config.optimizer.sub_config {
info!(
" Applying sub_config overrides: num_filters={}, max_db={:+.1}, min_db={:+.1}, max_q={:.1}",
sub_cfg.num_filters, sub_cfg.max_db, sub_cfg.min_db, sub_cfg.max_q,
);
opt.num_filters = sub_cfg.num_filters;
opt.max_db = sub_cfg.max_db;
opt.min_db = sub_cfg.min_db;
opt.min_q = sub_cfg.min_q;
opt.max_q = sub_cfg.max_q;
}
opt
};
match room_config.optimizer.processing_mode {
ProcessingMode::PhaseLinear => {
info!(" Generating FIR filter...");
// Report initial loss so the progress chart has data
if let Some(ref mut cb) = callback {
cb(1, pre_score);
}
// Check if we should force excess phase correction for GD-Opt on subwoofer
let mut opt_config = clamped_optimizer.clone();
if let Some(gd_opt) = &clamped_optimizer.gd_opt
&& gd_opt.enabled
&& (channel_name == "lfe" || channel_name.starts_with("sub"))
&& let Some(fir) = &mut opt_config.fir
{
fir.correct_excess_phase = true;
info!(
" GD-Opt: Forcing excess phase correction for '{}'",
channel_name
);
}
// Apply target tilt to the curve (subtract tilt from measurement),
// same as LowLatency does
let fir_input_curve = if let Some(ref tilt_curve) = target_tilt_curve {
Curve {
freq: curve_for_optim.freq.clone(),
spl: &curve_for_optim.spl - &tilt_curve.spl,
phase: curve_for_optim.phase.clone(),
}
} else {
curve_for_optim.clone()
};
// When tilt is baked into the curve, don't also pass target_curve
// to the optimizer (would double-apply the target)
let effective_target = if target_tilt_curve.is_some() {
None
} else {
room_config.target_curve.as_ref()
};
let coeffs = fir::generate_fir_correction(
&fir_input_curve,
&opt_config,
effective_target,
sample_rate,
)
.map_err(|e| AutoeqError::OptimizationFailed {
message: format!("FIR generation failed: {}", e),
})?;
let filename = format!("{}_fir.wav", channel_name);
let wav_path = output_dir.join(&filename);
crate::fir::save_fir_to_wav(&coeffs, sample_rate as u32, &wav_path).map_err(|e| {
AutoeqError::OptimizationFailed {
message: format!("Failed to save FIR WAV: {}", e),
}
})?;
info!(" Saved FIR filter to {}", wav_path.display());
// Build DSP chain with convolution plugin referencing the FIR WAV file
let convolution_plugin = output::create_convolution_plugin(&filename);
let mut chain = output::build_channel_dsp_chain_with_curves(
channel_name,
None,
broadband_plugins,
&[],
None,
None,
);
chain.plugins.push(convolution_plugin);
let complex_resp =
response::compute_fir_complex_response(&coeffs, &curve.freq, sample_rate);
let final_curve = response::apply_complex_response(&curve_for_optim, &complex_resp);
// Compute post_score consistently with pre_score (range-based mean)
let post_freqs_f32: Vec<f32> = final_curve.freq.iter().map(|&f| f as f32).collect();
let post_spl_f32: Vec<f32> = final_curve.spl.iter().map(|&s| s as f32).collect();
let mean_final = compute_average_response(
&post_freqs_f32,
&post_spl_f32,
Some((min_freq as f32, max_freq as f32)),
) as f64;
let normalized_final_spl = &final_curve.spl - mean_final;
let post_score = crate::loss::flat_loss(
&final_curve.freq,
&normalized_final_spl,
min_freq,
max_freq,
);
info!(
" Pre-score: {:.6}, Post-score: {:.6}",
pre_score, post_score
);
// Report final loss so the progress chart shows the FIR improvement
if let Some(ref mut cb) = callback {
cb(2, post_score);
}
// Extend curves to 20 Hz – 20 kHz for display output
let display_initial = output::extend_curve_to_full_range(&curve_raw);
let display_fir_resp =
response::compute_fir_complex_response(&coeffs, &display_initial.freq, sample_rate);
let display_final =
response::apply_complex_response(&display_initial, &display_fir_resp);
let mut initial_data: super::types::CurveData = (&display_initial).into();
initial_data.norm_range = norm_range;
let mut final_data: super::types::CurveData = (&display_final).into();
final_data.norm_range = norm_range;
chain.initial_curve = Some(initial_data.clone());
chain.final_curve = Some(final_data.clone());
chain.eq_response = Some(output::compute_eq_response(&initial_data, &final_data));
Ok((
chain,
pre_score,
post_score,
curve_raw.clone(),
final_curve,
vec![],
mean_spl,
arrival_time_ms,
Some(coeffs),
))
}
ProcessingMode::Hybrid => {
// Check for frequency-based crossover configuration
if let Some(mixed_config) = &room_config.optimizer.mixed_config {
// New frequency-based mixed mode: FIR on one band, IIR on the other
return process_mixed_mode_crossover(
channel_name,
&curve_for_optim,
room_config,
mixed_config,
sample_rate,
output_dir,
min_freq,
max_freq,
mean_spl,
pre_score,
arrival_time_ms,
callback,
);
}
// Legacy sequential mixed mode: IIR first, then FIR on residual
// Check if we should force excess phase correction for GD-Opt on subwoofer
let mut opt_config = clamped_optimizer.clone();
if let Some(gd_opt) = &clamped_optimizer.gd_opt
&& gd_opt.enabled
{
let is_sub = if let Some(sys) = &room_config.system {
// V2.1 System Config
if let Some(meas_key) = sys.speakers.get(channel_name) {
if let Some(subs) = &sys.subwoofers {
subs.mapping.contains_key(meas_key)
} else {
false
}
} else {
false
}
} else {
// Legacy
channel_name == "lfe" || channel_name.starts_with("sub")
};
if is_sub && let Some(fir) = &mut opt_config.fir {
fir.correct_excess_phase = true;
info!(
" GD-Opt: Forcing excess phase correction for '{}'",
channel_name
);
}
}
// Apply target tilt to the curve (subtract tilt from measurement),
// same as LowLatency does
let hybrid_optim_curve = if let Some(ref tilt_curve) = target_tilt_curve {
Curve {
freq: curve_for_optim.freq.clone(),
spl: &curve_for_optim.spl - &tilt_curve.spl,
phase: curve_for_optim.phase.clone(),
}
} else {
curve_for_optim.clone()
};
// When tilt is baked into the curve, don't also pass target_curve
// to the optimizer (would double-apply the target)
let effective_target = if target_tilt_curve.is_some() {
None
} else {
room_config.target_curve.as_ref()
};
let (eq_filters, _opt_loss) = if let Some(cb) = callback {
eq::optimize_channel_eq_with_callback(
&hybrid_optim_curve,
&opt_config, // Use modified config
effective_target,
sample_rate,
cb,
)
} else {
eq::optimize_channel_eq(
&hybrid_optim_curve,
&opt_config, // Use modified config
effective_target,
sample_rate,
)
}
.map_err(|e| AutoeqError::OptimizationFailed {
message: format!(
"IIR optimization failed for channel {}: {}",
channel_name, e
),
})?;
info!(" IIR stage: {} filters", eq_filters.len());
let iir_resp =
response::compute_peq_complex_response(&eq_filters, &curve.freq, sample_rate);
let final_curve_iir = response::apply_complex_response(&curve, &iir_resp);
let input_plus_iir = final_curve_iir.clone();
info!(" Generating FIR for residual...");
let coeffs = fir::generate_fir_correction(
&input_plus_iir,
&opt_config, // Use modified config
effective_target,
sample_rate,
)
.map_err(|e| AutoeqError::OptimizationFailed {
message: format!("FIR generation failed: {}", e),
})?;
let filename = format!("{}_residual_fir.wav", channel_name);
let wav_path = output_dir.join(&filename);
crate::fir::save_fir_to_wav(&coeffs, sample_rate as u32, &wav_path).map_err(|e| {
AutoeqError::OptimizationFailed {
message: format!("Failed to save FIR WAV: {}", e),
}
})?;
info!(" Saved FIR filter to {}", wav_path.display());
let conv_plugin = output::create_convolution_plugin(&filename);
let mut chain =
output::build_channel_dsp_chain(channel_name, None, broadband_plugins, &eq_filters);
chain.plugins.push(conv_plugin);
let fir_resp =
response::compute_fir_complex_response(&coeffs, &curve.freq, sample_rate);
let final_curve = response::apply_complex_response(&input_plus_iir, &fir_resp);
// Compute post_score consistently with pre_score (range-based mean)
let post_freqs_f32: Vec<f32> = final_curve.freq.iter().map(|&f| f as f32).collect();
let post_spl_f32: Vec<f32> = final_curve.spl.iter().map(|&s| s as f32).collect();
let mean_final = compute_average_response(
&post_freqs_f32,
&post_spl_f32,
Some((min_freq as f32, max_freq as f32)),
) as f64;
let normalized_final_spl = &final_curve.spl - mean_final;
let post_score = crate::loss::flat_loss(
&final_curve.freq,
&normalized_final_spl,
min_freq,
max_freq,
);
info!(
" Pre-score: {:.6}, Post-score: {:.6}",
pre_score, post_score
);
// Extend curves to 20 Hz – 20 kHz for display output.
// Use curve_raw since all_filters includes excursion HPF.
let display_initial = output::extend_curve_to_full_range(&curve_raw);
let display_iir_resp = response::compute_peq_complex_response(
&eq_filters,
&display_initial.freq,
sample_rate,
);
let display_iir_corrected =
response::apply_complex_response(&display_initial, &display_iir_resp);
let display_fir_resp =
response::compute_fir_complex_response(&coeffs, &display_initial.freq, sample_rate);
let display_final =
response::apply_complex_response(&display_iir_corrected, &display_fir_resp);
let mut initial_data: super::types::CurveData = (&display_initial).into();
initial_data.norm_range = norm_range;
let mut final_data: super::types::CurveData = (&display_final).into();
final_data.norm_range = norm_range;
chain.initial_curve = Some(initial_data.clone());
chain.final_curve = Some(final_data.clone());
chain.eq_response = Some(output::compute_eq_response(&initial_data, &final_data));
Ok((
chain,
pre_score,
post_score,
curve_raw.clone(),
final_curve,
eq_filters,
mean_spl,
arrival_time_ms,
Some(coeffs),
))
}
ProcessingMode::MixedPhase => {
// Mixed-phase correction: IIR for minimum-phase + short FIR for excess phase
// Step 1: Run standard IIR optimization (same as LowLatency)
let optimization_curve = if let Some(ref tilt_curve) = target_tilt_curve {
Curve {
freq: curve_for_optim.freq.clone(),
spl: &curve_for_optim.spl - &tilt_curve.spl,
phase: curve_for_optim.phase.clone(),
}
} else {
curve_for_optim.clone()
};
let effective_target = if target_tilt_curve.is_some() {
None
} else {
room_config.target_curve.as_ref()
};
let (eq_filters, _opt_loss) = optimize_eq_maybe_multi(
source,
&optimization_curve,
&clamped_optimizer,
effective_target,
sample_rate,
channel_name,
callback,
target_tilt_curve.as_ref(),
)?;
info!(" IIR stage: {} filters", eq_filters.len());
// Step 2: Decompose phase and generate excess phase FIR
let mp_config = match &room_config.optimizer.mixed_phase {
Some(sc) => super::mixed_phase::MixedPhaseConfig {
max_fir_length_ms: sc.max_fir_length_ms,
pre_ringing_threshold_db: sc.pre_ringing_threshold_db,
min_spatial_depth: sc.min_spatial_depth,
phase_smoothing_octaves: sc.phase_smoothing_octaves,
},
None => super::mixed_phase::MixedPhaseConfig::default(),
};
// Compute spatial correction depth mask if multi-measurement data is available.
// This prevents the excess phase FIR from correcting position-dependent phase.
let spatial_depth = if matches!(source, MeasurementSource::Multiple(_)) {
match load::load_source_individual(source) {
Ok(curves) if curves.len() > 1 => {
let sr_config =
super::spatial_robustness::SpatialRobustnessConfig::default();
let analysis = super::spatial_robustness::analyze_spatial_robustness(
&curves, &sr_config,
);
info!(
" Spatial depth for mixed-phase: mean={:.2}",
analysis.correction_depth.iter().sum::<f64>()
/ analysis.correction_depth.len() as f64,
);
Some(analysis.correction_depth)
}
_ => None,
}
} else {
None
};
let fir_coeffs = if curve_for_optim.phase.is_some() {
match super::mixed_phase::decompose_phase(&curve_for_optim, &mp_config) {
Ok((_min_phase, _excess, delay_ms, residual)) => {
info!(
" Mixed-phase: delay={:.2} ms, generating excess phase FIR...",
delay_ms
);
let coeffs = super::mixed_phase::generate_excess_phase_fir_with_depth(
&curve_for_optim.freq,
&residual,
&mp_config,
sample_rate,
spatial_depth.as_ref(),
);
// Save FIR to WAV
let filename = format!("{}_excess_phase_fir.wav", channel_name);
let wav_path = output_dir.join(&filename);
if let Err(e) =
crate::fir::save_fir_to_wav(&coeffs, sample_rate as u32, &wav_path)
{
warn!("Failed to save excess phase FIR WAV: {}", e);
} else {
info!(" Saved excess phase FIR to {}", wav_path.display());
}
Some((coeffs, filename))
}
Err(e) => {
warn!(
" Mixed-phase decomposition failed for '{}': {}. Using IIR only.",
channel_name, e
);
None
}
}
} else {
info!(
" No phase data for '{}', using IIR only (skipping excess phase FIR).",
channel_name
);
None
};
// Build DSP chain (same pattern as LowLatency)
let mut chain = output::build_channel_dsp_chain_with_curves(
channel_name,
None,
broadband_plugins,
&eq_filters,
None,
None,
);
// Add convolution plugin for excess phase FIR if generated
let returned_fir = if let Some((ref coeffs, ref filename)) = fir_coeffs {
let convolution_plugin = output::create_convolution_plugin(filename);
chain.plugins.push(convolution_plugin);
Some(coeffs.clone())
} else {
None
};
// Compute final response (IIR + optional FIR)
let eq_resp = crate::response::compute_peq_complex_response(
&eq_filters,
&curve.freq,
sample_rate,
);
let after_eq = crate::response::apply_complex_response(&curve_for_optim, &eq_resp);
let final_curve = if let Some((ref coeffs, _)) = fir_coeffs {
let fir_resp = crate::response::compute_fir_complex_response(
coeffs,
&after_eq.freq,
sample_rate,
);
crate::response::apply_complex_response(&after_eq, &fir_resp)
} else {
after_eq
};
// Score
let post_freqs_f32: Vec<f32> = final_curve.freq.iter().map(|&f| f as f32).collect();
let post_spl_f32: Vec<f32> = final_curve.spl.iter().map(|&s| s as f32).collect();
let mean_final = compute_average_response(
&post_freqs_f32,
&post_spl_f32,
Some((min_freq as f32, max_freq as f32)),
) as f64;
let normalized_final_spl = &final_curve.spl - mean_final;
let post_score = crate::loss::flat_loss(
&final_curve.freq,
&normalized_final_spl,
min_freq,
max_freq,
);
info!(
" Mixed-phase result: pre={:.6}, post={:.6}",
pre_score, post_score
);
let display_initial = output::extend_curve_to_full_range(&curve_raw);
let display_eq_resp = crate::response::compute_peq_complex_response(
&eq_filters,
&display_initial.freq,
sample_rate,
);
let display_after_eq =
crate::response::apply_complex_response(&display_initial, &display_eq_resp);
let display_final = if let Some((ref coeffs, _)) = fir_coeffs {
let fir_resp = crate::response::compute_fir_complex_response(
coeffs,
&display_after_eq.freq,
sample_rate,
);
crate::response::apply_complex_response(&display_after_eq, &fir_resp)
} else {
display_after_eq
};
let mut initial_data: super::types::CurveData = (&display_initial).into();
initial_data.norm_range = norm_range;
let mut final_data: super::types::CurveData = (&display_final).into();
final_data.norm_range = norm_range;
chain.initial_curve = Some(initial_data.clone());
chain.final_curve = Some(final_data.clone());
chain.eq_response = Some(output::compute_eq_response(&initial_data, &final_data));
Ok((
chain,
pre_score,
post_score,
curve_raw.clone(),
final_curve,
eq_filters,
mean_spl,
arrival_time_ms,
returned_fir,
))
}
ProcessingMode::LowLatency => {
// Default IIR mode with enhanced processing
// Apply target tilt to the curve (subtract tilt from measurement)
let optimization_curve = if let Some(ref tilt_curve) = target_tilt_curve {
Curve {
freq: curve_for_optim.freq.clone(),
spl: &curve_for_optim.spl - &tilt_curve.spl,
phase: curve_for_optim.phase.clone(),
}
} else {
curve_for_optim.clone()
};
// When tilt is baked into the curve, don't also pass target_curve
// to the optimizer (would double-apply the target)
let effective_target = if target_tilt_curve.is_some() {
None
} else {
room_config.target_curve.as_ref()
};
// ================================================================
// Schroeder Split Optimization (if configured)
// ================================================================
let eq_filters = if let Some(schroeder_config) = &room_config.optimizer.schroeder_split
{
if schroeder_config.enabled {
let schroeder_freq = if let Some(ref dims) = schroeder_config.room_dimensions {
let calculated = dims.schroeder_frequency();
info!(
" Schroeder split: calculated frequency {:.1} Hz from room dimensions",
calculated
);
calculated
} else {
schroeder_config.schroeder_freq
};
info!(
" Schroeder split: optimizing below {:.1} Hz with max_q={:.1}, above with max_q={:.1}",
schroeder_freq,
schroeder_config.low_freq_config.max_q,
schroeder_config.high_freq_config.max_q
);
// Two-pass optimization with different Q constraints
let (low_filters, high_filters) = optimize_with_schroeder_split(
&optimization_curve,
&clamped_optimizer,
schroeder_config,
sample_rate,
)?;
let mut combined_filters = low_filters;
combined_filters.extend(high_filters);
info!(
" Schroeder split: {} low-freq filters + {} high-freq filters",
combined_filters
.iter()
.filter(|f| f.freq < schroeder_freq)
.count(),
combined_filters
.iter()
.filter(|f| f.freq >= schroeder_freq)
.count()
);
combined_filters
} else {
// Standard optimization (with multi-measurement dispatch)
let (filters, _opt_loss) = optimize_eq_maybe_multi(
source,
&optimization_curve,
&clamped_optimizer,
effective_target,
sample_rate,
channel_name,
callback,
target_tilt_curve.as_ref(),
)?;
filters
}
} else {
// Standard optimization (with multi-measurement dispatch)
let (filters, _opt_loss) = optimize_eq_maybe_multi(
source,
&optimization_curve,
&clamped_optimizer,
effective_target,
sample_rate,
channel_name,
callback,
target_tilt_curve.as_ref(),
)?;
filters
};
info!(" Optimized {} EQ filters", eq_filters.len());
// Pass 3: User Preference Filters (bass/treble shelves as separate pass)
// When 3-pass mode is active, extract preference as separate output filters
// instead of baking them into the target curve.
// (reuses cea2034_active computed at the start of process_single_speaker)
let preference_filters = if cea2034_active {
if let Some(ref target_resp) = room_config.optimizer.target_response {
super::cea2034_correction::generate_preference_filters(
&target_resp.preference,
sample_rate,
)
} else {
vec![]
}
} else {
vec![]
};
// all_filters includes every biquad for response simulation only.
// The DSP chain uses separate labeled plugins to avoid double-application.
let mut all_filters = excursion_filters.clone();
all_filters.extend(cea2034_filters.iter().cloned());
all_filters.extend(broadband_biquads.iter().cloned());
all_filters.extend(eq_filters.clone());
all_filters.extend(preference_filters.iter().cloned());
// Filters for the main EQ plugin in the chain (only excursion + room EQ).
// CEA2034, broadband, and preference are added as separate labeled plugins.
let mut main_eq_filters = excursion_filters.clone();
main_eq_filters.extend(eq_filters.clone());
// Build plugin chain: CEA2034 + broadband as separate plugins,
// then main EQ, then preference — each applied exactly once.
let mut pre_plugins = Vec::new();
pre_plugins.extend(cea2034_plugins.iter().cloned());
pre_plugins.extend(broadband_plugins.iter().cloned());
let mut chain = output::build_channel_dsp_chain_with_curves(
channel_name,
None,
pre_plugins,
&main_eq_filters,
None,
None,
);
// Add Pass 3 preference EQ plugin if non-empty
if !preference_filters.is_empty() {
chain.plugins.push(output::create_labeled_eq_plugin(
&preference_filters,
"user_preference",
));
}
// Compute final response including all corrections (HPF + broadband + EQ).
// Apply to curve_raw (original measurement) since all_filters includes
// the excursion HPF and broadband shelves.
let mut score_raw = curve_raw.clone();
score_raw.spl += bb_mean_shift; // broadband gain
let all_resp =
response::compute_peq_complex_response(&all_filters, &score_raw.freq, sample_rate);
let final_curve = response::apply_complex_response(&score_raw, &all_resp);
// Compute post_score consistently with pre_score (flatness of corrected response)
// If target tilt is applied, score against the tilt target
let score_curve = if let Some(ref tilt_curve) = target_tilt_curve {
Curve {
freq: final_curve.freq.clone(),
spl: &final_curve.spl - &tilt_curve.spl,
phase: final_curve.phase.clone(),
}
} else {
final_curve.clone()
};
let post_freqs_f32: Vec<f32> = score_curve.freq.iter().map(|&f| f as f32).collect();
let post_spl_f32: Vec<f32> = score_curve.spl.iter().map(|&s| s as f32).collect();
let mean_final = compute_average_response(
&post_freqs_f32,
&post_spl_f32,
Some((min_freq as f32, max_freq as f32)),
) as f64;
let normalized_final_spl = &score_curve.spl - mean_final;
let post_score = crate::loss::flat_loss(
&score_curve.freq,
&normalized_final_spl,
min_freq,
max_freq,
);
info!(
" Pre-score: {:.6}, Post-score: {:.6}",
pre_score, post_score
);
// Extend curves to 20 Hz – 20 kHz for display output.
// Use curve_raw (not HPF-adjusted) since all_filters includes the HPF.
let display_initial = output::extend_curve_to_full_range(&curve_raw);
let mut display_raw_with_bb = display_initial.clone();
display_raw_with_bb.spl += bb_mean_shift; // broadband gain
let display_resp = response::compute_peq_complex_response(
&all_filters,
&display_raw_with_bb.freq,
sample_rate,
);
let display_final =
response::apply_complex_response(&display_raw_with_bb, &display_resp);
let mut initial_data: super::types::CurveData = (&display_initial).into();
initial_data.norm_range = norm_range;
let mut final_data: super::types::CurveData = (&display_final).into();
final_data.norm_range = norm_range;
chain.initial_curve = Some(initial_data.clone());
chain.final_curve = Some(final_data.clone());
chain.eq_response = Some(output::compute_eq_response(&initial_data, &final_data));
// Build effective target curve in absolute SPL coordinates for display.
// The optimizer works on mean-normalized data, so the effective target is
// mean_spl + tilt (if any). This lets the frontend show what the optimizer
// was actually aiming for instead of a misleading 0dB line.
let display_target_spl = if let Some(ref tilt_curve) = target_tilt_curve {
// Interpolate tilt to display frequency grid
let tilt_at_display = crate::read::normalize_and_interpolate_response(
&display_initial.freq,
tilt_curve,
);
&tilt_at_display.spl + mean_spl
} else {
ndarray::Array1::from_elem(display_initial.freq.len(), mean_spl)
};
chain.target_curve = Some(super::types::CurveData {
freq: display_initial.freq.to_vec(),
spl: display_target_spl.to_vec(),
phase: None,
norm_range,
});
Ok((
chain,
pre_score,
post_score,
curve_raw,
final_curve,
eq_filters,
mean_spl,
arrival_time_ms,
None,
))
}
ProcessingMode::WarpedIir | ProcessingMode::KautzModal => {
// Both modes reuse the LowLatency IIR pipeline for now.
//
// WarpedIir: The warped biquad's benefits come from perceptually-weighted
// frequency resolution. Full integration (x2warped_peq) is a future step.
// Currently routes through the same optimizer as LowLatency.
//
// KautzModal: Detects room modes and converts Kautz gains to equivalent
// biquad Peak filters. Falls back to standard optimizer if no modes found.
let mode_name = match room_config.optimizer.processing_mode {
ProcessingMode::WarpedIir => "WarpedIir",
ProcessingMode::KautzModal => "KautzModal",
_ => unreachable!(),
};
info!(" {} mode: starting optimization...", mode_name);
let optimization_curve = if let Some(ref tilt_curve) = target_tilt_curve {
Curve {
freq: curve_for_optim.freq.clone(),
spl: &curve_for_optim.spl - &tilt_curve.spl,
phase: curve_for_optim.phase.clone(),
}
} else {
curve_for_optim.clone()
};
let effective_target = if target_tilt_curve.is_some() {
None
} else {
room_config.target_curve.as_ref()
};
// KautzModal: try mode detection + Kautz gain optimization first
let eq_filters = if matches!(
room_config.optimizer.processing_mode,
ProcessingMode::KautzModal
) {
let decomposed_config =
super::impulse_analysis::DecomposedCorrectionConfig::default();
let room_modes = super::impulse_analysis::detect_room_modes(
&optimization_curve.freq,
&optimization_curve.spl,
&decomposed_config,
);
if !room_modes.is_empty() {
info!(" Detected {} room modes, building Kautz filter", room_modes.len());
let mode_tuples: Vec<(f64, f64)> =
room_modes.iter().map(|m| (m.frequency, m.q)).collect();
let mut kautz =
math_audio_iir_fir::KautzFilter::from_room_modes(&mode_tuples, sample_rate);
let freqs_f64: Vec<f64> = optimization_curve.freq.iter().copied().collect();
let measured_f64: Vec<f64> = optimization_curve.spl.iter().copied().collect();
let target_f64: Vec<f64> = vec![0.0; freqs_f64.len()];
kautz.optimize_gains(&freqs_f64, &measured_f64, &target_f64);
// Convert Kautz sections to equivalent Peak biquads
let kautz_filters: Vec<Biquad> = room_modes
.iter()
.zip(kautz.sections.iter())
.filter(|(_, s)| s.gain.abs() > 0.1)
.map(|(mode, section)| {
use math_audio_iir_fir::BiquadFilterType;
Biquad::new(
BiquadFilterType::Peak,
mode.frequency,
sample_rate,
mode.q.max(0.5),
section.gain,
)
})
.collect();
info!(
" KautzModal: {} biquad filters from {} modes",
kautz_filters.len(),
room_modes.len()
);
kautz_filters
} else {
info!(" No room modes detected, falling back to standard optimizer");
let (filters, _) = optimize_eq_maybe_multi(
source,
&optimization_curve,
&clamped_optimizer,
effective_target,
sample_rate,
channel_name,
callback,
target_tilt_curve.as_ref(),
)?;
filters
}
} else {
// WarpedIir: use standard optimizer (warped evaluation is future work)
let (filters, _) = optimize_eq_maybe_multi(
source,
&optimization_curve,
&clamped_optimizer,
effective_target,
sample_rate,
channel_name,
callback,
target_tilt_curve.as_ref(),
)?;
filters
};
info!(" {} mode: {} EQ filters", mode_name, eq_filters.len());
// Combine all filters and build chain (same pattern as LowLatency)
let preference_filters = if cea2034_active {
if let Some(ref target_resp) = room_config.optimizer.target_response {
super::cea2034_correction::generate_preference_filters(
&target_resp.preference,
sample_rate,
)
} else {
vec![]
}
} else {
vec![]
};
let mut all_filters = excursion_filters.clone();
all_filters.extend(cea2034_filters.iter().cloned());
all_filters.extend(broadband_biquads.iter().cloned());
all_filters.extend(eq_filters.clone());
all_filters.extend(preference_filters.iter().cloned());
let mut main_eq_filters = excursion_filters.clone();
main_eq_filters.extend(eq_filters.clone());
let mut pre_plugins = Vec::new();
pre_plugins.extend(cea2034_plugins.iter().cloned());
pre_plugins.extend(broadband_plugins.iter().cloned());
let mut chain = output::build_channel_dsp_chain_with_curves(
channel_name,
None,
pre_plugins,
&main_eq_filters,
None,
None,
);
if !preference_filters.is_empty() {
chain.plugins.push(output::create_labeled_eq_plugin(
&preference_filters,
"user_preference",
));
}
// Score and build curves (same as LowLatency)
let mut score_raw = curve_raw.clone();
score_raw.spl += bb_mean_shift;
let all_resp =
response::compute_peq_complex_response(&all_filters, &score_raw.freq, sample_rate);
let final_curve = response::apply_complex_response(&score_raw, &all_resp);
let score_curve = if let Some(ref tilt_curve) = target_tilt_curve {
Curve {
freq: final_curve.freq.clone(),
spl: &final_curve.spl - &tilt_curve.spl,
phase: final_curve.phase.clone(),
}
} else {
final_curve.clone()
};
let post_freqs_f32: Vec<f32> = score_curve.freq.iter().map(|&f| f as f32).collect();
let post_spl_f32: Vec<f32> = score_curve.spl.iter().map(|&s| s as f32).collect();
let mean_final = compute_average_response(
&post_freqs_f32,
&post_spl_f32,
Some((min_freq as f32, max_freq as f32)),
) as f64;
let normalized_final_spl = &score_curve.spl - mean_final;
let post_score = crate::loss::flat_loss(
&score_curve.freq,
&normalized_final_spl,
min_freq,
max_freq,
);
info!(
" Pre-score: {:.6}, Post-score: {:.6}",
pre_score, post_score
);
let display_initial = output::extend_curve_to_full_range(&curve_raw);
let mut display_raw_with_bb = display_initial.clone();
display_raw_with_bb.spl += bb_mean_shift;
let display_resp = response::compute_peq_complex_response(
&all_filters,
&display_raw_with_bb.freq,
sample_rate,
);
let display_final =
response::apply_complex_response(&display_raw_with_bb, &display_resp);
let mut initial_data: super::types::CurveData = (&display_initial).into();
initial_data.norm_range = norm_range;
let mut final_data: super::types::CurveData = (&display_final).into();
final_data.norm_range = norm_range;
chain.initial_curve = Some(initial_data.clone());
chain.final_curve = Some(final_data.clone());
chain.eq_response = Some(output::compute_eq_response(&initial_data, &final_data));
let display_target_spl = if let Some(ref tilt_curve) = target_tilt_curve {
let tilt_at_display = crate::read::normalize_and_interpolate_response(
&display_initial.freq,
tilt_curve,
);
&tilt_at_display.spl + mean_spl
} else {
ndarray::Array1::from_elem(display_initial.freq.len(), mean_spl)
};
chain.target_curve = Some(super::types::CurveData {
freq: display_initial.freq.to_vec(),
spl: display_target_spl.to_vec(),
phase: None,
norm_range,
});
Ok((
chain,
pre_score,
post_score,
curve_raw,
final_curve,
eq_filters,
mean_spl,
arrival_time_ms,
None,
))
}
}
}
/// Optimize EQ with optional Schroeder frequency split.
///
/// If the optimizer config has an enabled Schroeder split, performs two-pass
/// optimization with different Q constraints. Otherwise falls back to standard
/// single-pass optimization.
///
/// This is the unified entry point for EQ optimization that both the generic
/// pipeline and system-config workflows should use.
pub(super) fn optimize_eq_with_optional_schroeder(
curve: &Curve,
optimizer: &OptimizerConfig,
target_config: Option<&super::types::TargetCurveConfig>,
sample_rate: f64,
) -> std::result::Result<(Vec<Biquad>, f64), Box<dyn std::error::Error>> {
if let Some(schroeder_config) = &optimizer.schroeder_split
&& schroeder_config.enabled
{
let schroeder_freq = if let Some(ref dims) = schroeder_config.room_dimensions {
dims.schroeder_frequency()
} else {
schroeder_config.schroeder_freq
};
info!(
" Schroeder split: optimizing below {:.1} Hz with max_q={:.1}, above with max_q={:.1}",
schroeder_freq,
schroeder_config.low_freq_config.max_q,
schroeder_config.high_freq_config.max_q
);
let (low_filters, high_filters) =
optimize_with_schroeder_split(curve, optimizer, schroeder_config, sample_rate)
.map_err(|e| -> Box<dyn std::error::Error> { Box::new(e) })?;
let mut combined = low_filters;
combined.extend(high_filters);
// Loss is approximate (sum of both passes) — not used for scoring
let loss = 0.0;
Ok((combined, loss))
} else {
eq::optimize_channel_eq(curve, optimizer, target_config, sample_rate)
}
}
/// Optimize EQ with Schroeder frequency split
///
/// Performs two-pass optimization with different Q constraints:
/// - Below Schroeder: high-Q narrow filters for room modes
/// - Above Schroeder: low-Q broad filters for tonal adjustment
pub(super) fn optimize_with_schroeder_split(
curve: &Curve,
optimizer: &OptimizerConfig,
schroeder_config: &super::types::SchroederSplitConfig,
sample_rate: f64,
) -> Result<(Vec<Biquad>, Vec<Biquad>)> {
let schroeder_freq = if let Some(ref dims) = schroeder_config.room_dimensions {
dims.schroeder_frequency()
} else {
schroeder_config.schroeder_freq
};
let low_config = &schroeder_config.low_freq_config;
let high_config = &schroeder_config.high_freq_config;
// Determine filter allocation (roughly proportional to frequency range)
let total_filters = optimizer.num_filters;
let log_range_total = (optimizer.max_freq / optimizer.min_freq).log2();
let log_range_low = (schroeder_freq / optimizer.min_freq).max(1.0).log2();
let low_ratio = log_range_low / log_range_total;
let low_filters = ((total_filters as f64 * low_ratio).round() as usize)
.max(1)
.min(total_filters - 1);
let high_filters = total_filters - low_filters;
debug!(
" Schroeder split: {} filters below {:.1}Hz, {} filters above",
low_filters, schroeder_freq, high_filters
);
// Each sub-pass gets the full maxeval budget. With fewer filters (lower
// dimensionality) the optimizer converges faster, so the same budget is
// adequate for each pass independently.
// When target_tilt is active, the optimizer works on a tilt-adjusted curve
// where following the tilt may require both boosts and cuts. Allow limited
// boost (half the configured max) to give the optimizer enough freedom.
let has_non_flat_target = optimizer
.target_response
.as_ref()
.map(|tr| tr.shape != TargetShape::Flat)
.unwrap_or(false)
|| optimizer.target_tilt.is_some();
let low_max_db = if let Some(configured_max) = low_config.max_db {
// Explicit max_db override for below-Schroeder (handles large room modes)
configured_max
} else if low_config.allow_boost {
optimizer.max_db
} else if has_non_flat_target {
(optimizer.max_db / 2.0).min(3.0) // limited boost for tilt tracking
} else {
0.0
};
let low_min_db = if low_config.max_db.is_some() {
// When max_db is explicitly set, allow symmetric range
-low_max_db.abs()
} else {
optimizer.min_db
};
let low_optimizer = OptimizerConfig {
num_filters: low_filters,
min_freq: optimizer.min_freq,
max_freq: schroeder_freq,
min_q: low_config.min_q,
max_q: low_config.max_q,
min_db: low_min_db,
max_db: low_max_db,
..optimizer.clone()
};
let (low_eq_filters, _) = eq::optimize_channel_eq(
curve,
&low_optimizer,
None, // No additional target for split optimization
sample_rate,
)
.map_err(|e| AutoeqError::OptimizationFailed {
message: format!("Low-frequency EQ optimization failed: {}", e),
})?;
// High frequency optimization (above Schroeder)
let high_optimizer = OptimizerConfig {
num_filters: high_filters,
min_freq: schroeder_freq,
max_freq: optimizer.max_freq,
min_q: optimizer.min_q.max(0.3), // Ensure minimum Q for broad filters
max_q: high_config.max_q,
..optimizer.clone()
};
// Apply low-freq correction first, then optimize high-freq on residual
let low_resp =
response::compute_peq_complex_response(&low_eq_filters, &curve.freq, sample_rate);
let curve_with_low_correction = response::apply_complex_response(curve, &low_resp);
let (high_eq_filters, _) = eq::optimize_channel_eq(
&curve_with_low_correction,
&high_optimizer,
None,
sample_rate,
)
.map_err(|e| AutoeqError::OptimizationFailed {
message: format!("High-frequency EQ optimization failed: {}", e),
})?;
// Post-optimization Q clamping: NLopt COBYLA can violate bounds slightly (or
// significantly with low maxeval). Enforce the configured Q constraints on the
// returned filters to guarantee the Schroeder split invariant.
let low_eq_filters = clamp_filter_q(low_eq_filters, low_config.min_q, low_config.max_q);
let high_eq_filters =
clamp_filter_q(high_eq_filters, optimizer.min_q.max(0.3), high_config.max_q);
Ok((low_eq_filters, high_eq_filters))
}
/// Clamp Q values of filters to [min_q, max_q], recomputing biquad coefficients.
pub(super) fn clamp_filter_q(filters: Vec<Biquad>, min_q: f64, max_q: f64) -> Vec<Biquad> {
filters
.into_iter()
.map(|f| {
let clamped_q = f.q.clamp(min_q, max_q);
if (clamped_q - f.q).abs() > 1e-6 {
debug!(
" Clamping filter Q at {:.0} Hz: {:.2} -> {:.2}",
f.freq, f.q, clamped_q
);
Biquad::new(f.filter_type, f.freq, f.srate, clamped_q, f.db_gain)
} else {
f
}
})
.collect()
}
/// Determine optimization frequency bands for each driver
///
/// Returns a vector of (min_freq, max_freq) tuples for each driver.
/// Bandwidth extends 1 octave beyond the intended crossover region.
pub(super) fn determine_optimization_bands(
n_drivers: usize,
room_config: &RoomConfig,
crossover_config: &super::types::CrossoverConfig,
) -> Vec<(f64, f64)> {
let global_min = room_config.optimizer.min_freq;
let global_max = room_config.optimizer.max_freq;
let mut bands = Vec::with_capacity(n_drivers);
// Determine crossover points estimates
// If fixed frequencies or range provided, use those.
// Otherwise, assume log-spaced distribution.
let xover_points = if let Some(ref freqs) = crossover_config.frequencies {
freqs.clone()
} else if let Some(freq) = crossover_config.frequency {
vec![freq]
} else if let Some((min, max)) = crossover_config.frequency_range {
// If range provided for 2-way, use geometric mean as center estimate
// but for bounds calculation, we use the range limits.
// Actually, for optimization limits:
// Low driver max = max_range * 2
// High driver min = min_range / 2
vec![min, max] // Placeholder, logic below handles range
} else {
Vec::new() // No info
};
// Helper to get safe crossover bounds
let get_xover_bounds = |idx: usize| -> (f64, f64) {
if let Some((min, max)) = crossover_config.frequency_range {
// If explicit range is given, use it for the single crossover (2-way)
if n_drivers == 2 && idx == 0 {
return (min, max);
}
}
if !xover_points.is_empty() && idx < xover_points.len() {
let f = xover_points[idx];
return (f, f);
}
// Fallback: log-distribute between 80Hz and 3000Hz
// This is a rough heuristic if no info is present
(80.0, 3000.0)
};
for i in 0..n_drivers {
let min_f = if i == 0 {
global_min
} else {
// Highpass: 1 octave below crossover
let (xover_min, _) = get_xover_bounds(i - 1);
xover_min * 0.5
};
let max_f = if i == n_drivers - 1 {
global_max
} else {
// Lowpass: 1 octave above crossover
let (_, xover_max) = get_xover_bounds(i);
xover_max * 2.0
};
bands.push((min_f.max(global_min), max_f.min(global_max)));
}
bands
}