bliss-audio 0.11.2

A song analysis library for making playlists
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
//! Module containing utilities to properly manage a library of [Song]s,
//! for people wanting to e.g. implement a bliss plugin for an existing
//! audio player. A good resource to look at for inspiration is
//! [blissify](https://github.com/Polochon-street/blissify-rs)'s source code.
//!
//! Useful to have direct and easy access to functions that analyze
//! and store analysis of songs in a SQLite database, as well as retrieve it,
//! and make playlists directly from analyzed songs. All functions are as
//! thoroughly tested as possible, so you don't have to do it yourself,
//! including for instance bliss features version handling, etc.
//!
//! It works in three parts:
//! * The first part is the configuration part, which allows you to
//!   specify extra information that your plugin might need that will
//!   be automatically stored / retrieved when you instanciate a
//!   [Library] (the core of your plugin).
//!
//!   To do so implies specifying a configuration struct, that will implement
//!   [AppConfigTrait], i.e. implement `Serialize`, `Deserialize`, and a
//!   function to retrieve the [BaseConfig] (which is just a structure
//!   holding the path to the configuration file and the path to the database).
//!
//!   The most straightforward way to do so is to have something like this (
//!   in this example, we assume that `path_to_extra_information` is something
//!   you would want stored in your configuration file, path to a second music
//!   folder for instance:
//!   ```
//!     use anyhow::Result;
//!     use serde::{Deserialize, Serialize};
//!     use std::path::PathBuf;
//!     use bliss_audio::{BlissError};
//!     use bliss_audio::AnalysisOptions;
//!     use bliss_audio::library::{AppConfigTrait, BaseConfig};
//!
//!     #[derive(Serialize, Deserialize, Clone, Debug)]
//!     pub struct Config {
//!         #[serde(flatten)]
//!         pub base_config: BaseConfig,
//!         pub music_library_path: PathBuf,
//!     }
//!
//!     impl AppConfigTrait for Config {
//!         fn base_config(&self) -> &BaseConfig {
//!             &self.base_config
//!         }
//!
//!         fn base_config_mut(&mut self) -> &mut BaseConfig {
//!             &mut self.base_config
//!         }
//!     }
//!     impl Config {
//!         pub fn new(
//!             music_library_path: PathBuf,
//!             config_path: Option<PathBuf>,
//!             database_path: Option<PathBuf>,
//!             analysis_options: Option<AnalysisOptions>,
//!         ) -> Result<Self> {
//!             // Note that by passing `(None, None)` here, the paths will
//!             // be inferred automatically using user data dirs.
//!             let base_config = BaseConfig::new(config_path, database_path, analysis_options)?;
//!             Ok(Self {
//!                 base_config,
//!                 music_library_path,
//!             })
//!         }
//!     }
//!   ```
//!
//! * The second part is the actual [Library] structure, that makes the
//!   bulk of the plug-in. To initialize a library once with a given config,
//!   you can do (here with a base configuration, requiring ffmpeg):
#![cfg_attr(
    feature = "ffmpeg",
    doc = r##"
```no_run
  use anyhow::{Error, Result};
  use bliss_audio::library::{BaseConfig, Library};
  use bliss_audio::decoder::ffmpeg::FFmpegDecoder;
  use std::path::PathBuf;

  let config_path = Some(PathBuf::from("path/to/config/config.json"));
  let database_path = Some(PathBuf::from("path/to/config/bliss.db"));
  let config = BaseConfig::new(config_path, database_path, None)?;
  let library: Library<BaseConfig, FFmpegDecoder> = Library::new(config)?;
  # Ok::<(), Error>(())
```"##
)]
//!   Once this is done, you can simply load the library by doing
//!   `Library::from_config_path(config_path);`
//! * The third part is using the [Library] itself: it provides you with
//!   utilies such as [Library::analyze_paths], which analyzes all songs
//!   in given paths and stores it in the databases, as well as
//!   [Library::playlist_from], which allows you to generate a playlist
//!   from any given analyzed song(s), and [Library::playlist_from_custom],
//!   which allows you to customize the way you generate playlists.
//!
//!   The [Library] structure also comes with a [LibrarySong] song struct,
//!   which represents a song stored in the database.
//!
//!   It is made of a `bliss_song` field, containing the analyzed bliss
//!   song (with the normal metatada such as the artist, etc), and an
//!   `extra_info` field, which can be any user-defined serialized struct.
//!   For most use cases, it would just be the unit type `()` (which is no
//!   extra info), that would be used like
//!   `library.playlist_from<()>(song, path, playlist_length)`,
//!   but functions such as [Library::analyze_paths_extra_info] and
//!   [Library::analyze_paths_convert_extra_info] let you customize what
//!   information you store for each song.
//!
//! The files in
//! [examples/library.rs](https://github.com/Polochon-street/bliss-rs/blob/master/examples/library.rs)
//! and
//! [examples/libray_extra_info.rs](https://github.com/Polochon-street/bliss-rs/blob/master/examples/library_extra_info.rs)
//! should provide the user with enough information to start with. For a more
//! "real-life" example, the
//! [blissify](https://github.com/Polochon-street/blissify-rs)'s code is using
//! [Library] to implement bliss for a MPD player.
use crate::cue::CueInfo;
use crate::playlist::closest_album_to_group;
use crate::playlist::closest_to_songs;
use crate::playlist::dedup_playlist_custom_distance;
use crate::playlist::euclidean_distance;
use crate::playlist::DistanceMetricBuilder;
use crate::song::AnalysisOptions;
use crate::FeaturesVersion;
use anyhow::{bail, Context, Result};
#[cfg(all(not(test), not(feature = "integration-tests")))]
use dirs::config_local_dir;
#[cfg(all(not(test), not(feature = "integration-tests")))]
use dirs::data_local_dir;
use indicatif::{ProgressBar, ProgressStyle};
use ndarray::Array2;
use rusqlite::params;
use rusqlite::params_from_iter;
use rusqlite::Connection;
use rusqlite::Params;
use rusqlite::Row;
use serde::de::DeserializeOwned;
use serde::Deserialize;
use serde::Serialize;
use std::collections::{HashMap, HashSet};
use std::env;
use std::fs;
use std::fs::create_dir_all;
use std::marker::PhantomData;
use std::num::NonZeroUsize;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::Mutex;

use crate::decoder::Decoder as DecoderTrait;
use crate::Song;
use crate::{Analysis, BlissError, NUMBER_FEATURES};
use rusqlite::types::ToSqlOutput;
use rusqlite::Error as RusqliteError;
use rusqlite::{
    types::{FromSql, FromSqlResult, ValueRef},
    ToSql,
};
use std::convert::TryInto;
use std::time::Duration;

impl ToSql for FeaturesVersion {
    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
        Ok(ToSqlOutput::from(*self as u16))
    }
}

impl FromSql for FeaturesVersion {
    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
        let value = value.as_i64()?;
        FeaturesVersion::try_from(u16::try_from(value).unwrap())
            .map_err(|e| rusqlite::types::FromSqlError::Other(Box::new(e)))
    }
}

/// Configuration trait, used for instance to customize
/// the format in which the configuration file should be written.
pub trait AppConfigTrait: Serialize + Sized + DeserializeOwned {
    // Implementers have to provide these.
    /// This trait should return the [BaseConfig] from the parent,
    /// user-created `Config`.
    fn base_config(&self) -> &BaseConfig;

    // Implementers have to provide these.
    /// This trait should return the [BaseConfig] from the parent,
    /// user-created `Config`.
    fn base_config_mut(&mut self) -> &mut BaseConfig;

    // Default implementation to output the config as a JSON file.
    /// Convert the current config to a [String], to be written to
    /// a file.
    ///
    /// The default writes a JSON file, but any format can be used,
    /// using for example the various Serde libraries (`serde_yaml`, etc) -
    /// just overwrite this method.
    fn serialize_config(&self) -> Result<String> {
        Ok(serde_json::to_string_pretty(&self)?)
    }

    /// Set the number of desired cores for analysis, and write it to the
    /// configuration file.
    fn set_number_cores(&mut self, number_cores: NonZeroUsize) -> Result<()> {
        self.base_config_mut().analysis_options.number_cores = number_cores;
        self.write()
    }

    /// Set the desired version for analysis, and write it to the
    /// configuration file.
    fn set_features_version(&mut self, features_version: FeaturesVersion) -> Result<()> {
        self.base_config_mut().analysis_options.features_version = features_version;
        self.write()
    }

    /// Get the number of desired cores for analysis, and write it to the
    /// configuration file.
    fn get_features_version(&self) -> FeaturesVersion {
        self.base_config().analysis_options.features_version
    }

    /// Get the number of desired cores for analysis, and write it to the
    /// configuration file.
    fn get_number_cores(&self) -> NonZeroUsize {
        self.base_config().analysis_options.number_cores
    }

    /// Default implementation to load a config from a JSON file.
    /// Reads from a string.
    ///
    /// If you change the serialization format to use something else
    /// than JSON, you need to also overwrite that function with the
    /// format you chose.
    fn deserialize_config(data: &str) -> Result<Self> {
        Ok(serde_json::from_str(data)?)
    }

    /// Load a config from the specified path, using `deserialize_config`.
    ///
    /// This method can be overriden in the very unlikely case
    /// the user wants to do something Serde cannot.
    fn from_path(path: &str) -> Result<Self> {
        let data = fs::read_to_string(path)?;
        Self::deserialize_config(&data)
    }

    // This default impl is what requires the `Serialize` supertrait
    /// Write the configuration to a file using
    /// [AppConfigTrait::serialize_config].
    ///
    /// This method can be overriden
    /// to not use [AppConfigTrait::serialize_config], in the very unlikely
    /// case the user wants to do something Serde cannot.
    fn write(&self) -> Result<()> {
        let serialized = self.serialize_config()?;
        fs::write(&self.base_config().config_path, serialized)?;
        Ok(())
    }
}

#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
/// The minimum configuration an application needs to work with
/// a [Library].
pub struct BaseConfig {
    /// The path to where the configuration file should be stored,
    /// e.g. `/home/foo/.local/share/bliss-rs/config.json`
    pub config_path: PathBuf,
    /// The path to where the database file should be stored,
    /// e.g. `/home/foo/.local/share/bliss-rs/bliss.db`
    pub database_path: PathBuf,
    /// The analysis options set in the database (number of CPU cores for the
    /// analysis, desired feature version...)
    #[serde(flatten)]
    pub analysis_options: AnalysisOptions,
    /// The mahalanobis matrix used for mahalanobis distance.
    /// Used to customize the distance metric beyond simple euclidean distance.
    /// Uses ndarray's `serde` feature for serialization / deserialization.
    /// Field would look like this:
    /// "m": {"v": 1, "dim": [20, 20], "data": [1.0, 0.0, ..., 1.0]}
    #[serde(default = "default_m")]
    pub m: Array2<f32>,
}

fn default_m() -> Array2<f32> {
    Array2::eye(NUMBER_FEATURES)
}

impl BaseConfig {
    /// Because we spent some time using XDG_DATA_HOME instead of XDG_CONFIG_HOME
    /// as the default folder, we have to jump through some hoops:
    ///
    /// - Legacy path exists, new path doesn't exist => legacy path should be returned
    /// - Legacy path exists, new path exists => new path should be returned
    /// - Legacy path doesn't exist => new path should be returned
    pub(crate) fn get_default_data_folder() -> Result<PathBuf> {
        let error_message = "No suitable path found to store bliss' song database. Consider specifying such a path.";
        let default_folder = env::var("XDG_CONFIG_HOME")
            .map(|path| Path::new(&path).join("bliss-rs"))
            .or_else(|_| {
                config_local_dir()
                    .map(|p| p.join("bliss-rs"))
                    .with_context(|| error_message)
            });

        if let Ok(folder) = &default_folder {
            if folder.exists() {
                return Ok(folder.clone());
            }
        }

        if let Ok(legacy_folder) = BaseConfig::get_legacy_data_folder() {
            if legacy_folder.exists() {
                return Ok(legacy_folder);
            }
        }

        // If neither default_folder nor legacy_folder exist, return the default folder
        default_folder
    }

    fn get_legacy_data_folder() -> Result<PathBuf> {
        let path = match env::var("XDG_DATA_HOME") {
            Ok(path) => Path::new(&path).join("bliss-rs"),
            Err(_) => data_local_dir().with_context(|| "No suitable path found to store bliss' song database. Consider specifying such a path.")?.join("bliss-rs"),
        };
        Ok(path)
    }

    /// Create a new, basic config. Upon calls of `Config.write()`, it will be
    /// written to `config_path`.
    //
    /// Any path omitted will instead default to a "clever" path using
    /// data directory inference. The "clever" thinking is as follows:
    /// - If the user specified only one of the paths, it will put the other
    ///   file in the same folder as the given path.
    /// - If the user specified both paths, it will go with what the user
    ///   chose.
    /// - If the user didn't select any path, it will try to put everything in
    ///   the user's configuration directory, i.e. XDG_CONFIG_HOME.
    ///
    /// The number of cores is the number of cores that should be used for
    /// any analysis. If not provided, it will default to the computer's
    /// number of cores.
    pub fn new(
        config_path: Option<PathBuf>,
        database_path: Option<PathBuf>,
        analysis_options: Option<AnalysisOptions>,
    ) -> Result<Self> {
        let provided_database_path = database_path.is_some();
        let provided_config_path = config_path.is_some();
        let mut final_config_path = {
            // User provided a path; let the future file creation determine
            // whether it points to something valid or not
            if let Some(path) = config_path {
                path
            } else {
                Self::get_default_data_folder()?.join(Path::new("config.json"))
            }
        };

        let mut final_database_path = {
            if let Some(path) = database_path {
                path
            } else {
                Self::get_default_data_folder()?.join(Path::new("songs.db"))
            }
        };

        if provided_database_path && !provided_config_path {
            final_config_path = final_database_path
                .parent()
                .ok_or(BlissError::ProviderError(String::from(
                    "provided database path was invalid.",
                )))?
                .join(Path::new("config.json"))
        } else if !provided_database_path && provided_config_path {
            final_database_path = final_config_path
                .parent()
                .ok_or(BlissError::ProviderError(String::from(
                    "provided config path was invalid.",
                )))?
                .join(Path::new("songs.db"))
        }

        Ok(Self {
            config_path: final_config_path,
            database_path: final_database_path,
            analysis_options: analysis_options.unwrap_or_default(),
            m: Array2::eye(NUMBER_FEATURES),
        })
    }
}

impl AppConfigTrait for BaseConfig {
    fn base_config(&self) -> &BaseConfig {
        self
    }

    fn base_config_mut(&mut self) -> &mut BaseConfig {
        self
    }
}

/// A struct used to hold a collection of [Song]s, with convenience
/// methods to add, remove and update songs.
///
/// Provide it either the `BaseConfig`, or a `Config` extending
/// `BaseConfig`.
/// TODO code example
pub struct Library<Config, D: ?Sized> {
    /// The configuration struct, containing both information
    /// from `BaseConfig` as well as user-defined values.
    pub config: Config,
    /// SQL connection to the database.
    pub sqlite_conn: Arc<Mutex<Connection>>,
    decoder: PhantomData<D>,
}

/// Hold an error that happened while processing songs during analysis.
#[derive(Debug, Eq, PartialEq)]
pub struct ProcessingError {
    /// The path of the song whose analysis was attempted.
    pub song_path: PathBuf,
    /// The actual error string.
    pub error: String,
    /// Features version the analysis was attempted with.
    pub features_version: FeaturesVersion,
}

/// Struct holding both a Bliss song, as well as any extra info
/// that a user would want to store in the database related to that
/// song.
///
/// The only constraint is that `extra_info` must be serializable, so,
/// something like
/// ```no_compile
/// #[derive(Serialize)]
/// struct ExtraInfo {
///     ignore: bool,
///     unique_id: i64,
/// }
/// let extra_info = ExtraInfo { ignore: true, unique_id = 123 };
/// let song = LibrarySong { bliss_song: song, extra_info };
/// ```
/// is totally possible.
#[derive(Debug, PartialEq, Clone)]
pub struct LibrarySong<T: Serialize + DeserializeOwned + Clone> {
    /// Actual bliss song, containing the song's metadata, as well
    /// as the bliss analysis.
    pub bliss_song: Song,
    /// User-controlled information regarding that specific song.
    pub extra_info: T,
}

impl<T: Serialize + DeserializeOwned + Clone> AsRef<Song> for LibrarySong<T> {
    fn as_ref(&self) -> &Song {
        &self.bliss_song
    }
}

/// An enum containing potential sanity errors wrt. database and
/// songs' features version.
#[derive(Debug, PartialEq)]
pub enum SanityError {
    /// If there are songs analyzed with different features version in the
    /// database.
    MultipleVersionsInDB {
        /// The FeaturesVersion found in the database.
        versions: Vec<FeaturesVersion>,
    },
    /// If songs in the database are analyzed with a lower features version
    /// number than the latest version advertised by bliss.
    OldFeaturesVersionInDB {
        /// The oldest version of the features in the database.
        version: FeaturesVersion,
    },
}

