autoeq 0.4.24

Automatic equalization for speakers, headphones and rooms!
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
//! Main optimization entry points for room EQ.
//!
//! This module provides the primary public API for room optimization.

use crate::Curve;
use crate::error::{AutoeqError, Result};
use log::{debug, info, warn};
use math_audio_dsp::analysis::{compute_average_response, find_db_point};
use math_audio_iir_fir::Biquad;
use std::collections::HashMap;
use std::path::Path;
use std::sync::{Arc, Mutex};

use super::config::validate_room_config;
use super::fir;
use super::group_delay;
use super::output;
use super::phase_alignment;
use super::types::{
    ChannelDspChain, DspChainOutput, MeasurementSource, OptimizationMetadata, OptimizerConfig,
    ProcessingMode, RoomConfig, SpeakerConfig, SystemModel, TargetCurveConfig,
};

// Private module imports for extracted functions
pub(super) use super::speaker_eq::optimize_eq_with_optional_schroeder;
use super::speaker_eq::process_single_speaker; // Re-export for workflows

use super::crossover_utils::check_group_consistency;
use super::group_processing::{
    process_cardioid, process_dba, process_multisub_group, process_speaker_group,
};

// ============================================================================
// Type Aliases
// ============================================================================

/// Internal result type for speaker processing to reduce type complexity
/// Returns: (channel_name, chain, pre_score, post_score, initial_curve, final_curve, biquads, mean_spl, arrival_time_ms, fir_coeffs)
type SpeakerProcessResult = std::result::Result<
    (
        String,
        ChannelDspChain,
        f64,
        f64,
        crate::Curve,
        crate::Curve,
        Vec<crate::iir::Biquad>,
        f64,
        Option<f64>,
        Option<Vec<f64>>,
    ),
    AutoeqError,
>;

/// Result type for mixed mode processing
/// Returns: (chain, pre_score, post_score, initial_curve, final_curve, biquads, mean_spl, arrival_time_ms, fir_coeffs)
type MixedModeResult = (
    ChannelDspChain,
    f64,
    f64,
    Curve,
    Curve,
    Vec<Biquad>,
    f64,
    Option<f64>,
    Option<Vec<f64>>,
);

/// Detect passband and compute mean SPL for normalization
///
/// Smooths the measurement at 1 octave to eliminate room mode dips, then
/// finds the -10 dB points relative to the median SPL. Validates the result
/// against 2-octave smoothing to ensure stability.
pub(super) fn detect_passband_and_mean(curve: &Curve) -> (Option<(f64, f64)>, f64) {
    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();

    if spl_f32.is_empty() {
        return (None, 0.0);
    }

    // Smooth at 1 octave to filter out room modes and comb filtering
    let smoothed_1oct = crate::read::smooth_one_over_n_octave(curve, 1);
    let spl_1oct: Vec<f32> = smoothed_1oct.spl.iter().map(|&s| s as f32).collect();

    // Use median of smoothed SPL as reference (robust to residual peaks/nulls)
    let mut sorted_spl: Vec<f32> = spl_1oct.clone();
    sorted_spl.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    let median_spl = sorted_spl[sorted_spl.len() / 2];

    if median_spl < -100.0 {
        return (None, 0.0);
    }

    let threshold = median_spl - 10.0;
    let f_low_1 = find_db_point(&freqs_f32, &spl_1oct, threshold, true).unwrap_or(freqs_f32[0]);
    let f_high_1 = find_db_point(&freqs_f32, &spl_1oct, threshold, false)
        .unwrap_or(freqs_f32[freqs_f32.len() - 1]);

    // Validate against double-smoothed (1 oct applied twice ≈ 2 oct effective).
    // If the passband differs significantly, the 1-oct result is unstable;
    // use the wider estimate.
    let spl_2oct: Vec<f32> = {
        let double_smooth = crate::read::smooth_one_over_n_octave(&smoothed_1oct, 1);
        double_smooth.spl.iter().map(|&s| s as f32).collect()
    };

    let f_low_2 = find_db_point(&freqs_f32, &spl_2oct, threshold, true).unwrap_or(freqs_f32[0]);
    let f_high_2 = find_db_point(&freqs_f32, &spl_2oct, threshold, false)
        .unwrap_or(freqs_f32[freqs_f32.len() - 1]);

    // Use the wider (more conservative) passband from the two estimates
    let f_low = f_low_1.min(f_low_2);
    let f_high = f_high_1.max(f_high_2);

    // Compute mean on the original (unsmoothed) curve within the detected passband
    let norm_range_f32 = Some((f_low, f_high));
    let mean = compute_average_response(&freqs_f32, &spl_f32, norm_range_f32) as f64;

    (Some((f_low as f64, f_high as f64)), mean)
}

/// Post-generate FIR coefficients for a channel that only has IIR results.
///
/// For Hybrid mode, uses the IIR-corrected curve as FIR input;
/// for PhaseLinear (FIR-only) mode, uses the raw measurement.
fn post_generate_fir(
    name: &str,
    initial_curve: &Curve,
    final_curve: &Curve,
    config: &super::types::OptimizerConfig,
    target_curve: Option<&super::types::TargetCurveConfig>,
    sample_rate: f64,
    output_dir: Option<&Path>,
) -> Option<Vec<f64>> {
    let fir_input = match config.processing_mode {
        ProcessingMode::Hybrid => final_curve,
        _ => initial_curve,
    };
    match fir::generate_fir_correction(fir_input, config, target_curve, sample_rate) {
        Ok(coeffs) => {
            if let Some(out_dir) = output_dir {
                let filename = format!("{}_fir.wav", name);
                let wav_path = out_dir.join(&filename);
                if let Err(e) = crate::fir::save_fir_to_wav(&coeffs, sample_rate as u32, &wav_path)
                {
                    warn!("Failed to save FIR WAV for {}: {}", name, e);
                } else {
                    info!("  Saved FIR filter to {}", wav_path.display());
                }
            }
            Some(coeffs)
        }
        Err(e) => {
            warn!("FIR generation failed for {}: {}", name, e);
            None
        }
    }
}

/// Post-generate a short excess-phase FIR for MixedPhase mode.
///
/// The workflow path only runs IIR optimisation.  For MixedPhase we still need
/// the short FIR that corrects residual excess phase.  This mirrors the logic
/// in `optimize_speaker_eq` MixedPhase branch but runs after the workflow.
fn post_generate_mixed_phase_fir(
    name: &str,
    initial_curve: &Curve,
    config: &super::types::OptimizerConfig,
    sample_rate: f64,
    output_dir: Option<&Path>,
) -> Option<Vec<f64>> {
    let phase = initial_curve.phase.as_ref()?;
    if phase.is_empty() {
        return None;
    }

    let mp_config = match &config.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(),
    };

    match super::mixed_phase::decompose_phase(initial_curve, &mp_config) {
        Ok((_min_phase, _excess, delay_ms, residual)) => {
            info!(
                "  Mixed-phase (post-workflow) '{}': delay={:.2} ms",
                name, delay_ms
            );
            let coeffs = super::mixed_phase::generate_excess_phase_fir(
                &initial_curve.freq,
                &residual,
                &mp_config,
                sample_rate,
            );

            if let Some(out_dir) = output_dir {
                let filename = format!("{}_excess_phase_fir.wav", name);
                let wav_path = out_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 for {}: {}", name, e);
                } else {
                    info!("  Saved excess phase FIR to {}", wav_path.display());
                }
            }

            Some(coeffs)
        }
        Err(e) => {
            warn!(
                "  Mixed-phase decomposition failed for '{}': {}. Using IIR only.",
                name, e
            );
            None
        }
    }
}

