koan-core 0.60.3

Core library for koan — bit-perfect music player. Audio engine, player, database, format strings.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
//! The profiles in `config.local.toml`, as every front end changes them.
//!
//! Imported responses are kept under `dsp/<profile>/` beside the config, one
//! 32-bit float WAV per rate, or a `.cfg` with it where routes mix or delay
//! channels. Whatever they were imported from — a Roon zip, a CamillaDSP
//! setup, a share from another app — is read once and not needed again.

use std::path::{Path, PathBuf};

use super::import::Imported;
use super::{Setup, convolver, raw};
use crate::config::{self, Config, DspEar, DspMeasurement, DspProfile, DspRole, DspScope};

#[derive(Debug, Clone, PartialEq)]
pub struct Summary {
    pub name: String,
    pub devices: Vec<String>,
    pub bands: usize,
    /// Profiles it plays first, for a stack.
    pub layers: usize,
    /// Rates there are responses for.
    pub rates: Vec<u32>,
    /// Why the profile would not load, if it would not.
    pub problem: Option<String>,
    pub role: DspRole,
    /// Built from a measurement.
    pub measured: bool,
    /// For a group: its members, in order, and the one playing.
    pub members: Vec<String>,
    pub playing: Option<String>,
    /// A preset: a correction and its tuning saved together.
    pub preset: bool,
    /// Changed since it was imported, so it can go back.
    pub edited: bool,
    /// The devices it is chosen for: as their correction, in their tuning,
    /// or as the preset they were set from.
    pub used_on: Vec<String>,
    /// Kept on every device of the account.
    pub everywhere: bool,
    /// The presets and groups that hold it.
    pub held_by: Vec<String>,
}

/// What a device plays, as the apps' EQ page shows it: for a front end
/// without one, such as the CLI and an assistant driving it.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct ChainView {
    pub device: String,
    pub correction: Option<String>,
    /// The target the correction aims at, by name.
    pub target: Option<String>,
    pub tuning: Vec<TuningView>,
    pub preset: Option<String>,
    /// Changed since it was set from `preset`.
    pub edited: bool,
    /// The tuning's EQs that do not play, by name; `notes` says why.
    pub left_out: Vec<String>,
    pub notes: Option<String>,
    /// No correction and no tuning: it plays untouched.
    pub flat: bool,
    /// The chain in words, as the EQ page says it.
    pub sentence: String,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct TuningView {
    pub name: String,
    pub on: bool,
}

/// What `device` plays.
pub fn chain_view(device: &str) -> ChainView {
    let o = overview_for(Some(device.to_owned()));
    let cfg = Config::cached();
    let all = &cfg.dsp.profiles;
    let chosen = cfg.dsp.profile_for(device);
    let target = chosen
        .and_then(|c| aims_at(c, all))
        .map(|t| target_name(&t));
    let includes = chosen.is_some_and(|c| shown_role(c, all) == DspRole::Baked);
    let playing: Vec<&str> = if includes {
        Vec::new()
    } else {
        o.chain
            .iter()
            .filter(|(name, on)| *on && !o.left_out_eqs.contains(name))
            .map(|(name, _)| name.as_str())
            .collect()
    };
    let sentence = match (&o.active, playing.is_empty()) {
        (None, true) => format!("{device} is flat: the music plays untouched."),
        (active, _) => {
            let mut parts = Vec::new();
            if let Some(c) = active {
                parts.push(match &target {
                    Some(t) => format!("corrected by {c} to {t}"),
                    None => format!("corrected by {c}"),
                });
            }
            if !playing.is_empty() {
                parts.push(format!("tuned with {}", and_list(&playing)));
            }
            format!("Music to {device}, {}.", parts.join(", then "))
        }
    };
    ChainView {
        device: device.to_owned(),
        flat: o.active.is_none() && o.chain.is_empty(),
        correction: o.active,
        target,
        tuning: o
            .chain
            .into_iter()
            .map(|(name, on)| TuningView { name, on })
            .collect(),
        edited: o.preset.as_ref().is_some_and(|(_, e)| *e),
        preset: o.preset.map(|(name, _)| name),
        left_out: o.left_out_eqs,
        notes: o.left_out,
        sentence,
    }
}