// TODO add logging statement
// TODO maybe return number of elements updated / deleted / whatev in analysis
//      functions?
// TODO should it really use anyhow errors?
// TODO make sure that the path to string is consistent
impl<Config: AppConfigTrait, D: ?Sized + DecoderTrait> Library<Config, D> {
    const SQLITE_SCHEMA: &'static str = "
        create table song (
                id integer primary key,
                path text not null unique,
                duration float,
                album_artist text,
                artist text,
                title text,
                album text,
                track_number integer,
                disc_number integer,
                genre text,
                cue_path text,
                audio_file_path text,
                stamp timestamp default current_timestamp,
                version integer not null,
                analyzed boolean default false,
                extra_info json,
                error text
            );
            pragma foreign_keys = on;
            create table feature (
                id integer primary key,
                song_id integer not null,
                feature real not null,
                feature_index integer not null,
                unique(song_id, feature_index),
                foreign key(song_id) references song(id) on delete cascade
            )
        ";
    const SQLITE_MIGRATIONS: &'static [&'static str] = &[
        "",
        "
            alter table song add column track_number_1 integer;
            update song set track_number_1 = s1.cast_track_number from (
                select cast(track_number as int) as cast_track_number, id from song
            ) as s1 where s1.id = song.id and cast(track_number as int) != 0;
            alter table song drop column track_number;
            alter table song rename column track_number_1 to track_number;
        ",
        "alter table song add column disc_number integer;",
        "
            -- Training triplets used to do metric learning, in conjunction with
            -- a human-processed survey. In this table, songs pointed to
            -- by song_1_id and song_2_id are closer together than they
            -- are to the song pointed to by odd_one_out_id, i.e.
            -- d(s1, s2) < d(s1, odd_one_out) and d(s1, s2) < d(s2, odd_one_out)
            create table training_triplet (
                id integer primary key,
                song_1_id integer not null,
                song_2_id integer not null,
                odd_one_out_id integer not null,
                stamp timestamp default current_timestamp,
                foreign key(song_1_id) references song(id) on delete cascade,
                foreign key(song_2_id) references song(id) on delete cascade,
                foreign key(odd_one_out_id) references song(id) on delete cascade
            )
        ",
        // Add the "not null" constraint to the "version" column
        "
            create table song_bak (
                id integer primary key,
                path text not null unique,
                duration float,
                album_artist text,
                artist text,
                title text,
                album text,
                track_number integer,
                disc_number integer,
                genre text,
                cue_path text,
                audio_file_path text,
                stamp timestamp default current_timestamp,
                version integer not null,
                analyzed boolean default false,
                extra_info json,
                error text
            );
            insert into song_bak (
                id, path, duration, album_artist, artist, title, album, track_number,
                disc_number,genre, cue_path, audio_file_path, stamp, version,
                analyzed, extra_info, error
            ) select
                id, path, duration, album_artist, artist, title, album, track_number,
                disc_number,genre, cue_path, audio_file_path, stamp,
                coalesce(version, 1), analyzed, extra_info, error
            from song;
            drop table song;
            alter table song_bak rename to song;
        ",
    ];

    /// Create a new [Library] object from the given Config struct that
    /// implements the [AppConfigTrait].
    /// writing the configuration to the file given in
    /// `config.config_path`.
    ///
    /// This function should only be called once, when a user wishes to
    /// create a completely new "library".
    /// Otherwise, load an existing library file using
    /// [Library::from_config_path].
    pub fn new(config: Config) -> Result<Self> {
        if !config
            .base_config()
            .config_path
            .parent()
            .ok_or_else(|| {
                BlissError::ProviderError(format!(
                    "specified path {} is not a valid file path.",
                    config.base_config().config_path.display()
                ))
            })?
            .is_dir()
        {
            create_dir_all(config.base_config().config_path.parent().unwrap())?;
        }
        let sqlite_conn = Connection::open(&config.base_config().database_path)?;

        Library::<Config, D>::upgrade(&sqlite_conn).map_err(|e| {
            BlissError::ProviderError(format!("Could not run database upgrade: {e}"))
        })?;

        config.write()?;
        Ok(Self {
            config,
            sqlite_conn: Arc::new(Mutex::new(sqlite_conn)),
            decoder: PhantomData,
        })
    }

    fn upgrade(sqlite_conn: &Connection) -> Result<()> {
        let version: u32 = sqlite_conn
            .query_row("pragma user_version", [], |row| row.get(0))
            .map_err(|e| {
                BlissError::ProviderError(format!("Could not get database version: {e}."))
            })?;

        let migrations = Library::<Config, D>::SQLITE_MIGRATIONS;
        match version.cmp(&(migrations.len() as u32)) {
            std::cmp::Ordering::Equal => return Ok(()),
            std::cmp::Ordering::Greater => bail!(format!(
                "bliss-rs version {} is older than the schema version {}",
                version,
                migrations.len()
            )),
            _ => (),
        };

        let number_tables: u32 = sqlite_conn
            .query_row("select count(*) from pragma_table_list", [], |row| {
                row.get(0)
            })
            .map_err(|e| {
                BlissError::ProviderError(format!(
                    "Could not query initial database information: {e}",
                ))
            })?;
        let is_database_new = number_tables <= 2;

        if version == 0 && is_database_new {
            sqlite_conn
                .execute_batch(Library::<Config, D>::SQLITE_SCHEMA)
                .map_err(|e| {
                    BlissError::ProviderError(format!("Could not initialize schema: {e}."))
                })?;
        } else {
            for migration in migrations.iter().skip(version as usize) {
                sqlite_conn.execute_batch(migration).map_err(|e| {
                    BlissError::ProviderError(format!("Could not execute migration: {e}."))
                })?;
            }
        }

        sqlite_conn
            .execute(&format!("pragma user_version = {}", migrations.len()), [])
            .map_err(|e| {
                BlissError::ProviderError(format!("Could not update database version: {e}."))
            })?;

        Ok(())
    }

    /// Load a library from a configuration path.
    ///
    /// If no configuration path is provided, the path is
    /// set using default data folder path.
    pub fn from_config_path(config_path: Option<PathBuf>) -> Result<Self> {
        let config_path: Result<PathBuf> =
            config_path.map_or_else(|| Ok(BaseConfig::new(None, None, None)?.config_path), Ok);
        let config_path = config_path?;
        let data = fs::read_to_string(config_path)?;
        let config = Config::deserialize_config(&data)?;
        let sqlite_conn = Connection::open(&config.base_config().database_path)?;
        Library::<Config, D>::upgrade(&sqlite_conn)?;
        let library = Self {
            config,
            sqlite_conn: Arc::new(Mutex::new(sqlite_conn)),
            decoder: PhantomData,
        };
        Ok(library)
    }

    /// Check whether the library contains songs analyzed with different,
    /// incompatible versions of bliss.
    ///
    /// Returns a vector filled with potential errors. A sane database would return
    /// Ok() with an empty vector.
    pub fn version_sanity_check(&mut self) -> Result<Vec<SanityError>> {
        let mut errors = vec![];
        let connection = self
            .sqlite_conn
            .lock()
            .map_err(|e| BlissError::ProviderError(e.to_string()))?;
        let mut stmt = connection.prepare("select distinct version from song")?;

        let mut features_version: Vec<FeaturesVersion> = stmt
            .query_map([], |row| row.get::<_, FeaturesVersion>(0))?
            .collect::<rusqlite::Result<Vec<_>>>()?;

        features_version.sort();
        if features_version.len() > 1 {
            errors.push(SanityError::MultipleVersionsInDB {
                versions: features_version.to_owned(),
            })
        }
        if features_version
            .iter()
            .any(|features_version_in_db| features_version_in_db != &FeaturesVersion::LATEST)
        {
            errors.push(SanityError::OldFeaturesVersionInDB {
                version: features_version[0],
            });
        }
        Ok(errors)
    }

    /// Create a new [Library] object from a minimal configuration setup,
    /// writing it to `config_path`.
    pub fn new_from_base(
        config_path: Option<PathBuf>,
        database_path: Option<PathBuf>,
        analysis_options: Option<AnalysisOptions>,
    ) -> Result<Self>
    where
        BaseConfig: Into<Config>,
    {
        let base = BaseConfig::new(config_path, database_path, analysis_options)?;
        let config = base.into();
        Self::new(config)
    }

    /// Build a playlist of `playlist_length` items from a set of already analyzed
    /// songs in the library at `song_path`.
    ///
    /// It uses the ExentedIsolationForest score as a distance between songs, and deduplicates
    /// songs that are too close.
    ///
    /// Generating a playlist from a single song is also possible, and is just the special case
    /// where song_paths is a slice of length 1.
    pub fn playlist_from<'a, T: Serialize + DeserializeOwned + Clone + 'a>(
        &self,
        song_paths: &[&str],
    ) -> Result<impl Iterator<Item = LibrarySong<T>> + 'a> {
        self.playlist_from_custom(song_paths, &euclidean_distance, closest_to_songs, true)
    }

    /// Build a playlist of `playlist_length` items from a set of already analyzed
    /// song(s) in the library `initial_song_paths`, using distance metric `distance`,
    /// and sorting function `sort_by`.
    /// Note: The resulting playlist includes the songs specified in `initial_song_paths`
    /// at the beginning. Use [Iterator::skip] on the resulting iterator to avoid it.
    ///
    /// You can use ready-to-use distance metrics such as
    /// [ExtendedIsolationForest](extended_isolation_forest::Forest) or [euclidean_distance],
    /// and ready-to-use sorting functions like [closest_to_songs] or
    /// [crate::playlist::song_to_song].
    ///
    /// If you want to use the sorting functions in a uniform manner, you can do something like
    /// this:
    /// ```
    /// use bliss_audio::library::LibrarySong;
    /// use bliss_audio::playlist::{closest_to_songs, song_to_song};
    ///
    /// // The user would be choosing this
    /// let use_closest_to_songs = true;
    /// let sort = |x: &[LibrarySong<()>],
    ///             y: &[LibrarySong<()>],
    ///             z|
    ///  -> Box<dyn Iterator<Item = LibrarySong<()>>> {
    ///     match use_closest_to_songs {
    ///         false => Box::new(closest_to_songs(x, y, z)),
    ///         true => Box::new(song_to_song(x, y, z)),
    ///     }
    /// };
    /// ```
    /// and use `playlist_from_custom` with that sort as `sort_by`.
    ///
    /// Generating a playlist from a single song is also possible, and is just the special case
    /// where song_paths is a slice with a single song.
    pub fn playlist_from_custom<'a, T, F, I>(
        &self,
        initial_song_paths: &[&str],
        distance: &'a dyn DistanceMetricBuilder,
        sort_by: F,
        deduplicate: bool,
    ) -> Result<impl Iterator<Item = LibrarySong<T>> + 'a>
    where
        T: Serialize + DeserializeOwned + Clone + 'a,
        F: Fn(&[LibrarySong<T>], &[LibrarySong<T>], &'a dyn DistanceMetricBuilder) -> I,
        I: Iterator<Item = LibrarySong<T>> + 'a,
    {
        let initial_songs: Vec<LibrarySong<T>> = initial_song_paths
            .iter()
            .map(|s| {
                self.song_from_path(s).map_err(|_| {
                    BlissError::ProviderError(format!("song '{s}' has not been analyzed"))
                })
            })
            .collect::<Result<Vec<_>, BlissError>>()?;
        // Remove the initial songs, so they don't get
        // sorted in the mess.
        let songs = self
            .songs_from_library()?
            .into_iter()
            .filter(|s| {
                !initial_song_paths.contains(&&*s.bliss_song.path.to_string_lossy().to_string())
            })
            .collect::<Vec<_>>();

        let iterator = sort_by(&initial_songs, &songs, distance);
        let mut iterator: Box<dyn Iterator<Item = LibrarySong<T>>> =
            Box::new(initial_songs.into_iter().chain(iterator));
        if deduplicate {
            iterator = Box::new(dedup_playlist_custom_distance(iterator, None, distance));
        }
        Ok(iterator)
    }

    /// Make a playlist of `number_albums` albums closest to the album
    /// with title `album_title`.
    /// The playlist starts with the album with `album_title`, and contains
    /// `number_albums` on top of that one.
    ///
    /// Returns the songs of each album ordered by bliss' `track_number`.
    pub fn album_playlist_from<T: Serialize + DeserializeOwned + Clone + PartialEq>(
        &self,
        album_title: String,
        number_albums: usize,
    ) -> Result<Vec<LibrarySong<T>>> {
        let album = self.songs_from_album(&album_title)?;
        // Every song should be from the same album. Hopefully...
        let songs = self.songs_from_library()?;
        let playlist = closest_album_to_group(album, songs)?;

        let mut album_count = 0;
        let mut index = 0;
        let mut current_album = Some(album_title);
        for song in playlist.iter() {
            if song.bliss_song.album != current_album {
                album_count += 1;
                if album_count > number_albums {
                    break;
                }
                song.bliss_song.album.clone_into(&mut current_album);
            }
            index += 1;
        }
        let playlist = &playlist[..index];
        Ok(playlist.to_vec())
    }

    /// Analyze and store all songs in `paths` that haven't been already analyzed,
    /// re-analyzing songs with newer feature versions if there was an update
    /// of bliss features.
    ///
    /// Use this function if you don't have any extra data to bundle with each song.
    ///
    /// Setting `delete_everything_else` to true will delete the paths that are
    /// not mentionned in `paths_extra_info` from the database. If you do not
    /// use it, because you only pass the new paths that need to be analyzed to
    /// this function, make sure to delete yourself from the database the songs
    /// that have been deleted from storage.
    ///
    /// If your library
    /// contains CUE files, pass the CUE file path only, and not individual
    /// CUE track names: passing `vec![file.cue]` will add
    /// individual tracks with the `cue_info` field set in the database.
    // TODO: align these functions using maybe a struct. And make it more coherent,
    // we shouldn't be feeding paths to this one...
    pub fn update_library<P: Into<PathBuf>>(
        &mut self,
        paths: Vec<P>,
        delete_everything_else: bool,
        show_progress_bar: bool,
    ) -> Result<()> {
        let paths_extra_info = paths.into_iter().map(|path| (path, ())).collect::<Vec<_>>();
        self.update_library_convert_extra_info(
            paths_extra_info,
            delete_everything_else,
            show_progress_bar,
            |x, _, _| x,
            self.config.base_config().analysis_options,
        )
    }

    /// Analyze and store all songs in `paths` that haven't been already analyzed,
    /// with analysis options (including features version). If the features
    /// version in the analysis options are newer than the ones in the song
    /// database, all those songs are updated.
    ///
    /// Use this function if you don't have any extra data to bundle with each song.
    ///
    /// Setting `delete_everything_else` to true will delete the paths that are
    /// not mentionned in `paths_extra_info` from the database. If you do not
    /// use it, because you only pass the new paths that need to be analyzed to
    /// this function, make sure to delete yourself from the database the songs
    /// that have been deleted from storage.
    ///
    /// If your library
    /// contains CUE files, pass the CUE file path only, and not individual
    /// CUE track names: passing `vec![file.cue]` will add
    /// individual tracks with the `cue_info` field set in the database.
    // TODO: align these functions using maybe a struct. And make it more coherent,
    // we shouldn't be feeding paths to this one...
    pub fn update_library_with_options<P: Into<PathBuf>>(
        &mut self,
        paths: Vec<P>,
        delete_everything_else: bool,
        show_progress_bar: bool,
        analysis_options: AnalysisOptions,
    ) -> Result<()> {
        let paths_extra_info = paths.into_iter().map(|path| (path, ())).collect::<Vec<_>>();
        self.update_library_convert_extra_info(
            paths_extra_info,
            delete_everything_else,
            show_progress_bar,
            |x, _, _| x,
            analysis_options,
        )
    }

    /// Analyze and store all songs in `paths_extra_info` that haven't already
    /// been analyzed, along with some extra metadata serializable, and known
    /// before song analysis.
    ///
    /// Setting `delete_everything_else` to true will delete the paths that are
    /// not mentionned in `paths_extra_info` from the database. If you do not
    /// use it, because you only pass the new paths that need to be analyzed to
    /// this function, make sure to delete yourself from the database the songs
    /// that have been deleted from storage.
    pub fn update_library_extra_info<T: Serialize + DeserializeOwned + Clone, P: Into<PathBuf>>(
        &mut self,
        paths_extra_info: Vec<(P, T)>,
        delete_everything_else: bool,
        show_progress_bar: bool,
    ) -> Result<()> {
        self.update_library_convert_extra_info(
            paths_extra_info,
            delete_everything_else,
            show_progress_bar,
            |extra_info, _, _| extra_info,
            self.config.base_config().analysis_options,
        )
    }

    /// Analyze and store all songs in `paths_extra_info` that haven't
    /// been already analyzed, as well as handling extra, user-specified metadata,
    /// that can't directly be serializable,
    /// or that need input from the analyzed Song to be processed. If you
    /// just want to analyze and store songs along with some directly
    /// serializable values, consider using [Library::update_library_extra_info],
    /// or [Library::update_library] if you just want the analyzed songs
    /// stored as is.
    ///
    /// `paths_extra_info` is a tuple made out of song paths, along
    /// with any extra info you want to store for each song.
    /// If your library
    /// contains CUE files, pass the CUE file path only, and not individual
    /// CUE track names: passing `vec![file.cue]` will add
    /// individual tracks with the `cue_info` field set in the database.
    ///
    /// Setting `delete_everything_else` to true will delete the paths that are
    /// not mentionned in `paths_extra_info` from the database. If you do not
    /// use it, because you only pass the new paths that need to be analyzed to
    /// this function, make sure to delete yourself from the database the songs
    /// that have been deleted from storage.
    ///
    /// `convert_extra_info` is a function that you should specify how
    /// to convert that extra info to something serializable.
    ///
    /// `analysis_options` contains the desired analysis options, i.e. number
    /// of cores and the version of the features you want your library to be
    /// analyzed with. It will reanalyze songs that have features version older
    /// than latest's, and set the config file's features_version to the specified version.
    pub fn update_library_convert_extra_info<
        T: Serialize + DeserializeOwned + Clone,
        U,
        P: Into<PathBuf>,
    >(
        &mut self,
        paths_extra_info: Vec<(P, U)>,
        delete_everything_else: bool,
        show_progress_bar: bool,
        convert_extra_info: fn(U, &Song, &Self) -> T,
        analysis_options: AnalysisOptions,
    ) -> Result<()> {
        let existing_paths = {
            let connection = self
                .sqlite_conn
                .lock()
                .map_err(|e| BlissError::ProviderError(e.to_string()))?;
            let mut path_statement = connection.prepare(
                "
                select
                    path
                    from song where analyzed = true and version = ? order by id
                ",
            )?;
            #[allow(clippy::let_and_return)]
            let return_value = path_statement
                .query_map([analysis_options.features_version], |row| {
                    Ok(row.get_unwrap::<usize, String>(0))
                })?
                .map(|x| PathBuf::from(x.unwrap()))
                .collect::<HashSet<PathBuf>>();
            return_value
        };

        let paths_extra_info: Vec<_> = paths_extra_info
            .into_iter()
            .map(|(x, y)| (x.into(), y))
            .collect();
        let paths: HashSet<_> = paths_extra_info.iter().map(|(p, _)| p.to_owned()).collect();

        if delete_everything_else {
            let existing_paths_old_features_version = {
                let connection = self
                    .sqlite_conn
                    .lock()
                    .map_err(|e| BlissError::ProviderError(e.to_string()))?;
                let mut path_statement = connection.prepare(
                    "
                select
                    path
                    from song where analyzed = true order by id
                ",
                )?;
                #[allow(clippy::let_and_return)]
                let return_value = path_statement
                    .query_map([], |row| Ok(row.get_unwrap::<usize, String>(0)))?
                    .map(|x| PathBuf::from(x.unwrap()))
                    .collect::<HashSet<PathBuf>>();
                return_value
            };

            let paths_to_delete = existing_paths_old_features_version.difference(&paths);

            self.delete_paths(paths_to_delete)?;
        }

        // Can't use hashsets because we need the extra info here too,
        // and U might not be hashable.
        let paths_to_analyze = paths_extra_info
            .into_iter()
            .filter(|(path, _)| !existing_paths.contains(path))
            .collect::<Vec<(PathBuf, U)>>();

        {
            let connection = self
                .sqlite_conn
                .lock()
                .map_err(|e| BlissError::ProviderError(e.to_string()))?;

            if !paths_to_analyze.is_empty() {
                connection.execute(
                    "delete from song where version != ?",
                    params![analysis_options.features_version],
                )?;
            }
        }

        self.analyze_paths_convert_extra_info(
            paths_to_analyze,
            show_progress_bar,
            convert_extra_info,
            analysis_options,
        )
    }

    /// Analyze and store all songs in `paths`.
    ///
    /// Use this function if you don't have any extra data to bundle with each song.
    ///
    /// If your library contains CUE files, pass the CUE file path only, and not individual
    /// CUE track names: passing `vec![file.cue]` will add
    /// individual tracks with the `cue_info` field set in the database.
    pub fn analyze_paths<P: Into<PathBuf>>(
        &mut self,
        paths: Vec<P>,
        show_progress_bar: bool,
    ) -> Result<()> {
        let paths_extra_info = paths.into_iter().map(|path| (path, ())).collect::<Vec<_>>();
        let analysis_options = self.config.base_config().analysis_options;
        self.analyze_paths_convert_extra_info(
            paths_extra_info,
            show_progress_bar,
            |x, _, _| x,
            analysis_options,
        )
    }

    /// Analyze and store all songs in `paths`, setting analysis options such
    /// as features version and the number and cores.
    /// Be careful not to analyze
    /// some songs with a different features version than the rest of the database!
    ///
    /// Use this function if you don't have any extra data to bundle with each song.
    ///
    /// If your library contains CUE files, pass the CUE file path only, and not individual
    /// CUE track names: passing `vec![file.cue]` will add
    /// individual tracks with the `cue_info` field set in the database.
    pub fn analyze_paths_with_options<P: Into<PathBuf>>(
        &mut self,
        paths: Vec<P>,
        show_progress_bar: bool,
        analysis_options: AnalysisOptions,
    ) -> Result<()> {
        let paths_extra_info = paths.into_iter().map(|path| (path, ())).collect::<Vec<_>>();
        self.analyze_paths_convert_extra_info(
            paths_extra_info,
            show_progress_bar,
            |x, _, _| x,
            analysis_options,
        )
    }

    /// Analyze and store all songs in `paths_extra_info`, along with some
    /// extra metadata serializable, and known before song analysis.
    ///
    /// Updates the value of `features_version` in the config, using bliss'
    /// latest version.
    /// If your library
    /// contains CUE files, pass the CUE file path only, and not individual
    /// CUE track names: passing `vec![file.cue]` will add
    /// individual tracks with the `cue_info` field set in the database.
    pub fn analyze_paths_extra_info<
        T: Serialize + DeserializeOwned + std::fmt::Debug + Clone,
        P: Into<PathBuf>,
    >(
        &mut self,
        paths_extra_info: Vec<(P, T)>,
        show_progress_bar: bool,
        analysis_options: AnalysisOptions,
    ) -> Result<()> {
        self.analyze_paths_convert_extra_info(
            paths_extra_info,
            show_progress_bar,
            |extra_info, _, _| extra_info,
            analysis_options,
        )
    }

    /// Analyze and store all songs in `paths_extra_info`, along with some
    /// extra, user-specified metadata, that can't directly be serializable,
    /// or that need input from the analyzed Song to be processed.
    /// If you just want to analyze and store songs, along with some
    /// directly serializable metadata values, consider using
    /// [Library::analyze_paths_extra_info], or [Library::analyze_paths] for
    /// the simpler use cases.
    ///
    /// Updates the value of `features_version` in the config, using bliss'
    /// latest version.
    ///
    /// `paths_extra_info` is a tuple made out of song paths, along
    /// with any extra info you want to store for each song. If your library
    /// contains CUE files, pass the CUE file path only, and not individual
    /// CUE track names: passing `vec![file.cue]` will add
    /// individual tracks with the `cue_info` field set in the database.
    ///
    /// `convert_extra_info` is a function that you should specify
    /// to convert that extra info to something serializable.
    pub fn analyze_paths_convert_extra_info<
        T: Serialize + DeserializeOwned + Clone,
        U,
        P: Into<PathBuf>,
    >(
        &mut self,
        paths_extra_info: Vec<(P, U)>,
        show_progress_bar: bool,
        convert_extra_info: fn(U, &Song, &Self) -> T,
        analysis_options: AnalysisOptions,
    ) -> Result<()> {
        let number_songs = paths_extra_info.len();
        if number_songs == 0 {
            log::info!("No (new) songs found.");
            return Ok(());
        }
        log::info!("Analyzing {number_songs} song(s), this might take some time…",);
        let pb = if show_progress_bar {
            ProgressBar::new(number_songs.try_into().unwrap())
        } else {
            ProgressBar::hidden()
        };
        let style = ProgressStyle::default_bar()
            .template("[{elapsed_precise}] {bar:40} {pos:>7}/{len:7} {wide_msg}")?
            .progress_chars("##-");
        pb.set_style(style);

        let mut paths_extra_info: HashMap<PathBuf, U> = paths_extra_info
            .into_iter()
            .map(|(x, y)| (x.into(), y))
            .collect();
        let mut cue_extra_info: HashMap<PathBuf, String> = HashMap::new();

        let results = D::analyze_paths_with_options(paths_extra_info.keys(), analysis_options);
        let mut success_count = 0;
        let mut failure_count = 0;
        for (path, result) in results {
            if show_progress_bar {
                pb.set_message(format!("Analyzing {}", path.display()));
            }
            match result {
                Ok(song) => {
                    let is_cue = song.cue_info.is_some();
                    // If it's a song that's part of a CUE, its path will be
                    // something like `testcue.flac/CUE_TRACK001`, so we need
                    // to get the path of the main CUE file.
                    let path = {
                        if let Some(cue_info) = song.cue_info.to_owned() {
                            cue_info.cue_path
                        } else {
                            path
                        }
                    };
                    // Some magic to avoid having to depend on T: Clone, because
                    // all CUE tracks on a CUE file have the same extra_info.
                    // This serializes the data, store the serialized version
                    // in a hashmap, and then deserializes that when needed.
                    let extra = {
                        if is_cue && paths_extra_info.contains_key(&path) {
                            let extra = paths_extra_info.remove(&path).unwrap();
                            let e = convert_extra_info(extra, &song, self);
                            cue_extra_info.insert(
                                path,
                                serde_json::to_string(&e)
                                    .map_err(|e| BlissError::ProviderError(e.to_string()))?,
                            );
                            e
                        } else if is_cue {
                            let serialized_extra_info =
                                cue_extra_info.get(&path).unwrap().to_owned();
                            serde_json::from_str(&serialized_extra_info).unwrap()
                        } else {
                            let extra = paths_extra_info.remove(&path).unwrap();
                            convert_extra_info(extra, &song, self)
                        }
                    };
                    let library_song = LibrarySong::<T> {
                        bliss_song: song,
                        extra_info: extra,
                    };
                    self.store_song(&library_song)?;
                    success_count += 1;
                }
                Err(e) => {
                    log::error!(
                        "Analysis of song '{}' failed: {} The error has been stored.",
                        path.display(),
                        e
                    );

                    self.store_failed_song(path, e, analysis_options.features_version)?;
                    failure_count += 1;
                }
            };
            pb.inc(1);
        }
        pb.finish_with_message(format!(
            "Analyzed {success_count} song(s) successfully. {failure_count} Failure(s).",
        ));

        log::info!("Analyzed {success_count} song(s) successfully. {failure_count} Failure(s).",);

        self.config.base_config_mut().analysis_options = analysis_options;
        self.config.write()?;

        Ok(())
    }

    // Get songs from a songs / features statement.
    // BEWARE that the two songs and features query MUST be the same
    fn _songs_from_statement<T: Serialize + DeserializeOwned + Clone, P: Params + Clone>(
        &self,
        songs_statement: &str,
        features_statement: &str,
        params: P,
    ) -> Result<Vec<LibrarySong<T>>> {
        let connection = self
            .sqlite_conn
            .lock()
            .map_err(|e| BlissError::ProviderError(e.to_string()))?;
        let mut songs_statement = connection.prepare(songs_statement)?;
        let mut features_statement = connection.prepare(features_statement)?;
        let song_rows = songs_statement.query_map(params.to_owned(), |row| {
            Ok((row.get(13)?, Self::_song_from_row_closure(row)?))
        })?;
        let feature_rows =
            features_statement.query_map(params, |row| Ok((row.get(1)?, row.get(0)?)))?;

        let mut feature_iterator = feature_rows.into_iter().peekable();
        let mut songs = Vec::new();
        // Poor man's way to double check that each feature correspond to the
        // right song, and group them.
        for row in song_rows {
            let song_id: u32 = row.as_ref().unwrap().0;
            let mut chunk: Vec<f32> = Vec::with_capacity(NUMBER_FEATURES);

            while let Some(first_value) = feature_iterator.peek() {
                let (song_feature_id, feature): (u32, f32) = *first_value.as_ref().unwrap();
                if song_feature_id == song_id {
                    chunk.push(feature);
                    feature_iterator.next();
                } else {
                    break;
                };
            }
            let mut song = row.unwrap().1;
            song.bliss_song.analysis = Analysis::new(chunk, song.bliss_song.features_version)
                .map_err(|_| {
                    BlissError::ProviderError(format!(
                        "Song with ID {} and path {} has a different feature \
                        number than expected. Please rescan or update \
                        the song library.",
                        song_id,
                        song.bliss_song.path.display(),
                    ))
                })?;
            songs.push(song);
        }
        Ok(songs)
    }

    /// Retrieve all songs which have been analyzed with
    /// the bliss version specified in the configuration.
    ///
    /// Returns an error if one or several songs have a different number of
    /// features than they should, indicating the offending song id.
    ///
    // TODO maybe the error should make the song id / song path
    // accessible easily?
    pub fn songs_from_library<T: Serialize + DeserializeOwned + Clone>(
        &self,
    ) -> Result<Vec<LibrarySong<T>>> {
        let songs_statement = "
            select
                path, artist, title, album, album_artist,
                track_number, disc_number, genre, duration, version, extra_info, cue_path,
                audio_file_path, id
                from song where analyzed = true and version = ? order by id
            ";
        let features_statement = "
            select
                feature, song.id from feature join song on song.id = feature.song_id
                where song.analyzed = true and song.version = ? order by song_id, feature_index
                ";
        let params = params![self.config.base_config().analysis_options.features_version];
        self._songs_from_statement(songs_statement, features_statement, params)
    }

    /// Get a LibrarySong from a given album title.
    ///
    /// This will return all songs with corresponding bliss "album" tag,
    /// and will order them by track number.
    pub fn songs_from_album<T: Serialize + DeserializeOwned + Clone>(
        &self,
        album_title: &str,
    ) -> Result<Vec<LibrarySong<T>>> {
        let params = params![
            album_title,
            self.config.base_config().analysis_options.features_version
        ];
        let songs_statement = "
            select
                path, artist, title, album, album_artist,
                track_number, disc_number, genre, duration, version, extra_info, cue_path,
                audio_file_path, id
                from song where album = ? and analyzed = true and version = ?
                order
                by disc_number, track_number;
            ";

        // Get the song's analysis, and attach it to the existing song.
        let features_statement = "
            select
                feature, song.id from feature join song on song.id = feature.song_id
                where album=? and analyzed = true and version = ?
                order by disc_number, track_number;
            ";
        let songs = self._songs_from_statement(songs_statement, features_statement, params)?;
        if songs.is_empty() {
            bail!(BlissError::ProviderError(String::from(
                "target album was not found in the database.",
            )));
        };
        Ok(songs)
    }

    /// Get a LibrarySong from a given file path.
    /// TODO pathbuf here too
    pub fn song_from_path<T: Serialize + DeserializeOwned + Clone>(
        &self,
        song_path: &str,
    ) -> Result<LibrarySong<T>> {
        let connection = self
            .sqlite_conn
            .lock()
            .map_err(|e| BlissError::ProviderError(e.to_string()))?;
        // Get the song's metadata. The analysis is populated yet.
        let mut song = connection.query_row(
            "
            select
                path, artist, title, album, album_artist,
                track_number, disc_number, genre, duration, version, extra_info,
                cue_path, audio_file_path
                from song where path=? and analyzed = true
            ",
            params![song_path],
            Self::_song_from_row_closure,
        )?;

        // Get the song's analysis, and attach it to the existing song.
        let mut stmt = connection.prepare(
            "
            select
                feature from feature join song on song.id = feature.song_id
                where song.path = ? order by feature_index
            ",
        )?;
        let analysis = Analysis::new(
            stmt.query_map(params![song_path], |row| row.get(0))
                .unwrap()
                .map(|x| x.unwrap())
                .collect::<Vec<f32>>(),
            song.bliss_song.features_version,
        )
        .map_err(|_| {
            BlissError::ProviderError(format!(
                "song has more or less than {NUMBER_FEATURES} features",
            ))
        })?;
        song.bliss_song.analysis = analysis;
        Ok(song)
    }

    fn _song_from_row_closure<T: Serialize + DeserializeOwned + Clone>(
        row: &Row,
    ) -> Result<LibrarySong<T>, RusqliteError> {
        let path: String = row.get(0)?;

        let cue_path: Option<String> = row.get(11)?;
        let audio_file_path: Option<String> = row.get(12)?;
        let mut cue_info = None;
        if let Some(cue_path) = cue_path {
            cue_info = Some(CueInfo {
                cue_path: PathBuf::from(cue_path),
                audio_file_path: PathBuf::from(audio_file_path.unwrap()),
            })
        };

        let song = Song {
            path: PathBuf::from(path),
            artist: row
                .get_ref(1)
                .unwrap()
                .as_bytes_or_null()
                .unwrap()
                .map(|v| String::from_utf8_lossy(v).to_string()),
            title: row
                .get_ref(2)
                .unwrap()
                .as_bytes_or_null()
                .unwrap()
                .map(|v| String::from_utf8_lossy(v).to_string()),
            album: row
                .get_ref(3)
                .unwrap()
                .as_bytes_or_null()
                .unwrap()
                .map(|v| String::from_utf8_lossy(v).to_string()),
            album_artist: row
                .get_ref(4)
                .unwrap()
                .as_bytes_or_null()
                .unwrap()
                .map(|v| String::from_utf8_lossy(v).to_string()),
            track_number: row
                .get_ref(5)
                .unwrap()
                .as_i64_or_null()
                .unwrap()
                .map(|v| v as i32),
            disc_number: row
                .get_ref(6)
                .unwrap()
                .as_i64_or_null()
                .unwrap()
                .map(|v| v as i32),
            genre: row
                .get_ref(7)
                .unwrap()
                .as_bytes_or_null()
                .unwrap()
                .map(|v| String::from_utf8_lossy(v).to_string()),
            analysis: Analysis {
                internal_analysis: vec![0.; NUMBER_FEATURES],
                features_version: row.get(9).unwrap(),
            },
            duration: Duration::from_secs_f64(row.get(8).unwrap()),
            features_version: row.get(9).unwrap(),
            cue_info,
        };

        let serialized: Option<String> = row.get(10).unwrap();
        let serialized = serialized.unwrap_or_else(|| "null".into());
        let extra_info = serde_json::from_str(&serialized).unwrap();
        Ok(LibrarySong {
            bliss_song: song,
            extra_info,
        })
    }

    /// Store a [Song] in the database, overidding any existing
    /// song with the same path by that one.
    // TODO to_str() returns an option; return early and avoid panicking
    pub fn store_song<T: Serialize + DeserializeOwned + Clone>(
        &mut self,
        library_song: &LibrarySong<T>,
    ) -> Result<(), BlissError> {
        let mut sqlite_conn = self.sqlite_conn.lock().unwrap();
        let tx = sqlite_conn
            .transaction()
            .map_err(|e| BlissError::ProviderError(e.to_string()))?;
        let song = &library_song.bliss_song;
        let (cue_path, audio_file_path) = match &song.cue_info {
            Some(c) => (
                Some(c.cue_path.to_string_lossy()),
                Some(c.audio_file_path.to_string_lossy()),
            ),
            None => (None, None),
        };
        tx.execute(
            "
            insert into song (
                path, artist, title, album, album_artist,
                duration, track_number, disc_number, genre, analyzed, version, extra_info,
                cue_path, audio_file_path
            )
            values (
                ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14
            )
            on conflict(path)
            do update set
                artist=excluded.artist,
                title=excluded.title,
                album=excluded.album,
                track_number=excluded.track_number,
                disc_number=excluded.disc_number,
                album_artist=excluded.album_artist,
                duration=excluded.duration,
                genre=excluded.genre,
                analyzed=excluded.analyzed,
                version=excluded.version,
                extra_info=excluded.extra_info,
                cue_path=excluded.cue_path,
                audio_file_path=excluded.audio_file_path
            ",
            params![
                song.path.to_str(),
                song.artist,
                song.title,
                song.album,
                song.album_artist,
                song.duration.as_secs_f64(),
                song.track_number,
                song.disc_number,
                song.genre,
                true,
                song.features_version,
                serde_json::to_string(&library_song.extra_info)
                    .map_err(|e| BlissError::ProviderError(e.to_string()))?,
                cue_path,
                audio_file_path,
            ],
        )
        .map_err(|e| BlissError::ProviderError(e.to_string()))?;

        // Override existing features.
        tx.execute(
            "delete from feature where song_id in (select id from song where path = ?1);",
            params![song.path.to_str()],
        )
        .map_err(|e| BlissError::ProviderError(e.to_string()))?;

        for (index, feature) in song.analysis.as_vec().iter().enumerate() {
            tx.execute(
                "
                insert into feature (song_id, feature, feature_index)
                values ((select id from song where path = ?1), ?2, ?3)
                on conflict(song_id, feature_index) do update set feature=excluded.feature;
                ",
                params![song.path.to_str(), feature, index],
            )
            .map_err(|e| BlissError::ProviderError(e.to_string()))?;
        }
        tx.commit()
            .map_err(|e| BlissError::ProviderError(e.to_string()))?;
        Ok(())
    }

    /// Store an errored [Song] in the SQLite database.
    ///
    /// If there already is an existing song with that path, replace it by
    /// the latest failed result.
    pub fn store_failed_song<P: Into<PathBuf>>(
        &mut self,
        song_path: P,
        e: BlissError,
        features_version: FeaturesVersion,
    ) -> Result<()> {
        self.sqlite_conn
            .lock()
            .unwrap()
            .execute(
                "
            insert or replace into song (path, error, version) values (?1, ?2, ?3)
            ",
                params![
                    song_path.into().to_string_lossy().to_string(),
                    e.to_string(),
                    // At this point, FeaturesVersion::LATEST is the best indicator we have
                    // of the version (since we don't have a proper Song).
                    features_version,
                ],
            )
            .map_err(|e| BlissError::ProviderError(e.to_string()))?;
        Ok(())
    }

    /// Return all the songs that failed the analysis.
    pub fn get_failed_songs(&self) -> Result<Vec<ProcessingError>> {
        let conn = self.sqlite_conn.lock().unwrap();
        let mut stmt = conn.prepare(
            "
            select path, error, version
                from song where error is not null order by id
            ",
        )?;
        let rows = stmt.query_map([], |row| {
            Ok(ProcessingError {
                song_path: row.get::<_, String>(0)?.into(),
                error: row.get(1)?,
                features_version: row.get(2)?,
            })
        })?;
        Ok(rows
            .into_iter()
            .map(|r| r.unwrap())
            .collect::<Vec<ProcessingError>>())
    }

    /// Delete a song with path `song_path` from the database.
    ///
    /// Errors out if the song is not in the database.
    pub fn delete_path<P: Into<PathBuf>>(&mut self, song_path: P) -> Result<()> {
        let song_path = song_path.into();
        let count = self
            .sqlite_conn
            .lock()
            .unwrap()
            .execute(
                "
                delete from song where path = ?1;
            ",
                [song_path.to_str()],
            )
            .map_err(|e| BlissError::ProviderError(e.to_string()))?;
        if count == 0 {
            bail!(BlissError::ProviderError(format!(
                "tried to delete song {}, not existing in the database.",
                song_path.display(),
            )));
        }
        Ok(())
    }

    /// Delete a set of songs with paths `song_paths` from the database.
    ///
    /// Will return Ok(count) even if less songs than expected were deleted from the database.
    pub fn delete_paths<P: Into<PathBuf>, I: IntoIterator<Item = P>>(
        &mut self,
        paths: I,
    ) -> Result<usize> {
        let song_paths: Vec<String> = paths
            .into_iter()
            .map(|x| x.into().to_string_lossy().to_string())
            .collect();
        if song_paths.is_empty() {
            return Ok(0);
        };
        let count = self
            .sqlite_conn
            .lock()
            .unwrap()
            .execute(
                &format!(
                    "delete from song where path in ({})",
                    repeat_vars(song_paths.len()),
                ),
                params_from_iter(song_paths),
            )
            .map_err(|e| BlissError::ProviderError(e.to_string()))?;
        Ok(count)
    }
}