/// Apply standalone phase correction to a channel (rePhase-style).
///
/// Generates a phase-only FIR from the measurement's excess phase and appends it
/// to the channel's DSP chain. If the channel already has a magnitude FIR, the
/// two are convolved together so `fir_coeffs` remains a single filter for IR
/// computation.
fn apply_phase_correction(
    name: &str,
    ch: &mut ChannelOptimizationResult,
    chain: &mut super::types::ChannelDspChain,
    config: &super::types::MixedPhaseSerdeConfig,
    sample_rate: f64,
    output_dir: Option<&Path>,
) {
    let phase = match ch.initial_curve.phase.as_ref() {
        Some(p) if !p.is_empty() => p,
        _ => return,
    };
    let _ = phase; // used via initial_curve below

    let mp_config = super::mixed_phase::MixedPhaseConfig {
        max_fir_length_ms: config.max_fir_length_ms,
        pre_ringing_threshold_db: config.pre_ringing_threshold_db,
        min_spatial_depth: config.min_spatial_depth,
        phase_smoothing_octaves: config.phase_smoothing_octaves,
    };

    let phase_fir = match super::mixed_phase::decompose_phase(&ch.initial_curve, &mp_config) {
        Ok((_min, _excess, delay_ms, residual)) => {
            info!(
                "  Phase correction '{}': delay={:.2} ms, generating phase-only FIR",
                name, delay_ms
            );
            super::mixed_phase::generate_excess_phase_fir(
                &ch.initial_curve.freq,
                &residual,
                &mp_config,
                sample_rate,
            )
        }
        Err(e) => {
            warn!("  Phase correction failed for '{}': {}", name, e);
            return;
        }
    };

    // Save phase FIR WAV and add convolution plugin
    let filename = format!("{}_phase_correction.wav", name);
    if let Some(out_dir) = output_dir {
        let wav_path = out_dir.join(&filename);
        if let Err(e) = crate::fir::save_fir_to_wav(&phase_fir, sample_rate as u32, &wav_path) {
            warn!("Failed to save phase correction FIR for {}: {}", name, e);
        } else {
            info!("  Saved phase correction FIR to {}", wav_path.display());
        }
    }
    chain
        .plugins
        .push(super::output::create_convolution_plugin(&filename));

    // Combine with existing FIR for IR computation (convolve the two)
    if let Some(ref existing) = ch.fir_coeffs {
        ch.fir_coeffs = Some(convolve(existing, &phase_fir));
    } else {
        ch.fir_coeffs = Some(phase_fir);
    }
}

/// Linear convolution of two FIR filters.
fn convolve(a: &[f64], b: &[f64]) -> Vec<f64> {
    let len = a.len() + b.len() - 1;
    let mut out = vec![0.0; len];
    for (i, &av) in a.iter().enumerate() {
        for (j, &bv) in b.iter().enumerate() {
            out[i + j] += av * bv;
        }
    }
    out
}

/// Threshold in dB above which to warn about channel level differences
const LEVEL_DIFFERENCE_WARNING_THRESHOLD: f64 = 6.0;

/// Threshold in ms above which to warn about arrival time differences
const ARRIVAL_TIME_WARNING_THRESHOLD_MS: f64 = 50.0;

// ============================================================================
// Sub-Main Pairing Logic
// ============================================================================

/// Find subwoofer-to-main-speaker pairings using system config or heuristic fallback.
///
/// Returns `(sub_name, main_name)` pairs where names are keys into the curves/chains maps.
/// Used by both phase alignment and GD-Opt v2.
fn find_sub_main_pairings(
    config: &RoomConfig,
    curves: &HashMap<String, crate::Curve>,
) -> Vec<(String, String)> {
    let mut pairings = Vec::new();

    if let Some(sys) = &config.system {
        // Use explicit system configuration
        if let Some(subs) = &sys.subwoofers {
            // Invert speakers map to find roles from measurement keys
            // measurement_key -> role
            let meas_to_role: HashMap<&String, &String> =
                sys.speakers.iter().map(|(r, m)| (m, r)).collect();

            for (sub_meas_key, main_role) in &subs.mapping {
                if let Some(sub_role) = meas_to_role.get(sub_meas_key) {
                    pairings.push((sub_role.to_string(), main_role.clone()));
                } else {
                    warn!(
                        "Subwoofer measurement '{}' not mapped to any output channel",
                        sub_meas_key
                    );
                }
            }
        }
    } else {
        // Legacy heuristic: find "lfe" or "sub*" channel, pair with all non-sub channels
        let sub_channel = curves
            .keys()
            .find(|name| *name == "lfe" || name.starts_with("sub"))
            .cloned();
        if let Some(sub_name) = sub_channel {
            let main_channels: Vec<String> = curves
                .keys()
                .filter(|name| *name != &sub_name && !name.starts_with("sub"))
                .cloned()
                .collect();
            for main in main_channels {
                pairings.push((sub_name.clone(), main));
            }
        }
    }

    pairings
}

// ============================================================================
// Progress and Callback Types
// ============================================================================

/// Action to take after progress callback
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallbackAction {
    /// Continue optimization
    Continue,
    /// Stop optimization early
    Stop,
}

/// Progress update for room optimization
#[derive(Debug, Clone)]
pub struct RoomOptimizationProgress {
    /// Current speaker being optimized
    pub current_speaker: String,
    /// Speaker index (0-based)
    pub speaker_index: usize,
    /// Total number of speakers
    pub total_speakers: usize,
    /// Current iteration within this speaker
    pub iteration: usize,
    /// Maximum iterations for this speaker
    pub max_iterations: usize,
    /// Current loss value
    pub loss: f64,
    /// Overall progress (0.0 - 1.0)
    pub overall_progress: f64,
    /// Optional log message for display
    pub message: Option<String>,
}

/// Callback type for room optimization progress
pub type RoomOptimizationCallback =
    Box<dyn FnMut(&RoomOptimizationProgress) -> CallbackAction + Send>;

/// Callback type for single speaker optimization progress
pub type SpeakerOptimizationCallback =
    Box<dyn FnMut(&RoomOptimizationProgress) -> CallbackAction + Send>;

// ============================================================================
// Result Types
// ============================================================================

/// Result for a single channel optimization
#[derive(Debug, Clone)]
pub struct ChannelOptimizationResult {
    /// Channel name
    pub name: String,
    /// Pre-optimization score
    pub pre_score: f64,
    /// Post-optimization score
    pub post_score: f64,
    /// Initial frequency response curve
    pub initial_curve: Curve,
    /// Final corrected frequency response curve
    pub final_curve: Curve,
    /// Biquad filters (for IIR mode)
    pub biquads: Vec<Biquad>,
    /// FIR coefficients (for FIR/mixed mode)
    pub fir_coeffs: Option<Vec<f64>>,
}

/// Result of room optimization
#[derive(Debug, Clone)]
pub struct RoomOptimizationResult {
    /// Per-channel DSP chains
    pub channels: HashMap<String, ChannelDspChain>,
    /// Per-channel optimization results (initial/final curves, scores)
    pub channel_results: HashMap<String, ChannelOptimizationResult>,
    /// Combined pre-optimization score (average)
    pub combined_pre_score: f64,
    /// Combined post-optimization score (average)
    pub combined_post_score: f64,
    /// Optimization metadata
    pub metadata: OptimizationMetadata,
}