/// "A", "A and B", "A, B and C".
fn and_list(items: &[&str]) -> String {
    match items {
        [] => String::new(),
        [one] => (*one).to_owned(),
        [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
    }
}

/// Set `device`'s whole chain: its correction (`Some(None)` for none), its
/// tuning's EQs in order, all on. What is not given is left as it is, and
/// giving the same twice changes nothing. Refused, naming the choices, for
/// a correction or EQ that is not one.
pub fn set_chain(
    device: &str,
    correction: Option<Option<&str>>,
    tuning: Option<&[String]>,
) -> Result<(), String> {
    let cfg = Config::cached();
    let all = &cfg.dsp.profiles;
    let choices = |names: Vec<&str>| {
        if names.is_empty() {
            "none yet".to_owned()
        } else {
            names.join(", ")
        }
    };
    if let Some(Some(name)) = correction {
        let corrections: Vec<&str> = all
            .iter()
            .filter(|p| !p.preset && shown_role(p, all).corrects())
            .map(|p| p.name.as_str())
            .collect();
        if all.iter().any(|p| p.name == name && p.preset) {
            return Err(format!(
                "{name} is a preset, not a correction: set it with `koan dsp preset use {name:?}`"
            ));
        }
        if !corrections.contains(&name) {
            return Err(format!(
                "No correction called {name}. Corrections: {}",
                choices(corrections)
            ));
        }
    }
    if let Some(eqs) = tuning {
        let valid: Vec<&str> = all
            .iter()
            .filter(|p| !p.preset && check_tuning(&p.name, all).is_ok())
            .map(|p| p.name.as_str())
            .collect();
        for (i, eq) in eqs.iter().enumerate() {
            if !all.iter().any(|p| &p.name == eq) {
                return Err(format!("No EQ called {eq}. EQs: {}", choices(valid)));
            }
            check_tuning(eq, all)?;
            if eqs[..i].contains(eq) {
                return Err(format!("{eq} is in the tuning twice"));
            }
        }
        // Checked before anything is set, so a refusal changes nothing.
        let then = match correction {
            Some(c) => c.and_then(|c| all.iter().find(|p| p.name == c)),
            None => cfg.dsp.profile_for(device),
        };
        if let Some(c) = then
            && !eqs.is_empty()
            && shown_role(c, all) == DspRole::Baked
        {
            return Err(baked_already(&c.name));
        }
    }
    // One write, so the two never half-apply. What is not given stays, and
    // so does the preset the device was set from, which then reads as edited.
    let correction: Option<String> = match correction {
        Some(c) => c.map(str::to_owned),
        None => cfg.dsp.profile_for(device).map(|p| p.name.clone()),
    };
    let entries: Vec<(String, bool)> = match tuning {
        Some(eqs) => eqs.iter().map(|e| (e.clone(), true)).collect(),
        None => tunings_for(device),
    };
    let preset = preset_for(device).map(|(name, _)| name);
    persist(|cfg| {
        set_output(
            cfg,
            device,
            correction.as_deref(),
            &entries,
            preset.as_deref(),
        )
    })
}

/// What a device is set to, for a menu of presets.
#[derive(Debug, Clone, PartialEq)]
pub struct OutputState {
    pub device: String,
    /// The preset it was set from, and whether it was changed since.
    pub preset: Option<(String, bool)>,
    /// No correction and no tuning: it plays untouched.
    pub flat: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Overview {
    pub enabled: bool,
    /// The output device playback goes to.
    pub device: Option<String>,
    /// The profile for that device: its correction.
    pub active: Option<String>,
    /// The tuning it plays on top.
    pub tuning: Option<String>,
    /// Whether that tuning plays: not on a baked correction, nor where the
    /// chain cannot hold it.
    pub tuning_plays: bool,
    /// What of that device's choices does not play, and why.
    pub left_out: Option<String>,
    /// The EQs of its tuning left out entirely.
    pub left_out_eqs: Vec<String>,
    /// Every output's tuning, by device: its first EQ.
    pub tunings: Vec<(String, String)>,
    /// That device's tuning: its EQs in order, each on or off.
    pub chain: Vec<(String, bool)>,
    /// The preset that device was set from, and whether it was changed
    /// since.
    pub preset: Option<(String, bool)>,
    pub profiles: Vec<Summary>,
    /// Every device the EQ names, and what each is set to.
    pub outputs: Vec<OutputState>,
}

/// The device the player resolves to: the configured one if it is there, or
/// the system's.
pub fn current_device() -> Option<String> {
    let cfg = Config::cached();
    if let Some(name) = &cfg.playback.output_device
        && crate::audio::list_output_devices()
            .is_ok_and(|devices| devices.iter().any(|d| &d.name == name))
    {
        return Some(name.clone());
    }
    crate::audio::default_output_device().ok().map(|d| d.name)
}

pub fn overview() -> Overview {
    overview_for(current_device())
}

/// The profiles, and which `device` plays through. A front end that knows
/// a renderer is the output names it by its UDN here.
pub fn overview_for(device: Option<String>) -> Overview {
    let cfg = Config::cached();
    let base = config::config_dir();
    let chain = device
        .as_deref()
        .and_then(|d| super::output_chain(&cfg.dsp, d));
    Overview {
        enabled: cfg.dsp.enabled,
        active: device
            .as_deref()
            .and_then(|d| cfg.dsp.profile_for(d))
            .map(|p| p.name.clone()),
        tuning_plays: chain.as_ref().is_some_and(|c| c.tuning_plays),
        left_out_eqs: chain
            .as_ref()
            .map(|c| c.left_out_eqs.clone())
            .unwrap_or_default(),
        left_out: chain.and_then(|c| c.left_out),
        outputs: outputs(&cfg.dsp),
        tunings: cfg.dsp.tunings.iter().fold(Vec::new(), |mut first, t| {
            if !first.iter().any(|(d, _): &(String, String)| d == &t.device) {
                first.push((t.device.clone(), t.tuning.clone()));
            }
            first
        }),
        tuning: device.as_deref().and_then(tuning_for),
        chain: device.as_deref().map(tunings_for).unwrap_or_default(),
        preset: device.as_deref().and_then(preset_for),
        device,
        profiles: cfg
            .dsp
            .profiles
            .iter()
            .map(|p| {
                let (rates, problem) = match Setup::load(p, &cfg.dsp.profiles, &base) {
                    Ok(setup) => (setup.map(|s| s.rates()).unwrap_or_default(), None),
                    Err(e) => (Vec::new(), Some(e.to_string())),
                };
                Summary {
                    name: p.name.clone(),
                    devices: p.devices.clone(),
                    bands: p.filters.len(),
                    layers: p.layers.len(),
                    rates,
                    problem,
                    role: shown_role(p, &cfg.dsp.profiles),
                    measured: p.measurement.is_some(),
                    members: if p.group {
                        p.layers.iter().map(|l| l.profile.clone()).collect()
                    } else {
                        Vec::new()
                    },
                    playing: p
                        .group
                        .then(|| p.layers.iter().find(|l| l.on).map(|l| l.profile.clone()))
                        .flatten(),
                    preset: p.preset,
                    edited: edited(p),
                    used_on: used_on(&cfg.dsp, &p.name),
                    held_by: cfg
                        .dsp
                        .profiles
                        .iter()
                        .filter(|q| {
                            (q.preset || q.group) && q.layers.iter().any(|l| l.profile == p.name)
                        })
                        .map(|q| q.name.clone())
                        .collect(),
                    everywhere: scope(p, &cfg.dsp.profiles) == DspScope::Everywhere,
                }
            })
            .collect(),
    }
}

/// Every device the EQ names, in the order first named, and what each is
/// set to.
fn outputs(dsp: &crate::config::DspConfig) -> Vec<OutputState> {
    let mut devices: Vec<&str> = Vec::new();
    for d in dsp
        .profiles
        .iter()
        .filter(|p| !p.preset)
        .flat_map(|p| p.devices.iter())
        .chain(dsp.tunings.iter().map(|t| &t.device))
        .chain(dsp.presets.iter().map(|p| &p.device))
    {
        if !devices.contains(&d.as_str()) {
            devices.push(d);
        }
    }
    devices
        .into_iter()
        .map(|d| OutputState {
            device: d.to_owned(),
            preset: preset_for(d),
            flat: dsp.profile_for(d).is_none() && !dsp.tunings.iter().any(|t| t.device == d),
        })
        .collect()
}

/// The devices `name` is chosen for: as their correction, in their tuning,
/// or as the preset they were set from.
fn used_on(dsp: &crate::config::DspConfig, name: &str) -> Vec<String> {
    let mut on: Vec<String> = Vec::new();
    let correcting = dsp
        .profiles
        .iter()
        .filter(|p| p.name == name && !p.preset)
        .flat_map(|p| p.devices.iter());
    let tuning = dsp
        .tunings
        .iter()
        .filter(|t| t.tuning == name)
        .map(|t| &t.device);
    let preset = dsp
        .presets
        .iter()
        .filter(|p| p.preset == name)
        .map(|p| &p.device);
    for d in correcting.chain(tuning).chain(preset) {
        if !on.contains(d) {
            on.push(d.clone());
        }
    }
    on
}

/// Save an import as the profile `name`, or the name it came with. An existing
/// profile of that name keeps its devices, and whichever of its filters and
/// responses the import does not replace — so a room's responses and a
/// headphone EQ can be imported into one profile in turn.
pub fn save(imported: Imported, name: Option<&str>) -> Result<String, String> {
    let name = name
        .map(str::trim)
        .filter(|n| !n.is_empty())
        .unwrap_or(&imported.name)
        .to_string();
    let impulses = if imported.impulses.is_empty() {
        None
    } else {
        Some(write_impulses(&name, &imported)?)
    };
    let filters = (!imported.filters.is_empty()).then_some(imported.filters);
    let source = imported.source;
    persist(|cfg| {
        let profile = profile_mut(&mut cfg.dsp.profiles, &name);
        for s in source {
            if !profile.source.contains(&s) {
                profile.source.push(s);
            }
        }
        if let Some(filters) = filters {
            profile.filters = filters;
            // Derived from the filters, which now include these.
            profile.preamp_db = None;
            // Kept, so an edit can be undone.
            profile.original = Some(crate::config::DspOriginal {
                filters: profile.filters.clone(),
                preamp_db: None,
            });
        }
        if let Some(impulses) = impulses {
            profile.impulses = impulses;
        }
    })
    .map_err(|e| e.to_string())?;
    Ok(name)
}

fn write_impulses(name: &str, imported: &Imported) -> Result<Vec<PathBuf>, String> {
    let rel = Path::new("dsp").join(slug(name));
    let dir = config::config_dir().join(&rel);
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
    let mut paths = Vec::new();
    for ir in &imported.impulses {
        let shared_rate = imported
            .impulses
            .iter()
            .filter(|i| i.rate == ir.rate)
            .count()
            > 1;
        let stem = match (shared_rate, ir.channels) {
            (true, Some(n)) => format!("{}-{n}ch", ir.rate),
            _ => ir.rate.to_string(),
        };
        let file = match ir.as_channels() {
            Some(channels) => {
                let channels: Vec<Vec<f32>> = channels.into_iter().map(<[f32]>::to_vec).collect();
                let file = format!("{stem}.wav");
                raw::write_wav(&dir.join(&file), ir.rate, &channels).map_err(|e| e.to_string())?;
                file
            }
            None => convolver::write(&dir, &stem, ir)?
                .file_name()
                .map(|f| f.to_string_lossy().into_owned())
                .unwrap_or_default(),
        };
        paths.push(rel.join(file));
    }
    Ok(paths)
}

/// One impulse-response file in a profile, as the detail page shows it.
#[derive(Debug, Clone, PartialEq)]
pub struct ImpulseDetail {
    pub file: String,
    pub rate: u32,
    /// `None` for one response applied to every channel.
    pub channels: Option<usize>,
    pub taps: usize,
    pub routes: usize,
    /// Routes mix channels into others, as crossfeed does, rather than each
    /// channel being convolved on its own.
    pub mixes: bool,
    /// Channels delayed against each other.
    pub delayed: bool,
    /// Where the response peaks: the delay trimmed from playback.
    pub peak_ms: f64,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Detail {
    pub name: String,
    pub devices: Vec<String>,
    pub source: Vec<String>,
    pub filters: Vec<crate::config::DspFilter>,
    pub impulses: Vec<ImpulseDetail>,
    /// The gain applied ahead of the filters, at `preamp_rate`.
    pub preamp_db: f64,
    pub preamp_rate: u32,
    /// Set by hand rather than derived.
    pub preamp_set: bool,
    pub problem: Option<String>,
    /// Profiles it plays first, for a stack.
    pub layers: Vec<crate::config::DspLayer>,
    /// A group: one of `layers` plays, the one switched on.
    pub group: bool,
    /// Kept on every device of the account, rather than this one alone.
    pub everywhere: bool,
    /// Where it is kept was chosen, rather than following from what it is.
    pub scope_set: bool,
    pub role: DspRole,
    pub role_set: bool,
    /// A chain correcting twice, made before that was refused: which, and
    /// what to do.
    pub corrects_twice: Option<String>,
    /// The chain in a line each: see [`summary`].
    pub corrects: Option<String>,
    pub corrects_baked: bool,
    pub tunings: Vec<String>,
    /// For each of `layers`, what it is for; `None` where it is missing.
    pub layer_roles: Vec<Option<DspRole>>,
    pub measured: bool,
    pub made_for: Option<String>,
    /// For a tuning: the target it was made against.
    pub tuned_for: Option<String>,
    /// A preset: a correction and its tuning saved together.
    pub preset: bool,
    /// Changed since it was imported.
    pub edited: bool,
    /// Imported, so it can go back to how it was.
    pub can_revert: bool,
    /// A correction, which plays as made: its bands are not edited.
    pub read_only: bool,
}

/// Everything in the profile `name`.
pub fn detail(name: &str) -> Option<Detail> {
    let cfg = Config::cached();
    let profile = cfg.dsp.profiles.iter().find(|p| p.name == name)?;
    let base = config::config_dir();
    let mut problem = None;
    let mut impulses = Vec::new();
    for path in &profile.impulses {
        match super::load_impulses(path, &base) {
            Ok(irs) => impulses.extend(irs.into_iter().map(|ir| {
                ImpulseDetail {
                    file: path
                        .file_name()
                        .map(|f| f.to_string_lossy().into_owned())
                        .unwrap_or_default(),
                    rate: ir.rate,
                    channels: ir.channels,
                    taps: ir.taps(),
                    routes: ir.routes.len(),
                    mixes: ir.mixes(),
                    delayed: ir.in_delays.iter().chain(&ir.out_delays).any(|&d| d > 0),
                    peak_ms: ir.delay() as f64 * 1000.0 / ir.rate as f64,
                }
            })),
            Err(e) => problem = Some(e.to_string()),
        }
    }
    impulses.sort_by_key(|i| i.rate);
    let preamp_rate = impulses
        .iter()
        .map(|i| i.rate)
        .find(|&r| r == 48000)
        .or(impulses.first().map(|i| i.rate))
        .unwrap_or(48000);
    // What it plays is adjusted to stay within bounds: say how.
    let mut adjusted = profile.clone().sanitize();
    match super::chain_noted(profile, &cfg.dsp.profiles, &mut Vec::new()) {
        Ok((_, notes)) => {
            for n in notes {
                if !adjusted.contains(&n) {
                    adjusted.push(n);
                }
            }
        }
        Err(e) => problem = Some(e.to_string()),
    }
    let setup = Setup::load(profile, &cfg.dsp.profiles, &base)
        .ok()
        .flatten();
    if let Some(cut) = setup.as_ref().and_then(|s| s.headroom_cut(preamp_rate, 2)) {
        adjusted.push(format!("preamp −{cut:.1} dB for headroom"));
    }
    if !adjusted.is_empty() {
        let note = format!("Adjusted: {}", adjusted.join("; "));
        problem = Some(problem.map_or(note.clone(), |p| format!("{p}. {note}")));
    }
    let preamp_db = setup.map_or(0.0, |s| s.preamp_db(preamp_rate, 2));
    let chain_summary = summary(name).unwrap_or_default();
    Some(Detail {
        name: profile.name.clone(),
        devices: profile.devices.clone(),
        source: profile.source.clone(),
        filters: profile.filters.clone(),
        impulses,
        preamp_db,
        preamp_rate,
        preamp_set: profile.preamp_db.is_some(),
        layers: profile.layers.clone(),
        group: profile.group,
        problem,
        everywhere: scope(profile, &cfg.dsp.profiles) == DspScope::Everywhere,
        scope_set: profile.scope.is_some(),
        role: shown_role(profile, &cfg.dsp.profiles),
        role_set: profile.role.is_some(),
        corrects_twice: corrects_twice(profile, &cfg.dsp.profiles),
        corrects: chain_summary.correction,
        corrects_baked: chain_summary.baked,
        tunings: chain_summary.tunings,
        layer_roles: profile
            .layers
            .iter()
            .map(|l| {
                cfg.dsp
                    .profiles
                    .iter()
                    .find(|p| p.name == l.profile)
                    .map(role)
            })
            .collect(),
        measured: profile.measurement.is_some(),
        made_for: profile.target.as_ref().map(|t| t.made_for.clone()),
        tuned_for: profile.tuned_for.clone(),
        preset: profile.preset,
        edited: edited(profile),
        can_revert: profile.original.is_some(),
        read_only: shown_role(profile, &cfg.dsp.profiles).corrects(),
    })
}

/// Rename a profile, moving the responses koan keeps for it.
pub fn rename(old: &str, new: &str) -> Result<(), String> {
    let new = new.trim();
    if new.is_empty() {
        return Err("It needs a name".into());
    }
    if new == old {
        return Ok(());
    }
    let cfg = Config::cached();
    if cfg.dsp.profiles.iter().any(|p| p.name == new) {
        return Err(format!("There is already an EQ called {new}"));
    }
    if !cfg.dsp.profiles.iter().any(|p| p.name == old) {
        return Err(format!("No EQ called {old}"));
    }
    let (from, to) = (
        Path::new("dsp").join(slug(old)),
        Path::new("dsp").join(slug(new)),
    );
    let base = config::config_dir();
    let moved = from != to && base.join(&from).exists();
    if moved {
        if base.join(&to).exists() {
            return Err(format!("{} is in the way", to.display()));
        }
        std::fs::rename(base.join(&from), base.join(&to)).map_err(|e| e.to_string())?;
    }
    persist(|cfg| {
        // The stacks that play it follow the new name.
        for l in cfg
            .dsp
            .profiles
            .iter_mut()
            .flat_map(|p| p.layers.iter_mut())
        {
            if l.profile == old {
                l.profile = new.to_string();
            }
        }
        // So do the outputs that play it as their tuning, or were set from it.
        for t in &mut cfg.dsp.tunings {
            if t.tuning == old {
                t.tuning = new.to_string();
            }
        }
        for p in &mut cfg.dsp.presets {
            if p.preset == old {
                p.preset = new.to_string();
            }
        }
        if let Some(p) = cfg.dsp.profiles.iter_mut().find(|p| p.name == old) {
            p.name = new.to_string();
            if moved {
                for path in &mut p.impulses {
                    if let Ok(rest) = path.strip_prefix(&from) {
                        *path = to.join(rest);
                    }
                }
            }
        }
    })
    .map_err(|e| e.to_string())
}

/// Write the profiles, and say so: what each output plays through is shown
/// on every device that can choose it, here and on the devices controlling
/// this one.
fn persist(mutate: impl FnOnce(&mut crate::config::Config)) -> Result<(), String> {
    Config::persist(mutate).map_err(|e| e.to_string())?;
    crate::signal::engine_changed().bump();
    crate::remote::dsp_sync::changed();
    Ok(())
}

/// Where `name` keeps its files: responses, and an AutoEQ result's CSV.
pub fn dir(name: &str) -> PathBuf {
    config::config_dir().join("dsp").join(slug(name))
}

/// Record the target `name`'s correction was made for: one that ships,
/// since a move is worked out against it. A target chosen in its place is
/// kept where it is for the same kind of headphone. Refused for a
/// correction built from a measurement, which is made for the target it is
/// corrected to.
pub fn set_made_for(name: &str, made_for: Option<&str>) -> Result<(), String> {
    use super::targets;
    let cfg = Config::cached();
    let p = cfg
        .dsp
        .profiles
        .iter()
        .find(|p| p.name == name)
        .ok_or_else(|| format!("No EQ called {name}"))?;
    if p.measurement.is_some() {
        return Err(format!(
            "{name} is built from a measurement: choose the target it is corrected to instead"
        ));
    }
    let made = match made_for {
        Some(id) => Some(targets::shipped(id).ok_or_else(|| format!("No target called {id}"))?),
        None => None,
    };
    let chosen = p
        .target
        .as_ref()
        .and_then(|t| t.chosen.clone())
        .filter(|c| made.is_some_and(|m| targets::shipped(c).is_none_or(|t| t.ear == m.ear)));
    persist(|cfg| {
        if let Some(p) = cfg.dsp.profiles.iter_mut().find(|p| p.name == name) {
            p.target = made.map(|m| crate::config::DspTarget {
                made_for: m.id.to_owned(),
                chosen,
            });
        }
    })
}

/// The headphone `p` corrects, as measured, and the target it is corrected
/// to, for drawing: an AutoEQ result's own two curves, its target moved as a
/// chosen target moves it; or a measurement and its target, levelled at
/// 1 kHz so they are drawn against each other.
fn headphone(p: &DspProfile) -> Option<(super::targets::Curve, super::targets::Curve)> {
    use super::targets;
    let folder = dir(&p.name);
    if let Some(m) = &p.measurement {
        let level = |c: targets::Curve| {
            let k = targets::at(&c, 1000.0);
            c.into_iter()
                .map(|(hz, db)| (hz, db - k))
                .collect::<targets::Curve>()
        };
        return Some((
            level(targets::measurement(&folder)?),
            level(targets::choice_curve(&m.target)?),
        ));
    }
    let (raw, made_for) = targets::autoeq_measurement(&folder)?;
    let moved = p
        .target
        .as_ref()
        .and_then(|t| Some((t.chosen.as_ref()?, &t.made_for)))
        .and_then(|(to, from)| {
            Some(targets::difference(
                &targets::choice_curve(from)?,
                &targets::choice_curve(to)?,
            ))
        });
    Some((
        raw,
        match moved {
            Some(step) => targets::moved(&made_for, &step),
            None => made_for,
        },
    ))
}

/// What `name` offers to move its correction to.
#[derive(Debug, Clone, PartialEq)]
pub struct TargetChoices {
    /// The target an AutoEQ correction or a ready-made EQ was made for;
    /// none for one built from a measurement, which is made for `chosen`.
    pub made_for: Option<&'static super::targets::Target>,
    pub chosen: Option<String>,
    /// The shipped targets for the same kind of headphone, then those added.
    pub choices: Vec<TargetChoice>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct TargetChoice {
    pub id: String,
    pub name: String,
    /// What it does, in a few plain words; empty for one added.
    pub does: String,
    /// What it sounds like; empty for one added.
    pub character: String,
}

/// The targets `name` can move to, for a correction installed from AutoEQ
/// whose target is known.
pub fn target_choices(name: &str) -> Option<TargetChoices> {
    use super::targets;
    let cfg = Config::cached();
    let p = cfg.dsp.profiles.iter().find(|p| p.name == name)?;
    let (made_for, chosen, ear) = match (&p.measurement, &p.target) {
        (Some(m), _) => (
            None,
            Some(m.target.clone()),
            match m.ear {
                DspEar::In => targets::Ear::In,
                DspEar::Over => targets::Ear::Over,
            },
        ),
        (None, Some(t)) => {
            let made_for = targets::shipped(&t.made_for)?;
            (Some(made_for), t.chosen.clone(), made_for.ear)
        }
        (None, None) => return None,
    };
    let mut choices: Vec<TargetChoice> = targets::TARGETS
        .iter()
        .filter(|c| c.ear == ear)
        .map(|c| TargetChoice {
            id: c.id.into(),
            name: c.name.into(),
            does: c.does.into(),
            character: c.character.into(),
        })
        .collect();
    choices.extend(targets::added().into_iter().map(|a| TargetChoice {
        id: a.id,
        name: a.name,
        does: String::new(),
        character: String::new(),
    }));
    Some(TargetChoices {
        made_for,
        chosen,
        choices,
    })
}

/// Move `name`'s correction to `chosen`, or with `None` back to the target it
/// was made for.
pub fn choose_target(name: &str, chosen: Option<&str>) -> Result<(), String> {
    let choices =
        target_choices(name).ok_or_else(|| format!("{name} has no target to move from"))?;
    if let Some(c) = chosen
        && !choices.choices.iter().any(|x| x.id == c)
    {
        return Err(format!("No target {c} for {name}"));
    }
    persist(|cfg| {
        let Some(p) = cfg.dsp.profiles.iter_mut().find(|p| p.name == name) else {
            return;
        };
        if let Some(m) = p.measurement.as_mut() {
            // Built from a measurement: it is made for the target chosen.
            if let Some(c) = chosen {
                m.target = c.to_owned();
            }
        } else if let Some(t) = p.target.as_mut() {
            t.chosen = chosen.filter(|c| *c != t.made_for).map(str::to_owned);
        }
    })
    .map_err(|e| e.to_string())
}

/// Play `device` through `name`, or untouched with `None`.
pub fn assign(name: Option<&str>, device: &str) -> Result<(), String> {
    if let Some(name) = name {
        let cfg = Config::cached();
        let Some(p) = cfg.dsp.profiles.iter().find(|p| p.name == name) else {
            return Err(format!("No EQ called {name}"));
        };
        // A preset is never an output's correction: it sets one.
        if p.preset {
            return apply_preset(device, Some(name));
        }
    }
    persist(|cfg| {
        for p in &mut cfg.dsp.profiles {
            p.devices.retain(|d| d != device);
            if Some(p.name.as_str()) == name {
                p.devices.push(device.to_string());
            }
        }
    })
    .map_err(|e| e.to_string())
}

/// The ranges a band edited by hand is held to: the audible band, what a
/// correction plausibly asks, and Q from very broad to very narrow.
const BAND_HZ: std::ops::RangeInclusive<f64> = 10.0..=22_000.0;
const BAND_DB: std::ops::RangeInclusive<f64> = -30.0..=30.0;
const BAND_Q: std::ops::RangeInclusive<f64> = 0.1..=20.0;

fn clamp(v: f64, r: &std::ops::RangeInclusive<f64>) -> Result<f64, String> {
    if !v.is_finite() {
        return Err("Not a number".into());
    }
    Ok(v.clamp(*r.start(), *r.end()))
}

/// Refused unless `name` is there and can be edited: not a correction.
fn may_edit(name: &str) -> Result<(), String> {
    let cfg = Config::cached();
    let p = cfg
        .dsp
        .profiles
        .iter()
        .find(|p| p.name == name)
        .ok_or_else(|| format!("No EQ called {name}"))?;
    editable(p, &cfg.dsp.profiles)
}

/// Set filter `index` of `name`, a parametric band, to `kind` at `freq`,
/// `gain_db` and `q`, held within the ranges a band may have. Its channels
/// are kept. Delays, mixes and graphic curves are not edited this way.
/// Refused for a correction, which plays as made.
pub fn set_band(
    name: &str,
    index: usize,
    kind: &str,
    freq: f64,
    gain_db: f64,
    q: f64,
) -> Result<(), String> {
    use crate::config::{DspFilter, EqFilterKind};
    let kind: EqFilterKind = serde_json::from_value(serde_json::Value::String(kind.into()))
        .map_err(|_| format!("No band type called {kind}"))?;
    may_edit(name)?;
    let (freq, gain_db, q) = (
        clamp(freq, &BAND_HZ)?,
        clamp(gain_db, &BAND_DB)?,
        clamp(q, &BAND_Q)?,
    );
    let mut found = Err(format!("{name} has no band {}", index + 1));
    persist(|cfg| {
        if let Some(DspFilter::Band(b)) = cfg
            .dsp
            .profiles
            .iter_mut()
            .find(|p| p.name == name)
            .and_then(|p| p.filters.get_mut(index))
        {
            (b.kind, b.freq, b.gain_db, b.q) = (kind, freq, gain_db, q);
            found = Ok(());
        }
    })
    .map_err(|e| e.to_string())?;
    found
}

/// Add a band to `name`: flat, at 1 kHz, for shaping from there. Answers
/// with its index among the profile's filters.
pub fn add_band(name: &str) -> Result<usize, String> {
    use crate::config::{DspFilter, EqFilter, EqFilterKind};
    may_edit(name)?;
    let mut index = 0;
    persist(|cfg| {
        let p = profile_mut(&mut cfg.dsp.profiles, name);
        p.filters.push(DspFilter::Band(EqFilter {
            kind: EqFilterKind::Peaking,
            freq: 1000.0,
            gain_db: 0.0,
            q: 1.0,
            channels: vec![],
        }));
        index = p.filters.len() - 1;
    })
    .map_err(|e| e.to_string())?;
    Ok(index)
}

/// Take filter `index` out of `name`.
pub fn remove_filter(name: &str, index: usize) -> Result<(), String> {
    may_edit(name)?;
    let mut found = Err(format!("{name} has no filter {}", index + 1));
    persist(|cfg| {
        if let Some(p) = cfg.dsp.profiles.iter_mut().find(|p| p.name == name)
            && index < p.filters.len()
        {
            p.filters.remove(index);
            found = Ok(());
        }
    })
    .map_err(|e| e.to_string())?;
    found
}

/// What a profile does to the sound, for drawing: every curve on AutoEQ's
/// grid, in dB.
#[derive(Debug, Clone, PartialEq)]
pub struct Response {
    pub freqs: Vec<f64>,
    /// Everything it plays, layers, target step and impulse responses
    /// included, on the first channel. The preamp is left out, so the
    /// curve lines up with the bands' own gains; it is `preamp_db`.
    pub total: Vec<f64>,
    /// Each of its own parametric bands alone, in order.
    pub bands: Vec<Vec<f64>>,
    /// Each layer as it plays alone, for a stack.
    pub layers: Vec<LayerResponse>,
    /// For a correction from AutoEQ (or a stack with one among its layers):
    /// the headphone as measured, the target it plays to, and the measurement
    /// with everything here applied.
    pub measurement: Option<Vec<f64>>,
    pub target: Option<Vec<f64>>,
    pub predicted: Option<Vec<f64>>,
    /// The gain ahead of it all at `rate`.
    pub preamp_db: f64,
    /// For a chain with both a correction and tuning: what the correction
    /// does, and what the tuning on top does, so each can be drawn as its
    /// own. `total` is the two together.
    pub correction: Option<Vec<f64>>,
    pub tuning: Option<Vec<f64>>,
    /// For a split's preview: the baked EQ it comes from, which `total`
    /// plays the same as.
    pub original: Option<Vec<f64>>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct LayerResponse {
    pub name: String,
    pub on: bool,
    pub db: Vec<f64>,
}

/// What `name` does to the sound at `rate`, from the filters the DSP runs.
/// `None` for a profile that is not there or would not play.
pub fn response(name: &str, rate: u32) -> Option<Response> {
    let cfg = Config::cached();
    let all = &cfg.dsp.profiles;
    response_of(all.iter().find(|p| p.name == name)?, all, rate)
}

/// What the output `device` plays at `rate`: its correction and the tuning
/// on top, as the player builds them.
pub fn output_response(device: &str, rate: u32) -> Option<Response> {
    let chain = super::output_chain(&Config::cached().dsp, device)?;
    response_of(&chain.profile, &chain.all, rate)
}

fn response_of(profile: &DspProfile, all: &[DspProfile], rate: u32) -> Option<Response> {
    use super::targets;
    let freqs = targets::grid();
    let curve = |filters: &[crate::config::DspFilter]| super::response(filters, &freqs, rate);
    let setup = Setup::load(profile, all, &config::config_dir()).ok()?;
    let total = setup
        .as_ref()
        .map_or_else(|| vec![0.0; freqs.len()], |s| s.response(&freqs, rate));
    let bands = profile
        .filters
        .iter()
        .filter(|f| matches!(f, crate::config::DspFilter::Band(_)))
        .map(|f| curve(std::slice::from_ref(f)))
        .collect();
    // The correction alone, where the chain has tuning besides.
    let corrector = corrections_in(profile, all)
        .first()
        .and_then(|c| all.iter().find(|p| &p.name == c))
        .filter(|c| c.name != profile.name || !profile.layers.is_empty());
    let correction = corrector.and_then(|c| {
        let alone = DspProfile {
            layers: Vec::new(),
            ..c.clone()
        };
        Setup::load(&alone, all, &config::config_dir())
            .ok()
            .flatten()
            .map(|s| s.response(&freqs, rate))
    });
    let tuning = correction
        .as_ref()
        .map(|c| {
            total
                .iter()
                .zip(c)
                .map(|(t, c)| t - c)
                .collect::<Vec<f64>>()
        })
        .filter(|t| t.iter().any(|db| db.abs() > 0.05));
    let correction = correction.filter(|_| tuning.is_some());
    let layers = profile
        .layers
        .iter()
        .filter_map(|l| {
            let p = all.iter().find(|p| p.name == l.profile)?;
            let filters = super::chain(p, all, &mut Vec::new()).ok()?;
            Some(LayerResponse {
                // An output's tuning is resolved under a name of its own.
                name: l
                    .profile
                    .rsplit('\u{1}')
                    .next()
                    .unwrap_or_default()
                    .to_owned(),
                on: l.on,
                db: curve(&filters),
            })
        })
        .collect();

    // The headphone this chain corrects, as measured, and the target it is
    // corrected to: this profile's, or the first of its layers that has one.
    let measured = std::iter::once(profile)
        .chain(
            profile
                .layers
                .iter()
                .filter(|l| l.on)
                .filter_map(|l| all.iter().find(|p| p.name == l.profile)),
        )
        .find_map(headphone);
    let (measurement, target, predicted) = match measured {
        Some((raw, aim)) => {
            let raw: Vec<f64> = freqs.iter().map(|&hz| targets::at(&raw, hz)).collect();
            let aim: Vec<f64> = freqs.iter().map(|&hz| targets::at(&aim, hz)).collect();
            let predicted = raw.iter().zip(&total).map(|(r, t)| r + t).collect();
            (Some(raw), Some(aim), Some(predicted))
        }
        None => (None, None, None),
    };
    let preamp_db = setup.map_or(0.0, |s| s.preamp_db(s.output_rate(rate), 2));
    Some(Response {
        freqs,
        total,
        bands,
        layers,
        measurement,
        target,
        predicted,
        preamp_db,
        correction,
        tuning,
        original: None,
    })
}

/// Play `member` of the group `group`, and none of the others.
pub fn select(group: &str, member: &str) -> Result<(), String> {
    let cfg = Config::cached();
    let g = cfg
        .dsp
        .profiles
        .iter()
        .find(|p| p.name == group)
        .ok_or_else(|| format!("No EQ called {group}"))?;
    if !g.group {
        return Err(format!("{group} is not a group"));
    }
    if !g.layers.iter().any(|l| l.profile == member) {
        return Err(format!("{member} is not in {group}"));
    }
    persist(|cfg| {
        if let Some(g) = cfg.dsp.profiles.iter_mut().find(|p| p.name == group) {
            for l in &mut g.layers {
                l.on = l.profile == member;
            }
        }
    })
    .map_err(|e| e.to_string())
}

/// Make `name` a group, where one of its layers plays, or a stack, where
/// each is switched on or off. Made a group, the first layer switched on
/// is the one that plays.
pub fn set_group(name: &str, group: bool) -> Result<(), String> {
    persist(|cfg| {
        if let Some(p) = cfg.dsp.profiles.iter_mut().find(|p| p.name == name) {
            p.group = group;
            if group {
                let first = p.layers.iter().position(|l| l.on).unwrap_or(0);
                for (i, l) in p.layers.iter_mut().enumerate() {
                    l.on = i == first;
                }
            }
        }
    })
    .map_err(|e| e.to_string())
}

/// `name`, or numbered where it or the folder its files would go in is
/// taken, so nothing already here is written over.
pub fn free_name(name: &str) -> String {
    let cfg = Config::cached();
    let taken = |n: &str| {
        let folder = dir(n);
        cfg.dsp
            .profiles
            .iter()
            .any(|p| p.name == n || dir(&p.name) == folder)
            || folder.exists()
    };
    std::iter::once(name.to_owned())
        .chain((2..).map(|n| format!("{name} {n}")))
        .find(|n| !taken(n))
        .expect("some number is free")
}

/// Make `name` a group of `members`, in order, the first playing. Refused
/// over a profile of that name.
pub fn make_group(name: &str, members: &[String]) -> Result<(), String> {
    let name = name.trim();
    if name.is_empty() {
        return Err("A group needs a name".into());
    }
    if Config::cached().dsp.profiles.iter().any(|p| p.name == name) {
        return Err(format!("There is already an EQ called {name}"));
    }
    let group = DspProfile {
        name: name.to_owned(),
        layers: members
            .iter()
            .enumerate()
            .map(|(i, m)| crate::config::DspLayer {
                profile: m.clone(),
                on: i == 0,
            })
            .collect(),
        group: true,
        ..Default::default()
    };
    // Each member as it would play, so a group that cannot is never kept.
    let mut all = Config::cached().dsp.profiles.clone();
    all.push(group.clone());
    for m in members {
        let mut check = group.clone();
        for l in &mut check.layers {
            l.on = &l.profile == m;
        }
        super::chain(&check, &all, &mut Vec::new()).map_err(|e| e.to_string())?;
    }
    persist(|cfg| cfg.dsp.profiles.push(group)).map_err(|e| e.to_string())
}

/// Where `profile` is kept: as set, or as follows from what it is. A room
/// or speaker correction, with impulse responses, or one for an output that
/// stays put (built in, or an amplifier on the network) is this device's; a
/// headphone correction from AutoEQ is the account's, since headphones move
/// between devices; a stack is the account's when every layer is.
pub fn scope(profile: &DspProfile, all: &[DspProfile]) -> DspScope {
    scope_in(profile, all, &mut Vec::new())
}

fn scope_in(profile: &DspProfile, all: &[DspProfile], seen: &mut Vec<String>) -> DspScope {
    if let Some(scope) = profile.scope {
        return scope;
    }
    if !profile.impulses.is_empty() {
        return DspScope::Device;
    }
    if profile.target.is_some() || profile.measurement.is_some() {
        return DspScope::Everywhere;
    }
    if !profile.layers.is_empty() {
        if seen.contains(&profile.name) {
            return DspScope::Device;
        }
        seen.push(profile.name.clone());
        let everywhere = profile.layers.iter().all(|l| {
            all.iter()
                .find(|p| p.name == l.profile)
                .is_some_and(|p| scope_in(p, all, seen) == DspScope::Everywhere)
        });
        return if everywhere {
            DspScope::Everywhere
        } else {
            DspScope::Device
        };
    }
    if profile.devices.iter().any(|d| stays_put(d)) {
        return DspScope::Device;
    }
    DspScope::Everywhere
}

/// An output that does not travel: built in, an amplifier on the network
/// (named by its UDN), or a phone's own speaker.
fn stays_put(device: &str) -> bool {
    device.starts_with("uuid:")
        || device == "Speaker"
        || crate::audio::list_output_devices().is_ok_and(|devices| {
            devices
                .iter()
                .any(|d| d.name == device && d.kind == crate::audio::backend::OutputKind::BuiltIn)
        })
}

/// The first of `layers` kept on this device alone, which a stack kept
/// everywhere cannot play on the account's other devices.
fn local_layer<'a>(layers: &'a [crate::config::DspLayer], all: &[DspProfile]) -> Option<&'a str> {
    layers
        .iter()
        .find(|l| {
            all.iter()
                .find(|p| p.name == l.profile)
                .is_some_and(|p| scope(p, all) == DspScope::Device)
        })
        .map(|l| l.profile.as_str())
}

fn kept_here(stack: &str, layer: &str) -> String {
    format!(
        "{layer} is kept on this device, so {stack}, which is kept everywhere, \
         could not play it on your other devices. Keep {layer} everywhere, or {stack} on this device"
    )
}

/// Keep `name` everywhere or on this device alone. A stack kept everywhere
/// cannot have a layer kept here: refused either way round.
pub fn set_scope(name: &str, to: DspScope) -> Result<(), String> {
    let cfg = Config::cached();
    let all = &cfg.dsp.profiles;
    let profile = all
        .iter()
        .find(|p| p.name == name)
        .ok_or_else(|| format!("No EQ called {name}"))?;
    match to {
        DspScope::Everywhere => {
            if let Some(layer) = local_layer(&profile.layers, all) {
                return Err(kept_here(name, layer));
            }
        }
        DspScope::Device => {
            if let Some(stack) = all.iter().find(|p| {
                p.layers.iter().any(|l| l.profile == name) && scope(p, all) == DspScope::Everywhere
            }) {
                return Err(format!(
                    "{name} is played by {}, which is kept everywhere and would lose it on \
                     your other devices. Keep {} on this device first",
                    stack.name, stack.name
                ));
            }
        }
    }
    persist(|cfg| {
        if let Some(p) = cfg.dsp.profiles.iter_mut().find(|p| p.name == name) {
            p.scope = Some(to);
        }
    })
    .map_err(|e| e.to_string())
}

/// What `profile` is for: as set, or a correction where it was installed
/// from AutoEQ, built from a measurement or said to be made for a target,
/// and a tuning otherwise.
pub fn role(profile: &DspProfile) -> DspRole {
    // Impulse responses correct a room or a device: never a tuning.
    profile.role.unwrap_or(
        if profile.target.is_some() || profile.measurement.is_some() || !profile.impulses.is_empty()
        {
            DspRole::Correction
        } else {
            DspRole::Tuning
        },
    )
}

/// What `profile` is for, as shown: a stack with nothing of its own is what
/// it plays, a correction where it holds one, as that correction is.
pub fn shown_role(profile: &DspProfile, all: &[DspProfile]) -> DspRole {
    let own = !profile.filters.is_empty() || !profile.impulses.is_empty();
    if profile.role.is_some() || own || profile.layers.is_empty() {
        return role(profile);
    }
    corrections_in(profile, all)
        .first()
        .and_then(|c| all.iter().find(|p| &p.name == c))
        .map_or(DspRole::Tuning, role)
}

/// The target the chain `profile` corrects to: its correction's chosen
/// target, or the one it was made for or is built from a measurement to.
/// None for a correction with a tuning baked in, whose target is not only a
/// target, or one whose target is not known.
pub fn aims_at(profile: &DspProfile, all: &[DspProfile]) -> Option<String> {
    let first = corrections_in(profile, all).into_iter().next()?;
    let c = all.iter().find(|p| p.name == first)?;
    if role(c) != DspRole::Correction {
        return None;
    }
    c.measurement
        .as_ref()
        .map(|m| m.target.clone())
        .or_else(|| {
            c.target
                .as_ref()
                .map(|t| t.chosen.clone().unwrap_or_else(|| t.made_for.clone()))
        })
}

/// The first EQ of `device`'s tuning: what an app showing one shows.
pub fn tuning_for(device: &str) -> Option<String> {
    tunings_for(device).into_iter().next().map(|(name, _)| name)
}

/// `device`'s tuning: its EQs in the order they play, each on or off.
pub fn tunings_for(device: &str) -> Vec<(String, bool)> {
    Config::cached()
        .dsp
        .tunings
        .iter()
        .filter(|t| t.device == device)
        .map(|t| (t.tuning.clone(), t.on))
        .collect()
}

/// Play `tuning` alone on top of `device`'s correction, or none.
pub fn set_tuning(device: &str, tuning: Option<&str>) -> Result<(), String> {
    let list: Vec<(String, bool)> = tuning.map(|t| (t.to_owned(), true)).into_iter().collect();
    set_tunings(device, &list)
}

/// Make `device`'s tuning `tunings`, EQs in the order they play, each on or
/// off. Only EQs, each once, none with impulse responses; and none on over
/// a correction with a tuning baked in, which would add taste twice.
pub fn set_tunings(device: &str, tunings: &[(String, bool)]) -> Result<(), String> {
    let cfg = Config::cached();
    let all = &cfg.dsp.profiles;
    for (i, (name, _)) in tunings.iter().enumerate() {
        check_tuning(name, all)?;
        if tunings[..i].iter().any(|(n, _)| n == name) {
            return Err(format!("{name} is in the tuning twice"));
        }
    }
    if tunings.iter().any(|(_, on)| *on)
        && let Some(c) = cfg.dsp.profile_for(device)
        && shown_role(c, all) == DspRole::Baked
    {
        return Err(baked_already(&c.name));
    }
    persist(|cfg| {
        cfg.dsp.tunings.retain(|t| t.device != device);
        cfg.dsp.tunings.extend(
            tunings
                .iter()
                .map(|(name, on)| crate::config::DspOutputTuning {
                    device: device.to_owned(),
                    tuning: name.clone(),
                    on: *on,
                }),
        );
    })
}

/// Whether `name` can be an EQ of a tuning, and why not.
fn check_tuning(name: &str, all: &[DspProfile]) -> Result<(), String> {
    let t = all
        .iter()
        .find(|p| p.name == name)
        .ok_or_else(|| format!("No EQ called {name}"))?;
    if !super::responses(t, all).is_empty() {
        return Err(format!(
            "{name} has impulse responses, which correct a room or speakers: choose it as the correction instead"
        ));
    }
    if shown_role(t, all) != DspRole::Tuning {
        return Err(format!(
            "{name} corrects headphones: choose it as the correction instead"
        ));
    }
    Ok(())
}

/// Why a correction's bands are not edited.
pub fn read_only(name: &str) -> String {
    format!(
        "{name} is a correction, which plays as made: add a tuning on top to change the sound, or make it a tuning on its page to edit it"
    )
}

/// Refused for a correction, which plays as made.
fn editable(profile: &DspProfile, all: &[DspProfile]) -> Result<(), String> {
    if shown_role(profile, all).corrects() {
        return Err(read_only(&profile.name));
    }
    Ok(())
}

/// Whether `profile` was changed since it was imported.
pub fn edited(profile: &DspProfile) -> bool {
    profile
        .original
        .as_ref()
        .is_some_and(|o| o.filters != profile.filters || o.preamp_db != profile.preamp_db)
}

/// Put `name` back as it was imported.
pub fn revert(name: &str) -> Result<(), String> {
    let cfg = Config::cached();
    let p = cfg
        .dsp
        .profiles
        .iter()
        .find(|p| p.name == name)
        .ok_or_else(|| format!("No EQ called {name}"))?;
    let Some(original) = p.original.clone() else {
        return Err(format!(
            "{name} was not imported, so there is nothing to go back to"
        ));
    };
    persist(|cfg| {
        if let Some(p) = cfg.dsp.profiles.iter_mut().find(|p| p.name == name) {
            p.filters = original.filters;
            p.preamp_db = original.preamp_db;
        }
    })
}

/// A copy of `name` as it is now, under `new` or "<name> copy": its filters,
/// files, role, targets and where it is kept, used by no output. Its own,
/// with nothing to revert to. The copy's name.
pub fn duplicate(name: &str, new: Option<&str>) -> Result<String, String> {
    let cfg = Config::cached();
    let p = cfg
        .dsp
        .profiles
        .iter()
        .find(|p| p.name == name)
        .ok_or_else(|| format!("No EQ called {name}"))?;
    let new = match new.map(str::trim).filter(|n| !n.is_empty()) {
        Some(n) if free_name(n) != n => {
            return Err(format!("There is already an EQ called {n}"));
        }
        Some(n) => n.to_owned(),
        None => free_name(&format!("{name} copy")),
    };
    let (from, to) = (dir(name), dir(&new));
    if from.is_dir() {
        copy_dir(&from, &to).map_err(|e| e.to_string())?;
    }
    let mut copy = p.clone();
    let rel = |d: &Path| Path::new("dsp").join(d.file_name().unwrap_or_default());
    copy.impulses = copy
        .impulses
        .iter()
        .map(|i| match i.strip_prefix(rel(&from)) {
            Ok(rest) => rel(&to).join(rest),
            Err(_) => i.clone(),
        })
        .collect();
    copy.name = new.clone();
    copy.devices.clear();
    copy.uid = None;
    copy.origin = None;
    copy.original = None;
    copy.source.clear();
    persist(|cfg| cfg.dsp.profiles.push(copy))?;
    Ok(new)
}

fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> {
    std::fs::create_dir_all(to)?;
    for entry in std::fs::read_dir(from)? {
        let entry = entry?;
        let target = to.join(entry.file_name());
        if entry.file_type()?.is_dir() {
            copy_dir(&entry.path(), &target)?;
        } else {
            std::fs::copy(entry.path(), target)?;
        }
    }
    Ok(())
}

/// The preset `device` was last set from, and whether its correction or
/// tuning has been changed since.
pub fn preset_for(device: &str) -> Option<(String, bool)> {
    let cfg = Config::cached();
    let name = cfg
        .dsp
        .presets
        .iter()
        .find(|p| p.device == device)?
        .preset
        .clone();
    let preset = cfg
        .dsp
        .profiles
        .iter()
        .find(|p| p.name == name && p.preset)?;
    let now = chain_of(&cfg.dsp, device);
    Some((name, now != preset.layers))
}

/// `device`'s correction and tuning as a preset's layers: the correction,
/// then the tuning's EQs.
fn chain_of(dsp: &crate::config::DspConfig, device: &str) -> Vec<crate::config::DspLayer> {
    let correction = dsp
        .profiles
        .iter()
        .find(|p| !p.preset && p.devices.iter().any(|d| d == device));
    correction
        .map(|c| crate::config::DspLayer {
            profile: c.name.clone(),
            on: true,
        })
        .into_iter()
        .chain(
            dsp.tunings
                .iter()
                .filter(|t| t.device == device)
                .map(|t| crate::config::DspLayer {
                    profile: t.tuning.clone(),
                    on: t.on,
                }),
        )
        .collect()
}

/// Save `device`'s correction and tuning as the preset `name`, over one of
/// that name, and say the output is set from it.
pub fn save_preset(device: &str, name: &str) -> Result<String, String> {
    let name = name.trim();
    if name.is_empty() {
        return Err("A preset needs a name".into());
    }
    let cfg = Config::cached();
    if cfg.dsp.profiles.iter().any(|p| p.name == name && !p.preset) {
        return Err(format!("There is already an EQ called {name}"));
    }
    let layers = chain_of(&cfg.dsp, device);
    let unsaid = unsaid_correction(&cfg.dsp, device);
    persist(|cfg| {
        say_corrects(cfg, unsaid.as_deref());
        match cfg.dsp.profiles.iter_mut().find(|p| p.name == name) {
            Some(p) => p.layers = layers,
            None => cfg.dsp.profiles.push(DspProfile {
                name: name.to_owned(),
                preset: true,
                layers,
                ..Default::default()
            }),
        }
        cfg.dsp.presets.retain(|p| p.device != device);
        cfg.dsp.presets.push(crate::config::DspOutputPreset {
            device: device.to_owned(),
            preset: name.to_owned(),
        });
    })?;
    Ok(name.to_owned())
}

/// `device`'s correction where nothing says it is one: a profile with no
/// role that would read as a tuning, chosen as a correction before roles
/// were asked. A preset saved from it must still put it back as one.
fn unsaid_correction(dsp: &crate::config::DspConfig, device: &str) -> Option<String> {
    dsp.profiles
        .iter()
        .find(|p| !p.preset && p.devices.iter().any(|d| d == device))
        .filter(|p| p.role.is_none() && !shown_role(p, &dsp.profiles).corrects())
        .map(|p| p.name.clone())
}

/// Say that `name` corrects, as the output it is chosen for uses it.
fn say_corrects(cfg: &mut Config, name: Option<&str>) {
    if let Some(p) = cfg
        .dsp
        .profiles
        .iter_mut()
        .find(|p| Some(p.name.as_str()) == name)
    {
        p.role = Some(DspRole::Correction);
    }
}

/// What a preset's layers set an output to: its correction, where the first
/// layer is one and on, and its tuning's EQs in order. A correction switched
/// off is no correction, as it played in a stack.
fn preset_parts(
    layers: &[crate::config::DspLayer],
    all: &[DspProfile],
) -> (Option<String>, Vec<(String, bool)>) {
    let mut layers = layers.iter().peekable();
    let correction = layers
        .next_if(|l| {
            all.iter()
                .any(|q| q.name == l.profile && shown_role(q, all).corrects())
        })
        .filter(|l| l.on)
        .map(|l| l.profile.clone());
    (
        correction,
        layers.map(|l| (l.profile.clone(), l.on)).collect(),
    )
}

/// Set `device` to play `correction` and `tunings`, set from `preset`.
fn set_output(
    cfg: &mut Config,
    device: &str,
    correction: Option<&str>,
    tunings: &[(String, bool)],
    preset: Option<&str>,
) {
    for p in &mut cfg.dsp.profiles {
        p.devices.retain(|d| d != device);
        if Some(p.name.as_str()) == correction {
            p.devices.push(device.to_owned());
        }
    }
    cfg.dsp.tunings.retain(|t| t.device != device);
    cfg.dsp.tunings.extend(
        tunings
            .iter()
            .map(|(t, on)| crate::config::DspOutputTuning {
                device: device.to_owned(),
                tuning: t.clone(),
                on: *on,
            }),
    );
    cfg.dsp.presets.retain(|p| p.device != device);
    if let Some(preset) = preset {
        cfg.dsp.presets.push(crate::config::DspOutputPreset {
            device: device.to_owned(),
            preset: preset.to_owned(),
        });
    }
}

/// Set `device` from the preset `name`: its correction, and its tuning's
/// EQs in order, on and off as saved. With `None`, flat: no correction and
/// no tuning, which plays untouched.
pub fn apply_preset(device: &str, name: Option<&str>) -> Result<(), String> {
    let cfg = Config::cached();
    let all = &cfg.dsp.profiles;
    let (correction, tunings) = match name {
        None => (None, Vec::new()),
        Some(name) => {
            let p = all
                .iter()
                .find(|p| p.name == name && p.preset)
                .ok_or_else(|| {
                    let presets: Vec<&str> = all
                        .iter()
                        .filter(|p| p.preset)
                        .map(|p| p.name.as_str())
                        .collect();
                    format!(
                        "No preset called {name}. Presets: {}",
                        if presets.is_empty() {
                            "none yet".to_owned()
                        } else {
                            presets.join(", ")
                        }
                    )
                })?;
            let parts = preset_parts(&p.layers, all);
            for (t, _) in &parts.1 {
                check_tuning(t, all)?;
            }
            parts
        }
    };
    persist(|cfg| set_output(cfg, device, correction.as_deref(), &tunings, name))
}

/// An output set from a preset by `migrate`: the device, its correction,
/// its tuning and the preset.
type Setting = (String, Option<String>, Vec<(String, bool)>, String);

/// Bring configs from before presets and tunings of several EQs up to
/// them, once at start, and again harmlessly after:
/// - a stack that is a correction with EQs on top is a preset, and an output
///   that played it plays its correction and EQs, set from it, then the
///   tuning it had on top; a correction switched off in the stack is none;
/// - an output a preset is assigned to as its correction, as the apps
///   before this could and a synced preset can, is set from it the same way;
/// - an output whose correction is a group, of which one member plays, has
///   that member; a group in a tuning becomes its member playing;
/// - with processing switched off, which is no longer a thing, every output
///   is flat, its correction and tuning kept as a preset to go back to.
pub fn migrate() -> Result<(), String> {
    migrate_presets()?;
    flatten_off()
}

/// Processing switched off becomes every output flat. What an output played
/// is kept as a preset named for it, unless it was set from one and not
/// changed since.
fn flatten_off() -> Result<(), String> {
    let cfg = Config::cached();
    if cfg.dsp.enabled {
        return Ok(());
    }
    let mut devices: Vec<&str> = Vec::new();
    for d in cfg
        .dsp
        .profiles
        .iter()
        .filter(|p| !p.preset)
        .flat_map(|p| p.devices.iter())
        .chain(cfg.dsp.tunings.iter().map(|t| &t.device))
    {
        if !devices.contains(&d.as_str()) {
            devices.push(d);
        }
    }
    let mut taken: Vec<String> = cfg.dsp.profiles.iter().map(|p| p.name.clone()).collect();
    let mut kept: Vec<(String, Vec<crate::config::DspLayer>)> = Vec::new();
    let mut unsaid: Vec<String> = Vec::new();
    for device in &devices {
        if preset_for(device).is_some_and(|(_, edited)| !edited) {
            continue;
        }
        let layers = chain_of(&cfg.dsp, device);
        if layers.is_empty() {
            continue;
        }
        unsaid.extend(unsaid_correction(&cfg.dsp, device));
        let name = (1..)
            .map(|n| match n {
                1 => (*device).to_owned(),
                n => format!("{device} {n}"),
            })
            .find(|n| !taken.contains(n))
            .expect("a name is free");
        taken.push(name.clone());
        kept.push((name, layers));
    }
    persist(|cfg| {
        for name in &unsaid {
            say_corrects(cfg, Some(name));
        }
        for (name, layers) in &kept {
            cfg.dsp.profiles.push(DspProfile {
                name: name.clone(),
                preset: true,
                layers: layers.clone(),
                ..Default::default()
            });
        }
        for device in &devices {
            set_output(cfg, device, None, &[], None);
        }
        cfg.dsp.enabled = true;
    })
}

fn migrate_presets() -> Result<(), String> {
    let cfg = Config::cached();
    let all = &cfg.dsp.profiles;
    let used_as_layer = |name: &str| {
        all.iter()
            .any(|p| p.layers.iter().any(|l| l.profile == name))
    };
    let corrects = |name: &str| {
        all.iter()
            .any(|q| q.name == name && shown_role(q, all).corrects())
    };
    let is_eq = |name: &str| check_tuning(name, all).is_ok();
    // Each stack becoming a preset, or preset assigned to an output: its
    // name, the layers it keeps as a preset, and the outputs it set.
    let presets: Vec<(String, Vec<crate::config::DspLayer>, Vec<String>)> = all
        .iter()
        .filter(|p| {
            (p.preset && !p.devices.is_empty())
                || (!p.preset
                    && !p.group
                    && p.filters.is_empty()
                    && p.impulses.is_empty()
                    && p.target.is_none()
                    && p.measurement.is_none()
                    && !used_as_layer(&p.name)
                    && p.layers.first().is_some_and(|l| corrects(&l.profile))
                    && p.layers.iter().skip(1).all(|l| is_eq(&l.profile)))
        })
        .map(|p| {
            let mut layers = p.layers.clone();
            if layers
                .first()
                .is_some_and(|l| !l.on && corrects(&l.profile))
            {
                layers.remove(0);
            }
            (p.name.clone(), layers, p.devices.clone())
        })
        .collect();
    // Each output those set: its correction, and its tuning, the preset's
    // EQs then those it had on top.
    let mut set: Vec<Setting> = Vec::new();
    for (name, layers, devices) in &presets {
        let (correction, eqs) = preset_parts(layers, all);
        for device in devices {
            let mut tunings = eqs.clone();
            for t in cfg.dsp.tunings.iter().filter(|t| &t.device == device) {
                if !tunings.iter().any(|(n, _)| n == &t.tuning) {
                    tunings.push((t.tuning.clone(), t.on));
                }
            }
            set.push((device.clone(), correction.clone(), tunings, name.clone()));
        }
    }
    let playing = |p: &DspProfile| super::playing(p, all).map(|m| m.name.clone());
    let groups: Vec<(String, String)> = all
        .iter()
        .filter(|p| p.group)
        .filter_map(|g| playing(g).map(|m| (g.name.clone(), m)))
        .collect();
    let groups_in_use = groups.iter().any(|(g, _)| {
        all.iter().any(|p| &p.name == g && !p.devices.is_empty())
            || cfg.dsp.tunings.iter().any(|t| &t.tuning == g)
    });
    if presets.is_empty() && !groups_in_use {
        return Ok(());
    }
    persist(|cfg| {
        for (device, correction, tunings, preset) in &set {
            set_output(cfg, device, correction.as_deref(), tunings, Some(preset));
        }
        for (name, layers, _) in &presets {
            if let Some(p) = cfg.dsp.profiles.iter_mut().find(|p| &p.name == name) {
                p.preset = true;
                p.layers = layers.clone();
                p.devices.clear();
            }
        }
        for (group, member) in &groups {
            let devices: Vec<String> = cfg
                .dsp
                .profiles
                .iter()
                .find(|p| &p.name == group)
                .map(|p| p.devices.clone())
                .unwrap_or_default();
            for p in &mut cfg.dsp.profiles {
                if &p.name == group {
                    p.devices.clear();
                } else if &p.name == member {
                    for d in &devices {
                        if !p.devices.contains(d) {
                            p.devices.push(d.clone());
                        }
                    }
                }
            }
            for t in &mut cfg.dsp.tunings {
                if &t.tuning == group {
                    t.tuning = member.clone();
                }
            }
        }
    })
}

/// Why no tuning goes on top of `correction`.
pub fn baked_already(correction: &str) -> String {
    format!(
        "{correction} already includes a tuning. Split it into a correction and an EQ to change the tuning."
    )
}

/// Say which target the tuning `name` was made against, or that it is not
/// known: a target that ships or one added.
pub fn set_tuned_for(name: &str, target: Option<&str>) -> Result<(), String> {
    if !Config::cached().dsp.profiles.iter().any(|p| p.name == name) {
        return Err(format!("No EQ called {name}"));
    }
    if let Some(t) = target
        && super::targets::choice_curve(t).is_none()
    {
        return Err(format!("No target called {t}"));
    }
    persist(|cfg| {
        if let Some(p) = cfg.dsp.profiles.iter_mut().find(|p| p.name == name) {
            p.tuned_for = target.map(str::to_owned);
        }
    })
}

/// The corrections a chain plays, `profile` and its layers switched on, in
/// the order they play.
pub fn corrections_in(profile: &DspProfile, all: &[DspProfile]) -> Vec<String> {
    fn walk(p: &DspProfile, all: &[DspProfile], seen: &mut Vec<String>, out: &mut Vec<String>) {
        if seen.contains(&p.name) || seen.len() > 64 {
            return;
        }
        seen.push(p.name.clone());
        // A group plays one member, so only it counts.
        let played: Vec<&DspProfile> = if p.group {
            super::playing(p, all).into_iter().collect()
        } else {
            p.layers
                .iter()
                .filter(|l| l.on)
                .filter_map(|l| all.iter().find(|q| q.name == l.profile))
                .collect()
        };
        for q in played {
            walk(q, all, seen, out);
        }
        if role(p).corrects() && !out.contains(&p.name) {
            out.push(p.name.clone());
        }
    }
    let mut out = Vec::new();
    walk(profile, all, &mut Vec::new(), &mut out);
    out
}

/// A correction by name and kind, as a warning names it: "Cantor (AutoEQ)".
fn correction_label(p: &DspProfile) -> String {
    let kind = if role(p) == DspRole::Baked {
        "includes a tuning"
    } else if p.measurement.is_some() {
        "measured"
    } else if super::targets::autoeq_measurement(&dir(&p.name)).is_some() {
        "AutoEQ"
    } else if p.target.is_some() {
        "ready-made"
    } else {
        "correction"
    };
    if p.name.to_lowercase().contains(&kind.to_lowercase()) {
        p.name.clone()
    } else {
        format!("{} ({kind})", p.name)
    }
}

/// What a chain correcting more than once says: each undoes the same
/// headphone, so it plays twice the correction. Stacks made before that was
/// refused still play, and say so.
pub fn corrects_twice(profile: &DspProfile, all: &[DspProfile]) -> Option<String> {
    let c = corrections_in(profile, all);
    if c.len() < 2 {
        return None;
    }
    let labels: Vec<String> = c
        .iter()
        .filter_map(|n| all.iter().find(|p| &p.name == n))
        .map(correction_label)
        .collect();
    let (last, rest) = labels.split_last()?;
    Some(format!(
        "This EQ corrects twice: {} and {last}. Keep one.",
        rest.join(", ")
    ))
}

/// Why a chain with more than one correction is refused.
pub fn two_corrections(corrections: &[String]) -> String {
    format!(
        "This EQ already plays the correction {}. Take that out first, or add {} to a device's tuning instead.",
        corrections[0],
        corrections.get(1).map_or("this", String::as_str)
    )
}

/// Say what `name` is for. Always taken, since it is what the profile is:
/// a stack it makes correct twice says so on its page (`corrects_twice`),
/// and gains no further correction.
pub fn set_role(name: &str, to: DspRole) -> Result<(), String> {
    if !Config::cached().dsp.profiles.iter().any(|p| p.name == name) {
        return Err(format!("No EQ called {name}"));
    }
    persist(|cfg| {
        if let Some(p) = cfg.dsp.profiles.iter_mut().find(|p| p.name == name) {
            p.role = Some(to);
        }
    })
}

/// A target's name, by id: one that ships, one added, or the id itself.
pub fn target_name(id: &str) -> String {
    use super::targets;
    targets::shipped(id).map_or_else(
        || {
            targets::added()
                .into_iter()
                .find(|a| a.id == id)
                .map_or_else(|| id.to_owned(), |a| a.name)
        },
        |t| t.name.to_owned(),
    )
}

/// What a chain does, in a line each: the headphone it corrects and how,
/// and the tunings on top.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ChainSummary {
    pub correction: Option<String>,
    /// The correction has a tuning baked in.
    pub baked: bool,
    pub tunings: Vec<String>,
}

pub fn summary(name: &str) -> Option<ChainSummary> {
    use super::targets;
    let cfg = Config::cached();
    let all = &cfg.dsp.profiles;
    let profile = all.iter().find(|p| p.name == name)?;
    let mut chain: Vec<&DspProfile> = profile
        .layers
        .iter()
        .filter(|l| l.on)
        .filter_map(|l| all.iter().find(|p| p.name == l.profile))
        .collect();
    chain.push(profile);
    let mut out = ChainSummary::default();
    for p in chain {
        match role(p) {
            DspRole::Tuning => {
                if !p.filters.is_empty() || !p.impulses.is_empty() {
                    out.tunings.push(p.name.clone());
                }
                continue;
            }
            DspRole::Baked => {
                if out.correction.is_none() {
                    out.correction = Some(format!("{} (correction + tuning in one)", p.name));
                    out.baked = true;
                }
                continue;
            }
            DspRole::Correction => {}
        }
        let line = if let Some(m) = &p.measurement {
            format!("{} → {} (from measurement)", p.name, target_name(&m.target))
        } else if let Some(t) = &p.target {
            let autoeq = targets::autoeq_measurement(&dir(&p.name)).is_some();
            match (&t.chosen, autoeq) {
                (Some(c), true) => format!(
                    "{} → {} (rebuilt from AutoEQ's measurement)",
                    p.name,
                    target_name(c)
                ),
                (Some(c), false) => format!("{} → {}", p.name, target_name(c)),
                (None, true) => format!("{} → {}", p.name, target_name(&t.made_for)),
                (None, false) => format!(
                    "{}: ready-made EQ (made for {})",
                    p.name,
                    target_name(&t.made_for)
                ),
            }
        } else {
            format!("{}: ready-made EQ (made for an unknown target)", p.name)
        };
        out.correction.get_or_insert(line);
    }
    Some(out)
}

/// A measurement, checked: frequency and level pairs covering the audible
/// band, as squig.link and REW export them.
pub fn read_measurement(text: &str) -> Result<super::targets::Curve, String> {
    super::targets::covering(text, "A measurement")
}

/// What a measurement corrected to a target would do, before anything is
/// saved: the curves the Headphone view draws, and the EQ's own.
pub fn preview_measurement(text: &str, target: &str, rate: u32) -> Result<Response, String> {
    use super::targets;
    let measured = read_measurement(text)?;
    let aim = targets::choice_curve(target).ok_or_else(|| format!("No target {target}"))?;
    let freqs = targets::grid();
    let filters = [config::DspFilter::Graphic(targets::correction(
        &measured, &aim,
    ))];
    let total = super::response(&filters, &freqs, rate);
    let level = |c: &targets::Curve| {
        let k = targets::at(c, 1000.0);
        freqs
            .iter()
            .map(|&hz| targets::at(c, hz) - k)
            .collect::<Vec<f64>>()
    };
    let raw = level(&measured);
    let predicted = raw.iter().zip(&total).map(|(r, t)| r + t).collect();
    Ok(Response {
        bands: Vec::new(),
        layers: Vec::new(),
        measurement: Some(raw),
        target: Some(level(&aim)),
        predicted: Some(predicted),
        preamp_db: 0.0,
        correction: None,
        tuning: None,
        original: None,
        total,
        freqs,
    })
}

/// A baked EQ taken apart, given the headphones' measurement and the target
/// that counts as neutral: the correction, target − measurement, and what
/// the EQ does beyond it, its taste, as a curve. The reverse of what
/// squig.link does to make one.
struct Split {
    taste: crate::config::GraphicEq,
    freqs: Vec<f64>,
    original: Vec<f64>,
    correction: Vec<f64>,
    tuning: Vec<f64>,
}

fn split(name: &str, text: &str, target: &str, rate: u32) -> Result<Split, String> {
    use super::targets;
    use crate::config::DspFilter;
    let cfg = Config::cached();
    let all = &cfg.dsp.profiles;
    let p = all
        .iter()
        .find(|p| p.name == name)
        .ok_or_else(|| format!("No EQ called {name}"))?;
    if !super::responses(p, all).is_empty() {
        return Err(format!(
            "{name} has impulse responses: only an EQ splits into a correction and a tuning"
        ));
    }
    // What is split is one EQ, the same on every channel: a stack or group
    // would lose its layers, and a mix, a delay or one side's bands would be
    // folded into a curve for both.
    if !p.layers.is_empty() || p.group {
        return Err(format!(
            "{name} plays other EQs: split the one among them that includes a tuning instead"
        ));
    }
    if p.filters.iter().any(|f| match f {
        DspFilter::Band(b) => !b.channels.is_empty(),
        DspFilter::Graphic(g) => !g.channels.is_empty(),
        DspFilter::Mix(_) | DspFilter::Delay(_) => true,
    }) {
        return Err(format!(
            "{name} treats its channels differently: only an EQ the same on every channel splits"
        ));
    }
    let measured = read_measurement(text)?;
    let aim = targets::choice_curve(target).ok_or_else(|| format!("No target {target}"))?;
    let freqs = targets::grid();
    let filters = super::chain(p, all, &mut Vec::new()).map_err(|e| e.to_string())?;
    let original = super::response(&filters, &freqs, rate);
    let correction = super::response(
        &[DspFilter::Graphic(targets::correction(&measured, &aim))],
        &freqs,
        rate,
    );
    let curve =
        |db: &[f64]| -> targets::Curve { freqs.iter().copied().zip(db.iter().copied()).collect() };
    // The taste is what the EQ does beyond target minus measurement whole,
    // its treble too, so it carries to other headphones; the correction
    // saved holds the treble back where measurements disagree.
    let neutral = super::response(
        &[DspFilter::Graphic(targets::difference(&measured, &aim))],
        &freqs,
        rate,
    );
    let taste = targets::difference(&curve(&neutral), &curve(&original));
    let tuning = super::response(&[DspFilter::Graphic(taste.clone())], &freqs, rate);
    Ok(Split {
        taste,
        freqs,
        original,
        correction,
        tuning,
    })
}

/// What splitting the baked EQ `name` would give, before anything is saved:
/// the correction and the tuning, their sum as `total`, and the EQ itself as
/// `original`, which the sum follows but for the treble a correction holds
/// back.
pub fn preview_split(name: &str, text: &str, target: &str, rate: u32) -> Result<Response, String> {
    let s = split(name, text, target, rate)?;
    let total = s
        .correction
        .iter()
        .zip(&s.tuning)
        .map(|(c, t)| c + t)
        .collect();
    Ok(Response {
        bands: Vec::new(),
        layers: Vec::new(),
        measurement: None,
        target: None,
        predicted: None,
        preamp_db: 0.0,
        correction: Some(s.correction),
        tuning: Some(s.tuning),
        original: Some(s.original),
        total,
        freqs: s.freqs,
    })
}

/// Split the baked EQ `name` into a correction built from the headphones'
/// measurement, to `target`, and a tuning holding the rest, made against
/// `target` so it carries to other headphones. Every output that played
/// `name` plays the two instead; `name` itself is kept. The new profiles'
/// names, correction then tuning.
pub fn split_baked(
    name: &str,
    text: &str,
    ear: DspEar,
    target: &str,
) -> Result<(String, String), String> {
    let s = split(name, text, target, 48_000)?;
    let devices = Config::cached()
        .dsp
        .profiles
        .iter()
        .find(|p| p.name == name)
        .map(|p| p.devices.clone())
        .unwrap_or_default();
    let mut correction =
        measured_profile(&free_name(&format!("{name} correction")), text, ear, target)?;
    let tuning = free_name(&format!("{name} tuning"));
    let made = (correction.name.clone(), tuning.clone());
    // One write: both profiles, and every output moved to them, or nothing.
    correction.devices = devices.clone();
    let written = persist(|cfg| {
        for p in &mut cfg.dsp.profiles {
            p.devices.retain(|d| !devices.contains(d));
        }
        cfg.dsp.tunings.retain(|t| !devices.contains(&t.device));
        cfg.dsp
            .tunings
            .extend(devices.iter().map(|d| crate::config::DspOutputTuning {
                device: d.clone(),
                tuning: tuning.clone(),
                on: true,
            }));
        cfg.dsp.profiles.push(correction);
        cfg.dsp.profiles.push(DspProfile {
            name: tuning.clone(),
            filters: vec![crate::config::DspFilter::Graphic(s.taste)],
            role: Some(DspRole::Tuning),
            tuned_for: Some(target.to_owned()),
            ..Default::default()
        });
    });
    if written.is_err() {
        let _ = std::fs::remove_dir_all(dir(&made.0));
    }
    written.map(|()| made)
}

/// Save a correction built from a measurement: the headphone `name`,
/// measured as `text`, corrected to `target`. A correction, kept everywhere
/// like any headphone's.
pub fn save_measured(name: &str, text: &str, ear: DspEar, target: &str) -> Result<String, String> {
    save_measured_from(name, text, ear, target, None)
}

/// [`save_measured`], saying where the measurement came from, as an import
/// says its files: one found on squig.link credits the site it was
/// measured for.
pub fn save_measured_from(
    name: &str,
    text: &str,
    ear: DspEar,
    target: &str,
    source: Option<&str>,
) -> Result<String, String> {
    let mut profile = measured_profile(name, text, ear, target)?;
    profile.source = source.into_iter().map(str::to_owned).collect();
    let name = profile.name.clone();
    persist(|cfg| cfg.dsp.profiles.push(profile))?;
    Ok(name)
}

/// The profile `save_measured` keeps, its measurement written to its folder
/// and the profile itself not yet.
fn measured_profile(
    name: &str,
    text: &str,
    ear: DspEar,
    target: &str,
) -> Result<DspProfile, String> {
    use super::targets;
    let name = name.trim();
    if name.is_empty() {
        return Err("It needs a name".into());
    }
    if Config::cached().dsp.profiles.iter().any(|p| p.name == name) {
        return Err(format!("There is already an EQ called {name}"));
    }
    let measured = read_measurement(text)?;
    if targets::choice_curve(target).is_none() {
        return Err(format!("No target {target}"));
    }
    let folder = dir(name);
    if folder.exists() {
        return Err(format!("{} is in the way", folder.display()));
    }
    std::fs::create_dir_all(&folder).map_err(|e| e.to_string())?;
    std::fs::write(
        targets::measurement_path(&folder),
        targets::on_grid(&measured),
    )
    .map_err(|e| e.to_string())?;
    Ok(DspProfile {
        name: name.to_owned(),
        role: Some(DspRole::Correction),
        measurement: Some(DspMeasurement {
            ear,
            target: target.to_owned(),
        }),
        ..Default::default()
    })
}

/// Make `name` a stack of `layers`, in order, creating it if there is none.
/// Refused where it could not play: a layer missing, a layer of itself, one
/// with impulse responses, one kept on this device under a stack kept
/// everywhere.
pub fn set_layers(name: &str, layers: Vec<crate::config::DspLayer>) -> Result<(), String> {
    let name = name.trim();
    if name.is_empty() {
        return Err("It needs a name".into());
    }
    if let Some(twice) = layers
        .iter()
        .enumerate()
        .find(|(i, l)| layers[..*i].iter().any(|e| e.profile == l.profile))
        .map(|(_, l)| &l.profile)
    {
        return Err(format!("{twice} is in {name} twice; each plays once"));
    }
    let cfg = Config::cached();
    let mut all = cfg.dsp.profiles.clone();
    let probe = profile_mut(&mut all, name);
    probe.layers = layers.clone();
    // Every layer, on or off: one switched off now is one switched on later.
    // A group's members are alternatives, one playing whichever is picked.
    let mut check = probe.clone();
    if !check.group {
        for l in &mut check.layers {
            l.on = true;
        }
    }
    let corrections = corrections_in(&check, &all);
    // Every correction it had, on or off: a stack that already corrects
    // twice can still be edited, but gains no other.
    let before = cfg
        .dsp
        .profiles
        .iter()
        .find(|p| p.name == name)
        .map(|p| {
            let mut p = p.clone();
            if !p.group {
                for l in &mut p.layers {
                    l.on = true;
                }
            }
            corrections_in(&p, &cfg.dsp.profiles)
        })
        .unwrap_or_default();
    if corrections.len() > 1 && corrections.iter().any(|c| !before.contains(c)) {
        // The one it had first, then the one being added.
        let mut named: Vec<String> = before
            .iter()
            .filter(|c| corrections.contains(c))
            .cloned()
            .collect();
        named.extend(corrections.iter().filter(|c| !before.contains(c)).cloned());
        return Err(two_corrections(&named));
    }
    super::chain(&check, &all, &mut Vec::new()).map_err(|e| e.to_string())?;
    if everywhere_by_choice(&all, name)
        && let Some(layer) = local_layer(&layers, &all)
    {
        return Err(kept_here(name, layer));
    }
    persist(|cfg| {
        let p = profile_mut(&mut cfg.dsp.profiles, name);
        p.layers = layers;
        // A group plays one: the first switched on, or the first of all.
        if p.group {
            let first = p.layers.iter().position(|l| l.on).unwrap_or(0);
            for (i, l) in p.layers.iter_mut().enumerate() {
                l.on = i == first;
            }
        }
    })
    .map_err(|e| e.to_string())
}

/// Delete `name`, and the responses kōan keeps for it. The presets and groups that hold it go on without it; an
/// EQ that plays it refuses, since what it plays is that EQ's to say.
pub fn remove(name: &str) -> Result<(), String> {
    let cfg = Config::cached();
    let playing: Vec<String> = cfg
        .dsp
        .profiles
        .iter()
        .filter(|p| !p.preset && !p.group && p.layers.iter().any(|l| l.profile == name))
        .map(|p| p.name.clone())
        .collect();
    if !playing.is_empty() {
        return Err(format!(
            "{} plays {name}: take it out of {} first",
            playing.join(", "),
            if playing.len() == 1 { "it" } else { "them" }
        ));
    }
    let shared = Config::cached()
        .dsp
        .profiles
        .iter()
        .any(|p| p.name != name && slug(&p.name) == slug(name));
    persist(|cfg| {
        cfg.dsp.profiles.retain(|p| p.name != name);
        for p in &mut cfg.dsp.profiles {
            p.layers.retain(|l| l.profile != name);
            // A group whose member playing went plays its first.
            if p.group
                && !p.layers.iter().any(|l| l.on)
                && let Some(first) = p.layers.first_mut()
            {
                first.on = true;
            }
        }
        cfg.dsp.tunings.retain(|t| t.tuning != name);
        cfg.dsp.presets.retain(|p| p.preset != name);
    })
    .map_err(|e| e.to_string())?;
    // Another profile's name may map to the same folder: its files stay.
    if !shared {
        let _ = std::fs::remove_dir_all(dir(name));
    }
    Ok(())
}

pub fn set_enabled(enabled: bool) -> Result<(), String> {
    persist(|cfg| cfg.dsp.enabled = enabled).map_err(|e| e.to_string())
}

/// Whether `name` is kept everywhere by choice: a stack kept so only because
/// its layers are follows them instead.
fn everywhere_by_choice(all: &[DspProfile], name: &str) -> bool {
    all.iter()
        .find(|p| p.name == name)
        .is_some_and(|p| p.scope == Some(DspScope::Everywhere))
}

fn profile_mut<'a>(profiles: &'a mut Vec<DspProfile>, name: &str) -> &'a mut DspProfile {
    let index = match profiles.iter().position(|p| p.name == name) {
        Some(i) => i,
        None => {
            profiles.push(DspProfile {
                name: name.into(),
                ..Default::default()
            });
            profiles.len() - 1
        }
    };
    &mut profiles[index]
}