// Copied from
// https://docs.rs/rusqlite/latest/rusqlite/struct.ParamsFromIter.html#realistic-use-case
fn repeat_vars(count: usize) -> String {
    assert_ne!(count, 0);
    let mut s = "?,".repeat(count);
    // Remove trailing comma
    s.pop();
    s
}

#[cfg(any(test, feature = "integration-tests"))]
fn data_local_dir() -> Option<PathBuf> {
    Some(PathBuf::from("/tmp/data"))
}

#[cfg(any(test, feature = "integration-tests"))]
fn config_local_dir() -> Option<PathBuf> {
    Some(PathBuf::from("/tmp/"))
}

#[cfg(test)]
// TODO refactor (especially the helper functions)
// TODO the tests should really open a songs.db
// TODO test with invalid UTF-8
mod test {
    use super::*;
    use crate::{decoder::PreAnalyzedSong, Analysis, NUMBER_FEATURES};
    use ndarray::Array1;
    use pretty_assertions::assert_eq;
    use serde::{de::DeserializeOwned, Deserialize};
    use serde_json::Value;
    use std::thread;
    use std::{convert::TryInto, fmt::Debug, str::FromStr, sync::MutexGuard, time::Duration};
    use tempdir::TempDir;

    #[cfg(feature = "ffmpeg")]
    use crate::song::decoder::ffmpeg::FFmpegDecoder as Decoder;
    use crate::song::decoder::Decoder as DecoderTrait;