impl RoomOptimizationResult {
    /// Convert to DspChainOutput for serialization
    pub fn to_dsp_chain_output(&self) -> DspChainOutput {
        output::create_dsp_chain_output(self.channels.clone(), Some(self.metadata.clone()))
    }
}

/// Result for single speaker optimization
#[derive(Debug, Clone)]
pub struct SpeakerOptimizationResult {
    /// DSP chain for this speaker
    pub chain: ChannelDspChain,
    /// Pre-optimization score
    pub pre_score: f64,
    /// Post-optimization score
    pub post_score: f64,
    /// Initial curve
    pub initial_curve: Curve,
    /// Final curve
    pub final_curve: Curve,
    /// Biquad filters
    pub biquads: Vec<Biquad>,
    /// FIR coefficients (if applicable)
    pub fir_coeffs: Option<Vec<f64>>,
}

// ============================================================================
// Main Entry Points
// ============================================================================

/// Optimize a complete room configuration
///
/// Processes all speakers in parallel and returns DSP chains for each channel.
///
/// # Arguments
/// * `config` - Complete room configuration
/// * `sample_rate` - Sample rate for filter design (e.g., 48000.0)
/// * `callback` - Optional progress callback
///
/// # Returns
/// * `RoomOptimizationResult` containing DSP chains and optimization results
pub fn optimize_room(
    config: &RoomConfig,
    sample_rate: f64,
    mut callback: Option<RoomOptimizationCallback>,
    output_dir: Option<&Path>,
) -> Result<RoomOptimizationResult> {
    // Ensure legacy target_tilt/broadband fields are migrated.
    // load_config() does this already, but callers building RoomConfig in memory
    // (tests, GPUI) may not have called it.
    let mut config = config.clone();
    config.optimizer.migrate_target_config();

    // Pre-fetch CEA2034 data for all speakers when speaker pre-correction is enabled
    if config
        .optimizer
        .cea2034_correction
        .as_ref()
        .is_some_and(|c| c.enabled)
    {
        let cache = super::cea2034_correction::pre_fetch_all_cea2034(&config);
        if !cache.is_empty() {
            info!(
                "  CEA2034 cache: loaded data for {} speaker(s)",
                cache.len()
            );
            config.cea2034_cache = Some(cache);
        }
    }

    let config = &config;

    // Validate configuration
    let validation = validate_room_config(config);
    validation.print_results();
    if !validation.is_valid {
        return Err(AutoeqError::OptimizationFailed {
            message: format!(
                "Configuration validation failed with {} errors",
                validation.errors.len()
            ),
        });
    }

    /// Helper to invoke the callback if present, returning true if Stop was requested.
    fn send_progress(
        cb: &mut Option<RoomOptimizationCallback>,
        progress: &RoomOptimizationProgress,
    ) -> bool {
        if let Some(f) = cb {
            f(progress) == CallbackAction::Stop
        } else {
            false
        }
    }

    // Dispatch to specific workflows based on topology
    if let Some(sys) = &config.system {
        // If any channel uses SpeakerConfig::Group, fall through to the generic path
        // which handles Groups via process_speaker_group.
        let has_group = sys
            .speakers
            .values()
            .any(|key| matches!(config.speakers.get(key), Some(SpeakerConfig::Group(_))));

        // The Stereo 2.0 workflow (no subwoofer) doesn't implement per-channel
        // features like excursion protection, target tilt, or broadband matching.
        // These are only in process_single_speaker (the generic path). For simple
        // stereo configs, fall through to the generic path when these features are
        // active. Multi-channel workflows (2.1, 5.1) have subwoofer/crossover logic
        // that the generic path cannot replicate, so keep them on their workflows.
        let use_generic_for_stereo = sys.model == SystemModel::Stereo
            && sys.subwoofers.is_none()
            && (config
                .optimizer
                .excursion_protection
                .as_ref()
                .is_some_and(|e| e.enabled)
                || config.optimizer.target_response.is_some()
                || config.optimizer.target_tilt.is_some()
                || config
                    .optimizer
                    .broadband_target_matching
                    .as_ref()
                    .is_some_and(|b| b.enabled));

        if use_generic_for_stereo {
            info!("Stereo 2.0 with excursion/tilt/broadband features, using generic path");
        }

        if !has_group && !use_generic_for_stereo {
            let workflow_name = match sys.model {
                SystemModel::Stereo => {
                    if sys.subwoofers.is_some() {
                        "Stereo 2.1"
                    } else {
                        "Stereo 2.0"
                    }
                }
                SystemModel::HomeCinema => "Home Cinema",
                SystemModel::Custom => "Custom",
            };

            // Send pre-workflow progress message
            if sys.model != SystemModel::Custom {
                send_progress(
                    &mut callback,
                    &RoomOptimizationProgress {
                        current_speaker: String::new(),
                        speaker_index: 0,
                        total_speakers: sys.speakers.len(),
                        iteration: 0,
                        max_iterations: 0,
                        loss: 0.0,
                        overall_progress: 0.0,
                        message: Some(format!(
                            "Starting {} workflow ({} channels)",
                            workflow_name,
                            sys.speakers.len()
                        )),
                    },
                );
            }

            let workflow_result = match sys.model {
                SystemModel::Stereo => {
                    if sys.subwoofers.is_some() {
                        Some(super::workflows::optimize_stereo_2_1(
                            config,
                            sys,
                            sample_rate,
                            output_dir.unwrap_or(Path::new(".")),
                        ))
                    } else {
                        Some(super::workflows::optimize_stereo_2_0(
                            config,
                            sys,
                            sample_rate,
                            output_dir.unwrap_or(Path::new(".")),
                        ))
                    }
                }
                SystemModel::HomeCinema => Some(super::workflows::optimize_home_cinema(
                    config,
                    sys,
                    sample_rate,
                    output_dir.unwrap_or(Path::new(".")),
                )),
                SystemModel::Custom => None, // Fall through to generic path
            };

            if let Some(result) = workflow_result {
                let mut result = result?;

                // Send post-workflow summary
                let summary: Vec<String> = result
                    .channel_results
                    .iter()
                    .map(|(name, ch)| {
                        format!("  {}: {:.4} -> {:.4}", name, ch.pre_score, ch.post_score)
                    })
                    .collect();
                send_progress(
                    &mut callback,
                    &RoomOptimizationProgress {
                        current_speaker: String::new(),
                        speaker_index: result.channel_results.len(),
                        total_speakers: result.channel_results.len(),
                        iteration: 0,
                        max_iterations: 0,
                        loss: result.combined_post_score,
                        overall_progress: 1.0,
                        message: Some(format!(
                            "{} workflow complete:\n{}",
                            workflow_name,
                            summary.join("\n")
                        )),
                    },
                );
                // Workflows only do IIR. If FIR/Hybrid mode is requested, post-generate
                // full FIR coefficients for each channel.
                if matches!(
                    config.optimizer.processing_mode,
                    ProcessingMode::PhaseLinear | ProcessingMode::Hybrid
                ) {
                    let out_dir = output_dir.unwrap_or(Path::new("."));
                    for (name, ch) in result.channel_results.iter_mut() {
                        if ch.fir_coeffs.is_some() {
                            continue;
                        }
                        ch.fir_coeffs = post_generate_fir(
                            name,
                            &ch.initial_curve,
                            &ch.final_curve,
                            &config.optimizer,
                            config.target_curve.as_ref(),
                            sample_rate,
                            Some(out_dir),
                        );
                    }
                }
                // MixedPhase: post-generate short excess-phase FIR for each channel
                // and add convolution plugin to the DSP chain.
                if config.optimizer.processing_mode == ProcessingMode::MixedPhase {
                    let out_dir = output_dir.unwrap_or(Path::new("."));
                    for (name, ch) in result.channel_results.iter_mut() {
                        if ch.fir_coeffs.is_some() {
                            continue;
                        }
                        ch.fir_coeffs = post_generate_mixed_phase_fir(
                            name,
                            &ch.initial_curve,
                            &config.optimizer,
                            sample_rate,
                            Some(out_dir),
                        );
                        if ch.fir_coeffs.is_some()
                            && let Some(chain) = result.channels.get_mut(name)
                        {
                            let filename = format!("{}_excess_phase_fir.wav", name);
                            chain
                                .plugins
                                .push(super::output::create_convolution_plugin(&filename));
                        }
                    }
                }
                // Standalone phase correction (rePhase-style)
                if let Some(ref pc_config) = config.optimizer.phase_correction {
                    let out_dir = output_dir.unwrap_or(Path::new("."));
                    let names: Vec<String> = result.channel_results.keys().cloned().collect();
                    for name in &names {
                        if let Some(ch) = result.channel_results.get_mut(name)
                            && let Some(chain) = result.channels.get_mut(name)
                        {
                            apply_phase_correction(
                                name,
                                ch,
                                chain,
                                pc_config,
                                sample_rate,
                                Some(out_dir),
                            );
                        }
                    }
                }

                // Compute IR waveforms for the workflow result
                for (channel_name, ch_result) in &result.channel_results {
                    let delay_ms = result
                        .channels
                        .get(channel_name)
                        .and_then(|chain| chain.plugins.iter().find(|p| p.plugin_type == "delay"))
                        .and_then(|p| p.parameters.get("delay_ms").and_then(|v| v.as_f64()))
                        .unwrap_or(0.0);
                    if let Some((pre_ir, post_ir)) =
                        super::ir_waveform::compute_channel_ir_waveforms(
                            &ch_result.initial_curve,
                            &ch_result.biquads,
                            ch_result.fir_coeffs.as_deref(),
                            delay_ms,
                            sample_rate,
                        )
                        && let Some(chain) = result.channels.get_mut(channel_name)
                    {
                        chain.pre_ir = Some(pre_ir);
                        chain.post_ir = Some(post_ir);
                    }
                }

                // Compute inter-channel deviation and optionally correct it
                if result.channel_results.len() > 1 {
                    compute_and_correct_icd(&mut result, config, sample_rate);
                }

                return Ok(result);
            }
        }
    }

    // Determine channels to process based on system config or legacy config
    // Returns list of (output_channel_name, speaker_config)
    let channels_to_process: Vec<(String, SpeakerConfig)> = if let Some(sys) = &config.system {
        info!("Using SystemConfig for channel mapping");
        sys.speakers
            .iter()
            .filter_map(|(role, key)| match config.speakers.get(key) {
                Some(cfg) => Some((role.clone(), cfg.clone())),
                None => {
                    warn!(
                        "System config references missing speaker key '{}' for role '{}'",
                        key, role
                    );
                    None
                }
            })
            .collect()
    } else {
        config
            .speakers
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect()
    };

    let total_speakers = channels_to_process.len();
    info!("Processing {} channels", total_speakers);

    // ========================================================================
    // Pre-pass: compute shared average response level across all channels
    // ========================================================================
    // When multiple channels are present, load each Single-channel measurement
    // and compute its mean SPL. The cross-channel average becomes a shared
    // target reference level so every channel optimizes toward the SAME level,
    // naturally reducing inter-channel deviation at the source.
    let shared_mean_spl: Option<f64> = if total_speakers > 1 {
        let min_freq = config.optimizer.min_freq;
        let max_freq = config.optimizer.max_freq;
        let mut channel_means: Vec<f64> = Vec::new();
        let mut excluded_group_count = 0_usize;

        for (_name, speaker_config) in &channels_to_process {
            if let SpeakerConfig::Single(source) = speaker_config
                && let Ok(curve) = crate::read::load_source(source)
            {
                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 mean = compute_average_response(
                    &freqs_f32,
                    &spl_f32,
                    Some((min_freq as f32, max_freq as f32)),
                ) as f64;
                channel_means.push(mean);
            } else if !matches!(speaker_config, SpeakerConfig::Single(_)) {
                excluded_group_count += 1;
            }
        }

        if excluded_group_count > 0 {
            info!(
                "Shared mean pre-pass: {} non-Single speaker(s) excluded (Group/MultiSub/DBA/Cardioid)",
                excluded_group_count
            );
        }

        if channel_means.len() > 1 {
            let avg = channel_means.iter().sum::<f64>() / channel_means.len() as f64;
            info!(
                "Shared target level: {:.1} dB (average of {} channels)",
                avg,
                channel_means.len()
            );
            Some(avg)
        } else {
            None
        }
    } else {
        None
    };

    send_progress(
        &mut callback,
        &RoomOptimizationProgress {
            current_speaker: String::new(),
            speaker_index: 0,
            total_speakers,
            iteration: 0,
            max_iterations: 0,
            loss: 0.0,
            overall_progress: 0.0,
            message: Some(format!(
                "Starting optimization for {} channels",
                total_speakers
            )),
        },
    );

    // Process each speaker sequentially so we can report progress.
    // Wrap callback in Arc<Mutex> so we can create per-speaker OptimProgressCallbacks.
    //
    // Compute actual DE generation budget for accurate progress display.
    // The DE callback reports generation numbers, not function evals.
    // Formula mirrors optim_de::derive_de_budget.
    let params_per_filter = match config.optimizer.peq_model.as_str() {
        "free" | "ls-pk-hs" => 4,
        _ => 3,
    };
    let n_params = config.optimizer.num_filters * params_per_filter;
    let n_free = n_params.max(1); // all params are free in standard EQ
    let desired_pop = config
        .optimizer
        .population
        .max(1)
        .min(config.optimizer.max_iter.max(1));
    let pop_multiplier = desired_pop.div_ceil(n_free).max(4);
    let population_size = pop_multiplier * n_free;
    let max_iterations =
        (config.optimizer.max_iter.saturating_sub(population_size) / population_size).max(5000);
    info!(
        "DE budget: {} params, population_size={}, max_generations={} (from max_iter={}, floor=5000)",
        n_params, population_size, max_iterations, config.optimizer.max_iter
    );
    let callback_shared: Arc<Mutex<Option<RoomOptimizationCallback>>> =
        Arc::new(Mutex::new(callback));

    let mut results: Vec<SpeakerProcessResult> = Vec::with_capacity(total_speakers);
    for (speaker_idx, (channel_name, speaker_config)) in channels_to_process.into_iter().enumerate()
    {
        info!("Processing channel: {}", channel_name);

        {
            let mut guard = callback_shared.lock().unwrap();
            let stop = send_progress(
                &mut guard,
                &RoomOptimizationProgress {
                    current_speaker: channel_name.clone(),
                    speaker_index: speaker_idx,
                    total_speakers,
                    iteration: 0,
                    max_iterations: 0,
                    loss: 0.0,
                    overall_progress: speaker_idx as f64 / total_speakers as f64,
                    message: Some(format!("Processing channel: {}", channel_name)),
                },
            );
            if stop {
                break;
            }
        }

        // Create a per-speaker OptimProgressCallback that forwards to the room callback
        let eq_callback: Option<crate::optim::OptimProgressCallback> = {
            let cb = Arc::clone(&callback_shared);
            let name = channel_name.clone();
            let si = speaker_idx;
            let ts = total_speakers;
            let mi = max_iterations;
            Some(Box::new(move |iter: usize, loss: f64| {
                let base_progress = si as f64 / ts as f64;
                let speaker_progress = if mi > 0 { iter as f64 / mi as f64 } else { 0.0 };
                let overall = (base_progress + speaker_progress / ts as f64).min(1.0);

                if let Ok(mut guard) = cb.lock()
                    && let Some(room_cb) = guard.as_mut()
                {
                    let action = room_cb(&RoomOptimizationProgress {
                        current_speaker: name.clone(),
                        speaker_index: si,
                        total_speakers: ts,
                        iteration: iter,
                        max_iterations: mi,
                        loss,
                        overall_progress: overall,
                        message: None,
                    });
                    return match action {
                        CallbackAction::Continue => crate::de::CallbackAction::Continue,
                        CallbackAction::Stop => crate::de::CallbackAction::Stop,
                    };
                }
                crate::de::CallbackAction::Continue
            }))
        };

        let result = process_speaker_internal(
            &channel_name,
            &speaker_config,
            config,
            sample_rate,
            output_dir,
            eq_callback,
            shared_mean_spl,
        );

        match result {
            Ok((
                chain,
                pre_score,
                post_score,
                initial_curve,
                final_curve,
                biquads,
                mean_spl,
                arrival_time_ms,
                fir_coeffs,
            )) => {
                {
                    let mut guard = callback_shared.lock().unwrap();
                    let stop = send_progress(
                        &mut guard,
                        &RoomOptimizationProgress {
                            current_speaker: channel_name.clone(),
                            speaker_index: speaker_idx,
                            total_speakers,
                            iteration: 0,
                            max_iterations: 0,
                            loss: post_score,
                            overall_progress: (speaker_idx + 1) as f64 / total_speakers as f64,
                            message: Some(format!(
                                "Channel {}: {:.4} -> {:.4}",
                                channel_name, pre_score, post_score
                            )),
                        },
                    );
                    // Note: can't break here since we're inside a match arm.
                    // The stop signal is handled by the per-iteration callback.
                    let _ = stop;
                }

                results.push(Ok((
                    channel_name,
                    chain,
                    pre_score,
                    post_score,
                    initial_curve,
                    final_curve,
                    biquads,
                    mean_spl,
                    arrival_time_ms,
                    fir_coeffs,
                )));
            }
            Err(e) => {
                results.push(Err(e));
            }
        }
    }

    // Collect results
    let mut channel_chains: HashMap<String, ChannelDspChain> = HashMap::new();
    let mut channel_results: HashMap<String, ChannelOptimizationResult> = HashMap::new();
    let mut pre_scores: Vec<f64> = Vec::new();
    let mut post_scores: Vec<f64> = Vec::new();
    let mut curves: HashMap<String, crate::Curve> = HashMap::new();
    let mut channel_means: HashMap<String, f64> = HashMap::new();
    let mut channel_arrivals: HashMap<String, f64> = HashMap::new();

    for res in results {
        let (
            channel_name,
            chain,
            pre_score,
            post_score,
            initial_curve,
            final_curve,
            biquads,
            mean_spl,
            arrival_time_ms,
            fir_coeffs,
        ) = res?;

        channel_chains.insert(channel_name.clone(), chain);
        curves.insert(channel_name.clone(), final_curve.clone());
        pre_scores.push(pre_score);
        post_scores.push(post_score);
        channel_means.insert(channel_name.clone(), mean_spl);
        if let Some(arrival_ms) = arrival_time_ms {
            channel_arrivals.insert(channel_name.clone(), arrival_ms);
        }

        // Post-generate FIR coefficients for channels that need them but don't have them
        // (e.g., speaker groups that only support IIR internally)
        let fir_coeffs = if fir_coeffs.is_none()
            && !matches!(
                config.optimizer.processing_mode,
                ProcessingMode::LowLatency | ProcessingMode::MixedPhase
            ) {
            post_generate_fir(
                &channel_name,
                &initial_curve,
                &final_curve,
                &config.optimizer,
                config.target_curve.as_ref(),
                sample_rate,
                output_dir,
            )
        } else {
            fir_coeffs
        };

        channel_results.insert(
            channel_name.clone(),
            ChannelOptimizationResult {
                name: channel_name,
                pre_score,
                post_score,
                initial_curve,
                final_curve,
                biquads,
                fir_coeffs,
            },
        );
    }

    // Auto IR sync: if no WAV-based arrivals were collected, estimate from phase data.
    // Runs unconditionally (does not require allow_delay = true).
    let phase_ir_sync = channel_arrivals.is_empty() && channel_results.len() > 1;
    if phase_ir_sync {
        for (channel_name, result) in &channel_results {
            if let Some(arrival_ms) =
                super::time_align::estimate_arrival_from_phase(&result.initial_curve, 200.0, 2000.0)
            {
                channel_arrivals.insert(channel_name.clone(), arrival_ms);
            }
        }
        if channel_arrivals.len() > 1 {
            info!(
                "Auto IR sync: phase-estimated arrival times for {} channels",
                channel_arrivals.len()
            );
            for (name, arrival) in &channel_arrivals {
                info!(
                    "  Channel '{}': phase-estimated arrival = {:.2} ms",
                    name, arrival
                );
            }
        } else {
            // Clear partial arrivals — not enough channels have phase data
            channel_arrivals.clear();
        }
    }

    // Time alignment: add delay plugins to align all channels to the slowest one
    // This is done PRE-EQ by inserting at the beginning of the plugin chain
    if (config.optimizer.allow_delay() || phase_ir_sync) && channel_arrivals.len() > 1 {
        let arrivals: Vec<f64> = channel_arrivals.values().copied().collect();
        let min_arrival = arrivals.iter().cloned().fold(f64::INFINITY, f64::min);
        let max_arrival = arrivals.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
        let arrival_spread = max_arrival - min_arrival;

        // Warn if arrival time differences are significant (might indicate measurement issues)
        if arrival_spread > ARRIVAL_TIME_WARNING_THRESHOLD_MS {
            warn!(
                "Channel arrival times differ by {:.1} ms (threshold: {:.1} ms). \
                This may indicate measurement issues or very different speaker distances.",
                arrival_spread, ARRIVAL_TIME_WARNING_THRESHOLD_MS
            );
            for (name, arrival) in &channel_arrivals {
                info!("  Channel '{}': arrival time = {:.2} ms", name, arrival);
            }
        }

        // Calculate alignment delays (slowest channel = reference, others get delays)
        let alignment_delays = super::time_align::calculate_alignment_delays(&channel_arrivals);

        // Add delay plugins at the BEGINNING of the chain (pre-EQ)
        for (channel_name, delay_ms) in &alignment_delays {
            // Only add delay plugin if the adjustment is significant (> 0.01 ms = ~0.5 samples at 48kHz)
            if *delay_ms > 0.01
                && let Some(chain) = channel_chains.get_mut(channel_name)
            {
                // Insert delay plugin at the beginning (before EQ)
                chain
                    .plugins
                    .insert(0, output::create_delay_plugin(*delay_ms));
                info!(
                    "  Channel '{}': added {:.3} ms delay for time alignment",
                    channel_name, delay_ms
                );
            }
        }
    } else if channel_arrivals.is_empty() && config.speakers.len() > 1 {
        info!("No arrival time data (WAV or phase) available for time alignment. Skipping.");
    }

    // Spectral channel alignment: fit low-shelf + high-shelf + flat gain to each
    // channel's deviation from the average post-EQ curve. This corrects both broadband
    // level differences and frequency-dependent tilt between channels.
    if curves.len() > 1 {
        let min_freq = config.optimizer.min_freq;
        let max_freq = config.optimizer.max_freq;
        let sample_rate = config
            .recording_config
            .as_ref()
            .and_then(|rc| rc.playback_sample_rate)
            .unwrap_or(48000) as f64;

        // Compute post-EQ mean SPL per channel for the level spread warning
        let mut post_eq_means: HashMap<String, f64> = HashMap::new();
        for (channel_name, final_curve) in &curves {
            let freqs_f32: Vec<f32> = final_curve.freq.iter().map(|&f| f as f32).collect();
            let spl_f32: Vec<f32> = final_curve.spl.iter().map(|&s| s as f32).collect();
            let post_mean = compute_average_response(
                &freqs_f32,
                &spl_f32,
                Some((min_freq as f32, max_freq as f32)),
            ) as f64;
            post_eq_means.insert(channel_name.clone(), post_mean);
        }

        let means: Vec<f64> = post_eq_means.values().copied().collect();
        let min_mean = means.iter().cloned().fold(f64::INFINITY, f64::min);
        let max_mean = means.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
        let level_spread = max_mean - min_mean;

        info!(
            "Post-EQ spectral alignment: level spread = {:.2} dB across {} channels",
            level_spread,
            post_eq_means.len()
        );
        for (name, mean) in &post_eq_means {
            info!("  Channel '{}': post-EQ mean SPL = {:.1} dB", name, mean);
        }

        // Warn if level differences are significant (might indicate measurement issues)
        if level_spread > LEVEL_DIFFERENCE_WARNING_THRESHOLD {
            warn!(
                "Channel levels differ by {:.1} dB (threshold: {:.1} dB). \
                This may indicate measurement issues (mic placement, cable problems, etc.).",
                level_spread, LEVEL_DIFFERENCE_WARNING_THRESHOLD
            );
        }

        // Compute spectral alignment (shelf + gain) for each channel
        let alignment_results = super::spectral_align::compute_spectral_alignment(
            &curves,
            sample_rate,
            min_freq,
            max_freq,
        );
        super::spectral_align::log_spectral_alignment(&alignment_results);

        // Insert alignment plugins after the per-channel PEQ
        for (channel_name, result) in &alignment_results {
            if let Some(chain) = channel_chains.get_mut(channel_name) {
                let (eq_plugin, gain_plugin) =
                    super::spectral_align::create_alignment_plugins(result, sample_rate);
                if let Some(eq) = eq_plugin {
                    chain.plugins.push(eq);
                }
                if let Some(gain) = gain_plugin {
                    chain.plugins.push(gain);
                }
            }
        }
    }

    // ========================================================================
    // Voice of God (VoG) — Timbre-match satellites to a reference channel
    // ========================================================================
    if let Some(vog_config) = &config.optimizer.vog
        && vog_config.enabled
    {
        info!(
            "Running Voice of God alignment (reference: '{}')...",
            vog_config.reference_channel
        );

        // Build corrected curves from the current channel results
        let corrected_curves: HashMap<String, Curve> = channel_results
            .iter()
            .map(|(name, result)| (name.clone(), result.final_curve.clone()))
            .collect();

        match super::voice_of_god::compute_voice_of_god(
            &corrected_curves,
            &vog_config.reference_channel,
            sample_rate,
            config.optimizer.min_freq,
            config.optimizer.max_freq,
        ) {
            Ok(vog_results) => {
                for (channel_name, vog_result) in &vog_results {
                    let plugins = super::voice_of_god::create_vog_plugins(vog_result, sample_rate);
                    if !plugins.is_empty()
                        && let Some(chain) = channel_chains.get_mut(channel_name)
                    {
                        for plugin in plugins {
                            chain.plugins.push(plugin);
                        }
                    }
                }
            }
            Err(e) => {
                warn!("Voice of God optimization failed: {}", e);
            }
        }
    }

    // ========================================================================
    // Phase Alignment Optimization (Scenario A: WITH Subwoofers)
    // ========================================================================
    // Phase alignment maximizes energy sum in the crossover region by optimizing
    // delay and polarity. This runs BEFORE group delay optimization.
    // Uses the same sub-main pairing logic as GD-Opt v2 (system config or heuristic).
    let mut phase_alignment_results: HashMap<String, (f64, bool)> = HashMap::new();

    if config.optimizer.allow_delay()
        && let Some(phase_config) = &config.optimizer.phase_alignment
        && phase_config.enabled
    {
        let pairings = find_sub_main_pairings(config, &curves);

        if pairings.is_empty() {
            warn!("Phase alignment enabled but no valid sub-main pairings found.");
        } else {
            info!("Running phase alignment optimization...");
            send_progress(
                &mut callback_shared.lock().unwrap(),
                &RoomOptimizationProgress {
                    current_speaker: String::new(),
                    speaker_index: 0,
                    total_speakers: pairings.len(),
                    iteration: 0,
                    max_iterations: 0,
                    loss: 0.0,
                    overall_progress: 0.0,
                    message: Some("Running phase alignment...".to_string()),
                },
            );

            for (sub_name, main_name) in &pairings {
                let sub_curve = match curves.get(sub_name) {
                    Some(c) => c,
                    None => {
                        warn!(
                            "Subwoofer channel '{}' not found for phase alignment",
                            sub_name
                        );
                        continue;
                    }
                };

                if let Some(speaker_curve) = curves.get(main_name) {
                    // Phase alignment requires phase data
                    if sub_curve.phase.is_some() && speaker_curve.phase.is_some() {
                        match phase_alignment::optimize_phase_alignment(
                            sub_curve,
                            speaker_curve,
                            phase_config,
                        ) {
                            Ok(result) => {
                                info!(
                                    "  Phase alignment '{}' with '{}': delay={:.2}ms, invert={}, improvement={:.2}dB",
                                    main_name,
                                    sub_name,
                                    result.delay_ms,
                                    result.invert_polarity,
                                    result.improvement_db
                                );
                                phase_alignment_results.insert(
                                    main_name.clone(),
                                    (result.delay_ms, result.invert_polarity),
                                );
                            }
                            Err(e) => {
                                warn!("  Phase alignment failed for '{}': {}", main_name, e);
                            }
                        }
                    } else {
                        debug!(
                            "  Skipping phase alignment for '{}': no phase data available",
                            main_name
                        );
                    }
                }
            }
        }
    }

    // Apply phase alignment results (polarity inversion + delay)
    for (speaker_name, (delay_ms, invert)) in &phase_alignment_results {
        if let Some(chain) = channel_chains.get_mut(speaker_name) {
            if *invert {
                // Insert polarity inversion at the beginning of the chain
                let invert_plugin = output::create_gain_plugin_with_invert(0.0, true);
                chain.plugins.insert(0, invert_plugin);
                info!("  Applied polarity inversion to '{}'", speaker_name);
            }
            if *delay_ms > 0.01 {
                // Apply phase alignment delay (additive with any existing time-alignment delay)
                output::add_delay_plugin(chain, *delay_ms);
                info!(
                    "  Applied {:.3} ms phase alignment delay to '{}'",
                    delay_ms, speaker_name
                );
            }
        }
    }

    // ========================================================================
    // Group Delay Optimization (v2) - IIR Mode
    // ========================================================================
    // Align Main speakers to Subwoofer using All-Pass filters to match phase slope
    if let Some(gd_opt) = &config.optimizer.gd_opt
        && gd_opt.enabled
        && config.optimizer.processing_mode == ProcessingMode::LowLatency
    {
        info!("Running Group Delay Optimization (IIR Mode)...");

        let pairings = find_sub_main_pairings(config, &curves);

        if pairings.is_empty() {
            warn!("GD-Opt enabled but no valid sub-main pairings found.");
        } else {
            send_progress(
                &mut callback_shared.lock().unwrap(),
                &RoomOptimizationProgress {
                    current_speaker: String::new(),
                    speaker_index: 0,
                    total_speakers: pairings.len(),
                    iteration: 0,
                    max_iterations: 0,
                    loss: 0.0,
                    overall_progress: 0.0,
                    message: Some("Running group delay optimization...".to_string()),
                },
            );
        }

        let min_freq = config.optimizer.min_freq;
        let max_freq = 200.0;

        for (sub_name, main_name) in pairings {
            if let (Some(sub_curve), Some(main_curve)) =
                (curves.get(&sub_name), curves.get(&main_name))
            {
                info!("  Optimizing GD for '{}' vs '{}'", main_name, sub_name);
                send_progress(
                    &mut callback_shared.lock().unwrap(),
                    &RoomOptimizationProgress {
                        current_speaker: format!("GD {}", main_name),
                        speaker_index: 0,
                        total_speakers: 1,
                        iteration: 0,
                        max_iterations: 0,
                        loss: 0.0,
                        overall_progress: 0.0,
                        message: Some(format!("Optimizing GD for '{}'", main_name)),
                    },
                );

                match group_delay::optimize_gd_iir(
                    sub_curve,
                    main_curve,
                    min_freq,
                    max_freq,
                    sample_rate,
                ) {
                    Ok(filters) => {
                        if !filters.is_empty() {
                            info!(
                                "    Generated {} All-Pass filters for GD alignment",
                                filters.len()
                            );
                            if let Some(chain) = channel_chains.get_mut(&main_name) {
                                let plugin = output::create_eq_plugin(&filters);
                                chain.plugins.push(plugin);
                            }
                        } else {
                            info!("    No AP filters needed");
                        }
                    }
                    Err(e) => {
                        warn!("    GD optimization failed for '{}': {}", main_name, e);
                    }
                }
            } else {
                warn!(
                    "GD-Opt: Channel '{}' or '{}' not found in results",
                    sub_name, main_name
                );
            }
        }
    }

    // Standalone phase correction (rePhase-style)
    if let Some(ref pc_config) = config.optimizer.phase_correction {
        let names: Vec<String> = channel_results.keys().cloned().collect();
        for name in &names {
            if let Some(ch) = channel_results.get_mut(name.as_str())
                && let Some(chain) = channel_chains.get_mut(name.as_str())
            {
                apply_phase_correction(name, ch, chain, pc_config, sample_rate, output_dir);
            }
        }
    }

    // Compute IR waveforms (pre- and post-correction) for each channel
    for (channel_name, result) in &channel_results {
        let delay_ms = channel_chains
            .get(channel_name)
            .and_then(|chain| chain.plugins.iter().find(|p| p.plugin_type == "delay"))
            .and_then(|p| p.parameters.get("delay_ms").and_then(|v| v.as_f64()))
            .unwrap_or(0.0);

        if let Some((pre_ir, post_ir)) = super::ir_waveform::compute_channel_ir_waveforms(
            &result.initial_curve,
            &result.biquads,
            result.fir_coeffs.as_deref(),
            delay_ms,
            sample_rate,
        ) && let Some(chain) = channel_chains.get_mut(channel_name)
        {
            chain.pre_ir = Some(pre_ir);
            chain.post_ir = Some(post_ir);
        }
    }

    // Aggregate scores
    let avg_pre_score = if !pre_scores.is_empty() {
        pre_scores.iter().sum::<f64>() / pre_scores.len() as f64
    } else {
        0.0
    };
    let avg_post_score = if !post_scores.is_empty() {
        post_scores.iter().sum::<f64>() / post_scores.len() as f64
    } else {
        0.0
    };

    info!(
        "Average pre-score: {:.4}, post-score: {:.4}",
        avg_pre_score, avg_post_score
    );

    // Identify acoustic groups for consistency checks
    let acoustic_groups = identify_acoustic_groups(config);
    for (group_name, group_channels) in &acoustic_groups {
        if group_channels.len() > 1 {
            debug!("Acoustic Group '{}': {:?}", group_name, group_channels);

            // Perform consistency checks between speakers in the same group
            check_group_consistency(group_name, group_channels, &channel_means, &curves);
        }
    }

    let metadata = OptimizationMetadata {
        pre_score: avg_pre_score,
        post_score: avg_post_score,
        algorithm: config.optimizer.algorithm.clone(),
        iterations: config.optimizer.max_iter,
        timestamp: chrono::Utc::now().to_rfc3339(),
        inter_channel_deviation: None,
    };

    let mut result = RoomOptimizationResult {
        channels: channel_chains,
        channel_results,
        combined_pre_score: avg_pre_score,
        combined_post_score: avg_post_score,
        metadata,
    };

    // Compute inter-channel deviation and optionally correct it
    if curves.len() > 1 {
        compute_and_correct_icd(&mut result, config, sample_rate);
    }

    Ok(result)
}