/// A directory name for a profile name.
fn slug(name: &str) -> String {
    let s: String = name
        .chars()
        .map(|c| {
            if c.is_alphanumeric() {
                c.to_ascii_lowercase()
            } else {
                '-'
            }
        })
        .collect();
    let s = s
        .split('-')
        .filter(|p| !p.is_empty())
        .collect::<Vec<_>>()
        .join("-");
    if s.is_empty() { "profile".into() } else { s }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::audio::dsp::impulse::{Impulse, Route};

    #[test]
    fn an_import_lands_beside_the_config_and_merges_by_name() {
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());

        let eq = Imported {
            name: "HD 600".into(),
            source: vec![],
            filters: vec![crate::config::DspFilter::Band(crate::config::EqFilter {
                kind: crate::config::EqFilterKind::Peaking,
                freq: 100.0,
                gain_db: 3.0,
                q: 1.0,
                channels: vec![],
            })],
            impulses: vec![],
        };
        assert_eq!(save(eq, None).unwrap(), "HD 600");
        assert_eq!(slug("HD 600 / Röom"), "hd-600-röom");

        let crossfeed = Impulse {
            rate: 48000,
            channels: Some(2),
            routes: vec![Route {
                ir: vec![1.0],
                inputs: vec![(0, 0.5), (1, 0.5)],
                outputs: vec![(0, 1.0), (1, 1.0)],
            }],
            in_delays: vec![],
            out_delays: vec![],
        };
        let room = Imported {
            name: "whatever".into(),
            source: vec!["whatever-source".into()],
            filters: vec![],
            impulses: vec![Impulse::from_channels(44100, vec![vec![1.0]]), crossfeed],
        };
        save(room, Some("HD 600")).unwrap();
        assign(Some("HD 600"), "Topping E30").unwrap();

        let o = overview();
        let p = &o.profiles[0];
        assert_eq!(o.profiles.len(), 1);
        assert_eq!(p.bands, 1, "the EQ survived the second import");
        assert_eq!(p.rates, vec![44100, 48000]);
        assert_eq!(p.devices, vec!["Topping E30"]);
        assert!(p.problem.is_none(), "{:?}", p.problem);
        assert!(dir.path().join("dsp/hd-600/48000.cfg").exists());

        let d = detail("HD 600").unwrap();
        assert_eq!(d.impulses.len(), 2);
        assert!(!d.impulses[0].mixes);
        assert!(d.impulses[1].mixes, "the crossfeed route mixes");
        assert_eq!(d.source, vec!["whatever-source"]);

        rename("HD 600", "Desk").unwrap();
        assert!(dir.path().join("dsp/desk/48000.cfg").exists());
        let d = detail("Desk").unwrap();
        assert!(d.problem.is_none(), "{:?}", d.problem);
        assert_eq!(d.impulses.len(), 2);
        assert!(rename("Desk", "").is_err());

        remove("Desk").unwrap();
        assert!(!dir.path().join("dsp/desk").exists());
        assert!(overview().profiles.is_empty());
    }

    fn band(freq: f64) -> crate::config::DspFilter {
        crate::config::DspFilter::Band(crate::config::EqFilter {
            kind: crate::config::EqFilterKind::Peaking,
            freq,
            gain_db: 3.0,
            q: 1.0,
            channels: vec![],
        })
    }

    fn layer(profile: &str, on: bool) -> crate::config::DspLayer {
        crate::config::DspLayer {
            profile: profile.into(),
            on,
        }
    }

    /// A stack plays its layers that are on, in order, then its own filters;
    /// it follows a layer's rename, and keeps a layer it plays from being
    /// deleted.
    #[test]
    fn a_stack_plays_its_layers_in_order() {
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        persist(|c| {
            for (name, f) in [
                ("HD 650", 100.0),
                ("Bass +3", 60.0),
                ("Treble tilt", 8000.0),
            ] {
                c.dsp.profiles.push(DspProfile {
                    name: name.into(),
                    filters: vec![band(f)],
                    ..Default::default()
                });
            }
        })
        .unwrap();
        set_layers(
            "Desk",
            vec![
                layer("HD 650", true),
                layer("Bass +3", true),
                layer("Treble tilt", false),
            ],
        )
        .unwrap();
        let played = || {
            let cfg = Config::cached();
            let p = cfg.dsp.profiles.iter().find(|p| p.name == "Desk").unwrap();
            Setup::load(p, &cfg.dsp.profiles, dir.path())
                .unwrap()
                .unwrap()
                .filters
        };
        assert_eq!(played(), vec![band(100.0), band(60.0)]);
        set_layers(
            "Desk",
            vec![
                layer("Bass +3", true),
                layer("HD 650", true),
                layer("Treble tilt", true),
            ],
        )
        .unwrap();
        assert_eq!(played(), vec![band(60.0), band(100.0), band(8000.0)]);
        let summary = overview_for(None);
        assert_eq!(
            summary
                .profiles
                .iter()
                .find(|p| p.name == "Desk")
                .unwrap()
                .layers,
            3
        );

        rename("Bass +3", "Bass").unwrap();
        assert_eq!(detail("Desk").unwrap().layers[0].profile, "Bass");
        assert_eq!(played(), vec![band(60.0), band(100.0), band(8000.0)]);
        let refused = remove("Bass").unwrap_err();
        assert!(refused.contains("Desk"), "{refused}");
    }

    #[test]
    fn a_stack_that_could_not_play_is_refused() {
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        persist(|c| {
            c.dsp.profiles.push(DspProfile {
                name: "Room".into(),
                impulses: vec!["dsp/room/48000.wav".into()],
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "EQ".into(),
                filters: vec![band(100.0)],
                ..Default::default()
            });
        })
        .unwrap();
        assert!(
            set_layers("Desk", vec![layer("Nothing", true)]).is_err(),
            "missing"
        );
        assert!(
            set_layers("Desk", vec![layer("Room", true)]).is_err(),
            "impulses"
        );
        assert!(
            set_layers("Desk", vec![layer("Desk", true)]).is_err(),
            "itself"
        );
        set_layers("Desk", vec![layer("EQ", true)]).unwrap();
        // A cycle through another, even with the way back switched off.
        assert!(
            set_layers("EQ", vec![layer("Desk", false)]).is_err(),
            "cycle"
        );
    }

    /// Shared layers resolve, each where it is played; a ladder of them that
    /// would copy its filters exponentially is refused when set, and as a
    /// stack edited by hand it reports the problem and does not load, rather
    /// than growing the chain until the process aborts.
    #[test]
    fn a_stack_cannot_grow_without_bound() {
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        persist(|c| {
            c.dsp.profiles.push(DspProfile {
                name: "D".into(),
                filters: vec![band(100.0)],
                ..Default::default()
            });
        })
        .unwrap();
        // A diamond: B and C both play D.
        set_layers("B", vec![layer("D", true)]).unwrap();
        set_layers("C", vec![layer("D", true)]).unwrap();
        set_layers("A", vec![layer("B", true), layer("C", true)]).unwrap();
        {
            let cfg = Config::cached();
            let a = cfg.dsp.profiles.iter().find(|p| p.name == "A").unwrap();
            let played = Setup::load(a, &cfg.dsp.profiles, dir.path())
                .unwrap()
                .unwrap();
            assert_eq!(
                played.filters,
                vec![band(100.0), band(100.0)],
                "a diamond resolves"
            );
        }
        assert!(
            set_layers("X", vec![layer("D", true), layer("D", true)]).is_err(),
            "twice"
        );

        // A ladder, as a hand edit could leave it: each rung plays the two
        // below, 2^30 copies of D at the top.
        persist(|c| {
            for i in 0..30 {
                let below = |n: i32| {
                    if n < 0 {
                        "D".to_string()
                    } else {
                        format!("L{n}")
                    }
                };
                c.dsp.profiles.push(DspProfile {
                    name: format!("L{i}"),
                    layers: vec![layer(&below(i - 1), true), layer(&below(i - 2), true)],
                    ..Default::default()
                });
            }
        })
        .unwrap();
        let cfg = Config::cached();
        let top = cfg.dsp.profiles.iter().find(|p| p.name == "L29").unwrap();
        let err = Setup::load(top, &cfg.dsp.profiles, dir.path())
            .err()
            .unwrap();
        assert!(err.to_string().contains("L29"), "{err}");
        let summary = overview_for(None);
        let l29 = summary.profiles.iter().find(|p| p.name == "L29").unwrap();
        assert!(l29.problem.is_some(), "Settings shows why it does not play");
        assert!(set_layers("L30", vec![layer("L29", true)]).is_err());
    }

    /// The response is what the DSP plays: a 3 dB peak shows as 3 dB at its
    /// frequency and nothing far from it, a stack is its layers summed, and a
    /// band's own curve is drawn alone.
    #[test]
    fn a_response_is_the_filters_the_dsp_runs() {
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        persist(|c| {
            c.dsp.profiles.push(DspProfile {
                name: "Peak".into(),
                filters: vec![band(1000.0)],
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Shelf".into(),
                filters: vec![crate::config::DspFilter::Band(crate::config::EqFilter {
                    kind: crate::config::EqFilterKind::LowShelf,
                    freq: 100.0,
                    gain_db: 6.0,
                    q: 0.7,
                    channels: vec![],
                })],
                ..Default::default()
            });
        })
        .unwrap();
        let r = response("Peak", 48000).unwrap();
        let at = |r: &Response, curve: &[f64], hz: f64| {
            let i = r.freqs.iter().position(|f| *f >= hz).unwrap();
            curve[i]
        };
        assert!(
            (at(&r, &r.total, 1000.0) - 3.0).abs() < 0.2,
            "{}",
            at(&r, &r.total, 1000.0)
        );
        assert!(at(&r, &r.total, 20.0).abs() < 0.1);
        assert_eq!(r.bands.len(), 1);
        assert!(r.measurement.is_none());
        assert!(
            r.preamp_db < -2.5,
            "the peak is taken off ahead: {}",
            r.preamp_db
        );

        set_layers("Both", vec![layer("Shelf", true), layer("Peak", true)]).unwrap();
        let r = response("Both", 48000).unwrap();
        assert_eq!(r.layers.len(), 2);
        assert!((at(&r, &r.total, 30.0) - 6.0).abs() < 0.5, "the shelf");
        assert!((at(&r, &r.total, 1000.0) - 3.0).abs() < 0.5, "the peak");
        assert!(r.bands.is_empty(), "no bands of its own");
        set_layers("Both", vec![layer("Shelf", false), layer("Peak", true)]).unwrap();
        let r = response("Both", 48000).unwrap();
        assert!(at(&r, &r.total, 30.0).abs() < 0.3, "the shelf off");
        assert!(!r.layers[0].on);
    }

    /// A band edited by hand is held to its ranges, keeps its channels, and
    /// changes what plays; one added starts flat; one taken out is gone.
    #[test]
    fn bands_are_edited_in_place() {
        use crate::config::{DspFilter, EqFilter, EqFilterKind};
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        persist(|c| {
            c.dsp.profiles.push(DspProfile {
                name: "Mine".into(),
                filters: vec![DspFilter::Band(EqFilter {
                    kind: EqFilterKind::Peaking,
                    freq: 100.0,
                    gain_db: 3.0,
                    q: 1.0,
                    channels: vec![1],
                })],
                ..Default::default()
            })
        })
        .unwrap();
        set_band("Mine", 0, "low_shelf", 80.0, 99.0, 0.0).unwrap();
        let filters = || detail("Mine").unwrap().filters;
        assert_eq!(
            filters()[0],
            DspFilter::Band(EqFilter {
                kind: EqFilterKind::LowShelf,
                freq: 80.0,
                gain_db: 30.0,
                q: 0.1,
                channels: vec![1],
            })
        );
        assert!(set_band("Mine", 0, "wobble", 80.0, 0.0, 1.0).is_err());
        assert!(set_band("Mine", 0, "peaking", f64::NAN, 0.0, 1.0).is_err());
        assert!(set_band("Mine", 5, "peaking", 80.0, 0.0, 1.0).is_err());
        assert_eq!(add_band("Mine").unwrap(), 1);
        assert_eq!(filters().len(), 2);
        let r = response("Mine", 48000).unwrap();
        assert_eq!(r.bands.len(), 2);
        remove_filter("Mine", 0).unwrap();
        assert_eq!(filters().len(), 1);
        assert!(remove_filter("Mine", 3).is_err());
        assert!(add_band("Nobody").is_err());
    }

    /// A group plays one member, chosen like a radio button; a stack plays
    /// each layer switched on. A group can itself be a stack's layer.
    #[test]
    fn a_group_plays_one_member() {
        use crate::config::{DspFilter, DspLayer};
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        persist(|c| {
            for (name, hz) in [
                ("Warm", 100.0),
                ("Bright", 8000.0),
                ("Flat", 1000.0),
                ("Bass", 60.0),
            ] {
                c.dsp.profiles.push(DspProfile {
                    name: name.into(),
                    filters: vec![band(hz)],
                    ..Default::default()
                });
            }
        })
        .unwrap();
        let names = ["Warm", "Bright", "Flat"].map(String::from);
        make_group("Presets", &names).unwrap();
        assert!(make_group("Presets", &names).is_err());
        let freqs = |name: &str| -> Vec<f64> {
            let cfg = Config::cached();
            let p = cfg
                .dsp
                .profiles
                .iter()
                .find(|p| p.name == name)
                .unwrap()
                .clone();
            super::super::chain(&p, &cfg.dsp.profiles, &mut Vec::new())
                .unwrap()
                .into_iter()
                .map(|f| match f {
                    DspFilter::Band(b) => b.freq,
                    other => panic!("{other:?}"),
                })
                .collect()
        };
        assert_eq!(freqs("Presets"), [100.0], "the first plays");
        select("Presets", "Bright").unwrap();
        assert_eq!(freqs("Presets"), [8000.0]);
        assert!(select("Presets", "Bass").is_err(), "not a member");

        // Switching two on in a group leaves the first of them on.
        let layer = |p: &str, on: bool| DspLayer {
            profile: p.into(),
            on,
        };
        set_layers(
            "Presets",
            vec![
                layer("Warm", false),
                layer("Bright", true),
                layer("Flat", true),
            ],
        )
        .unwrap();
        assert_eq!(freqs("Presets"), [8000.0]);
        assert_eq!(
            detail("Presets")
                .unwrap()
                .layers
                .iter()
                .filter(|l| l.on)
                .count(),
            1
        );

        // A group as a stack's layer: its chosen member, then the tuning.
        set_layers("Desk", vec![layer("Presets", true), layer("Bass", true)]).unwrap();
        assert_eq!(freqs("Desk"), [8000.0, 60.0]);

        // A stack again: each layer switched on plays.
        set_group("Presets", false).unwrap();
        set_layers(
            "Presets",
            vec![
                layer("Warm", true),
                layer("Bright", true),
                layer("Flat", false),
            ],
        )
        .unwrap();
        assert_eq!(freqs("Presets"), [100.0, 8000.0]);
        set_group("Presets", true).unwrap();
        assert_eq!(
            freqs("Presets"),
            [100.0],
            "the first switched on keeps playing"
        );

        // None on, as a hand edit can leave it: the first plays.
        persist(|c| {
            let p = c.dsp.profiles.iter_mut().find(|p| p.name == "Presets");
            for l in &mut p.unwrap().layers {
                l.on = false;
            }
        })
        .unwrap();
        assert_eq!(freqs("Presets"), [100.0]);
    }

    /// A group of room corrections plays the chosen one's responses, since
    /// only one plays; a stack cannot layer such a group, as it cannot a
    /// response.
    #[test]
    fn a_group_plays_its_members_responses() {
        use crate::config::DspLayer;
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        let mut paths = Vec::new();
        for rate in [44100, 48000] {
            let path = dir.path().join(format!("{rate}.wav"));
            super::super::raw::write_wav(&path, rate, &[vec![1.0, 0.0]]).unwrap();
            paths.push(path);
        }
        persist(|c| {
            for (name, path) in [("Room 44", &paths[0]), ("Room 48", &paths[1])] {
                c.dsp.profiles.push(DspProfile {
                    name: name.into(),
                    impulses: vec![path.clone()],
                    ..Default::default()
                });
            }
        })
        .unwrap();
        make_group("Room", &["Room 44".into(), "Room 48".into()]).unwrap();
        let rates = || {
            let cfg = Config::cached();
            let p = cfg.dsp.profiles.iter().find(|p| p.name == "Room").unwrap();
            super::super::Setup::load(p, &cfg.dsp.profiles, dir.path())
                .unwrap()
                .unwrap()
                .rates()
        };
        assert_eq!(rates(), [44100]);
        select("Room", "Room 48").unwrap();
        assert_eq!(rates(), [48000]);
        let refused = set_layers(
            "Desk",
            vec![DspLayer {
                profile: "Room".into(),
                on: true,
            }],
        )
        .unwrap_err();
        assert!(
            refused.contains("only bands can be played by another EQ"),
            "{refused}"
        );
    }

    /// A name already taken, or one whose files would go in a folder that is,
    /// is numbered: nothing is written over.
    #[test]
    fn a_free_name_takes_nothing() {
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        assert_eq!(free_name("Room"), "Room");
        persist(|c| {
            c.dsp.profiles.push(DspProfile {
                name: "Room".into(),
                filters: vec![band(100.0)],
                ..Default::default()
            })
        })
        .unwrap();
        assert_eq!(free_name("Room"), "Room 2");
        assert_eq!(free_name("room!"), "room! 2", "the same folder as Room's");
    }

    /// A headphone correction travels and a room correction stays; a stack
    /// follows its layers unless set; a stack kept everywhere cannot have a
    /// layer kept here, either way round.
    #[test]
    fn where_a_profile_is_kept() {
        use crate::config::{DspLayer, DspTarget};
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        persist(|c| {
            c.dsp.profiles.push(DspProfile {
                name: "HD 650".into(),
                filters: vec![band(1000.0)],
                target: Some(DspTarget {
                    made_for: "harman-over-ear-2018".into(),
                    chosen: None,
                }),
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Room".into(),
                impulses: vec!["dsp/room/48000.wav".into()],
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Bass".into(),
                filters: vec![band(80.0)],
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Amp".into(),
                filters: vec![band(80.0)],
                devices: vec!["uuid:5f9ec1b3-ed59-79bb-4530-745e2b1d1b10".into()],
                ..Default::default()
            });
        })
        .unwrap();
        let kept = |name: &str| {
            let cfg = Config::cached();
            let p = cfg
                .dsp
                .profiles
                .iter()
                .find(|p| p.name == name)
                .unwrap()
                .clone();
            scope(&p, &cfg.dsp.profiles)
        };
        assert_eq!(kept("HD 650"), DspScope::Everywhere);
        assert_eq!(kept("Room"), DspScope::Device);
        assert_eq!(kept("Bass"), DspScope::Everywhere);
        assert_eq!(
            kept("Amp"),
            DspScope::Device,
            "an amplifier stays where it is"
        );

        let layer = |p: &str| DspLayer {
            profile: p.into(),
            on: true,
        };
        set_layers("Desk", vec![layer("HD 650"), layer("Bass")]).unwrap();
        assert_eq!(kept("Desk"), DspScope::Everywhere);
        set_layers("Speakers", vec![layer("Amp"), layer("Bass")]).unwrap();
        assert_eq!(
            kept("Speakers"),
            DspScope::Device,
            "a stack here may use shared layers"
        );

        set_scope("Desk", DspScope::Everywhere).unwrap();
        let refused = set_layers("Desk", vec![layer("HD 650"), layer("Amp")]).unwrap_err();
        assert!(refused.contains("Amp is kept on this device"), "{refused}");
        let refused = set_scope("Bass", DspScope::Device).unwrap_err();
        assert!(refused.contains("Bass is played by Desk"), "{refused}");
        set_scope("Speakers", DspScope::Everywhere).unwrap_err();
        set_scope("Desk", DspScope::Device).unwrap();
        set_scope("Bass", DspScope::Device).unwrap();
        assert_eq!(kept("Bass"), DspScope::Device);
    }

    /// A measurement as text: flat, with `bump` dB at 3 kHz.
    fn measured(bump: f64) -> String {
        let mut text = String::from("frequency,raw\n");
        for hz in super::super::targets::grid() {
            let db = bump * (-((hz / 3000.0).log2() * 3.0).powi(2)).exp();
            text.push_str(&format!("{hz:.2},{db:.2}\n"));
        }
        text
    }

    /// A headphone measured and corrected to a target: a correction, kept
    /// everywhere, playing target minus measurement, said in one line.
    #[test]
    fn a_measurement_is_corrected_to_its_target() {
        use super::super::targets;
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        let text = measured(6.0);
        assert!(
            read_measurement("1000,0\n").is_err(),
            "too little to correct from"
        );
        let preview = preview_measurement(&text, "harman-in-ear-2019", 48000).unwrap();
        assert!(preview.predicted.is_some() && preview.measurement.is_some());

        save_measured("AFUL Performer 8S", &text, DspEar::In, "harman-in-ear-2019").unwrap();
        assert!(
            save_measured("AFUL Performer 8S", &text, DspEar::In, "harman-in-ear-2019").is_err()
        );
        let cfg = Config::cached();
        let p = cfg
            .dsp
            .profiles
            .iter()
            .find(|p| p.name == "AFUL Performer 8S")
            .unwrap()
            .clone();
        assert_eq!(role(&p), DspRole::Correction);
        assert_eq!(scope(&p, &cfg.dsp.profiles), DspScope::Everywhere);
        assert_eq!(
            summary("AFUL Performer 8S").unwrap().correction.as_deref(),
            Some("AFUL Performer 8S → Harman in-ear 2019 (from measurement)")
        );

        // What plays is the correction from the measurement to the target.
        let r = response("AFUL Performer 8S", 48000).unwrap();
        let at = |curve: &[f64], hz: f64| curve[r.freqs.iter().position(|f| *f >= hz).unwrap()];
        let wanted = targets::correction(
            &targets::parse(&text),
            &targets::choice_curve("harman-in-ear-2019").unwrap(),
        );
        let expect = targets::at(&wanted.points, 3000.0);
        assert!(
            (at(&r.total, 3000.0) - expect).abs() < 1.0,
            "{} vs {expect}",
            at(&r.total, 3000.0)
        );
        // Held to ±3 dB in the treble, where rigs disagree.
        assert!(
            wanted
                .points
                .iter()
                .filter(|(hz, _)| *hz >= 10_000.0)
                .all(|(_, db)| db.abs() <= 3.0)
        );

        // Another target: the same measurement, corrected to it.
        let choices = target_choices("AFUL Performer 8S").unwrap();
        assert!(choices.made_for.is_none());
        choose_target("AFUL Performer 8S", Some("harman-in-ear-2019-without-bass")).unwrap();
        assert_eq!(
            summary("AFUL Performer 8S").unwrap().correction.as_deref(),
            Some("AFUL Performer 8S → Harman in-ear 2019, no bass shelf (from measurement)")
        );
    }

    /// One correction to a chain: a second layer is refused, naming the one
    /// already there, and one made so by its role is warned of; tuning on
    /// top is fine.
    #[test]
    fn a_chain_corrects_once() {
        use crate::config::{DspLayer, DspTarget};
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        persist(|c| {
            for (name, target) in [("HD 650", true), ("HD 600", true), ("Warm", false)] {
                c.dsp.profiles.push(DspProfile {
                    name: name.into(),
                    filters: vec![band(100.0)],
                    target: target.then(|| DspTarget {
                        made_for: "harman-over-ear-2018".into(),
                        chosen: None,
                    }),
                    ..Default::default()
                });
            }
        })
        .unwrap();
        let layer = |p: &str| DspLayer {
            profile: p.into(),
            on: true,
        };
        set_layers("Desk", vec![layer("HD 650"), layer("Warm")]).unwrap();
        let s = summary("Desk").unwrap();
        assert_eq!(
            s.correction.as_deref(),
            Some("HD 650: ready-made EQ (made for Harman over-ear 2018)")
        );
        assert_eq!(s.tunings, vec!["Warm".to_string()]);
        let refused = set_layers(
            "Desk",
            vec![layer("HD 650"), layer("Warm"), layer("HD 600")],
        )
        .unwrap_err();
        assert_eq!(
            refused,
            "This EQ already plays the correction HD 650. Take that out first, or add HD 600 to a device's tuning instead."
        );
        // Said to be a correction, it is one: the stack says so.
        set_role("Warm", DspRole::Correction).unwrap();
        assert_eq!(
            detail("Desk").unwrap().corrects_twice.as_deref(),
            Some("This EQ corrects twice: HD 650 (ready-made) and Warm (correction). Keep one.")
        );
        set_role("Warm", DspRole::Tuning).unwrap();
        set_role("HD 600", DspRole::Tuning).unwrap();
        set_layers(
            "Desk",
            vec![layer("HD 650"), layer("Warm"), layer("HD 600")],
        )
        .unwrap();
    }

    /// What a ready-made EQ was made for is a target that ships, said of a
    /// profile that is there and not built from a measurement; a target
    /// chosen for another kind of headphone goes with the old one.
    #[test]
    fn made_for_is_checked() {
        use crate::config::{DspEar, DspMeasurement};
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        persist(|c| {
            c.dsp.profiles.push(DspProfile {
                name: "Preset".into(),
                filters: vec![band(100.0)],
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Measured".into(),
                measurement: Some(DspMeasurement {
                    ear: DspEar::In,
                    target: "harman-in-ear-2019".into(),
                }),
                ..Default::default()
            });
        })
        .unwrap();
        assert!(set_made_for("Nobody", Some("harman-in-ear-2019")).is_err());
        assert!(set_made_for("Preset", Some("made-up")).is_err());
        assert!(set_made_for("Measured", Some("harman-in-ear-2019")).is_err());
        let target = || {
            Config::cached()
                .dsp
                .profiles
                .iter()
                .find(|p| p.name == "Preset")
                .unwrap()
                .target
                .clone()
        };
        assert_eq!(target(), None);
        set_made_for("Preset", Some("harman-in-ear-2019")).unwrap();
        choose_target("Preset", Some("diffuse-field-iso-11904-1")).unwrap();
        set_made_for("Preset", Some("harman-over-ear-2018")).unwrap();
        let t = target().unwrap();
        assert_eq!(t.made_for, "harman-over-ear-2018");
        assert_eq!(t.chosen, None, "an in-ear target is no move for over-ears");
        set_made_for("Preset", None).unwrap();
        assert_eq!(target(), None);
    }

    /// Where the target difference is what tips the chain past the filters
    /// it may hold, it is the step that goes: the tuning plays without it,
    /// and says so.
    #[test]
    fn the_target_difference_goes_before_the_tuning() {
        use crate::config::{DspFilter, DspLayer, DspTarget};
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        let spread = |n: usize, from: f64| -> Vec<DspFilter> {
            (0..n)
                .map(|i| {
                    DspFilter::Band(crate::config::EqFilter {
                        kind: crate::config::EqFilterKind::Peaking,
                        freq: from + i as f64,
                        gain_db: 1.0,
                        q: 1.0,
                        channels: vec![(i % 4) as u16],
                    })
                })
                .collect()
        };
        persist(|c| {
            c.dsp.profiles.push(DspProfile {
                name: "Base".into(),
                filters: spread(100, 1000.0),
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "HD 600".into(),
                filters: vec![band(100.0)],
                layers: vec![DspLayer {
                    profile: "Base".into(),
                    on: true,
                }],
                target: Some(DspTarget {
                    made_for: "harman-over-ear-2018".into(),
                    chosen: None,
                }),
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Many".into(),
                filters: spread(156, 100.0),
                tuned_for: Some("diffuse-field-gras-kemar".into()),
                ..Default::default()
            });
        })
        .unwrap();
        let dac = "Desk DAC";
        assign(Some("HD 600"), dac).unwrap();
        set_tuning(dac, Some("Many")).unwrap();
        let cfg = Config::cached();
        let chain = super::super::output_chain(&cfg.dsp, dac).unwrap();
        assert!(chain.tuning_plays);
        let played = super::super::chain(&chain.profile, &chain.all, &mut Vec::new()).unwrap();
        assert_eq!(
            played.len(),
            100 + 156 + 1,
            "Base, the tuning, the correction's own"
        );
        assert!(
            !played.iter().any(|f| matches!(f, DspFilter::Graphic(_))),
            "no target difference"
        );
        assert!(
            chain
                .left_out
                .as_deref()
                .is_some_and(|l| l.starts_with("Many plays without the target difference")),
            "{:?}",
            chain.left_out
        );
    }

    /// A baked EQ, a correction and a bass band in one, splits back into the
    /// two: the correction from the measurement, the band as the tuning,
    /// made against the target, and the output that played it plays them.
    #[test]
    fn a_baked_eq_splits_into_correction_and_tuning() {
        use super::super::targets;
        use crate::config::DspFilter;
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        let mut text = String::from("frequency,raw\n");
        for hz in targets::grid() {
            let peak = |at: f64, db: f64| db * (-(hz / at).log2().powi(2) / 0.1).exp();
            text.push_str(&format!(
                "{hz:.2},{:.2}\n",
                90.0 + peak(3000.0, 6.0) + peak(8000.0, 5.0)
            ));
        }
        let target = "harman-in-ear-2019";
        let measured = read_measurement(&text).unwrap();
        // As a squig.link export bakes it: target minus measurement whole.
        let correction = targets::difference(&measured, &targets::choice_curve(target).unwrap());
        persist(|c| {
            c.dsp.profiles.push(DspProfile {
                name: "Lush".into(),
                filters: vec![DspFilter::Graphic(correction), band(80.0)],
                role: Some(DspRole::Baked),
                devices: vec!["Desk DAC".into()],
                ..Default::default()
            })
        })
        .unwrap();

        let r = preview_split("Lush", &text, target, 48_000).unwrap();
        let at = |db: &[f64], hz: f64| {
            let i = r.freqs.iter().position(|&f| f >= hz).unwrap();
            db[i]
        };
        let tuning = r.tuning.as_ref().unwrap();
        assert!((at(tuning, 80.0) - 3.0).abs() < 1.0, "{}", at(tuning, 80.0));
        assert!(at(tuning, 3000.0).abs() < 0.7, "{}", at(tuning, 3000.0));
        // The headphones' treble is the correction's, not the taste's.
        assert!(at(tuning, 8000.0).abs() < 1.0, "{}", at(tuning, 8000.0));
        let original = r.original.as_ref().unwrap();
        for hz in [50.0, 200.0, 1000.0, 4000.0] {
            assert!((at(&r.total, hz) - at(original, hz)).abs() < 1.0, "{hz} Hz");
        }

        let (c, t) = split_baked("Lush", &text, DspEar::In, target).unwrap();
        assert_eq!((c.as_str(), t.as_str()), ("Lush correction", "Lush tuning"));
        let cfg = Config::cached();
        assert_eq!(cfg.dsp.profile_for("Desk DAC").unwrap().name, c);
        assert_eq!(tuning_for("Desk DAC").as_deref(), Some(t.as_str()));
        let made = cfg.dsp.profiles.iter().find(|p| p.name == t).unwrap();
        assert_eq!(made.tuned_for.as_deref(), Some(target));
        assert_eq!(role(made), DspRole::Tuning);
        assert!(cfg.dsp.profiles.iter().any(|p| p.name == "Lush"), "kept");
        // On its own target, no difference to play: the tuning's curve and
        // the correction's.
        let chain = super::super::output_chain(&cfg.dsp, "Desk DAC").unwrap();
        let played = super::super::chain(&chain.profile, &chain.all, &mut Vec::new()).unwrap();
        assert_eq!(played.len(), 2);
        assert!(split_baked("Lush", &text, DspEar::In, "made-up").is_err());

        // One EQ the same on every channel splits; nothing else does.
        let stack = |c: &mut Config| {
            c.dsp.profiles.push(DspProfile {
                name: "Stack".into(),
                layers: vec![crate::config::DspLayer {
                    profile: "Lush".into(),
                    on: true,
                }],
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Left".into(),
                filters: vec![DspFilter::Band(crate::config::EqFilter {
                    kind: crate::config::EqFilterKind::Peaking,
                    freq: 100.0,
                    gain_db: 2.0,
                    q: 1.0,
                    channels: vec![0],
                })],
                ..Default::default()
            });
        };
        persist(stack).unwrap();
        let refused = preview_split("Stack", &text, target, 48_000).unwrap_err();
        assert!(refused.contains("plays other EQs"), "{refused}");
        let refused = preview_split("Left", &text, target, 48_000).unwrap_err();
        assert!(
            refused.contains("treats its channels differently"),
            "{refused}"
        );
    }

    /// A tuning is EQs in order, each on or off, each with its own target
    /// difference; a preset saves a correction and its tuning and sets an
    /// output from them, and says when the output was changed since.
    #[test]
    fn a_tuning_is_eqs_in_order_and_a_preset_saves_it() {
        use crate::config::{DspFilter, DspTarget};
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        let curve = |db: f64| {
            DspFilter::Graphic(crate::config::GraphicEq {
                points: vec![(20.0, 0.0), (1000.0, db), (20_000.0, 0.0)],
                channels: vec![],
            })
        };
        persist(|c| {
            let harman = || {
                Some(DspTarget {
                    made_for: "harman-over-ear-2018".into(),
                    chosen: None,
                })
            };
            c.dsp.profiles.push(DspProfile {
                name: "HD 600".into(),
                filters: vec![band(100.0)],
                target: harman(),
                ..Default::default()
            });
            for (name, freq, made) in [
                ("Warm", 60.0, Some("diffuse-field-gras-kemar")),
                ("Bright", 8000.0, Some("harman-over-ear-2018")),
                ("Spare", 200.0, None),
            ] {
                c.dsp.profiles.push(DspProfile {
                    name: name.into(),
                    filters: vec![band(freq)],
                    tuned_for: made.map(str::to_owned),
                    ..Default::default()
                });
            }
            for (name, db) in [("Tilt", 1.0), ("Lift", 2.0)] {
                c.dsp.profiles.push(DspProfile {
                    name: name.into(),
                    filters: vec![curve(db)],
                    ..Default::default()
                });
            }
        })
        .unwrap();
        let dac = "Desk DAC";
        let plays = |device: &str| -> Vec<String> {
            let cfg = Config::cached();
            let Some(chain) = super::super::output_chain(&cfg.dsp, device) else {
                return Vec::new();
            };
            super::super::chain(&chain.profile, &chain.all, &mut Vec::new())
                .unwrap()
                .into_iter()
                .map(|f| match f {
                    DspFilter::Band(b) => format!("{}", b.freq),
                    DspFilter::Graphic(_) => "curve".into(),
                    other => panic!("{other:?}"),
                })
                .collect()
        };
        let list = |names: &[(&str, bool)]| -> Vec<(String, bool)> {
            names.iter().map(|(n, on)| (n.to_string(), *on)).collect()
        };
        assign(Some("HD 600"), dac).unwrap();
        set_tunings(
            dac,
            &list(&[("Warm", true), ("Bright", true), ("Spare", false)]),
        )
        .unwrap();
        // Warm's difference ahead of it, Bright on its own target, Spare off;
        // then the correction's own band.
        assert_eq!(plays(dac), ["curve", "60", "8000", "100"]);
        assert_eq!(tuning_for(dac).as_deref(), Some("Warm"));
        assert!(set_tunings(dac, &list(&[("Warm", true), ("Warm", false)])).is_err());
        assert!(set_tunings(dac, &list(&[("HD 600", true)])).is_err());

        // The correction's curves first, then each EQ's while they fit.
        set_tunings(
            dac,
            &list(&[("Tilt", true), ("Lift", true), ("Spare", true)]),
        )
        .unwrap();
        assert_eq!(plays(dac), ["curve", "curve", "200", "100"]);
        let o = overview_for(Some(dac.into()));
        assert!(o.left_out.as_deref().is_none(), "{:?}", o.left_out);
        persist(|c| {
            let hd = c
                .dsp
                .profiles
                .iter_mut()
                .find(|p| p.name == "HD 600")
                .unwrap();
            hd.filters.push(curve(-1.0));
        })
        .unwrap();
        assert_eq!(plays(dac), ["curve", "200", "100", "curve"]);
        let o = overview_for(Some(dac.into()));
        assert!(
            o.left_out
                .as_deref()
                .is_some_and(|l| l.starts_with("Lift is left out")),
            "{:?}",
            o.left_out
        );

        // A preset saves the correction and the tuning, on and off.
        set_tunings(dac, &list(&[("Warm", true), ("Spare", false)])).unwrap();
        save_preset(dac, "Late night").unwrap();
        assert_eq!(preset_for(dac), Some(("Late night".into(), false)));
        let other = "Speakers";
        apply_preset(other, Some("Late night")).unwrap();
        assert_eq!(
            Config::cached().dsp.profile_for(other).unwrap().name,
            "HD 600"
        );
        assert_eq!(
            tunings_for(other),
            list(&[("Warm", true), ("Spare", false)])
        );
        assert_eq!(plays(other), plays(dac));
        set_tunings(other, &list(&[("Warm", true), ("Spare", true)])).unwrap();
        assert_eq!(
            preset_for(other),
            Some(("Late night".into(), true)),
            "edited"
        );
        assert!(save_preset(other, "Warm").is_err(), "not over an EQ");
        // Flat: nothing, and untouched.
        apply_preset(other, None).unwrap();
        assert!(Config::cached().dsp.profile_for(other).is_none());
        assert!(tunings_for(other).is_empty());
        assert_eq!(preset_for(other), None);
        assert!(plays(other).is_empty());
    }

    /// A correction plays as made: its bands are not edited. An imported EQ
    /// keeps what it was imported as, says when it was changed, and goes
    /// back; a copy is its own.
    #[test]
    fn corrections_are_read_only_and_imports_can_go_back() {
        use crate::config::DspTarget;
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        persist(|c| {
            c.dsp.profiles.push(DspProfile {
                name: "HD 600".into(),
                filters: vec![band(100.0)],
                target: Some(DspTarget {
                    made_for: "harman-over-ear-2018".into(),
                    chosen: None,
                }),
                ..Default::default()
            })
        })
        .unwrap();
        let refused = set_band("HD 600", 0, "peaking", 200.0, 1.0, 1.0).unwrap_err();
        assert!(refused.contains("plays as made"), "{refused}");
        assert!(add_band("HD 600").is_err());
        assert!(remove_filter("HD 600", 0).is_err());
        assert!(detail("HD 600").unwrap().read_only);

        let lush = Imported {
            name: "Lush".into(),
            source: vec!["Lush.txt".into()],
            filters: vec![band(80.0)],
            impulses: vec![],
        };
        save(lush, None).unwrap();
        let d = detail("Lush").unwrap();
        assert!(!d.read_only && d.can_revert && !d.edited);
        set_band("Lush", 0, "peaking", 80.0, 12.0, 1.0).unwrap();
        assert!(detail("Lush").unwrap().edited);
        let copy = duplicate("Lush", None).unwrap();
        assert_eq!(copy, "Lush copy");
        let c = detail(&copy).unwrap();
        assert!(!c.can_revert && c.devices.is_empty());
        assert_eq!(c.filters, detail("Lush").unwrap().filters, "as it is now");
        revert("Lush").unwrap();
        assert!(!detail("Lush").unwrap().edited);
        assert!(revert(&copy).is_err(), "made here");
        assert!(duplicate("Lush", Some("Lush copy")).is_err(), "taken");
    }

    /// Configs from before: a stack of a correction and EQs becomes a
    /// preset, its outputs set from it with the tuning they had on top and
    /// without a correction switched off; an output a preset was assigned to
    /// is set from it; an output whose correction was a group plays the
    /// member that played.
    #[test]
    fn old_stacks_become_presets() {
        use crate::config::{DspLayer, DspTarget};
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        let layer = |p: &str, on: bool| DspLayer {
            profile: p.into(),
            on,
        };
        persist(|c| {
            for name in ["HD 600", "HD 650"] {
                c.dsp.profiles.push(DspProfile {
                    name: name.into(),
                    filters: vec![band(100.0)],
                    target: Some(DspTarget {
                        made_for: "harman-over-ear-2018".into(),
                        chosen: None,
                    }),
                    ..Default::default()
                });
            }
            for (name, hz) in [("Warm", 60.0), ("Bright", 8000.0)] {
                c.dsp.profiles.push(DspProfile {
                    name: name.into(),
                    filters: vec![band(hz)],
                    ..Default::default()
                });
            }
            c.dsp.tunings.push(crate::config::DspOutputTuning {
                device: "DAC".into(),
                tuning: "Bright".into(),
                on: true,
            });
            c.dsp.profiles.push(DspProfile {
                name: "Quiet".into(),
                devices: vec!["Amp".into()],
                layers: vec![layer("HD 650", false), layer("Warm", true)],
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Saved".into(),
                devices: vec!["Speaker".into()],
                preset: true,
                layers: vec![layer("HD 650", true), layer("Bright", true)],
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Desk".into(),
                devices: vec!["DAC".into()],
                layers: vec![layer("HD 600", true), layer("Warm", false)],
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Cans".into(),
                devices: vec!["Phone".into()],
                group: true,
                layers: vec![layer("HD 600", false), layer("HD 650", true)],
                ..Default::default()
            });
        })
        .unwrap();
        migrate().unwrap();
        let cfg = Config::cached();
        let desk = cfg.dsp.profiles.iter().find(|p| p.name == "Desk").unwrap();
        assert!(desk.preset && desk.devices.is_empty());
        assert_eq!(cfg.dsp.profile_for("DAC").unwrap().name, "HD 600");
        assert_eq!(
            tunings_for("DAC"),
            vec![("Warm".to_string(), false), ("Bright".to_string(), true)],
            "the stack's EQs, then the tuning it had on top"
        );
        assert_eq!(preset_for("DAC"), Some(("Desk".into(), true)));
        assert!(cfg.dsp.profile_for("Amp").is_none(), "switched off");
        assert_eq!(tunings_for("Amp"), vec![("Warm".to_string(), true)]);
        assert_eq!(preset_for("Amp"), Some(("Quiet".into(), false)));
        assert_eq!(cfg.dsp.profile_for("Speaker").unwrap().name, "HD 650");
        assert_eq!(tunings_for("Speaker"), vec![("Bright".to_string(), true)]);
        assert_eq!(preset_for("Speaker"), Some(("Saved".into(), false)));
        assert_eq!(cfg.dsp.profile_for("Phone").unwrap().name, "HD 650");
        assign(Some("Saved"), "Laptop").unwrap();
        assert_eq!(preset_for("Laptop"), Some(("Saved".into(), false)));
        assert!(
            Config::cached()
                .dsp
                .profiles
                .iter()
                .all(|p| !p.preset || p.devices.is_empty()),
            "a preset sets an output, never is its correction"
        );
        migrate().unwrap();
        assert_eq!(
            Config::cached().dsp.profile_for("DAC").unwrap().name,
            "HD 600",
            "once"
        );
    }

    /// A whole chain set in one go, the same twice changing nothing; a name
    /// that is not a correction or EQ refused with the choices, before
    /// anything is set; and the chain said as the EQ page says it.
    #[test]
    fn a_chain_is_set_whole_and_said() {
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        persist(|c| {
            c.dsp.profiles.push(DspProfile {
                name: "Wharfedale".into(),
                filters: vec![band(100.0)],
                role: Some(DspRole::Correction),
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Lush".into(),
                filters: vec![band(60.0)],
                role: Some(DspRole::Baked),
                ..Default::default()
            });
            for (name, hz) in [("Warm", 80.0), ("Air", 9000.0)] {
                c.dsp.profiles.push(DspProfile {
                    name: name.into(),
                    filters: vec![band(hz)],
                    ..Default::default()
                });
            }
        })
        .unwrap();
        let dac = "Scarlett";
        let eqs = ["Warm".to_string(), "Air".to_string()];
        assert_eq!(
            chain_view(dac).sentence,
            "Scarlett is flat: the music plays untouched."
        );
        set_chain(dac, Some(Some("Wharfedale")), Some(&eqs)).unwrap();
        let once = std::fs::read_to_string(dir.path().join("config.local.toml")).unwrap();
        set_chain(dac, Some(Some("Wharfedale")), Some(&eqs)).unwrap();
        let twice = std::fs::read_to_string(dir.path().join("config.local.toml")).unwrap();
        assert_eq!(once, twice, "the same twice changes nothing");
        let view = chain_view(dac);
        assert_eq!(view.correction.as_deref(), Some("Wharfedale"));
        assert_eq!(view.tuning.len(), 2);
        assert_eq!(
            view.sentence,
            "Music to Scarlett, corrected by Wharfedale, then tuned with Warm and Air."
        );

        let refused = set_chain(dac, Some(Some("Nope")), None).unwrap_err();
        assert_eq!(
            refused,
            "No correction called Nope. Corrections: Wharfedale, Lush"
        );
        let refused = set_chain(dac, None, Some(&["Nope".to_string()])).unwrap_err();
        assert_eq!(refused, "No EQ called Nope. EQs: Warm, Air");
        let twice = ["Warm".to_string(), "Warm".to_string()];
        let refused = set_chain(dac, Some(None), Some(&twice)).unwrap_err();
        assert_eq!(refused, "Warm is in the tuning twice");
        assert_eq!(
            chain_view(dac).correction.as_deref(),
            Some("Wharfedale"),
            "a refusal changes nothing"
        );
        // A correction that includes a tuning takes none: nothing is set.
        set_chain(dac, Some(Some("Lush")), Some(&eqs)).unwrap_err();
        assert_eq!(chain_view(dac).correction.as_deref(), Some("Wharfedale"));
        set_chain(dac, Some(Some("Lush")), Some(&[])).unwrap();
        assert_eq!(
            chain_view(dac).sentence,
            "Music to Scarlett, corrected by Lush."
        );
        set_chain(dac, Some(None), None).unwrap();
        assert!(chain_view(dac).flat);
    }

    /// Deleting an EQ takes it out of the presets and groups that hold it;
    /// an EQ that plays it refuses, naming itself.
    #[test]
    fn a_deleted_eq_leaves_its_presets_and_groups() {
        use crate::config::DspLayer;
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        let layer = |p: &str, on: bool| DspLayer {
            profile: p.into(),
            on,
        };
        persist(|c| {
            for (name, hz) in [("Warm", 60.0), ("Air", 9000.0)] {
                c.dsp.profiles.push(DspProfile {
                    name: name.into(),
                    filters: vec![band(hz)],
                    ..Default::default()
                });
            }
            c.dsp.profiles.push(DspProfile {
                name: "Evening".into(),
                preset: true,
                layers: vec![layer("Warm", true), layer("Air", true)],
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Tastes".into(),
                group: true,
                layers: vec![layer("Warm", true), layer("Air", false)],
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Both".into(),
                layers: vec![layer("Air", true)],
                ..Default::default()
            });
        })
        .unwrap();
        let held = overview()
            .profiles
            .into_iter()
            .find(|p| p.name == "Warm")
            .unwrap()
            .held_by;
        assert_eq!(held, ["Evening", "Tastes"]);
        assert_eq!(
            remove("Air").unwrap_err(),
            "Both plays Air: take it out of it first"
        );
        remove("Warm").unwrap();
        let cfg = Config::cached();
        let of = |n: &str| {
            cfg.dsp
                .profiles
                .iter()
                .find(|p| p.name == n)
                .unwrap()
                .layers
                .clone()
        };
        assert_eq!(of("Evening"), vec![layer("Air", true)]);
        assert_eq!(
            of("Tastes"),
            vec![layer("Air", true)],
            "the group plays what is left"
        );
    }

    /// Processing switched off is every output flat, what each played kept
    /// as a preset named for it, unless a preset already holds it as it was.
    #[test]
    fn processing_off_becomes_flat() {
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        persist(|c| {
            c.dsp.profiles.push(DspProfile {
                name: "HD 600".into(),
                filters: vec![band(100.0)],
                role: Some(DspRole::Correction),
                devices: vec!["DAC".into(), "Amp".into()],
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Warm".into(),
                filters: vec![band(60.0)],
                ..Default::default()
            });
            // Chosen as corrections before roles were asked: a room's
            // impulse response, and bands with no role.
            c.dsp.profiles.push(DspProfile {
                name: "Room".into(),
                impulses: vec!["room.wav".into()],
                devices: vec!["Monitors".into()],
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Plain".into(),
                filters: vec![band(300.0)],
                devices: vec!["Phones".into()],
                ..Default::default()
            });
            // Taken: the preset is named apart from it.
            c.dsp.profiles.push(DspProfile {
                name: "DAC".into(),
                filters: vec![band(80.0)],
                role: Some(DspRole::Tuning),
                ..Default::default()
            });
        })
        .unwrap();
        set_tunings("DAC", &[("Warm".into(), true)]).unwrap();
        save_preset("Amp", "Speakers").unwrap();
        set_enabled(false).unwrap();
        migrate().unwrap();
        let cfg = Config::cached();
        assert!(cfg.dsp.enabled);
        for device in ["DAC", "Amp"] {
            assert!(cfg.dsp.profile_for(device).is_none(), "{device} is flat");
            assert!(tunings_for(device).is_empty());
            assert_eq!(preset_for(device), None);
        }
        let kept = cfg.dsp.profiles.iter().find(|p| p.name == "DAC 2").unwrap();
        assert!(kept.preset);
        apply_preset("DAC", Some("DAC 2")).unwrap();
        assert_eq!(
            Config::cached().dsp.profile_for("DAC").unwrap().name,
            "HD 600"
        );
        assert_eq!(tunings_for("DAC"), vec![("Warm".to_string(), true)]);
        assert!(
            !Config::cached()
                .dsp
                .profiles
                .iter()
                .any(|p| p.name == "Amp"),
            "Amp was set from Speakers, unchanged"
        );
        for (device, correction) in [("Monitors", "Room"), ("Phones", "Plain")] {
            assert!(Config::cached().dsp.profile_for(device).is_none());
            apply_preset(device, Some(device)).unwrap();
            assert_eq!(
                Config::cached().dsp.profile_for(device).unwrap().name,
                correction,
                "back as {device}'s correction"
            );
            assert!(tunings_for(device).is_empty(), "{device}");
        }
    }

    /// An output plays its tuning on top of its correction, with the
    /// difference between the correction's target and the one the tuning was
    /// made against: dynamic baking. Never on a correction with a tuning
    /// baked in, and never across kinds of headphone.
    #[test]
    fn an_output_plays_its_tuning_on_its_correction() {
        use crate::config::{DspFilter, DspTarget};
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        persist(|c| {
            c.dsp.profiles.push(DspProfile {
                name: "HD 600".into(),
                filters: vec![band(100.0)],
                target: Some(DspTarget {
                    made_for: "harman-over-ear-2018".into(),
                    chosen: None,
                }),
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Warm".into(),
                filters: vec![band(60.0)],
                tuned_for: Some("diffuse-field-gras-kemar".into()),
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Lush".into(),
                filters: vec![band(200.0)],
                role: Some(DspRole::Baked),
                ..Default::default()
            });
            let harman = || {
                Some(DspTarget {
                    made_for: "harman-over-ear-2018".into(),
                    chosen: None,
                })
            };
            c.dsp.profiles.push(DspProfile {
                name: "HD 650".into(),
                filters: vec![band(110.0)],
                target: harman(),
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Bright".into(),
                filters: vec![band(8000.0)],
                tuned_for: Some("harman-over-ear-2018".into()),
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Room".into(),
                impulses: vec!["dsp/room/48000.wav".into()],
                ..Default::default()
            });
            let curve = |db: f64| {
                DspFilter::Graphic(crate::config::GraphicEq {
                    points: vec![(20.0, 0.0), (1000.0, db), (20_000.0, 0.0)],
                    channels: vec![],
                })
            };
            c.dsp.profiles.push(DspProfile {
                name: "Curved".into(),
                filters: vec![curve(2.0)],
                target: harman(),
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Tilt".into(),
                filters: vec![curve(-1.0)],
                tuned_for: Some("diffuse-field-gras-kemar".into()),
                ..Default::default()
            });
        })
        .unwrap();
        let dac = "Desk DAC";
        let shown = || {
            super::super::output_chain(&Config::cached().dsp, dac)
                .unwrap()
                .name
        };
        let plays = || -> Vec<String> {
            let cfg = Config::cached();
            let Some(chain) = super::super::output_chain(&cfg.dsp, dac) else {
                return Vec::new();
            };
            super::super::chain(&chain.profile, &chain.all, &mut Vec::new())
                .unwrap()
                .into_iter()
                .map(|f| match f {
                    DspFilter::Band(b) => format!("{}", b.freq),
                    DspFilter::Graphic(_) => "step".into(),
                    other => panic!("{other:?}"),
                })
                .collect()
        };
        assign(Some("HD 600"), dac).unwrap();
        assert_eq!(plays(), ["100"]);

        // Made against neutral, played on a correction to Harman: Harman's
        // preference comes out first.
        set_tuning(dac, Some("Warm")).unwrap();
        assert_eq!(tuning_for(dac).as_deref(), Some("Warm"));
        assert_eq!(plays(), ["step", "60", "100"]);
        // Made against the correction's own target, or nothing said: as it is.
        set_tuned_for("Warm", Some("harman-over-ear-2018")).unwrap();
        assert_eq!(plays(), ["60", "100"]);
        set_tuned_for("Warm", None).unwrap();
        assert_eq!(plays(), ["60", "100"]);
        // An in-ear target says nothing of over-ears.
        set_tuned_for("Warm", Some("harman-in-ear-2019")).unwrap();
        assert_eq!(plays(), ["60", "100"]);
        assert!(set_tuned_for("Warm", Some("made-up")).is_err());

        // A correction is not a tuning, and a baked one takes none.
        let refused = set_tuning(dac, Some("HD 600")).unwrap_err();
        assert!(refused.contains("corrects headphones"), "{refused}");
        assign(Some("Lush"), dac).unwrap();
        assert_eq!(plays(), ["200"], "the tuning waits");
        assert_eq!(
            overview_for(Some(dac.into())).left_out.as_deref(),
            Some("Warm is left out: Lush already includes a tuning."),
            "and says why"
        );
        assert_eq!(
            set_tuning(dac, Some("Warm")).unwrap_err(),
            "Lush already includes a tuning. Split it into a correction and an EQ to change the tuning."
        );

        // A group corrects with its member playing, the tuning on top, and is
        // called by its own name.
        make_group("Cans", &["HD 600".into(), "HD 650".into()]).unwrap();
        assign(Some("Cans"), dac).unwrap();
        set_tuning(dac, Some("Warm")).unwrap();
        set_tuned_for("Warm", Some("diffuse-field-gras-kemar")).unwrap();
        assert_eq!(plays(), ["step", "60", "100"]);
        select("Cans", "HD 650").unwrap();
        assert_eq!(plays(), ["step", "60", "110"]);
        assert_eq!(shown(), "Cans");

        // A group of tunings is made against its playing member's target.
        make_group("Tastes", &["Warm".into(), "Bright".into()]).unwrap();
        set_tuning(dac, Some("Tastes")).unwrap();
        assert_eq!(plays(), ["step", "60", "110"]);
        select("Tastes", "Bright").unwrap();
        assert_eq!(plays(), ["8000", "110"], "made against Harman, on Harman");
        set_tuning(dac, Some("Warm")).unwrap();
        remove("Tastes").unwrap();

        // Impulse responses correct a room: never a tuning.
        let refused = set_tuning(dac, Some("Room")).unwrap_err();
        assert!(refused.contains("impulse responses"), "{refused}");

        // The correction's curves come first in the chain's budget: the step
        // is left out rather than push one out.
        assign(Some("Curved"), dac).unwrap();
        set_tuning(dac, Some("Tilt")).unwrap();
        let cfg = Config::cached();
        let chain = super::super::output_chain(&cfg.dsp, dac).unwrap();
        let played = super::super::chain(&chain.profile, &chain.all, &mut Vec::new()).unwrap();
        let curved = cfg
            .dsp
            .profiles
            .iter()
            .find(|p| p.name == "Curved")
            .unwrap();
        assert_eq!(played.len(), 2, "the tuning's curve and the correction's");
        assert_eq!(played.last(), curved.filters.first());
        let o = overview_for(Some(dac.into()));
        assert!(o.tuning_plays);
        assert!(
            o.left_out
                .as_deref()
                .is_some_and(|l| l.starts_with("Tilt plays without the target difference")),
            "{:?}",
            o.left_out
        );
        set_tuning(dac, Some("Warm")).unwrap();

        // A chain past the filters one may hold loses the tuning, never the
        // correction, and says so. Each is within bounds, a channel's bands
        // spread over four; the layers together are not.
        let spread = |n: usize, from: f64| -> Vec<DspFilter> {
            (0..n)
                .map(|i| {
                    DspFilter::Band(crate::config::EqFilter {
                        kind: crate::config::EqFilterKind::Peaking,
                        freq: from + i as f64,
                        gain_db: 1.0,
                        q: 1.0,
                        channels: vec![(i % 4) as u16],
                    })
                })
                .collect()
        };
        persist(|c| {
            c.dsp.profiles.push(DspProfile {
                name: "Busy".into(),
                filters: spread(200, 100.0),
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "Base".into(),
                filters: spread(100, 1000.0),
                ..Default::default()
            });
            let hd = c
                .dsp
                .profiles
                .iter_mut()
                .find(|p| p.name == "HD 600")
                .unwrap();
            hd.layers = vec![crate::config::DspLayer {
                profile: "Base".into(),
                on: true,
            }];
        })
        .unwrap();
        assign(Some("HD 600"), dac).unwrap();
        set_tuning(dac, Some("Busy")).unwrap();
        assert_eq!(plays().len(), 101, "the correction alone");
        let o = overview_for(Some(dac.into()));
        assert!(!o.tuning_plays);
        assert!(
            o.left_out
                .as_deref()
                .is_some_and(|l| l.starts_with("Busy is left out")),
            "{:?}",
            o.left_out
        );
        assign(Some("Curved"), dac).unwrap();
        set_tuning(dac, Some("Warm")).unwrap();

        // Nor without a correction: nothing plays, and it says why.
        persist(|c| {
            c.dsp.profiles.push(DspProfile {
                name: "Heavy".into(),
                layers: ["Busy", "Base"]
                    .map(|p| crate::config::DspLayer {
                        profile: p.into(),
                        on: true,
                    })
                    .to_vec(),
                ..Default::default()
            });
        })
        .unwrap();
        assign(None, dac).unwrap();
        set_tuning(dac, Some("Heavy")).unwrap();
        assert!(plays().is_empty());
        let o = overview_for(Some(dac.into()));
        assert!(!o.tuning_plays);
        assert!(
            o.left_out
                .as_deref()
                .is_some_and(|l| l.starts_with("Heavy is left out")),
            "{:?}",
            o.left_out
        );
        set_tuning(dac, Some("Warm")).unwrap();

        // No correction: the tuning alone, called by its name.
        assign(None, dac).unwrap();
        assert_eq!(plays(), ["60"]);
        assert_eq!(shown(), "Warm");

        // It follows the profile's name, and goes with it.
        rename("Warm", "Warm bass").unwrap();
        assert_eq!(tuning_for(dac).as_deref(), Some("Warm bass"));
        remove("Warm bass").unwrap();
        assert_eq!(tuning_for(dac), None);
        assert!(plays().is_empty());
    }

    /// A correction with a tuning baked in is the chain's correction. A stack
    /// made before a second correction was refused still plays, says so,
    /// and can be edited, but gains no other correction.
    #[test]
    fn a_baked_preset_is_the_correction() {
        use crate::config::{DspLayer, DspTarget};
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        let layer = |p: &str, on: bool| DspLayer {
            profile: p.into(),
            on,
        };
        persist(|c| {
            let autoeq = || {
                Some(DspTarget {
                    made_for: "harman-in-ear-2019".into(),
                    chosen: None,
                })
            };
            c.dsp.profiles.push(DspProfile {
                name: "Cantor".into(),
                filters: vec![band(100.0)],
                target: autoeq(),
                ..Default::default()
            });
            c.dsp.profiles.push(DspProfile {
                name: "HD 600".into(),
                filters: vec![band(100.0)],
                target: autoeq(),
                ..Default::default()
            });
            for name in ["Performer 8S", "Warm"] {
                c.dsp.profiles.push(DspProfile {
                    name: name.into(),
                    filters: vec![band(200.0)],
                    ..Default::default()
                });
            }
            // As 0.59 allowed: two corrections in one stack.
            c.dsp.profiles.push(DspProfile {
                name: "Old".into(),
                layers: vec![layer("Cantor", true), layer("Performer 8S", true)],
                ..Default::default()
            });
        })
        .unwrap();
        // AutoEQ's measurement, kept beside Cantor as an install keeps it.
        let folder = super::dir("Cantor");
        std::fs::create_dir_all(&folder).unwrap();
        let mut csv = String::from("frequency,raw,target\n");
        for hz in super::super::targets::grid() {
            csv.push_str(&format!("{hz:.2},0.0,0.0\n"));
        }
        std::fs::write(super::super::targets::result_path(&folder), csv).unwrap();
        let cfg = Config::cached();
        let named = |n: &str| cfg.dsp.profiles.iter().find(|p| p.name == n).unwrap();
        assert_eq!(
            role(named("Cantor")),
            DspRole::Correction,
            "an AutoEQ install"
        );
        assert_eq!(role(named("Warm")), DspRole::Tuning, "anything else");
        assert_eq!(
            shown_role(named("Old"), &cfg.dsp.profiles),
            DspRole::Correction,
            "a stack is what it corrects with"
        );
        assert_eq!(corrects_twice(named("Old"), &cfg.dsp.profiles), None);

        set_role("Performer 8S", DspRole::Baked).unwrap();
        let d = detail("Old").unwrap();
        assert_eq!(
            d.corrects_twice.as_deref(),
            Some(
                "This EQ corrects twice: Cantor (AutoEQ) and Performer 8S (includes a tuning). Keep one."
            )
        );
        assert_eq!(
            d.layer_roles,
            vec![Some(DspRole::Correction), Some(DspRole::Baked)]
        );
        // It still plays, and can be edited towards one correction.
        let cfg = Config::cached();
        let old = cfg.dsp.profiles.iter().find(|p| p.name == "Old").unwrap();
        assert!(super::super::chain(old, &cfg.dsp.profiles, &mut Vec::new()).is_ok());
        set_layers(
            "Old",
            vec![layer("Cantor", true), layer("Performer 8S", false)],
        )
        .unwrap();
        let refused = set_layers(
            "Old",
            vec![
                layer("Cantor", true),
                layer("Performer 8S", false),
                layer("HD 600", true),
            ],
        )
        .unwrap_err();
        assert!(
            refused.starts_with("This EQ already plays the correction"),
            "{refused}"
        );

        // A baked preset is a stack's correction: another is refused.
        set_layers(
            "Desk",
            vec![layer("Performer 8S", true), layer("Warm", true)],
        )
        .unwrap();
        let s = summary("Desk").unwrap();
        assert_eq!(
            s.correction.as_deref(),
            Some("Performer 8S (correction + tuning in one)")
        );
        assert!(s.baked);
        assert_eq!(s.tunings, vec!["Warm".to_string()]);
        let refused = set_layers(
            "Desk",
            vec![
                layer("Performer 8S", true),
                layer("Warm", true),
                layer("Cantor", true),
            ],
        )
        .unwrap_err();
        assert_eq!(
            refused,
            "This EQ already plays the correction Performer 8S. Take that out first, or add Cantor to a device's tuning instead."
        );
    }

    /// An AutoEQ correction moved to another target is rebuilt from the
    /// measurement AutoEQ kept, rather than played as its bands and a step.
    #[test]
    fn autoeq_moved_to_another_target_is_rebuilt() {
        use crate::config::{DspFilter, DspTarget};
        let _guard = crate::config::tests::PERSIST_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let dir = tempfile::tempdir().unwrap();
        config::set_config_dir(dir.path());
        let folder = super::dir("HD 650");
        std::fs::create_dir_all(&folder).unwrap();
        let mut csv = String::from("frequency,raw,target\n");
        for hz in super::super::targets::grid() {
            csv.push_str(&format!("{hz:.2},0.0,0.0\n"));
        }
        std::fs::write(super::super::targets::result_path(&folder), csv).unwrap();
        persist(|c| {
            c.dsp.profiles.push(DspProfile {
                name: "HD 650".into(),
                filters: vec![band(100.0), band(1000.0)],
                target: Some(DspTarget {
                    made_for: "harman-over-ear-2018".into(),
                    chosen: None,
                }),
                ..Default::default()
            })
        })
        .unwrap();
        let chain = || {
            let cfg = Config::cached();
            let p = cfg.dsp.profiles[0].clone();
            super::super::chain(&p, &cfg.dsp.profiles, &mut Vec::new()).unwrap()
        };
        assert_eq!(chain().len(), 2, "AutoEQ's bands, as made");
        choose_target("HD 650", Some("harman-over-ear-2018-without-bass")).unwrap();
        let rebuilt = chain();
        assert_eq!(rebuilt.len(), 1, "{rebuilt:?}");
        assert!(matches!(rebuilt[0], DspFilter::Graphic(_)));
        assert!(
            summary("HD 650")
                .unwrap()
                .correction
                .unwrap()
                .contains("rebuilt from AutoEQ's measurement")
        );
    }
}