    struct DummyDecoder;

    // Here to test an ffmpeg-agnostic library
    impl DecoderTrait for DummyDecoder {
        fn decode(_: &Path) -> crate::BlissResult<crate::decoder::PreAnalyzedSong> {
            Ok(PreAnalyzedSong::default())
        }
    }

    #[derive(Deserialize, Serialize, Debug, PartialEq, Clone, Default)]
    struct ExtraInfo {
        ignore: bool,
        metadata_bliss_does_not_have: String,
    }

    #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)]
    struct CustomConfig {
        #[serde(flatten)]
        base_config: BaseConfig,
        second_path_to_music_library: String,
        ignore_wav_files: bool,
    }

    impl AppConfigTrait for CustomConfig {
        fn base_config(&self) -> &BaseConfig {
            &self.base_config
        }

        fn base_config_mut(&mut self) -> &mut BaseConfig {
            &mut self.base_config
        }
    }

    fn nzus(i: usize) -> NonZeroUsize {
        NonZeroUsize::new(i).unwrap()
    }

    // Returning the TempDir here, so it doesn't go out of scope, removing
    // the directory.
    //
    // Setup a test library made of analyzed songs, with every field being different,
    // as well as an unanalyzed song and a song analyzed with a previous version.
    //
    // TODO the SQL database should be populated with the actual songs created here using
    // format strings
    #[cfg(feature = "ffmpeg")]
    fn setup_test_library() -> (
        Library<BaseConfig, Decoder>,
        TempDir,
        (
            LibrarySong<ExtraInfo>,
            LibrarySong<ExtraInfo>,
            LibrarySong<ExtraInfo>,
            LibrarySong<ExtraInfo>,
            LibrarySong<ExtraInfo>,
            LibrarySong<ExtraInfo>,
            LibrarySong<ExtraInfo>,
            LibrarySong<ExtraInfo>,
        ),
    ) {
        let config_dir = TempDir::new("coucou").unwrap();
        let config_file = config_dir.path().join("config.json");
        let database_file = config_dir.path().join("bliss.db");
        let library = Library::<BaseConfig, Decoder>::new_from_base(
            Some(config_file),
            Some(database_file),
            None,
        )
        .unwrap();

        let analysis_vector = (0..NUMBER_FEATURES)
            .map(|x| x as f32 / 10.)
            .collect::<Vec<f32>>();

        let song = Song {
            path: "/path/to/song1001".into(),
            artist: Some("Artist1001".into()),
            title: Some("Title1001".into()),
            album: Some("An Album1001".into()),
            album_artist: Some("An Album Artist1001".into()),
            track_number: Some(3),
            disc_number: Some(1),
            genre: Some("Electronica1001".into()),
            analysis: Analysis {
                internal_analysis: analysis_vector,
                features_version: FeaturesVersion::LATEST,
            },
            duration: Duration::from_secs(310),
            features_version: FeaturesVersion::LATEST,
            cue_info: None,
        };
        let first_song = LibrarySong {
            bliss_song: song,
            extra_info: ExtraInfo {
                ignore: true,
                metadata_bliss_does_not_have: String::from("/path/to/charlie1001"),
            },
        };

        let analysis_vector = (0..NUMBER_FEATURES)
            .map(|x| x as f32 + 10.)
            .collect::<Vec<f32>>();

        let song = Song {
            path: "/path/to/song2001".into(),
            artist: Some("Artist2001".into()),
            title: Some("Title2001".into()),
            album: Some("An Album2001".into()),
            album_artist: Some("An Album Artist2001".into()),
            track_number: Some(2),
            disc_number: Some(1),
            genre: Some("Electronica2001".into()),
            analysis: Analysis {
                internal_analysis: analysis_vector,
                features_version: FeaturesVersion::LATEST,
            },
            duration: Duration::from_secs(410),
            features_version: FeaturesVersion::LATEST,
            cue_info: None,
        };
        let second_song = LibrarySong {
            bliss_song: song,
            extra_info: ExtraInfo {
                ignore: false,
                metadata_bliss_does_not_have: String::from("/path/to/charlie2001"),
            },
        };

        let analysis_vector = (0..NUMBER_FEATURES)
            .map(|x| x as f32 + 10.)
            .collect::<Vec<f32>>();

        let song = Song {
            path: "/path/to/song2201".into(),
            artist: Some("Artist2001".into()),
            title: Some("Title2001".into()),
            album: Some("An Album2001".into()),
            album_artist: Some("An Album Artist2001".into()),
            track_number: Some(1),
            disc_number: Some(2),
            genre: Some("Electronica2001".into()),
            analysis: Analysis {
                internal_analysis: analysis_vector,
                features_version: FeaturesVersion::LATEST,
            },
            duration: Duration::from_secs(410),
            features_version: FeaturesVersion::LATEST,
            cue_info: None,
        };
        let second_song_dupe = LibrarySong {
            bliss_song: song,
            extra_info: ExtraInfo {
                ignore: false,
                metadata_bliss_does_not_have: String::from("/path/to/charlie2201"),
            },
        };

        let analysis_vector = (0..NUMBER_FEATURES)
            .map(|x| x as f32 / 2.)
            .collect::<Vec<f32>>();

        let song = Song {
            path: "/path/to/song5001".into(),
            artist: Some("Artist5001".into()),
            title: Some("Title5001".into()),
            album: Some("An Album1001".into()),
            album_artist: Some("An Album Artist5001".into()),
            track_number: Some(1),
            disc_number: Some(1),
            genre: Some("Electronica5001".into()),
            analysis: Analysis {
                internal_analysis: analysis_vector,
                features_version: FeaturesVersion::LATEST,
            },
            duration: Duration::from_secs(610),
            features_version: FeaturesVersion::LATEST,
            cue_info: None,
        };
        let third_song = LibrarySong {
            bliss_song: song,
            extra_info: ExtraInfo {
                ignore: false,
                metadata_bliss_does_not_have: String::from("/path/to/charlie5001"),
            },
        };

        let analysis_vector = (0..NUMBER_FEATURES)
            .map(|x| x as f32 * 0.9)
            .collect::<Vec<f32>>();

        let song = Song {
            path: "/path/to/song6001".into(),
            artist: Some("Artist6001".into()),
            title: Some("Title6001".into()),
            album: Some("An Album2001".into()),
            album_artist: Some("An Album Artist6001".into()),
            track_number: Some(1),
            disc_number: Some(1),
            genre: Some("Electronica6001".into()),
            analysis: Analysis {
                internal_analysis: analysis_vector,
                features_version: FeaturesVersion::LATEST,
            },
            duration: Duration::from_secs(710),
            features_version: FeaturesVersion::LATEST,
            cue_info: None,
        };
        let fourth_song = LibrarySong {
            bliss_song: song,
            extra_info: ExtraInfo {
                ignore: false,
                metadata_bliss_does_not_have: String::from("/path/to/charlie6001"),
            },
        };

        let analysis_vector = (0..NUMBER_FEATURES)
            .map(|x| x as f32 * 50.)
            .collect::<Vec<f32>>();

        let song = Song {
            path: "/path/to/song7001".into(),
            artist: Some("Artist7001".into()),
            title: Some("Title7001".into()),
            album: Some("An Album7001".into()),
            album_artist: Some("An Album Artist7001".into()),
            track_number: Some(1),
            disc_number: Some(1),
            genre: Some("Electronica7001".into()),
            analysis: Analysis {
                internal_analysis: analysis_vector,
                features_version: FeaturesVersion::LATEST,
            },
            duration: Duration::from_secs(810),
            features_version: FeaturesVersion::LATEST,
            cue_info: None,
        };
        let fifth_song = LibrarySong {
            bliss_song: song,
            extra_info: ExtraInfo {
                ignore: false,
                metadata_bliss_does_not_have: String::from("/path/to/charlie7001"),
            },
        };

        let analysis_vector = (0..NUMBER_FEATURES)
            .map(|x| x as f32 * 100.)
            .collect::<Vec<f32>>();

        let song = Song {
            path: "/path/to/cuetrack.cue/CUE_TRACK001".into(),
            artist: Some("CUE Artist".into()),
            title: Some("CUE Title 01".into()),
            album: Some("CUE Album".into()),
            album_artist: Some("CUE Album Artist".into()),
            track_number: Some(1),
            disc_number: Some(1),
            genre: None,
            analysis: Analysis {
                internal_analysis: analysis_vector,
                features_version: FeaturesVersion::LATEST,
            },
            duration: Duration::from_secs(810),
            features_version: FeaturesVersion::LATEST,
            cue_info: Some(CueInfo {
                cue_path: PathBuf::from("/path/to/cuetrack.cue"),
                audio_file_path: PathBuf::from("/path/to/cuetrack.flac"),
            }),
        };
        let sixth_song = LibrarySong {
            bliss_song: song,
            extra_info: ExtraInfo {
                ignore: false,
                metadata_bliss_does_not_have: String::from("/path/to/charlie7001"),
            },
        };

        let analysis_vector = (0..NUMBER_FEATURES)
            .map(|x| x as f32 * 101.)
            .collect::<Vec<f32>>();

        let song = Song {
            path: "/path/to/cuetrack.cue/CUE_TRACK002".into(),
            artist: Some("CUE Artist".into()),
            title: Some("CUE Title 02".into()),
            album: Some("CUE Album".into()),
            album_artist: Some("CUE Album Artist".into()),
            track_number: Some(2),
            disc_number: Some(1),
            genre: None,
            analysis: Analysis {
                internal_analysis: analysis_vector,
                features_version: FeaturesVersion::LATEST,
            },
            duration: Duration::from_secs(910),
            features_version: FeaturesVersion::LATEST,
            cue_info: Some(CueInfo {
                cue_path: PathBuf::from("/path/to/cuetrack.cue"),
                audio_file_path: PathBuf::from("/path/to/cuetrack.flac"),
            }),
        };
        let seventh_song = LibrarySong {
            bliss_song: song,
            extra_info: ExtraInfo {
                ignore: false,
                metadata_bliss_does_not_have: String::from("/path/to/charlie7001"),
            },
        };

        {
            let connection = library.sqlite_conn.lock().unwrap();
            connection
                .execute(
                    &format!(
                        "
                    insert into song (
                        id, path, artist, title, album, album_artist, track_number,
                        disc_number, genre, duration, analyzed, version, extra_info,
                        cue_path, audio_file_path, error
                    ) values (
                        1001, '/path/to/song1001', 'Artist1001', 'Title1001', 'An Album1001',
                        'An Album Artist1001', 3, 1, 'Electronica1001', 310, true,
                        {new_version}, '{{\"ignore\": true, \"metadata_bliss_does_not_have\":
                        \"/path/to/charlie1001\"}}', null, null, null
                    ),
                    (
                        2001, '/path/to/song2001', 'Artist2001', 'Title2001', 'An Album2001',
                        'An Album Artist2001', 2, 1, 'Electronica2001', 410, true,
                        {new_version}, '{{\"ignore\": false, \"metadata_bliss_does_not_have\":
                        \"/path/to/charlie2001\"}}', null, null, null
                    ),
                    (
                        2201, '/path/to/song2201', 'Artist2001', 'Title2001', 'An Album2001',
                        'An Album Artist2001', 1, 2, 'Electronica2001', 410, true,
                        {new_version}, '{{\"ignore\": false, \"metadata_bliss_does_not_have\":
                        \"/path/to/charlie2201\"}}', null, null, null
                    ),
                    (
                        3001, '/path/to/song3001', null, null, null,
                        null, null, null, null, null, false, {new_version}, '{{}}', null, null, null
                    ),
                    (
                        4001, '/path/to/song4001', 'Artist4001', 'Title4001', 'An Album4001',
                        'An Album Artist4001', 1, 1, 'Electronica4001', 510, true,
                        {old_version}, '{{\"ignore\": false, \"metadata_bliss_does_not_have\":
                        \"/path/to/charlie4001\"}}', null, null, null
                    ),
                    (
                        5001, '/path/to/song5001', 'Artist5001', 'Title5001', 'An Album1001',
                        'An Album Artist5001', 1, 1, 'Electronica5001', 610, true,
                        {new_version}, '{{\"ignore\": false, \"metadata_bliss_does_not_have\":
                        \"/path/to/charlie5001\"}}', null, null, null
                    ),
                    (
                        6001, '/path/to/song6001', 'Artist6001', 'Title6001', 'An Album2001',
                        'An Album Artist6001', 1, 1, 'Electronica6001', 710, true,
                        {new_version}, '{{\"ignore\": false, \"metadata_bliss_does_not_have\":
                        \"/path/to/charlie6001\"}}', null, null, null
                    ),
                    (
                        7001, '/path/to/song7001', 'Artist7001', 'Title7001', 'An Album7001',
                        'An Album Artist7001', 1, 1, 'Electronica7001', 810, true,
                        {new_version}, '{{\"ignore\": false, \"metadata_bliss_does_not_have\":
                        \"/path/to/charlie7001\"}}', null, null, null
                    ),
                    (
                        7002, '/path/to/cuetrack.cue/CUE_TRACK001', 'CUE Artist',
                        'CUE Title 01', 'CUE Album',
                        'CUE Album Artist', 1, 1, null, 810, true,
                        {new_version}, '{{\"ignore\": false, \"metadata_bliss_does_not_have\":
                        \"/path/to/charlie7001\"}}', '/path/to/cuetrack.cue',
                        '/path/to/cuetrack.flac', null
                    ),
                    (
                        7003, '/path/to/cuetrack.cue/CUE_TRACK002', 'CUE Artist',
                        'CUE Title 02', 'CUE Album',
                        'CUE Album Artist', 2, 1, null, 910, true,
                        {new_version}, '{{\"ignore\": false, \"metadata_bliss_does_not_have\":
                        \"/path/to/charlie7001\"}}', '/path/to/cuetrack.cue',
                        '/path/to/cuetrack.flac', null
                    ),
                    (
                        8001, '/path/to/song8001', 'Artist8001', 'Title8001', 'An Album1001',
                        'An Album Artist8001', 3, 1, 'Electronica8001', 910, true,
                        {old_version}, '{{\"ignore\": false, \"metadata_bliss_does_not_have\":
                        \"/path/to/charlie8001\"}}', null, null, null
                    ),
                    (
                        9001, './data/s16_stereo_22_5kHz.flac', 'Artist9001', 'Title9001',
                        'An Album9001', 'An Album Artist8001', 3, 1, 'Electronica8001',
                        1010, true, {old_version}, '{{\"ignore\": false, \"metadata_bliss_does_not_have\":
                        \"/path/to/charlie7001\"}}', null, null, null
                    ),
                    (
                        404, './data/not-existing.m4a', null, null,
                        null, null, null, null, null,
                        null, false, {old_version}, null, null, null, 'error finding the file'
                    ),
                    (
                        502, './data/invalid-file.m4a', null, null,
                        null, null, null, null, null,
                        null, false, {old_version}, null, null, null, 'error decoding the file'
                    );
                    ",
                        new_version = FeaturesVersion::LATEST as u16,
                        old_version = FeaturesVersion::Version1 as u16,
                    ),
                    [],
                )
                .unwrap();
            for index in 0..NUMBER_FEATURES {
                connection
                    .execute(
                        "
                            insert into feature(song_id, feature, feature_index)
                            values
                                (1001, ?2, ?1),
                                (2001, ?3, ?1),
                                (3001, ?4, ?1),
                                (5001, ?5, ?1),
                                (6001, ?6, ?1),
                                (7001, ?7, ?1),
                                (7002, ?8, ?1),
                                (7003, ?9, ?1),
                                (2201, ?10, ?1);
                            ",
                        params![
                            index,
                            index as f32 / 10.,
                            index as f32 + 10.,
                            index as f32 / 10. + 1.,
                            index as f32 / 2.,
                            index as f32 * 0.9,
                            index as f32 * 50.,
                            index as f32 * 100.,
                            index as f32 * 101.,
                            index as f32 + 10.,
                        ],
                    )
                    .unwrap();
            }
            // Imaginary version 0 of bliss with less features.
            for index in 0..NUMBER_FEATURES - 5 {
                connection
                    .execute(
                        "
                            insert into feature(song_id, feature, feature_index)
                            values
                                (8001, ?2, ?1),
                                (9001, ?3, ?1);
                            ",
                        params![index, index as f32 / 20., index + 1],
                    )
                    .unwrap();
            }
        }
        (
            library,
            config_dir,
            (
                first_song,
                second_song,
                second_song_dupe,
                third_song,
                fourth_song,
                fifth_song,
                sixth_song,
                seventh_song,
            ),
        )
    }