/// Compute inter-channel deviation and optionally apply correction filters.
///
/// Called after per-channel optimization on any result with >1 channel.
/// If `channel_matching` config is enabled and ICD exceeds threshold, adds
/// targeted PEQ filters to bring channels closer together.
fn compute_and_correct_icd(
    result: &mut RoomOptimizationResult,
    config: &RoomConfig,
    sample_rate: f64,
) {
    let final_curves: HashMap<String, crate::Curve> = result
        .channel_results
        .iter()
        .map(|(name, ch)| (name.clone(), ch.final_curve.clone()))
        .collect();

    let f3 = final_curves
        .values()
        .filter_map(|c| super::excursion::detect_f3(c, None).ok().map(|r| r.f3_hz))
        .reduce(f64::min)
        .unwrap_or(50.0);

    let icd = super::spectral_align::compute_inter_channel_deviation(&final_curves, f3);
    info!(
        "Inter-channel deviation: midrange_rms={:.2}dB, peak={:.1}dB @{:.0}Hz, passband_rms={:.2}dB",
        icd.midrange_rms_db, icd.midrange_peak_db, icd.midrange_peak_freq, icd.passband_rms_db,
    );

    // Check if correction is enabled and needed
    let matching_cfg = config.optimizer.channel_matching.as_ref();
    let enabled = matching_cfg.is_some_and(|c| c.enabled);
    let threshold = matching_cfg.map_or(1.5, |c| c.threshold_db);
    let max_filters = matching_cfg.map_or(3, |c| c.max_filters);

    if enabled && icd.midrange_rms_db > threshold {
        info!(
            "ICD midrange_rms={:.2}dB > threshold={:.1}dB — applying channel matching correction (max {} filters/ch)",
            icd.midrange_rms_db, threshold, max_filters,
        );

        let corrections = super::spectral_align::correct_inter_channel_deviation(
            &final_curves,
            f3,
            max_filters,
            sample_rate,
        );

        for correction in &corrections {
            if let Some(plugin) = &correction.plugin {
                info!(
                    "  Channel '{}': {} matching filters",
                    correction.channel_name,
                    correction.filters.len(),
                );
                for f in &correction.filters {
                    info!(
                        "    PK @ {:.0} Hz, Q={:.2}, gain={:+.1} dB",
                        f.freq, f.q, f.db_gain,
                    );
                }

                // Add plugin to DSP chain
                if let Some(chain) = result.channels.get_mut(&correction.channel_name) {
                    chain.plugins.push(plugin.clone());
                }

                // Update the final curve with the correction applied
                if let Some(ch_result) = result.channel_results.get_mut(&correction.channel_name) {
                    let resp = crate::response::compute_peq_complex_response(
                        &correction.filters,
                        &ch_result.final_curve.freq,
                        sample_rate,
                    );
                    ch_result.final_curve =
                        crate::response::apply_complex_response(&ch_result.final_curve, &resp);

                    // Also update the display final_curve in the chain
                    if let Some(chain) = result.channels.get_mut(&correction.channel_name)
                        && let Some(ref display_final) = chain.final_curve
                    {
                        let display_curve: crate::Curve = display_final.clone().into();
                        let display_resp = crate::response::compute_peq_complex_response(
                            &correction.filters,
                            &display_curve.freq,
                            sample_rate,
                        );
                        let corrected =
                            crate::response::apply_complex_response(&display_curve, &display_resp);
                        chain.final_curve = Some((&corrected).into());
                    }
                }
            }
        }

        // Re-compute ICD after correction
        let corrected_curves: HashMap<String, crate::Curve> = result
            .channel_results
            .iter()
            .map(|(name, ch)| (name.clone(), ch.final_curve.clone()))
            .collect();
        let icd_after =
            super::spectral_align::compute_inter_channel_deviation(&corrected_curves, f3);
        info!(
            "ICD after correction: midrange_rms={:.2}dB (was {:.2}dB), peak={:.1}dB @{:.0}Hz",
            icd_after.midrange_rms_db,
            icd.midrange_rms_db,
            icd_after.midrange_peak_db,
            icd_after.midrange_peak_freq,
        );
        result.metadata.inter_channel_deviation = Some(icd_after);
    } else {
        if enabled {
            info!(
                "ICD midrange_rms={:.2}dB <= threshold={:.1}dB — no correction needed",
                icd.midrange_rms_db, threshold,
            );
        }
        result.metadata.inter_channel_deviation = Some(icd);
    }
}

/// Identify Acoustic Groups from RoomConfig
///
/// Acoustic Groups are speakers expected to be acoustically similar (e.g., L/R pair).
/// Uses explicit speaker_name metadata if available, otherwise falls back to
/// positional heuristics (L/R, SL/SR, etc.).
fn identify_acoustic_groups(config: &RoomConfig) -> HashMap<String, Vec<String>> {
    let mut groups: HashMap<String, Vec<String>> = HashMap::new();
    let mut positioned_channels: HashMap<String, String> = HashMap::new();

    // 1. Group by explicit speaker_name
    for (channel_name, speaker_cfg) in &config.speakers {
        if let Some(speaker_name) = speaker_cfg.speaker_name() {
            groups
                .entry(speaker_name.to_string())
                .or_default()
                .push(channel_name.clone());
        } else {
            positioned_channels.insert(channel_name.clone(), channel_name.clone());
        }
    }

    // 2. Positional heuristics for remaining channels
    let pairs = [
        ("L", "R"),
        ("SL", "SR"),
        ("SBL", "SBR"),
        ("TFL", "TFR"),
        ("TRL", "TRR"),
        ("FWL", "FWR"),
    ];

    for (p1, p2) in pairs {
        if positioned_channels.contains_key(p1) && positioned_channels.contains_key(p2) {
            let group_name = format!("{}-{}", p1, p2);
            let mut group = Vec::new();
            if let Some(c1) = positioned_channels.remove(p1) {
                group.push(c1);
            }
            if let Some(c2) = positioned_channels.remove(p2) {
                group.push(c2);
            }
            groups.insert(group_name, group);
        }
    }

    groups
}