    fn _library_song_from_database<T: DeserializeOwned + Serialize + Clone + Debug>(
        connection: MutexGuard<Connection>,
        song_path: &str,
    ) -> LibrarySong<T> {
        let mut song = connection
            .query_row(
                "
            select
                path, artist, title, album, album_artist,
                track_number, disc_number, genre, duration, version, extra_info,
                cue_path, audio_file_path
                from song where path=?
            ",
                params![song_path],
                |row| {
                    let path: String = row.get(0)?;
                    let cue_path: Option<String> = row.get(11)?;
                    let audio_file_path: Option<String> = row.get(12)?;
                    let mut cue_info = None;
                    if let Some(cue_path) = cue_path {
                        cue_info = Some(CueInfo {
                            cue_path: PathBuf::from(cue_path),
                            audio_file_path: PathBuf::from(audio_file_path.unwrap()),
                        })
                    };
                    let features_version: FeaturesVersion = row.get(9).unwrap();
                    let song = Song {
                        path: PathBuf::from(path),
                        artist: row.get(1).unwrap(),
                        title: row.get(2).unwrap(),
                        album: row.get(3).unwrap(),
                        album_artist: row.get(4).unwrap(),
                        track_number: row.get(5).unwrap(),
                        disc_number: row.get(6).unwrap(),
                        genre: row.get(7).unwrap(),
                        analysis: Analysis {
                            internal_analysis: vec![0.; features_version.feature_count()],
                            features_version: features_version,
                        },
                        duration: Duration::from_secs_f64(row.get(8).unwrap()),
                        features_version: features_version,
                        cue_info,
                    };

                    let serialized: String = row.get(10).unwrap();
                    let extra_info = serde_json::from_str(&serialized).unwrap();
                    Ok(LibrarySong {
                        bliss_song: song,
                        extra_info,
                    })
                },
            )
            .expect("Song does not exist in the database");
        let mut stmt = connection
            .prepare(
                "
            select
                feature from feature join song on song.id = feature.song_id
                where song.path = ? order by feature_index
            ",
            )
            .unwrap();
        let analysis_vector = Analysis {
            internal_analysis: stmt
                .query_map(params![song_path], |row| row.get(0))
                .unwrap()
                .into_iter()
                .map(|x| x.unwrap())
                .collect::<Vec<f32>>()
                .try_into()
                .unwrap(),
            features_version: song.bliss_song.analysis.features_version,
        };
        song.bliss_song.analysis = analysis_vector;
        song
    }

    fn _basic_song_from_database(connection: MutexGuard<Connection>, song_path: &str) -> Song {
        let mut expected_song = connection
            .query_row(
                "
            select
                path, artist, title, album, album_artist,
                track_number, disc_number, genre, duration, version
                from song where path=? and analyzed = true
            ",
                params![song_path],
                |row| {
                    let path: String = row.get(0)?;
                    Ok(Song {
                        path: PathBuf::from(path),
                        artist: row.get(1).unwrap(),
                        title: row.get(2).unwrap(),
                        album: row.get(3).unwrap(),
                        album_artist: row.get(4).unwrap(),
                        track_number: row.get(5).unwrap(),
                        disc_number: row.get(6).unwrap(),
                        genre: row.get(7).unwrap(),
                        analysis: Analysis {
                            internal_analysis: vec![0.; NUMBER_FEATURES],
                            features_version: FeaturesVersion::Version2,
                        },
                        duration: Duration::from_secs_f64(row.get(8).unwrap()),
                        features_version: row.get(9).unwrap(),
                        cue_info: None,
                    })
                },
            )
            .expect("Song is probably not in the db");
        let mut stmt = connection
            .prepare(
                "
            select
                feature from feature join song on song.id = feature.song_id
                where song.path = ? order by feature_index
            ",
            )
            .unwrap();
        let expected_analysis_vector = Analysis {
            internal_analysis: stmt
                .query_map(params![song_path], |row| row.get(0))
                .unwrap()
                .into_iter()
                .map(|x| x.unwrap())
                .collect::<Vec<f32>>()
                .try_into()
                .map_err(|v| {
                    BlissError::ProviderError(format!("Could not retrieve analysis for song {} that was supposed to be analyzed: {:?}.", song_path, v))
                })
                .unwrap(),
                features_version: FeaturesVersion::Version2,
        };
        expected_song.analysis = expected_analysis_vector;
        expected_song
    }

    fn _generate_basic_song(path: Option<String>) -> Song {
        let path = path.unwrap_or_else(|| "/path/to/song".into());
        // Add some "randomness" to the features
        let analysis_vector = (0..NUMBER_FEATURES)
            .map(|x| x as f32 + 0.1)
            .collect::<Vec<f32>>();
        Song {
            path: path.into(),
            artist: Some("An Artist".into()),
            title: Some("Title".into()),
            album: Some("An Album".into()),
            album_artist: Some("An Album Artist".into()),
            track_number: Some(3),
            disc_number: Some(1),
            genre: Some("Electronica".into()),
            analysis: Analysis {
                internal_analysis: analysis_vector,
                features_version: FeaturesVersion::Version2,
            },
            duration: Duration::from_secs(80),
            features_version: FeaturesVersion::LATEST,
            cue_info: None,
        }
    }

    fn _generate_library_song(path: Option<String>) -> LibrarySong<ExtraInfo> {
        let song = _generate_basic_song(path);
        let extra_info = ExtraInfo {
            ignore: true,
            metadata_bliss_does_not_have: "FoobarIze".into(),
        };
        LibrarySong {
            bliss_song: song,
            extra_info,
        }
    }