/// Optimize a single speaker (simple or group)
///
/// # Arguments
/// * `channel_name` - Name of the channel
/// * `speaker_config` - Speaker configuration
/// * `optimizer_config` - Optimizer parameters
/// * `target_curve` - Optional target curve configuration
/// * `sample_rate` - Sample rate for filter design
/// * `callback` - Optional progress callback
///
/// # Returns
/// * `SpeakerOptimizationResult` containing DSP chain and optimization results
pub fn optimize_speaker(
    channel_name: &str,
    speaker_config: &SpeakerConfig,
    optimizer_config: &OptimizerConfig,
    target_curve: Option<&TargetCurveConfig>,
    sample_rate: f64,
    _callback: Option<SpeakerOptimizationCallback>,
) -> Result<SpeakerOptimizationResult> {
    // Create a minimal RoomConfig for internal processing
    let room_config = RoomConfig {
        version: super::types::default_config_version(),
        system: None,
        speakers: HashMap::new(),
        crossovers: None,
        target_curve: target_curve.cloned(),
        optimizer: optimizer_config.clone(),
        recording_config: None,
        cea2034_cache: None,
    };

    let (
        chain,
        pre_score,
        post_score,
        initial_curve,
        final_curve,
        biquads,
        _mean_spl,
        _arrival_time_ms,
        fir_coeffs,
    ) = process_speaker_internal(
        channel_name,
        speaker_config,
        &room_config,
        sample_rate,
        None,
        None,
        None, // no shared mean for standalone single-channel optimization
    )?;

    Ok(SpeakerOptimizationResult {
        chain,
        pre_score,
        post_score,
        initial_curve,
        final_curve,
        biquads,
        fir_coeffs,
    })
}

// ============================================================================
// Internal Processing Functions
// ============================================================================

/// Process a single speaker (simple or group)
///
/// Returns: (DSP chain, pre_score, post_score, initial_curve, final_curve, biquads, mean_spl, arrival_time_ms)
fn process_speaker_internal(
    channel_name: &str,
    speaker_config: &SpeakerConfig,
    room_config: &RoomConfig,
    sample_rate: f64,
    output_dir: Option<&Path>,
    callback: Option<crate::optim::OptimProgressCallback>,
    shared_mean_spl: Option<f64>,
) -> Result<MixedModeResult> {
    let output_dir = output_dir.unwrap_or(Path::new("."));

    match speaker_config {
        SpeakerConfig::Single(source) => process_single_speaker(
            channel_name,
            source,
            room_config,
            sample_rate,
            output_dir,
            callback,
            None, // probe_arrival_ms: use WAV-based detection
            shared_mean_spl,
        ),
        SpeakerConfig::Group(group) => {
            process_speaker_group(channel_name, group, room_config, sample_rate, output_dir)
        }
        SpeakerConfig::MultiSub(group) => {
            process_multisub_group(channel_name, group, room_config, sample_rate, output_dir)
        }
        SpeakerConfig::Dba(config) => {
            process_dba(channel_name, config, room_config, sample_rate, output_dir)
        }
        SpeakerConfig::Cardioid(config) => {
            process_cardioid(channel_name, config, room_config, sample_rate, output_dir)
        }
    }
}

/// Extract wav_path from a MeasurementSource if available
pub(super) fn extract_wav_path(source: &MeasurementSource) -> Option<String> {
    match source {
        MeasurementSource::Single(s) => {
            if let crate::MeasurementRef::Inline(inline) = &s.measurement {
                inline.wav_path.clone()
            } else {
                None
            }
        }
        MeasurementSource::Multiple(m) => {
            // Use the first measurement's wav_path if available
            m.measurements.first().and_then(|r| {
                if let crate::MeasurementRef::Inline(inline) = r {
                    inline.wav_path.clone()
                } else {
                    None
                }
            })
        }
        MeasurementSource::InMemory(_) | MeasurementSource::InMemoryMultiple(_) => None,
    }
}