    fn first_factor_distance(a: &Array1<f32>, b: &Array1<f32>) -> f32 {
        (a[1] - b[1]).abs()
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_playlist_song_not_existing() {
        let (library, _temp_dir, _) = setup_test_library();
        assert!(library
            .playlist_from::<ExtraInfo>(&["not-existing"])
            .is_err());
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_simple_playlist() {
        let (library, _temp_dir, _) = setup_test_library();
        let songs: Vec<LibrarySong<ExtraInfo>> = library
            .playlist_from(&["/path/to/song2001"])
            .unwrap()
            .collect();
        assert_eq!(
            vec![
                "/path/to/song2001",
                "/path/to/song6001",
                "/path/to/song5001",
                "/path/to/song1001",
                "/path/to/song7001",
                "/path/to/cuetrack.cue/CUE_TRACK001",
                "/path/to/cuetrack.cue/CUE_TRACK002",
            ],
            songs
                .into_iter()
                .map(|s| s.bliss_song.path.to_string_lossy().to_string())
                .collect::<Vec<String>>(),
        )
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_playlist_dupe_order_preserved() {
        let (library, _temp_dir, _) = setup_test_library();
        let songs: Vec<LibrarySong<ExtraInfo>> = library
            .playlist_from_custom(
                &["/path/to/song2201"],
                &euclidean_distance,
                closest_to_songs,
                false,
            )
            .unwrap()
            .collect();
        assert_eq!(
            vec![
                "/path/to/song2201",
                "/path/to/song2001",
                "/path/to/song6001",
                "/path/to/song5001",
                "/path/to/song1001",
                "/path/to/song7001",
                "/path/to/cuetrack.cue/CUE_TRACK001",
                "/path/to/cuetrack.cue/CUE_TRACK002",
            ],
            songs
                .into_iter()
                .map(|s| s.bliss_song.path.to_string_lossy().to_string())
                .collect::<Vec<String>>(),
        )
    }

    fn first_factor_divided_by_30_distance(a: &Array1<f32>, b: &Array1<f32>) -> f32 {
        ((a[1] - b[1]).abs() / 30.).floor()
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_playlist_deduplication() {
        let (library, _temp_dir, _) = setup_test_library();
        let songs: Vec<LibrarySong<ExtraInfo>> = library
            .playlist_from_custom(
                &["/path/to/song2001"],
                &first_factor_divided_by_30_distance,
                closest_to_songs,
                true,
            )
            .unwrap()
            .collect();
        assert_eq!(
            vec![
                "/path/to/song2001",
                "/path/to/song7001",
                "/path/to/cuetrack.cue/CUE_TRACK001",
            ],
            songs
                .into_iter()
                .map(|s| s.bliss_song.path.to_string_lossy().to_string())
                .collect::<Vec<String>>(),
        );

        let songs: Vec<LibrarySong<ExtraInfo>> = library
            .playlist_from_custom(
                &["/path/to/song2001"],
                &first_factor_distance,
                &closest_to_songs,
                true,
            )
            .unwrap()
            .collect();
        assert_eq!(
            vec![
                "/path/to/song2001",
                "/path/to/song6001",
                "/path/to/song5001",
                "/path/to/song1001",
                "/path/to/song7001",
                "/path/to/cuetrack.cue/CUE_TRACK001",
                "/path/to/cuetrack.cue/CUE_TRACK002",
            ],
            songs
                .into_iter()
                .map(|s| s.bliss_song.path.to_string_lossy().to_string())
                .collect::<Vec<String>>(),
        )
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_playlist_take() {
        let (library, _temp_dir, _) = setup_test_library();
        let songs: Vec<LibrarySong<ExtraInfo>> = library
            .playlist_from(&["/path/to/song2001"])
            .unwrap()
            .take(4)
            .collect();
        assert_eq!(
            vec![
                "/path/to/song2001",
                "/path/to/song6001",
                "/path/to/song5001",
                "/path/to/song1001",
            ],
            songs
                .into_iter()
                .map(|s| s.bliss_song.path.to_string_lossy().to_string())
                .collect::<Vec<String>>(),
        )
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_custom_playlist_distance() {
        let (library, _temp_dir, _) = setup_test_library();
        let songs: Vec<LibrarySong<ExtraInfo>> = library
            .playlist_from_custom(
                &["/path/to/song2001"],
                &first_factor_distance,
                closest_to_songs,
                false,
            )
            .unwrap()
            .collect();
        assert_eq!(
            vec![
                "/path/to/song2001",
                "/path/to/song2201",
                "/path/to/song6001",
                "/path/to/song5001",
                "/path/to/song1001",
                "/path/to/song7001",
                "/path/to/cuetrack.cue/CUE_TRACK001",
                "/path/to/cuetrack.cue/CUE_TRACK002",
            ],
            songs
                .into_iter()
                .map(|s| s.bliss_song.path.to_string_lossy().to_string())
                .collect::<Vec<String>>(),
        )
    }

    fn custom_sort(
        _: &[LibrarySong<ExtraInfo>],
        songs: &[LibrarySong<ExtraInfo>],
        _distance: &dyn DistanceMetricBuilder,
    ) -> impl Iterator<Item = LibrarySong<ExtraInfo>> {
        let mut songs = songs.to_vec();
        songs.sort_by(|s1, s2| s1.bliss_song.path.cmp(&s2.bliss_song.path));
        songs.to_vec().into_iter()
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_custom_playlist_sort() {
        let (library, _temp_dir, _) = setup_test_library();
        let songs: Vec<LibrarySong<ExtraInfo>> = library
            .playlist_from_custom(
                &["/path/to/song2001"],
                &euclidean_distance,
                custom_sort,
                false,
            )
            .unwrap()
            .collect();
        assert_eq!(
            vec![
                "/path/to/song2001",
                "/path/to/cuetrack.cue/CUE_TRACK001",
                "/path/to/cuetrack.cue/CUE_TRACK002",
                "/path/to/song1001",
                "/path/to/song2201",
                "/path/to/song5001",
                "/path/to/song6001",
                "/path/to/song7001",
            ],
            songs
                .into_iter()
                .map(|s| s.bliss_song.path.to_string_lossy().to_string())
                .collect::<Vec<String>>(),
        )
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_album_playlist() {
        let (library, _temp_dir, _) = setup_test_library();
        let album: Vec<LibrarySong<ExtraInfo>> = library
            .album_playlist_from("An Album1001".to_string(), 20)
            .unwrap();
        assert_eq!(
            vec![
                // First album.
                "/path/to/song5001".to_string(),
                "/path/to/song1001".to_string(),
                // Second album, well ordered, disc 1
                "/path/to/song6001".to_string(),
                "/path/to/song2001".to_string(),
                // Second album disc 2
                "/path/to/song2201".to_string(),
                // Third album.
                "/path/to/song7001".to_string(),
                // Fourth album.
                "/path/to/cuetrack.cue/CUE_TRACK001".to_string(),
                "/path/to/cuetrack.cue/CUE_TRACK002".to_string(),
            ],
            album
                .into_iter()
                .map(|s| s.bliss_song.path.to_string_lossy().to_string())
                .collect::<Vec<_>>(),
        )
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_album_playlist_crop() {
        let (library, _temp_dir, _) = setup_test_library();
        let album: Vec<LibrarySong<ExtraInfo>> = library
            .album_playlist_from("An Album1001".to_string(), 1)
            .unwrap();
        assert_eq!(
            vec![
                // First album.
                "/path/to/song5001".to_string(),
                "/path/to/song1001".to_string(),
                // Second album, well ordered.
                "/path/to/song6001".to_string(),
                "/path/to/song2001".to_string(),
                "/path/to/song2201".to_string(),
            ],
            album
                .into_iter()
                .map(|s| s.bliss_song.path.to_string_lossy().to_string())
                .collect::<Vec<_>>(),
        )
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_songs_from_album() {
        let (library, _temp_dir, _) = setup_test_library();
        let album: Vec<LibrarySong<ExtraInfo>> = library.songs_from_album("An Album1001").unwrap();
        assert_eq!(
            vec![
                "/path/to/song5001".to_string(),
                "/path/to/song1001".to_string()
            ],
            album
                .into_iter()
                .map(|s| s.bliss_song.path.to_string_lossy().to_string())
                .collect::<Vec<_>>(),
        )
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_songs_from_album_proper_features_version() {
        let (library, _temp_dir, _) = setup_test_library();
        let album: Vec<LibrarySong<ExtraInfo>> = library.songs_from_album("An Album1001").unwrap();
        assert_eq!(
            vec![
                "/path/to/song5001".to_string(),
                "/path/to/song1001".to_string()
            ],
            album
                .into_iter()
                .map(|s| s.bliss_song.path.to_string_lossy().to_string())
                .collect::<Vec<_>>(),
        )
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_songs_from_album_not_existing() {
        let (library, _temp_dir, _) = setup_test_library();
        assert!(library
            .songs_from_album::<ExtraInfo>("not-existing")
            .is_err());
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_delete_path_non_existing() {
        let (mut library, _temp_dir, _) = setup_test_library();
        {
            let connection = library.sqlite_conn.lock().unwrap();
            let count: u32 = connection
                    .query_row(
                        "select count(*) from feature join song on song.id = feature.song_id where song.path = ?",
                        ["not-existing"],
                        |row| row.get(0),
                    )
                    .unwrap();
            assert_eq!(count, 0);
            let count: u32 = connection
                .query_row(
                    "select count(*) from song where path = ?",
                    ["not-existing"],
                    |row| row.get(0),
                )
                .unwrap();
            assert_eq!(count, 0);
        }
        assert!(library.delete_path("not-existing").is_err());
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_delete_path() {
        let (mut library, _temp_dir, _) = setup_test_library();
        {
            let connection = library.sqlite_conn.lock().unwrap();
            let count: u32 = connection
                    .query_row(
                        "select count(*) from feature join song on song.id = feature.song_id where song.path = ?",
                        ["/path/to/song1001"],
                        |row| row.get(0),
                    )
                    .unwrap();
            assert!(count >= 1);
            let count: u32 = connection
                .query_row(
                    "select count(*) from song where path = ?",
                    ["/path/to/song1001"],
                    |row| row.get(0),
                )
                .unwrap();
            assert!(count >= 1);
        }

        library.delete_path("/path/to/song1001").unwrap();

        {
            let connection = library.sqlite_conn.lock().unwrap();
            let count: u32 = connection
                .query_row(
                    "select count(*) from feature join song on song.id = feature.song_id where song.path = ?",
                    ["/path/to/song1001"],
                    |row| row.get(0),
                )
                .unwrap();
            assert_eq!(0, count);
            let count: u32 = connection
                .query_row(
                    "select count(*) from song where path = ?",
                    ["/path/to/song1001"],
                    |row| row.get(0),
                )
                .unwrap();
            assert_eq!(0, count);
        }
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_delete_paths() {
        let (mut library, _temp_dir, _) = setup_test_library();
        {
            let connection = library.sqlite_conn.lock().unwrap();
            let count: u32 = connection
                    .query_row(
                        "select count(*) from feature join song on song.id = feature.song_id where song.path in (?1, ?2)",
                        ["/path/to/song1001", "/path/to/song2001"],
                        |row| row.get(0),
                    )
                    .unwrap();
            assert!(count >= 1);
            let count: u32 = connection
                .query_row(
                    "select count(*) from song where path in (?1, ?2)",
                    ["/path/to/song1001", "/path/to/song2001"],
                    |row| row.get(0),
                )
                .unwrap();
            assert!(count >= 1);
        }

        library
            .delete_paths(vec!["/path/to/song1001", "/path/to/song2001"])
            .unwrap();

        {
            let connection = library.sqlite_conn.lock().unwrap();
            let count: u32 = connection
                .query_row(
                    "select count(*) from feature join song on song.id = feature.song_id where song.path in (?1, ?2)",
                    ["/path/to/song1001", "/path/to/song2001"],
                    |row| row.get(0),
                )
                .unwrap();
            assert_eq!(0, count);
            let count: u32 = connection
                .query_row(
                    "select count(*) from song where path in (?1, ?2)",
                    ["/path/to/song1001", "/path/to/song2001"],
                    |row| row.get(0),
                )
                .unwrap();
            assert_eq!(0, count);
            // Make sure we did not delete everything else
            let count: u32 = connection
                .query_row("select count(*) from feature", [], |row| row.get(0))
                .unwrap();
            assert!(count >= 1);
            let count: u32 = connection
                .query_row("select count(*) from song", [], |row| row.get(0))
                .unwrap();
            assert!(count >= 1);
        }
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_delete_paths_empty() {
        let (mut library, _temp_dir, _) = setup_test_library();
        assert_eq!(library.delete_paths::<String, _>([]).unwrap(), 0);
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_delete_paths_non_existing() {
        let (mut library, _temp_dir, _) = setup_test_library();
        assert_eq!(library.delete_paths(["not-existing"]).unwrap(), 0);
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_analyze_paths_cue() {
        let (mut library, _temp_dir, _) = setup_test_library();
        library
            .config
            .base_config_mut()
            .analysis_options
            .features_version = FeaturesVersion::Version1;
        {
            let sqlite_conn =
                Connection::open(&library.config.base_config().database_path).unwrap();
            sqlite_conn.execute("delete from song", []).unwrap();
        }

        let paths = vec![
            "./data/s16_mono_22_5kHz.flac",
            "./data/testcue.cue",
            "non-existing",
        ];
        library
            .analyze_paths_with_options(
                paths.to_owned(),
                false,
                AnalysisOptions {
                    features_version: FeaturesVersion::Version2,
                    ..Default::default()
                },
            )
            .unwrap();
        let expected_analyzed_paths = vec![
            "./data/s16_mono_22_5kHz.flac",
            "./data/testcue.cue/CUE_TRACK001",
            "./data/testcue.cue/CUE_TRACK002",
            "./data/testcue.cue/CUE_TRACK003",
        ];
        {
            let connection = library.sqlite_conn.lock().unwrap();
            let mut stmt = connection
                .prepare(
                    "
                select
                    path from song where analyzed = true and path not like '%song%'
                    order by path
                ",
                )
                .unwrap();
            let paths = stmt
                .query_map(params![], |row| row.get(0))
                .unwrap()
                .map(|x| x.unwrap())
                .collect::<Vec<String>>();

            assert_eq!(paths, expected_analyzed_paths);
        }
        {
            let connection = library.sqlite_conn.lock().unwrap();
            let song: LibrarySong<()> =
                _library_song_from_database(connection, "./data/testcue.cue/CUE_TRACK001");
            assert!(song.bliss_song.cue_info.is_some());
        }
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_analyze_paths() {
        let (mut library, _temp_dir, _) = setup_test_library();
        library
            .config
            .base_config_mut()
            .analysis_options
            .features_version = FeaturesVersion::LATEST;

        let paths = vec![
            "./data/s16_mono_22_5kHz.flac",
            "./data/s16_stereo_22_5kHz.flac",
            "non-existing",
        ];
        library.analyze_paths(paths.to_owned(), false).unwrap();
        let songs = paths[..2]
            .iter()
            .map(|path| {
                let connection = library.sqlite_conn.lock().unwrap();
                _library_song_from_database(connection, path)
            })
            .collect::<Vec<LibrarySong<()>>>();
        let expected_songs = paths[..2]
            .iter()
            .zip(vec![(), ()].into_iter())
            .map(|(path, expected_extra_info)| LibrarySong {
                bliss_song: Decoder::song_from_path(path).unwrap(),
                extra_info: expected_extra_info,
            })
            .collect::<Vec<LibrarySong<()>>>();
        assert_eq!(songs, expected_songs);
        assert_eq!(
            library
                .config
                .base_config_mut()
                .analysis_options
                .features_version,
            FeaturesVersion::LATEST
        );
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_analyze_paths_convert_extra_info() {
        let (mut library, _temp_dir, _) = setup_test_library();
        library
            .config
            .base_config_mut()
            .analysis_options
            .features_version = FeaturesVersion::Version1;
        let paths = vec![
            ("./data/s16_mono_22_5kHz.flac", true),
            ("./data/s16_stereo_22_5kHz.flac", false),
            ("non-existing", false),
        ];
        library
            .analyze_paths_convert_extra_info(
                paths.to_owned(),
                true,
                |b, _, _| ExtraInfo {
                    ignore: b,
                    metadata_bliss_does_not_have: String::from("coucou"),
                },
                AnalysisOptions::default(),
            )
            .unwrap();
        library
            .analyze_paths_convert_extra_info(
                paths.to_owned(),
                false,
                |b, _, _| ExtraInfo {
                    ignore: b,
                    metadata_bliss_does_not_have: String::from("coucou"),
                },
                AnalysisOptions::default(),
            )
            .unwrap();
        let songs = paths[..2]
            .iter()
            .map(|(path, _)| {
                let connection = library.sqlite_conn.lock().unwrap();
                _library_song_from_database(connection, path)
            })
            .collect::<Vec<LibrarySong<ExtraInfo>>>();
        let expected_songs = paths[..2]
            .iter()
            .zip(
                vec![
                    ExtraInfo {
                        ignore: true,
                        metadata_bliss_does_not_have: String::from("coucou"),
                    },
                    ExtraInfo {
                        ignore: false,
                        metadata_bliss_does_not_have: String::from("coucou"),
                    },
                ]
                .into_iter(),
            )
            .map(|((path, _extra_info), expected_extra_info)| LibrarySong {
                bliss_song: Decoder::song_from_path(path).unwrap(),
                extra_info: expected_extra_info,
            })
            .collect::<Vec<LibrarySong<ExtraInfo>>>();
        assert_eq!(songs, expected_songs);
        assert_eq!(
            library
                .config
                .base_config_mut()
                .analysis_options
                .features_version,
            FeaturesVersion::LATEST
        );
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_analyze_paths_extra_info() {
        let (mut library, _temp_dir, _) = setup_test_library();

        let paths = vec![
            (
                "./data/s16_mono_22_5kHz.flac",
                ExtraInfo {
                    ignore: true,
                    metadata_bliss_does_not_have: String::from("hey"),
                },
            ),
            (
                "./data/s16_stereo_22_5kHz.flac",
                ExtraInfo {
                    ignore: false,
                    metadata_bliss_does_not_have: String::from("hello"),
                },
            ),
            (
                "non-existing",
                ExtraInfo {
                    ignore: true,
                    metadata_bliss_does_not_have: String::from("coucou"),
                },
            ),
        ];
        library
            .analyze_paths_extra_info(paths.to_owned(), false, AnalysisOptions::default())
            .unwrap();
        let songs = paths[..2]
            .iter()
            .map(|(path, _)| {
                let connection = library.sqlite_conn.lock().unwrap();
                _library_song_from_database(connection, path)
            })
            .collect::<Vec<LibrarySong<ExtraInfo>>>();
        let expected_songs = paths[..2]
            .iter()
            .zip(
                vec![
                    ExtraInfo {
                        ignore: true,
                        metadata_bliss_does_not_have: String::from("hey"),
                    },
                    ExtraInfo {
                        ignore: false,
                        metadata_bliss_does_not_have: String::from("hello"),
                    },
                ]
                .into_iter(),
            )
            .map(|((path, _extra_info), expected_extra_info)| LibrarySong {
                bliss_song: Decoder::song_from_path(path).unwrap(),
                extra_info: expected_extra_info,
            })
            .collect::<Vec<LibrarySong<ExtraInfo>>>();
        assert_eq!(songs, expected_songs);
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    // Check that a song already in the database is not
    // analyzed again on updates.
    fn test_update_skip_analyzed() {
        let (mut library, _temp_dir, _) = setup_test_library();
        library
            .config
            .base_config_mut()
            .analysis_options
            .features_version = FeaturesVersion::Version1;
        for input in vec![
            ("./data/s16_mono_22_5kHz.flac", true),
            ("./data/s16_mono_22_5kHz.flac", false),
        ]
        .into_iter()
        {
            let paths = vec![input.to_owned()];
            library
                .update_library_convert_extra_info(
                    paths.to_owned(),
                    true,
                    false,
                    |b, _, _| ExtraInfo {
                        ignore: b,
                        metadata_bliss_does_not_have: String::from("coucou"),
                    },
                    AnalysisOptions {
                        features_version: FeaturesVersion::Version1,
                        ..Default::default()
                    },
                )
                .unwrap();
            let song = {
                let connection = library.sqlite_conn.lock().unwrap();
                _library_song_from_database::<ExtraInfo>(connection, "./data/s16_mono_22_5kHz.flac")
            };
            let expected_song = {
                LibrarySong {
                    bliss_song: Decoder::song_from_path_with_options(
                        "./data/s16_mono_22_5kHz.flac",
                        AnalysisOptions {
                            features_version: FeaturesVersion::Version1,
                            ..Default::default()
                        },
                    )
                    .unwrap(),
                    extra_info: ExtraInfo {
                        ignore: true,
                        metadata_bliss_does_not_have: String::from("coucou"),
                    },
                }
            };
            assert_eq!(song, expected_song);
            assert_eq!(
                library
                    .config
                    .base_config_mut()
                    .analysis_options
                    .features_version,
                FeaturesVersion::Version1
            );
        }
    }

    fn _get_song_analyzed(
        connection: MutexGuard<Connection>,
        path: String,
    ) -> Result<bool, RusqliteError> {
        let mut stmt = connection.prepare(
            "
                select
                    analyzed from song
                    where song.path = ?
                ",
        )?;
        stmt.query_row([path], |row| (row.get(0)))
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    // TODO test that LibrarySong<ExtraInfo> and LibrarySong<()> can't cohabitate in the same
    // library.
    //
    // Tests that a song with features version = 1 gets updated to the latest features version.
    fn test_update_library_override_old_features() {
        let (mut library, _temp_dir, _) = setup_test_library();
        let path: String = "./data/s16_stereo_22_5kHz.flac".into();

        // Check that s16_stereo_22_5kHz.flac is analyzed with the old features version.
        {
            let connection = library.sqlite_conn.lock().unwrap();
            let song: LibrarySong<ExtraInfo> = _library_song_from_database(connection, &path);
            assert_eq!(
                song.bliss_song.analysis,
                Analysis {
                    internal_analysis: vec![
                        1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17.,
                        18.
                    ],
                    features_version: FeaturesVersion::Version1,
                }
            )
        }
        // Check that there are indeed songs with older features version.
        {
            let connection = library.sqlite_conn.lock().unwrap();
            let count_old_features_version: u32 = connection
                .query_row(
                    "select count(*) from song where version = ? and analyzed = true",
                    params![FeaturesVersion::Version1],
                    |row| row.get(0),
                )
                .unwrap();
            assert!(count_old_features_version > 0);
        }

        library
            .update_library(vec![path.to_owned()], true, false)
            .unwrap();

        // Check that songs with older features version are gone.
        {
            let connection = library.sqlite_conn.lock().unwrap();
            let count_old_features_version: u32 = connection
                .query_row(
                    "select count(*) from song where version = ? and analyzed = true",
                    params![FeaturesVersion::Version1],
                    |row| row.get(0),
                )
                .unwrap();
            assert_eq!(count_old_features_version, 0);
        }

        let connection = library.sqlite_conn.lock().unwrap();
        let song: LibrarySong<()> = _library_song_from_database(connection, &path);
        // This should give us latest features version, but double-checking.
        let expected_analysis_vector = Decoder::song_from_path(path).unwrap().analysis;
        assert_eq!(song.bliss_song.analysis, expected_analysis_vector);
        assert_eq!(
            song.bliss_song.analysis.features_version,
            FeaturesVersion::LATEST
        );
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    // TODO test when updating the features version also
    fn test_update_library() {
        let (mut library, _temp_dir, _) = setup_test_library();
        library
            .config
            .base_config_mut()
            .analysis_options
            .features_version = FeaturesVersion::LATEST;

        {
            let connection = library.sqlite_conn.lock().unwrap();
            // Make sure that we tried to "update" song4001 with the new features.
            assert!(_get_song_analyzed(connection, "/path/to/song4001".into()).unwrap());
        }

        let paths = vec![
            "./data/s16_mono_22_5kHz.flac",
            "./data/s16_stereo_22_5kHz.flac",
            "/path/to/song4001",
            "non-existing",
        ];
        library
            .update_library(paths.to_owned(), true, false)
            .unwrap();
        library
            .update_library(paths.to_owned(), true, true)
            .unwrap();

        let songs = paths[..2]
            .iter()
            .map(|path| {
                let connection = library.sqlite_conn.lock().unwrap();
                _library_song_from_database(connection, path)
            })
            .collect::<Vec<LibrarySong<()>>>();
        let expected_songs = paths[..2]
            .iter()
            .zip(vec![(), ()].into_iter())
            .map(|(path, expected_extra_info)| LibrarySong {
                bliss_song: Decoder::song_from_path(path).unwrap(),
                extra_info: expected_extra_info,
            })
            .collect::<Vec<LibrarySong<()>>>();

        assert_eq!(songs, expected_songs);
        {
            let connection = library.sqlite_conn.lock().unwrap();
            // Make sure that we tried to "update" song4001 with the new features.
            assert!(!_get_song_analyzed(connection, "/path/to/song4001".into()).unwrap());
        }
        assert_eq!(
            library
                .config
                .base_config_mut()
                .analysis_options
                .features_version,
            FeaturesVersion::LATEST
        );
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    // TODO test when updating the features version also
    fn test_update_library_with_options() {
        let (mut library, _temp_dir, _) = setup_test_library();
        library
            .config
            .base_config_mut()
            .analysis_options
            .features_version = FeaturesVersion::LATEST;

        {
            let connection = library.sqlite_conn.lock().unwrap();
            // Make sure that we tried to "update" song4001 with the new features.
            assert!(_get_song_analyzed(connection, "/path/to/song4001".into()).unwrap());
        }
        {
            let connection = library.sqlite_conn.lock().unwrap();
            // Make sure that we tried to "update" song4001 with the new features.
            connection
                .execute("update song set extra_info = \"null\";", [])
                .unwrap();
        }

        let paths = vec![
            "./data/s16_mono_22_5kHz.flac",
            "./data/s16_stereo_22_5kHz.flac",
            "/path/to/song4001",
            "non-existing",
        ];
        library
            .update_library_with_options(
                paths.to_owned(),
                true,
                false,
                AnalysisOptions {
                    features_version: FeaturesVersion::Version1,
                    ..Default::default()
                },
            )
            .unwrap();
        library
            .update_library_with_options(
                paths.to_owned(),
                true,
                false,
                AnalysisOptions {
                    features_version: FeaturesVersion::Version1,
                    ..Default::default()
                },
            )
            .unwrap();

        let first_song = {
            let connection = library.sqlite_conn.lock().unwrap();
            _library_song_from_database(connection, paths[0])
        };
        let expected_song = LibrarySong {
            bliss_song: Decoder::song_from_path_with_options(
                paths[0],
                AnalysisOptions {
                    features_version: FeaturesVersion::Version1,
                    ..Default::default()
                },
            )
            .unwrap(),
            extra_info: (),
        };

        assert_eq!(first_song, expected_song);
        {
            let connection = library.sqlite_conn.lock().unwrap();
            // Make sure that we did not try to "update" song4001 with the new features, since
            // it was analyzed with version 1.
            assert!(_get_song_analyzed(connection, "/path/to/song4001".into()).unwrap());
        }
        assert_eq!(
            library
                .config
                .base_config_mut()
                .analysis_options
                .features_version,
            FeaturesVersion::Version1
        );
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_update_extra_info() {
        let (mut library, _temp_dir, _) = setup_test_library();
        library
            .config
            .base_config_mut()
            .analysis_options
            .features_version = FeaturesVersion::LATEST;

        {
            let connection = library.sqlite_conn.lock().unwrap();
            // Make sure that we tried to "update" song4001 with the new features.
            assert!(_get_song_analyzed(connection, "/path/to/song4001".into()).unwrap());
        }

        let paths = vec![
            ("./data/s16_mono_22_5kHz.flac", true),
            ("./data/s16_stereo_22_5kHz.flac", false),
            ("/path/to/song4001", false),
            ("non-existing", false),
        ];
        library
            .update_library_extra_info(paths.to_owned(), true, false)
            .unwrap();
        let songs = paths[..2]
            .iter()
            .map(|(path, _)| {
                let connection = library.sqlite_conn.lock().unwrap();
                _library_song_from_database(connection, path)
            })
            .collect::<Vec<LibrarySong<bool>>>();
        let expected_songs = paths[..2]
            .iter()
            .zip(vec![true, false].into_iter())
            .map(|((path, _extra_info), expected_extra_info)| LibrarySong {
                bliss_song: Decoder::song_from_path(path).unwrap(),
                extra_info: expected_extra_info,
            })
            .collect::<Vec<LibrarySong<bool>>>();
        assert_eq!(songs, expected_songs);
        {
            let connection = library.sqlite_conn.lock().unwrap();
            // Make sure that we tried to "update" song4001 with the new features.
            assert!(!_get_song_analyzed(connection, "/path/to/song4001".into()).unwrap());
        }
        assert_eq!(
            library
                .config
                .base_config_mut()
                .analysis_options
                .features_version,
            FeaturesVersion::LATEST
        );
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_update_convert_extra_info() {
        let (mut library, _temp_dir, _) = setup_test_library();
        library
            .config
            .base_config_mut()
            .analysis_options
            .features_version = FeaturesVersion::Version1;

        {
            let connection = library.sqlite_conn.lock().unwrap();
            // Make sure that we tried to "update" song4001 with the new features.
            assert!(_get_song_analyzed(connection, "/path/to/song4001".into()).unwrap());
        }
        {
            let connection = library.sqlite_conn.lock().unwrap();
            // Make sure that all the starting songs are there
            assert!(_get_song_analyzed(connection, "/path/to/song2001".into()).unwrap());
        }

        let paths = vec![
            ("./data/s16_mono_22_5kHz.flac", true),
            ("./data/s16_stereo_22_5kHz.flac", false),
            ("/path/to/song4001", false),
            ("non-existing", false),
        ];
        library
            .update_library_convert_extra_info(
                paths.to_owned(),
                true,
                false,
                |b, _, _| ExtraInfo {
                    ignore: b,
                    metadata_bliss_does_not_have: String::from("coucou"),
                },
                AnalysisOptions::default(),
            )
            .unwrap();
        let songs = paths[..2]
            .iter()
            .map(|(path, _)| {
                let connection = library.sqlite_conn.lock().unwrap();
                _library_song_from_database(connection, path)
            })
            .collect::<Vec<LibrarySong<ExtraInfo>>>();
        let expected_songs = paths[..2]
            .iter()
            .zip(
                vec![
                    ExtraInfo {
                        ignore: true,
                        metadata_bliss_does_not_have: String::from("coucou"),
                    },
                    ExtraInfo {
                        ignore: false,
                        metadata_bliss_does_not_have: String::from("coucou"),
                    },
                ]
                .into_iter(),
            )
            .map(|((path, _extra_info), expected_extra_info)| LibrarySong {
                bliss_song: Decoder::song_from_path(path).unwrap(),
                extra_info: expected_extra_info,
            })
            .collect::<Vec<LibrarySong<ExtraInfo>>>();
        assert_eq!(songs, expected_songs);
        {
            let connection = library.sqlite_conn.lock().unwrap();
            // Make sure that we tried to "update" song4001 with the new features.
            assert!(!_get_song_analyzed(connection, "/path/to/song4001".into()).unwrap());
        }
        {
            let connection = library.sqlite_conn.lock().unwrap();
            // Make sure that we deleted older songs
            assert_eq!(
                rusqlite::Error::QueryReturnedNoRows,
                _get_song_analyzed(connection, "/path/to/song2001".into()).unwrap_err(),
            );
        }
        assert_eq!(
            library
                .config
                .base_config_mut()
                .analysis_options
                .features_version,
            FeaturesVersion::LATEST
        );
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    // TODO maybe we can merge / DRY this and the function ⬆
    fn test_update_convert_extra_info_do_not_delete() {
        let (mut library, _temp_dir, _) = setup_test_library();
        library
            .config
            .base_config_mut()
            .analysis_options
            .features_version = FeaturesVersion::Version1;

        {
            let connection = library.sqlite_conn.lock().unwrap();
            // Make sure that we tried to "update" song4001 with the new features.
            assert!(_get_song_analyzed(connection, "/path/to/song4001".into()).unwrap());
        }
        {
            let connection = library.sqlite_conn.lock().unwrap();
            // Make sure that all the starting songs are there
            assert!(_get_song_analyzed(connection, "/path/to/song2001".into()).unwrap());
        }

        let paths = vec![
            ("./data/s16_mono_22_5kHz.flac", true),
            ("./data/s16_stereo_22_5kHz.flac", false),
            ("/path/to/song4001", false),
            ("non-existing", false),
        ];
        library
            .update_library_convert_extra_info(
                paths.to_owned(),
                false,
                false,
                |b, _, _| ExtraInfo {
                    ignore: b,
                    metadata_bliss_does_not_have: String::from("coucou"),
                },
                AnalysisOptions::default(),
            )
            .unwrap();
        let songs = paths[..2]
            .iter()
            .map(|(path, _)| {
                let connection = library.sqlite_conn.lock().unwrap();
                _library_song_from_database(connection, path)
            })
            .collect::<Vec<LibrarySong<ExtraInfo>>>();
        let expected_songs = paths[..2]
            .iter()
            .zip(
                vec![
                    ExtraInfo {
                        ignore: true,
                        metadata_bliss_does_not_have: String::from("coucou"),
                    },
                    ExtraInfo {
                        ignore: false,
                        metadata_bliss_does_not_have: String::from("coucou"),
                    },
                ]
                .into_iter(),
            )
            .map(|((path, _extra_info), expected_extra_info)| LibrarySong {
                bliss_song: Decoder::song_from_path(path).unwrap(),
                extra_info: expected_extra_info,
            })
            .collect::<Vec<LibrarySong<ExtraInfo>>>();
        assert_eq!(songs, expected_songs);
        {
            let connection = library.sqlite_conn.lock().unwrap();
            // Make sure that we tried to "update" song4001 with the new features.
            assert!(!_get_song_analyzed(connection, "/path/to/song4001".into()).unwrap());
        }
        {
            let connection = library.sqlite_conn.lock().unwrap();
            // Make sure that we did not delete older songs
            assert!(_get_song_analyzed(connection, "/path/to/song2001".into()).unwrap());
        }
        assert_eq!(
            library
                .config
                .base_config_mut()
                .analysis_options
                .features_version,
            FeaturesVersion::LATEST
        );
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_song_from_path() {
        let (library, _temp_dir, _) = setup_test_library();
        let analysis_vector = (0..NUMBER_FEATURES)
            .map(|x| x as f32 + 10.)
            .collect::<Vec<f32>>();

        let song = Song {
            path: "/path/to/song2001".into(),
            artist: Some("Artist2001".into()),
            title: Some("Title2001".into()),
            album: Some("An Album2001".into()),
            album_artist: Some("An Album Artist2001".into()),
            track_number: Some(2),
            disc_number: Some(1),
            genre: Some("Electronica2001".into()),
            analysis: Analysis {
                internal_analysis: analysis_vector,
                features_version: FeaturesVersion::Version2,
            },
            duration: Duration::from_secs(410),
            features_version: FeaturesVersion::Version2,
            cue_info: None,
        };
        let expected_song = LibrarySong {
            bliss_song: song,
            extra_info: ExtraInfo {
                ignore: false,
                metadata_bliss_does_not_have: String::from("/path/to/charlie2001"),
            },
        };

        let song = library
            .song_from_path::<ExtraInfo>("/path/to/song2001")
            .unwrap();
        assert_eq!(song, expected_song)
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_store_failed_song() {
        let (mut library, _temp_dir, _) = setup_test_library();
        library
            .store_failed_song(
                "/some/failed/path",
                BlissError::ProviderError("error with the analysis".into()),
                FeaturesVersion::Version1,
            )
            .unwrap();
        let connection = library.sqlite_conn.lock().unwrap();
        let (error, analyzed, features_version): (String, bool, FeaturesVersion) = connection
            .query_row(
                "
            select
                error, analyzed, version
                from song where path=?
            ",
                params!["/some/failed/path"],
                |row| Ok((row.get_unwrap(0), row.get_unwrap(1), row.get_unwrap(2))),
            )
            .unwrap();
        assert_eq!(
            error,
            String::from(
                "error happened with the music library provider - error with the analysis"
            )
        );
        assert_eq!(analyzed, false);
        assert_eq!(features_version, FeaturesVersion::Version1);
        let count_features: u32 = connection
            .query_row(
                "
            select
                count(*) from feature join song
                on song.id = feature.song_id where path=?
            ",
                params!["/some/failed/path"],
                |row| Ok(row.get_unwrap(0)),
            )
            .unwrap();
        assert_eq!(count_features, 0);
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_songs_from_library() {
        let (library, _temp_dir, expected_library_songs) = setup_test_library();

        let library_songs = library.songs_from_library::<ExtraInfo>().unwrap();
        assert_eq!(library_songs.len(), 8);
        assert_eq!(
            expected_library_songs,
            (
                library_songs[0].to_owned(),
                library_songs[1].to_owned(),
                library_songs[2].to_owned(),
                library_songs[3].to_owned(),
                library_songs[4].to_owned(),
                library_songs[5].to_owned(),
                library_songs[6].to_owned(),
                library_songs[7].to_owned(),
            )
        );
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_songs_from_library_screwed_db() {
        let (library, _temp_dir, _) = setup_test_library();
        {
            let connection = library.sqlite_conn.lock().unwrap();
            connection
                .execute(
                    "insert into feature (song_id, feature, feature_index)
                values (2001, 1.5, 29)
                ",
                    [],
                )
                .unwrap();
        }

        let error = library.songs_from_library::<ExtraInfo>().unwrap_err();
        assert_eq!(
            error.to_string(),
            String::from(
                "error happened with the music library provider - \
                Song with ID 2001 and path /path/to/song2001 has a \
                different feature number than expected. Please rescan or \
                update the song library.",
            ),
        );
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_song_from_path_not_analyzed() {
        let (library, _temp_dir, _) = setup_test_library();
        let error = library.song_from_path::<ExtraInfo>("/path/to/song404");
        assert!(error.is_err());
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_song_from_path_not_found() {
        let (library, _temp_dir, _) = setup_test_library();
        let error = library.song_from_path::<ExtraInfo>("/path/to/randomsong");
        assert!(error.is_err());
    }

    #[test]
    fn test_get_default_data_folder_no_default_path() {
        // Cases to test:
        // - Legacy path exists, new path doesn't exist => legacy path should be returned
        // - Legacy path exists, new path exists => new path should be returned
        // - Legacy path doesn't exist => new path should be returned

        // Nothing exists: XDG_CONFIG_HOME takes precedence
        env::set_var("XDG_CONFIG_HOME", "/home/foo/.config");
        env::set_var("XDG_DATA_HOME", "/home/foo/.local/share");
        assert_eq!(
            PathBuf::from("/home/foo/.config/bliss-rs"),
            BaseConfig::get_default_data_folder().unwrap()
        );
        env::remove_var("XDG_CONFIG_HOME");
        env::remove_var("XDG_DATA_HOME");

        // Legacy folder exists, new folder does not exist, it takes precedence
        let existing_legacy_folder = TempDir::new("tmp").unwrap();
        create_dir_all(existing_legacy_folder.path().join("bliss-rs")).unwrap();
        env::set_var("XDG_CONFIG_HOME", "/home/foo/.config");
        env::set_var("XDG_DATA_HOME", existing_legacy_folder.path().as_os_str());
        assert_eq!(
            existing_legacy_folder.path().join("bliss-rs"),
            BaseConfig::get_default_data_folder().unwrap()
        );

        // Both exists, new folder takes precedence
        let existing_folder = TempDir::new("tmp").unwrap();
        create_dir_all(existing_folder.path().join("bliss-rs")).unwrap();
        env::set_var("XDG_CONFIG_HOME", existing_folder.path().as_os_str());
        assert_eq!(
            existing_folder.path().join("bliss-rs"),
            BaseConfig::get_default_data_folder().unwrap()
        );

        env::remove_var("XDG_DATA_HOME");
        env::remove_var("XDG_CONFIG_HOME");

        assert_eq!(
            PathBuf::from("/tmp/bliss-rs/"),
            BaseConfig::get_default_data_folder().unwrap()
        );
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_new_default_write() {
        let (library, _temp_dir, _) = setup_test_library();
        let config_content = fs::read_to_string(&library.config.base_config().config_path)
            .unwrap()
            .replace(' ', "")
            .replace('\n', "");
        assert_eq!(
            config_content,
            format!(
                "{{\"config_path\":\"{}\",\"database_path\":\"{}\",\"\
                features_version\":{},\"number_cores\":{},\
                \"m\":{{\"v\":1,\"dim\":[{},{}],\"data\":{}}}}}",
                library.config.base_config().config_path.display(),
                library.config.base_config().database_path.display(),
                FeaturesVersion::LATEST as u16,
                thread::available_parallelism().unwrap_or(NonZeroUsize::new(1).unwrap()),
                NUMBER_FEATURES,
                NUMBER_FEATURES,
                // Terrible code, but would hardcoding be better?
                format!(
                    "{:?}",
                    Array2::<f32>::eye(NUMBER_FEATURES).as_slice().unwrap()
                )
                .replace(" ", ""),
            )
        );
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_new_create_database() {
        let (library, _temp_dir, _) = setup_test_library();
        let sqlite_conn = Connection::open(&library.config.base_config().database_path).unwrap();
        sqlite_conn
            .execute(
                "
            insert into song (
                id, path, artist, title, album, album_artist,
                track_number, disc_number, genre, stamp, version, duration, analyzed,
                extra_info
            )
            values (
                1, '/random/path', 'Some Artist', 'A Title', 'Some Album',
                'Some Album Artist', 1, 1, 'Electronica', '2022-01-01',
                1, 250, true, '{\"key\": \"value\"}'
            );
            ",
                [],
            )
            .unwrap();
        sqlite_conn
            .execute(
                "
            insert into feature(id, song_id, feature, feature_index)
            values (2000, 1, 1.1, 1)
            on conflict(song_id, feature_index) do update set feature=excluded.feature;
            ",
                [],
            )
            .unwrap();
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_new_database_upgrade() {
        let config_dir = TempDir::new("tmp").unwrap();
        let sqlite_db_path = config_dir.path().join("test.db");
        // Initialize the database with the contents of old_database.sql, without
        // having anything to do with Library (yet)
        {
            let sqlite_conn = Connection::open(sqlite_db_path.clone()).unwrap();
            let sql_statements = fs::read_to_string("data/old_database.sql").unwrap();
            sqlite_conn.execute_batch(&sql_statements).unwrap();
            let track_number: String = sqlite_conn
                .query_row("select track_number from song where id = 1", [], |row| {
                    row.get(0)
                })
                .unwrap();
            // Check that songs are indeed inserted the old way
            assert_eq!(track_number, "01");
            let version: u32 = sqlite_conn
                .query_row("pragma user_version", [], |row| row.get(0))
                .unwrap();
            assert_eq!(version, 0);
        }

        let library = Library::<BaseConfig, DummyDecoder>::new_from_base(
            Some(config_dir.path().join("config.txt")),
            Some(sqlite_db_path.clone()),
            Some(AnalysisOptions {
                number_cores: nzus(1),
                features_version: FeaturesVersion::Version1,
            }),
        )
        .unwrap();
        let sqlite_conn = library.sqlite_conn.lock().unwrap();
        let mut query = sqlite_conn
            .prepare("select track_number from song where id = ?1")
            .unwrap();

        let first_song_track_number: Option<u32> = query.query_row([1], |row| row.get(0)).unwrap();
        assert_eq!(first_song_track_number, Some(1));

        let second_song_track_number: Option<u32> = query.query_row([2], |row| row.get(0)).unwrap();
        assert_eq!(None, second_song_track_number);

        let third_song_track_number: Option<u32> = query.query_row([3], |row| row.get(0)).unwrap();
        assert_eq!(None, third_song_track_number);

        let fourth_song_track_number: Option<u32> = query.query_row([4], |row| row.get(0)).unwrap();
        assert_eq!(None, fourth_song_track_number);

        let version: u32 = sqlite_conn
            .query_row("pragma user_version", [], |row| row.get(0))
            .unwrap();
        assert_eq!(version, 5);
        // Make sure we can call this over and over without any problem
        Library::<BaseConfig, DummyDecoder>::new_from_base(
            Some(config_dir.path().join("config.txt")),
            Some(sqlite_db_path),
            Some(AnalysisOptions {
                number_cores: NonZeroUsize::new(1).unwrap(),
                ..Default::default()
            }),
        )
        .unwrap();
        let version: u32 = sqlite_conn
            .query_row("pragma user_version", [], |row| row.get(0))
            .unwrap();
        assert_eq!(version, 5);
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_new_database_already_last_version() {
        let config_dir = TempDir::new("tmp").unwrap();
        let sqlite_db_path = config_dir.path().join("test.db");
        Library::<BaseConfig, DummyDecoder>::new_from_base(
            Some(config_dir.path().join("config.txt")),
            Some(sqlite_db_path.clone()),
            Some(AnalysisOptions {
                number_cores: NonZeroUsize::new(1).unwrap(),
                ..Default::default()
            }),
        )
        .unwrap();
        let library = Library::<BaseConfig, DummyDecoder>::new_from_base(
            Some(config_dir.path().join("config.txt")),
            Some(sqlite_db_path.clone()),
            Some(AnalysisOptions {
                number_cores: NonZeroUsize::new(1).unwrap(),
                ..Default::default()
            }),
        )
        .unwrap();
        let sqlite_conn = library.sqlite_conn.lock().unwrap();
        let version: u32 = sqlite_conn
            .query_row("pragma user_version", [], |row| row.get(0))
            .unwrap();
        assert_eq!(version, 5);
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_store_song() {
        let (mut library, _temp_dir, _) = setup_test_library();
        let song = _generate_basic_song(None);
        let library_song = LibrarySong {
            bliss_song: song.to_owned(),
            extra_info: (),
        };
        library.store_song(&library_song).unwrap();
        let connection = library.sqlite_conn.lock().unwrap();
        let expected_song = _basic_song_from_database(connection, &song.path.to_string_lossy());
        assert_eq!(expected_song, song);
    }

    #[test]
    // Test that while creating a new BaseConfig with custom options,
    // the JSON file stores the information correctly.
    fn test_base_config_new() {
        let random_config_home = TempDir::new("config").unwrap();
        let config_path = random_config_home.path().join("test.json");
        let database_path = random_config_home.path().join("database.db");
        let base_config = BaseConfig::new(
            Some(config_path.to_owned()),
            Some(database_path.to_owned()),
            Some(AnalysisOptions {
                number_cores: NonZeroUsize::new(4).unwrap(),
                features_version: FeaturesVersion::Version1,
            }),
        )
        .unwrap();
        base_config.write().unwrap();
        let data = fs::read_to_string(&config_path).unwrap();
        let config = BaseConfig::deserialize_config(&data).unwrap();

        assert_eq!(
            config,
            BaseConfig {
                config_path: config_path,
                database_path: database_path,
                analysis_options: AnalysisOptions {
                    number_cores: NonZeroUsize::new(4).unwrap(),
                    features_version: FeaturesVersion::Version1
                },
                m: default_m(),
            }
        );

        let v: Value = serde_json::from_str(&data).unwrap();
        let obj = v.as_object().expect("top-level JSON must be an object");
        assert!(obj.contains_key("config_path"));
        assert!(obj.contains_key("database_path"));
        assert!(obj.contains_key("m"));
        assert!(obj.contains_key("features_version"));
        assert!(obj.contains_key("number_cores"));
    }

    #[test]
    // Test that the configuration serializes the default parameters correctly.
    fn test_base_config_new_default() {
        let random_config_home = TempDir::new("config").unwrap();
        let config_path = random_config_home.path().join("test.json");
        let base_config = BaseConfig::new(Some(config_path.to_owned()), None, None).unwrap();
        base_config.write().unwrap();
        let data = fs::read_to_string(&config_path).unwrap();
        let config = BaseConfig::deserialize_config(&data).unwrap();

        let cores = thread::available_parallelism().unwrap_or(NonZeroUsize::new(1).unwrap());

        assert_eq!(
            config,
            BaseConfig {
                config_path: config_path,
                database_path: random_config_home.path().join("songs.db"),
                analysis_options: AnalysisOptions {
                    number_cores: cores,
                    features_version: FeaturesVersion::LATEST,
                },
                m: default_m(),
            }
        );

        let v: Value = serde_json::from_str(&data).unwrap();
        let obj = v.as_object().expect("top-level JSON must be an object");
        assert!(obj.contains_key("config_path"));
        assert!(obj.contains_key("database_path"));
        assert!(obj.contains_key("m"));
        assert!(obj.contains_key("features_version"));
        assert!(obj.contains_key("number_cores"));
    }

    #[test]
    fn test_path_base_config_new() {
        {
            let xdg_config_home = TempDir::new("test-bliss").unwrap();
            fs::create_dir_all(xdg_config_home.path().join("bliss-rs")).unwrap();
            env::set_var("XDG_CONFIG_HOME", xdg_config_home.path());

            // First test case: default options go to the XDG_CONFIG_HOME path.
            let base_config = BaseConfig::new(None, None, None).unwrap();

            assert_eq!(
                base_config.config_path,
                xdg_config_home.path().join("bliss-rs/config.json"),
            );
            assert_eq!(
                base_config.database_path,
                xdg_config_home.path().join("bliss-rs/songs.db"),
            );
            base_config.write().unwrap();
            assert!(xdg_config_home.path().join("bliss-rs/config.json").exists());
        }

        // Second test case: config path, no db path.
        {
            let random_config_home = TempDir::new("config").unwrap();
            let base_config = BaseConfig::new(
                Some(random_config_home.path().join("test.json")),
                None,
                None,
            )
            .unwrap();
            base_config.write().unwrap();

            assert_eq!(
                base_config.config_path,
                random_config_home.path().join("test.json"),
            );
            assert_eq!(
                base_config.database_path,
                random_config_home.path().join("songs.db")
            );
            assert!(random_config_home.path().join("test.json").exists());
        }

        // Third test case: no config path, but db path.
        {
            let random_config_home = TempDir::new("database").unwrap();
            let base_config =
                BaseConfig::new(None, Some(random_config_home.path().join("test.db")), None)
                    .unwrap();
            base_config.write().unwrap();

            assert_eq!(
                base_config.config_path,
                random_config_home.path().join("config.json"),
            );
            assert_eq!(
                base_config.database_path,
                random_config_home.path().join("test.db"),
            );
        }
        // Last test case: both paths specified.
        {
            let random_config_home = TempDir::new("config").unwrap();
            let random_database_home = TempDir::new("database").unwrap();
            fs::create_dir_all(random_config_home.path().join("bliss-rs")).unwrap();
            let base_config = BaseConfig::new(
                Some(random_config_home.path().join("config_test.json")),
                Some(random_database_home.path().join("test-database.db")),
                None,
            )
            .unwrap();
            base_config.write().unwrap();

            assert_eq!(
                base_config.config_path,
                random_config_home.path().join("config_test.json"),
            );
            assert_eq!(
                base_config.database_path,
                random_database_home.path().join("test-database.db"),
            );
            assert!(random_config_home.path().join("config_test.json").exists());
        }
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_extra_info() {
        let (mut library, _temp_dir, _) = setup_test_library();
        let song = _generate_library_song(None);
        library.store_song(&song).unwrap();
        let connection = library.sqlite_conn.lock().unwrap();
        let returned_song =
            _library_song_from_database(connection, &song.bliss_song.path.to_string_lossy());
        assert_eq!(returned_song, song);
    }

    #[test]
    fn test_from_config_path_non_existing() {
        assert!(
            Library::<CustomConfig, DummyDecoder>::from_config_path(Some(PathBuf::from(
                "non-existing"
            )))
            .is_err()
        );
    }

    #[test]
    fn test_from_config_path() {
        let config_dir = TempDir::new("coucou").unwrap();
        let config_file = config_dir.path().join("config.json");
        let database_file = config_dir.path().join("bliss.db");

        // In reality, someone would just do that with `(None, None)` to get the default
        // paths.
        let base_config = BaseConfig::new(
            Some(config_file.to_owned()),
            Some(database_file),
            Some(AnalysisOptions {
                number_cores: nzus(1),
                ..Default::default()
            }),
        )
        .unwrap();

        let config = CustomConfig {
            base_config,
            second_path_to_music_library: "/path/to/somewhere".into(),
            ignore_wav_files: true,
        };
        // Test that it is possible to store a song in a library instance,
        // make that instance go out of scope, load the library again, and
        // get the stored song.
        let song = _generate_library_song(None);
        {
            let mut library = Library::<_, DummyDecoder>::new(config.to_owned()).unwrap();
            library.store_song(&song).unwrap();
        }

        let library: Library<CustomConfig, DummyDecoder> =
            Library::from_config_path(Some(config_file)).unwrap();
        let connection = library.sqlite_conn.lock().unwrap();
        let returned_song =
            _library_song_from_database(connection, &song.bliss_song.path.to_string_lossy());

        assert_eq!(library.config, config);
        assert_eq!(song, returned_song);
    }

    #[test]
    fn test_config_from_file() {
        let config = BaseConfig::from_path("./data/sample-config.json").unwrap();
        let mut m: Array2<f32> = Array2::eye(FeaturesVersion::Version1.feature_count());
        m[[0, 1]] = 1.;
        assert_eq!(
            config,
            BaseConfig {
                config_path: PathBuf::from_str("/tmp/bliss-rs/config.json").unwrap(),
                database_path: PathBuf::from_str("/tmp/bliss-rs/songs.db").unwrap(),
                analysis_options: AnalysisOptions {
                    features_version: FeaturesVersion::Version1,
                    number_cores: NonZeroUsize::new(8).unwrap()
                },
                m,
            }
        );
    }

    #[test]
    fn test_config_old_existing() {
        let config = BaseConfig::from_path("./data/old_config.json").unwrap();
        assert_eq!(
            config,
            BaseConfig {
                config_path: PathBuf::from_str("/tmp/bliss-rs/config.json").unwrap(),
                database_path: PathBuf::from_str("/tmp/bliss-rs/songs.db").unwrap(),
                analysis_options: AnalysisOptions {
                    features_version: FeaturesVersion::Version1,
                    number_cores: NonZeroUsize::new(8).unwrap()
                },
                m: Array2::eye(NUMBER_FEATURES),
            }
        );
    }

    #[test]
    fn test_config_serialize_deserialize() {
        let config_dir = TempDir::new("coucou").unwrap();
        let config_file = config_dir.path().join("config.json");
        let database_file = config_dir.path().join("bliss.db");

        // In reality, someone would just do that with `(None, None)` to get the default
        // paths.
        let base_config = BaseConfig::new(
            Some(config_file.to_owned()),
            Some(database_file),
            Some(AnalysisOptions {
                number_cores: nzus(1),
                features_version: FeaturesVersion::Version1,
            }),
        )
        .unwrap();

        let config = CustomConfig {
            base_config,
            second_path_to_music_library: "/path/to/somewhere".into(),
            ignore_wav_files: true,
        };
        config.write().unwrap();

        assert_eq!(
            config,
            CustomConfig::from_path(&config_file.to_string_lossy()).unwrap(),
        );
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_sanity_check_fail() {
        let (mut library, _temp_dir, _) = setup_test_library();
        assert_eq!(
            library.version_sanity_check().unwrap(),
            vec![
                SanityError::MultipleVersionsInDB {
                    versions: vec![FeaturesVersion::Version1, FeaturesVersion::Version2]
                },
                SanityError::OldFeaturesVersionInDB {
                    version: FeaturesVersion::Version1
                }
            ],
        );
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_sanity_check_ok() {
        let (mut library, _temp_dir, _) = setup_test_library();
        {
            let sqlite_conn =
                Connection::open(&library.config.base_config().database_path).unwrap();
            sqlite_conn
                .execute(
                    "delete from song where version != ?1",
                    [FeaturesVersion::LATEST],
                )
                .unwrap();
        }
        assert!(library.version_sanity_check().unwrap().is_empty());
    }

    #[test]
    fn test_config_number_cpus() {
        let config_dir = TempDir::new("coucou").unwrap();
        let config_file = config_dir.path().join("config.json");
        let database_file = config_dir.path().join("bliss.db");

        let base_config = BaseConfig::new(
            Some(config_file.to_owned()),
            Some(database_file.to_owned()),
            None,
        )
        .unwrap();
        let config = CustomConfig {
            base_config,
            second_path_to_music_library: "/path/to/somewhere".into(),
            ignore_wav_files: true,
        };

        assert_eq!(
            config.get_number_cores().get(),
            usize::from(thread::available_parallelism().unwrap_or(NonZeroUsize::new(1).unwrap())),
        );

        let base_config = BaseConfig::new(
            Some(config_file),
            Some(database_file),
            Some(AnalysisOptions {
                number_cores: nzus(1),
                ..Default::default()
            }),
        )
        .unwrap();
        let mut config = CustomConfig {
            base_config,
            second_path_to_music_library: "/path/to/somewhere".into(),
            ignore_wav_files: true,
        };

        assert_eq!(config.get_number_cores().get(), 1);
        config.set_number_cores(nzus(2)).unwrap();
        assert_eq!(config.get_number_cores().get(), 2);
    }

    #[test]
    fn test_config_features_version() {
        let config_dir = TempDir::new("coucou").unwrap();
        let config_file = config_dir.path().join("config.json");
        let database_file = config_dir.path().join("bliss.db");

        let base_config = BaseConfig::new(
            Some(config_file.to_owned()),
            Some(database_file.to_owned()),
            None,
        )
        .unwrap();
        let config = CustomConfig {
            base_config,
            second_path_to_music_library: "/path/to/somewhere".into(),
            ignore_wav_files: true,
        };

        assert_eq!(config.get_features_version(), FeaturesVersion::LATEST,);

        let base_config = BaseConfig::new(
            Some(config_file),
            Some(database_file),
            Some(AnalysisOptions {
                features_version: FeaturesVersion::Version1,
                ..Default::default()
            }),
        )
        .unwrap();
        let mut config = CustomConfig {
            base_config,
            second_path_to_music_library: "/path/to/somewhere".into(),
            ignore_wav_files: true,
        };

        assert_eq!(config.get_features_version(), FeaturesVersion::Version1);
        config
            .set_features_version(FeaturesVersion::Version2)
            .unwrap();
        assert_eq!(config.get_features_version(), FeaturesVersion::Version2);
    }

    #[test]
    fn test_library_create_all_dirs() {
        let config_dir = TempDir::new("coucou")
            .unwrap()
            .path()
            .join("path")
            .join("to");
        assert!(!config_dir.is_dir());
        let config_file = config_dir.join("config.json");
        let database_file = config_dir.join("bliss.db");
        Library::<BaseConfig, DummyDecoder>::new_from_base(
            Some(config_file),
            Some(database_file),
            Some(AnalysisOptions {
                number_cores: nzus(1),
                ..Default::default()
            }),
        )
        .unwrap();
        assert!(config_dir.is_dir());
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_library_get_failed_songs() {
        let (library, _temp_dir, _) = setup_test_library();
        let failed_songs = library.get_failed_songs().unwrap();
        assert_eq!(
            failed_songs,
            vec![
                ProcessingError {
                    song_path: PathBuf::from("./data/not-existing.m4a"),
                    error: String::from("error finding the file"),
                    features_version: FeaturesVersion::Version1,
                },
                ProcessingError {
                    song_path: PathBuf::from("./data/invalid-file.m4a"),
                    error: String::from("error decoding the file"),
                    features_version: FeaturesVersion::Version1,
                }
            ]
        );
    }

    #[test]
    #[cfg(feature = "ffmpeg")]
    fn test_analyze_store_failed_songs() {
        let (mut library, _temp_dir, _) = setup_test_library();
        library
            .config
            .base_config_mut()
            .analysis_options
            .features_version = FeaturesVersion::Version1;

        let paths = vec![
            "./data/s16_mono_22_5kHz.flac",
            "./data/s16_stereo_22_5kHz.flac",
            "non-existing",
        ];
        library.analyze_paths(paths.to_owned(), false).unwrap();
        let failed_songs = library.get_failed_songs().unwrap();
        assert!(failed_songs.contains(&ProcessingError {
            song_path: PathBuf::from("non-existing"),
            error: String::from("error happened while decoding file - while opening format for file 'non-existing': ffmpeg::Error(2: No such file or directory)."),
            features_version: FeaturesVersion::Version1,
        }));
    }
}