librespot 0.8.0

An open source client library for Spotify, with support for Spotify Connect
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
use data_encoding::HEXLOWER;
use futures_util::StreamExt;
#[cfg(feature = "alsa-backend")]
use librespot::playback::mixer::alsamixer::AlsaMixer;
use librespot::{
    connect::{ConnectConfig, Spirc},
    core::{
        Session, SessionConfig, authentication::Credentials, cache::Cache, config::DeviceType,
        version,
    },
    discovery::DnsSdServiceBuilder,
    playback::{
        audio_backend::{self, BACKENDS, SinkBuilder},
        config::{
            AudioFormat, Bitrate, NormalisationMethod, NormalisationType, PlayerConfig, VolumeCtrl,
        },
        dither,
        mixer::{self, MixerConfig, MixerFn},
        player::{Player, coefficient_to_duration, duration_to_coefficient},
    },
};
use librespot_oauth::OAuthClientBuilder;
use log::{debug, error, info, trace, warn};
use sha1::{Digest, Sha1};
use std::{
    env,
    ffi::OsStr,
    fs::create_dir_all,
    ops::RangeInclusive,
    path::{Path, PathBuf},
    pin::Pin,
    process::exit,
    str::FromStr,
    time::{Duration, Instant},
};
use sysinfo::{ProcessesToUpdate, System};
use thiserror::Error;
use tokio::sync::Semaphore;
use url::Url;

mod player_event_handler;
use player_event_handler::{EventHandler, run_program_on_sink_events};

fn device_id(name: &str) -> String {
    HEXLOWER.encode(&Sha1::digest(name.as_bytes()))
}

fn usage(program: &str, opts: &getopts::Options) -> String {
    let repo_home = env!("CARGO_PKG_REPOSITORY");
    let desc = env!("CARGO_PKG_DESCRIPTION");
    let version = get_version_string();
    let brief = format!("{version}\n\n{desc}\n\n{repo_home}\n\nUsage: {program} [<Options>]");
    opts.usage(&brief)
}

fn setup_logging(quiet: bool, verbose: bool) {
    let mut builder = env_logger::Builder::new();
    match env::var("RUST_LOG") {
        Ok(config) => {
            builder.parse_filters(&config);
            builder.init();

            if verbose {
                warn!("`--verbose` flag overidden by `RUST_LOG` environment variable");
            } else if quiet {
                warn!("`--quiet` flag overidden by `RUST_LOG` environment variable");
            }
        }
        Err(_) => {
            if verbose {
                builder.parse_filters("libmdns=info,librespot=trace");
            } else if quiet {
                builder.parse_filters("libmdns=warn,librespot=warn");
            } else {
                builder.parse_filters("libmdns=info,librespot=info");
            }
            builder.init();

            if verbose && quiet {
                warn!(
                    "`--verbose` and `--quiet` are mutually exclusive. Logging can not be both verbose and quiet. Using verbose mode."
                );
            }
        }
    }
}

fn list_backends() {
    println!("Available backends: ");
    for (&(name, _), idx) in BACKENDS.iter().zip(0..) {
        if idx == 0 {
            println!("- {name} (default)");
        } else {
            println!("- {name}");
        }
    }
}

#[derive(Debug, Error)]
pub enum ParseFileSizeError {
    #[error("empty argument")]
    EmptyInput,
    #[error("invalid suffix")]
    InvalidSuffix,
    #[error("invalid number: {0}")]
    InvalidNumber(#[from] std::num::ParseFloatError),
    #[error("non-finite number specified")]
    NotFinite(f64),
}

pub fn parse_file_size(input: &str) -> Result<u64, ParseFileSizeError> {
    use ParseFileSizeError::*;

    let mut iter = input.chars();
    let mut suffix = iter.next_back().ok_or(EmptyInput)?;
    let mut suffix_len = 0;

    let iec = matches!(suffix, 'i' | 'I');

    if iec {
        suffix_len += 1;
        suffix = iter.next_back().ok_or(InvalidSuffix)?;
    }

    let base: u64 = if iec { 1024 } else { 1000 };

    suffix_len += 1;
    let exponent = match suffix.to_ascii_uppercase() {
        '0'..='9' if !iec => {
            suffix_len -= 1;
            0
        }
        'K' => 1,
        'M' => 2,
        'G' => 3,
        'T' => 4,
        'P' => 5,
        'E' => 6,
        'Z' => 7,
        'Y' => 8,
        _ => return Err(InvalidSuffix),
    };

    let num = {
        let mut iter = input.chars();

        for _ in (&mut iter).rev().take(suffix_len) {}

        iter.as_str().parse::<f64>()?
    };

    if !num.is_finite() {
        return Err(NotFinite(num));
    }

    Ok((num * base.pow(exponent) as f64) as u64)
}

fn get_version_string() -> String {
    #[cfg(debug_assertions)]
    const BUILD_PROFILE: &str = "debug";
    #[cfg(not(debug_assertions))]
    const BUILD_PROFILE: &str = "release";

    format!(
        "librespot {semver} {sha} (Built on {build_date}, Build ID: {build_id}, Profile: {build_profile})",
        semver = version::SEMVER,
        sha = version::SHA_SHORT,
        build_date = version::BUILD_DATE,
        build_id = version::BUILD_ID,
        build_profile = BUILD_PROFILE
    )
}

/// Spotify's Desktop app uses these. Some of these are only available when requested with Spotify's client IDs.
static OAUTH_SCOPES: &[&str] = &[
    //const OAUTH_SCOPES: Vec<&str> = vec![
    "app-remote-control",
    "playlist-modify",
    "playlist-modify-private",
    "playlist-modify-public",
    "playlist-read",
    "playlist-read-collaborative",
    "playlist-read-private",
    "streaming",
    "ugc-image-upload",
    "user-follow-modify",
    "user-follow-read",
    "user-library-modify",
    "user-library-read",
    "user-modify",
    "user-modify-playback-state",
    "user-modify-private",
    "user-personalized",
    "user-read-birthdate",
    "user-read-currently-playing",
    "user-read-email",
    "user-read-play-history",
    "user-read-playback-position",
    "user-read-playback-state",
    "user-read-private",
    "user-read-recently-played",
    "user-top-read",
];

struct Setup {
    format: AudioFormat,
    backend: SinkBuilder,
    device: Option<String>,
    mixer: MixerFn,
    cache: Option<Cache>,
    player_config: PlayerConfig,
    session_config: SessionConfig,
    connect_config: ConnectConfig,
    mixer_config: MixerConfig,
    credentials: Option<Credentials>,
    enable_oauth: bool,
    oauth_port: Option<u16>,
    zeroconf_port: u16,
    player_event_program: Option<String>,
    emit_sink_events: bool,
    zeroconf_ip: Vec<std::net::IpAddr>,
    zeroconf_backend: Option<DnsSdServiceBuilder>,
}

async fn get_setup() -> Setup {
    const VALID_INITIAL_VOLUME_RANGE: RangeInclusive<u16> = 0..=100;
    const VALID_VOLUME_RANGE: RangeInclusive<f64> = 0.0..=100.0;
    const VALID_NORMALISATION_KNEE_RANGE: RangeInclusive<f64> = 0.0..=10.0;
    const VALID_NORMALISATION_PREGAIN_RANGE: RangeInclusive<f64> = -10.0..=10.0;
    const VALID_NORMALISATION_THRESHOLD_RANGE: RangeInclusive<f64> = -10.0..=0.0;
    const VALID_NORMALISATION_ATTACK_RANGE: RangeInclusive<u64> = 1..=500;
    const VALID_NORMALISATION_RELEASE_RANGE: RangeInclusive<u64> = 1..=1000;

    const ACCESS_TOKEN: &str = "access-token";
    const AP_PORT: &str = "ap-port";
    const AUTOPLAY: &str = "autoplay";
    const BACKEND: &str = "backend";
    const BITRATE: &str = "bitrate";
    const CACHE: &str = "cache";
    const CACHE_SIZE_LIMIT: &str = "cache-size-limit";
    const DEVICE: &str = "device";
    const DEVICE_TYPE: &str = "device-type";
    const DEVICE_IS_GROUP: &str = "group";
    const DISABLE_AUDIO_CACHE: &str = "disable-audio-cache";
    const DISABLE_CREDENTIAL_CACHE: &str = "disable-credential-cache";
    const DISABLE_DISCOVERY: &str = "disable-discovery";
    const DISABLE_GAPLESS: &str = "disable-gapless";
    const DITHER: &str = "dither";
    const EMIT_SINK_EVENTS: &str = "emit-sink-events";
    const ENABLE_OAUTH: &str = "enable-oauth";
    const ENABLE_VOLUME_NORMALISATION: &str = "enable-volume-normalisation";
    const FORMAT: &str = "format";
    const HELP: &str = "help";
    const INITIAL_VOLUME: &str = "initial-volume";
    const MIXER_TYPE: &str = "mixer";
    const ALSA_MIXER_DEVICE: &str = "alsa-mixer-device";
    const ALSA_MIXER_INDEX: &str = "alsa-mixer-index";
    const ALSA_MIXER_CONTROL: &str = "alsa-mixer-control";
    const NAME: &str = "name";
    const NORMALISATION_ATTACK: &str = "normalisation-attack";
    const NORMALISATION_GAIN_TYPE: &str = "normalisation-gain-type";
    const NORMALISATION_KNEE: &str = "normalisation-knee";
    const NORMALISATION_METHOD: &str = "normalisation-method";
    const NORMALISATION_PREGAIN: &str = "normalisation-pregain";
    const NORMALISATION_RELEASE: &str = "normalisation-release";
    const NORMALISATION_THRESHOLD: &str = "normalisation-threshold";
    const OAUTH_PORT: &str = "oauth-port";
    const ONEVENT: &str = "onevent";
    #[cfg(feature = "passthrough-decoder")]
    const PASSTHROUGH: &str = "passthrough";
    const PASSWORD: &str = "password";
    const PROXY: &str = "proxy";
    const QUIET: &str = "quiet";
    const SYSTEM_CACHE: &str = "system-cache";
    const TEMP_DIR: &str = "tmp";
    const USERNAME: &str = "username";
    const VERBOSE: &str = "verbose";
    const VERSION: &str = "version";
    const VOLUME_CTRL: &str = "volume-ctrl";
    const VOLUME_RANGE: &str = "volume-range";
    const VOLUME_STEPS: &str = "volume-steps";
    const ZEROCONF_PORT: &str = "zeroconf-port";
    const ZEROCONF_INTERFACE: &str = "zeroconf-interface";
    const ZEROCONF_BACKEND: &str = "zeroconf-backend";
    const LOCAL_FILE_DIR: &str = "local-file-dir";

    // Mostly arbitrary.
    const AP_PORT_SHORT: &str = "a";
    const AUTOPLAY_SHORT: &str = "A";
    const BACKEND_SHORT: &str = "B";
    const BITRATE_SHORT: &str = "b";
    const SYSTEM_CACHE_SHORT: &str = "C";
    const CACHE_SHORT: &str = "c";
    const DITHER_SHORT: &str = "D";
    const DEVICE_SHORT: &str = "d";
    const VOLUME_CTRL_SHORT: &str = "E";
    const VOLUME_RANGE_SHORT: &str = "e";
    const VOLUME_STEPS_SHORT: &str = ""; // no short flag
    const DEVICE_TYPE_SHORT: &str = "F";
    const FORMAT_SHORT: &str = "f";
    const DISABLE_AUDIO_CACHE_SHORT: &str = "G";
    const DISABLE_GAPLESS_SHORT: &str = "g";
    const DISABLE_CREDENTIAL_CACHE_SHORT: &str = "H";
    const HELP_SHORT: &str = "h";
    const ZEROCONF_INTERFACE_SHORT: &str = "i";
    const ENABLE_OAUTH_SHORT: &str = "j";
    const OAUTH_PORT_SHORT: &str = "K";
    const ACCESS_TOKEN_SHORT: &str = "k";
    const CACHE_SIZE_LIMIT_SHORT: &str = "M";
    const MIXER_TYPE_SHORT: &str = "m";
    const ENABLE_VOLUME_NORMALISATION_SHORT: &str = "N";
    const NAME_SHORT: &str = "n";
    const DISABLE_DISCOVERY_SHORT: &str = "O";
    const ONEVENT_SHORT: &str = "o";
    #[cfg(feature = "passthrough-decoder")]
    const PASSTHROUGH_SHORT: &str = "P";
    const PASSWORD_SHORT: &str = "p";
    const EMIT_SINK_EVENTS_SHORT: &str = "Q";
    const QUIET_SHORT: &str = "q";
    const INITIAL_VOLUME_SHORT: &str = "R";
    const ALSA_MIXER_DEVICE_SHORT: &str = "S";
    const ALSA_MIXER_INDEX_SHORT: &str = "s";
    const ALSA_MIXER_CONTROL_SHORT: &str = "T";
    const TEMP_DIR_SHORT: &str = "t";
    const NORMALISATION_ATTACK_SHORT: &str = "U";
    const USERNAME_SHORT: &str = "u";
    const VERSION_SHORT: &str = "V";
    const VERBOSE_SHORT: &str = "v";
    const NORMALISATION_GAIN_TYPE_SHORT: &str = "W";
    const NORMALISATION_KNEE_SHORT: &str = "w";
    const NORMALISATION_METHOD_SHORT: &str = "X";
    const PROXY_SHORT: &str = "x";
    const NORMALISATION_PREGAIN_SHORT: &str = "Y";
    const NORMALISATION_RELEASE_SHORT: &str = "y";
    const NORMALISATION_THRESHOLD_SHORT: &str = "Z";
    const ZEROCONF_PORT_SHORT: &str = "z";
    const ZEROCONF_BACKEND_SHORT: &str = ""; // no short flag
    const LOCAL_FILE_DIR_SHORT: &str = "l";

    // Options that have different descriptions
    // depending on what backends were enabled at build time.
    #[cfg(feature = "alsa-backend")]
    const MIXER_TYPE_DESC: &str = "Mixer to use {alsa|softvol}. Defaults to softvol.";
    #[cfg(not(feature = "alsa-backend"))]
    const MIXER_TYPE_DESC: &str = "Not supported by the included audio backend(s).";
    #[cfg(any(
        feature = "alsa-backend",
        feature = "rodio-backend",
        feature = "portaudio-backend"
    ))]
    const DEVICE_DESC: &str = "Audio device to use. Use ? to list options if using alsa, portaudio or rodio. Defaults to the backend's default.";
    #[cfg(not(any(
        feature = "alsa-backend",
        feature = "rodio-backend",
        feature = "portaudio-backend"
    )))]
    const DEVICE_DESC: &str = "Not supported by the included audio backend(s).";
    #[cfg(feature = "alsa-backend")]
    const ALSA_MIXER_CONTROL_DESC: &str =
        "Alsa mixer control, e.g. PCM, Master or similar. Defaults to PCM.";
    #[cfg(not(feature = "alsa-backend"))]
    const ALSA_MIXER_CONTROL_DESC: &str = "Not supported by the included audio backend(s).";
    #[cfg(feature = "alsa-backend")]
    const ALSA_MIXER_DEVICE_DESC: &str = "Alsa mixer device, e.g hw:0 or similar from `aplay -l`. Defaults to `--device` if specified, default otherwise.";
    #[cfg(not(feature = "alsa-backend"))]
    const ALSA_MIXER_DEVICE_DESC: &str = "Not supported by the included audio backend(s).";
    #[cfg(feature = "alsa-backend")]
    const ALSA_MIXER_INDEX_DESC: &str = "Alsa index of the cards mixer. Defaults to 0.";
    #[cfg(not(feature = "alsa-backend"))]
    const ALSA_MIXER_INDEX_DESC: &str = "Not supported by the included audio backend(s).";
    #[cfg(feature = "alsa-backend")]
    const INITIAL_VOLUME_DESC: &str = "Initial volume in % from 0 - 100. Default for softvol: 50. For the alsa mixer: the current volume.";
    #[cfg(not(feature = "alsa-backend"))]
    const INITIAL_VOLUME_DESC: &str = "Initial volume in % from 0 - 100. Defaults to 50.";
    #[cfg(feature = "alsa-backend")]
    const VOLUME_RANGE_DESC: &str = "Range of the volume control (dB) from 0.0 to 100.0. Default for softvol: 60.0. For the alsa mixer: what the control supports.";
    #[cfg(not(feature = "alsa-backend"))]
    const VOLUME_RANGE_DESC: &str =
        "Range of the volume control (dB) from 0.0 to 100.0. Defaults to 60.0.";
    const VOLUME_STEPS_DESC: &str =
        "Number of incremental steps when responding to volume control updates. Defaults to 64.";

    let mut opts = getopts::Options::new();
    opts.optflag(
        HELP_SHORT,
        HELP,
        "Print this help menu.",
    )
    .optflag(
        VERSION_SHORT,
        VERSION,
        "Display librespot version string.",
    )
    .optflag(
        VERBOSE_SHORT,
        VERBOSE,
        "Enable verbose log output.",
    )
    .optflag(
        QUIET_SHORT,
        QUIET,
        "Only log warning and error messages.",
    )
    .optflag(
        DISABLE_AUDIO_CACHE_SHORT,
        DISABLE_AUDIO_CACHE,
        "Disable caching of the audio data.",
    )
    .optflag(
        DISABLE_CREDENTIAL_CACHE_SHORT,
        DISABLE_CREDENTIAL_CACHE,
        "Disable caching of credentials.",
    )
    .optflag(
        DISABLE_DISCOVERY_SHORT,
        DISABLE_DISCOVERY,
        "Disable zeroconf discovery mode.",
    )
    .optflag(
        DISABLE_GAPLESS_SHORT,
        DISABLE_GAPLESS,
        "Disable gapless playback.",
    )
    .optflag(
        EMIT_SINK_EVENTS_SHORT,
        EMIT_SINK_EVENTS,
        "Run PROGRAM set by `--onevent` before the sink is opened and after it is closed.",
    )
    .optflag(
        ENABLE_VOLUME_NORMALISATION_SHORT,
        ENABLE_VOLUME_NORMALISATION,
        "Play all tracks at approximately the same apparent volume.",
    )
    .optflag(
        ENABLE_OAUTH_SHORT,
        ENABLE_OAUTH,
        "Perform interactive OAuth sign in.",
    )
    .optopt(
        NAME_SHORT,
        NAME,
        "Device name. Defaults to Librespot.",
        "NAME",
    )
    .optopt(
        BITRATE_SHORT,
        BITRATE,
        "Bitrate (kbps) {96|160|320}. Defaults to 160.",
        "BITRATE",
    )
    .optopt(
        FORMAT_SHORT,
        FORMAT,
        "Output format {F64|F32|S32|S24|S24_3|S16}. Defaults to S16.",
        "FORMAT",
    )
    .optopt(
        DITHER_SHORT,
        DITHER,
        "Specify the dither algorithm to use {none|gpdf|tpdf|tpdf_hp}. Defaults to tpdf for formats S16, S24, S24_3 and none for other formats.",
        "DITHER",
    )
    .optopt(
        DEVICE_TYPE_SHORT,
        DEVICE_TYPE,
        "Displayed device type. Defaults to speaker.",
        "TYPE",
    ).optflag(
        "",
        DEVICE_IS_GROUP,
        "Whether the device represents a group. Defaults to false.",
    )
    .optopt(
        TEMP_DIR_SHORT,
        TEMP_DIR,
        "Path to a directory where files will be temporarily stored while downloading.",
        "PATH",
    )
    .optopt(
        CACHE_SHORT,
        CACHE,
        "Path to a directory where files will be cached after downloading.",
        "PATH",
    )
    .optopt(
        SYSTEM_CACHE_SHORT,
        SYSTEM_CACHE,
        "Path to a directory where system files (credentials, volume) will be cached. May be different from the `--cache` option value.",
        "PATH",
    )
    .optopt(
        CACHE_SIZE_LIMIT_SHORT,
        CACHE_SIZE_LIMIT,
        "Limits the size of the cache for audio files. It's possible to use suffixes like K, M or G, e.g. 16G for example.",
        "SIZE"
    )
    .optopt(
        BACKEND_SHORT,
        BACKEND,
        "Audio backend to use. Use ? to list options.",
        "NAME",
    )
    .optopt(
        USERNAME_SHORT,
        USERNAME,
        "Username used to sign in with.",
        "USERNAME",
    )
    .optopt(
        PASSWORD_SHORT,
        PASSWORD,
        "Password used to sign in with.",
        "PASSWORD",
    )
    .optopt(
        ACCESS_TOKEN_SHORT,
        ACCESS_TOKEN,
        "Spotify access token to sign in with.",
        "TOKEN",
    )
    .optopt(
        OAUTH_PORT_SHORT,
        OAUTH_PORT,
        "The port the oauth redirect server uses 1 - 65535. Ports <= 1024 may require root privileges.",
        "PORT",
    )
    .optopt(
        ONEVENT_SHORT,
        ONEVENT,
        "Run PROGRAM when a playback event occurs.",
        "PROGRAM",
    )
    .optopt(
        ALSA_MIXER_CONTROL_SHORT,
        ALSA_MIXER_CONTROL,
        ALSA_MIXER_CONTROL_DESC,
        "NAME",
    )
    .optopt(
        ALSA_MIXER_DEVICE_SHORT,
        ALSA_MIXER_DEVICE,
        ALSA_MIXER_DEVICE_DESC,
        "DEVICE",
    )
    .optopt(
        ALSA_MIXER_INDEX_SHORT,
        ALSA_MIXER_INDEX,
        ALSA_MIXER_INDEX_DESC,
        "NUMBER",
    )
    .optopt(
        MIXER_TYPE_SHORT,
        MIXER_TYPE,
        MIXER_TYPE_DESC,
        "MIXER",
    )
    .optopt(
        DEVICE_SHORT,
        DEVICE,
        DEVICE_DESC,
        "NAME",
    )
    .optopt(
        INITIAL_VOLUME_SHORT,
        INITIAL_VOLUME,
        INITIAL_VOLUME_DESC,
        "VOLUME",
    )
    .optopt(
        VOLUME_CTRL_SHORT,
        VOLUME_CTRL,
        "Volume control scale type {cubic|fixed|linear|log}. Defaults to log.",
        "VOLUME_CTRL"
    )
    .optopt(
        VOLUME_RANGE_SHORT,
        VOLUME_RANGE,
        VOLUME_RANGE_DESC,
        "RANGE",
    )
    .optopt(
        VOLUME_STEPS_SHORT,
        VOLUME_STEPS,
        VOLUME_STEPS_DESC,
        "STEPS",
    )
    .optopt(
        NORMALISATION_METHOD_SHORT,
        NORMALISATION_METHOD,
        "Specify the normalisation method to use {basic|dynamic}. Defaults to dynamic.",
        "METHOD",
    )
    .optopt(
        NORMALISATION_GAIN_TYPE_SHORT,
        NORMALISATION_GAIN_TYPE,
        "Specify the normalisation gain type to use {track|album|auto}. Defaults to auto.",
        "TYPE",
    )
    .optopt(
        NORMALISATION_PREGAIN_SHORT,
        NORMALISATION_PREGAIN,
        "Pregain (dB) applied by volume normalisation from -10.0 to 10.0. Defaults to 0.0.",
        "PREGAIN",
    )
    .optopt(
        NORMALISATION_THRESHOLD_SHORT,
        NORMALISATION_THRESHOLD,
        "Threshold (dBFS) at which point the dynamic limiter engages to prevent clipping from 0.0 to -10.0. Defaults to -2.0.",
        "THRESHOLD",
    )
    .optopt(
        NORMALISATION_ATTACK_SHORT,
        NORMALISATION_ATTACK,
        "Attack time (ms) in which the dynamic limiter reduces gain from 1 to 500. Defaults to 5.",
        "TIME",
    )
    .optopt(
        NORMALISATION_RELEASE_SHORT,
        NORMALISATION_RELEASE,
        "Release or decay time (ms) in which the dynamic limiter restores gain from 1 to 1000. Defaults to 100.",
        "TIME",
    )
    .optopt(
        NORMALISATION_KNEE_SHORT,
        NORMALISATION_KNEE,
        "Knee width (dB) of the dynamic limiter from 0.0 to 10.0. Defaults to 5.0.",
        "KNEE",
    )
    .optopt(
        ZEROCONF_PORT_SHORT,
        ZEROCONF_PORT,
        "The port the internal server advertises over zeroconf 1 - 65535. Ports <= 1024 may require root privileges.",
        "PORT",
    )
    .optopt(
        PROXY_SHORT,
        PROXY,
        "HTTP proxy to use when connecting.",
        "URL",
    )
    .optopt(
        AP_PORT_SHORT,
        AP_PORT,
        "Connect to an AP with a specified port 1 - 65535. Available ports are usually 80, 443 and 4070.",
        "PORT",
    )
    .optopt(
        AUTOPLAY_SHORT,
        AUTOPLAY,
        "Explicitly set autoplay {on|off}. Defaults to following the client setting.",
        "OVERRIDE",
    )
    .optopt(
        ZEROCONF_INTERFACE_SHORT,
        ZEROCONF_INTERFACE,
        "Comma-separated interface IP addresses on which zeroconf will bind. Defaults to all interfaces. Ignored by DNS-SD.",
        "IP"
    )
    .optopt(
        ZEROCONF_BACKEND_SHORT,
        ZEROCONF_BACKEND,
        "Zeroconf (MDNS/DNS-SD) backend to use. Valid values are 'avahi', 'dns-sd' and 'libmdns', if librespot is compiled with the corresponding feature flags.",
        "BACKEND"
    ).optmulti(
        LOCAL_FILE_DIR_SHORT,
        LOCAL_FILE_DIR,
        "Directory to search for local file playback. Can be specified multiple times to add multiple search directories",
        "DIRECTORY"
    );

    #[cfg(feature = "passthrough-decoder")]
    opts.optflag(
        PASSTHROUGH_SHORT,
        PASSTHROUGH,
        "Pass a raw stream to the output. Only works with the pipe and subprocess backends.",
    );

    let args: Vec<_> = std::env::args_os()
        .filter_map(|s| match s.into_string() {
            Ok(valid) => Some(valid),
            Err(s) => {
                eprintln!(
                    "Command line argument was not valid Unicode and will not be evaluated: {s:?}"
                );
                None
            }
        })
        .collect();

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(e) => {
            eprintln!("Error parsing command line options: {e}");
            println!("\n{}", usage(&args[0], &opts));
            exit(1);
        }
    };

    let stripped_env_key = |k: &str| {
        k.trim_start_matches("LIBRESPOT_")
            .replace('_', "-")
            .to_lowercase()
    };

    let env_vars: Vec<_> = env::vars_os().filter_map(|(k, v)| match k.into_string() {
        Ok(key) if key.starts_with("LIBRESPOT_") => {
            let stripped_key = stripped_env_key(&key);
            // We only care about long option/flag names.
            if stripped_key.chars().count() > 1 && matches.opt_defined(&stripped_key) {
                match v.into_string() {
                    Ok(value) => Some((key, value)),
                    Err(s) => {
                        eprintln!("Environment variable was not valid Unicode and will not be evaluated: {key}={s:?}");
                        None
                    }
                }
            } else {
                None
            }
        },
        _ => None
    })
    .collect();

    let opt_present =
        |opt| matches.opt_present(opt) || env_vars.iter().any(|(k, _)| stripped_env_key(k) == opt);

    let opt_str = |opt| {
        if matches.opt_present(opt) {
            matches.opt_str(opt)
        } else {
            env_vars
                .iter()
                .find(|(k, _)| stripped_env_key(k) == opt)
                .map(|(_, v)| v.to_string())
        }
    };

    if opt_present(HELP) {
        println!("{}", usage(&args[0], &opts));
        exit(0);
    }

    if opt_present(VERSION) {
        println!("{}", get_version_string());
        exit(0);
    }

    setup_logging(opt_present(QUIET), opt_present(VERBOSE));

    info!("{}", get_version_string());

    if !env_vars.is_empty() {
        trace!("Environment variable(s):");

        for (k, v) in &env_vars {
            if matches!(
                k.as_str(),
                "LIBRESPOT_PASSWORD" | "LIBRESPOT_USERNAME" | "LIBRESPOT_ACCESS_TOKEN"
            ) {
                trace!("\t\t{k}=\"XXXXXXXX\"");
            } else if v.is_empty() {
                trace!("\t\t{k}=");
            } else {
                trace!("\t\t{k}=\"{v}\"");
            }
        }
    }

    let args_len = args.len();

    if args_len > 1 {
        trace!("Command line argument(s):");

        for (index, key) in args.iter().enumerate() {
            let opt = {
                let key = key.trim_start_matches('-');

                if let Some((s, _)) = key.split_once('=') {
                    s
                } else {
                    key
                }
            };

            if index > 0
                && key.starts_with('-')
                && &args[index - 1] != key
                && matches.opt_defined(opt)
                && matches.opt_present(opt)
            {
                if matches!(
                    opt,
                    PASSWORD
                        | PASSWORD_SHORT
                        | USERNAME
                        | USERNAME_SHORT
                        | ACCESS_TOKEN
                        | ACCESS_TOKEN_SHORT
                ) {
                    // Don't log creds.
                    trace!("\t\t{opt} \"XXXXXXXX\"");
                } else {
                    let value = matches.opt_str(opt).unwrap_or_default();
                    if value.is_empty() {
                        trace!("\t\t{opt}");
                    } else {
                        trace!("\t\t{opt} \"{value}\"");
                    }
                }
            }
        }
    }

    #[cfg(not(feature = "alsa-backend"))]
    for a in &[
        MIXER_TYPE,
        ALSA_MIXER_DEVICE,
        ALSA_MIXER_INDEX,
        ALSA_MIXER_CONTROL,
    ] {
        if opt_present(a) {
            warn!(
                "Alsa specific options have no effect if the alsa backend is not enabled at build time."
            );
            break;
        }
    }

    let backend_name = opt_str(BACKEND);
    if backend_name == Some("?".into()) {
        list_backends();
        exit(0);
    }

    // Can't use `-> fmt::Arguments` due to https://github.com/rust-lang/rust/issues/92698
    fn format_flag(long: &str, short: &str) -> String {
        if short.is_empty() {
            format!("`--{long}`")
        } else {
            format!("`--{long}` / `-{short}`")
        }
    }

    let invalid_error_msg =
        |long: &str, short: &str, invalid: &str, valid_values: &str, default_value: &str| {
            let flag = format_flag(long, short);
            error!("Invalid {flag}: \"{invalid}\"");

            if !valid_values.is_empty() {
                println!("Valid {flag} values: {valid_values}");
            }

            if !default_value.is_empty() {
                println!("Default: {default_value}");
            }
        };

    let empty_string_error_msg = |long: &str, short: &str| {
        error!("`--{long}` / `-{short}` can not be an empty string");
        exit(1);
    };

    let backend = audio_backend::find(backend_name).unwrap_or_else(|| {
        invalid_error_msg(
            BACKEND,
            BACKEND_SHORT,
            &opt_str(BACKEND).unwrap_or_default(),
            "",
            "",
        );

        list_backends();
        exit(1);
    });

    let format = opt_str(FORMAT)
        .as_deref()
        .map(|format| {
            AudioFormat::from_str(format).unwrap_or_else(|_| {
                let default_value = &format!("{:?}", AudioFormat::default());
                invalid_error_msg(
                    FORMAT,
                    FORMAT_SHORT,
                    format,
                    "F64, F32, S32, S24, S24_3, S16",
                    default_value,
                );

                exit(1);
            })
        })
        .unwrap_or_default();

    let device = opt_str(DEVICE);
    if let Some(ref value) = device {
        if value == "?" {
            backend(device, format);
            exit(0);
        } else if value.is_empty() {
            empty_string_error_msg(DEVICE, DEVICE_SHORT);
        }
    }

    #[cfg(feature = "alsa-backend")]
    let mixer_type = opt_str(MIXER_TYPE);
    #[cfg(not(feature = "alsa-backend"))]
    let mixer_type: Option<String> = None;

    let mixer = mixer::find(mixer_type.as_deref()).unwrap_or_else(|| {
        invalid_error_msg(
            MIXER_TYPE,
            MIXER_TYPE_SHORT,
            &opt_str(MIXER_TYPE).unwrap_or_default(),
            "alsa, softvol",
            "softvol",
        );

        exit(1);
    });

    let is_alsa_mixer = match mixer_type.as_deref() {
        #[cfg(feature = "alsa-backend")]
        Some(AlsaMixer::NAME) => true,
        _ => false,
    };

    #[cfg(feature = "alsa-backend")]
    if !is_alsa_mixer {
        for a in &[ALSA_MIXER_DEVICE, ALSA_MIXER_INDEX, ALSA_MIXER_CONTROL] {
            if opt_present(a) {
                warn!("Alsa specific mixer options have no effect if not using the alsa mixer.");
                break;
            }
        }
    }

    let mixer_config = {
        let mixer_default_config = MixerConfig::default();

        #[cfg(feature = "alsa-backend")]
        let index = if !is_alsa_mixer {
            mixer_default_config.index
        } else {
            opt_str(ALSA_MIXER_INDEX)
                .map(|index| {
                    index.parse::<u32>().unwrap_or_else(|_| {
                        invalid_error_msg(
                            ALSA_MIXER_INDEX,
                            ALSA_MIXER_INDEX_SHORT,
                            &index,
                            "",
                            &mixer_default_config.index.to_string(),
                        );

                        exit(1);
                    })
                })
                .unwrap_or_else(|| match device {
                    // Look for the dev index portion of --device.
                    // Specifically <dev index> when --device is <something>:CARD=<card name>,DEV=<dev index>
                    // or <something>:<card index>,<dev index>.

                    // If --device does not contain a ',' it does not contain a dev index.
                    // In the case that the dev index is omitted it is assumed to be 0 (mixer_default_config.index).
                    // Malformed --device values will also fallback to mixer_default_config.index.
                    Some(ref device_name) if device_name.contains(',') => {
                        // Turn <something>:CARD=<card name>,DEV=<dev index> or <something>:<card index>,<dev index>
                        // into DEV=<dev index> or <dev index>.
                        let dev = &device_name[device_name.find(',').unwrap_or_default()..]
                            .trim_start_matches(',');

                        // Turn DEV=<dev index> into <dev index> (noop if it's already <dev index>)
                        // and then parse <dev index>.
                        // Malformed --device values will fail the parse and fallback to mixer_default_config.index.
                        dev[dev.find('=').unwrap_or_default()..]
                            .trim_start_matches('=')
                            .parse::<u32>()
                            .unwrap_or(mixer_default_config.index)
                    }
                    _ => mixer_default_config.index,
                })
        };

        #[cfg(not(feature = "alsa-backend"))]
        let index = mixer_default_config.index;

        #[cfg(feature = "alsa-backend")]
        let device = if !is_alsa_mixer {
            mixer_default_config.device
        } else {
            match opt_str(ALSA_MIXER_DEVICE) {
                Some(mixer_device) => {
                    if mixer_device.is_empty() {
                        empty_string_error_msg(ALSA_MIXER_DEVICE, ALSA_MIXER_DEVICE_SHORT);
                    }

                    mixer_device
                }
                None => match device {
                    Some(ref device_name) => {
                        // Look for the card name or card index portion of --device.
                        // Specifically <card name> when --device is <something>:CARD=<card name>,DEV=<dev index>
                        // or card index when --device is <something>:<card index>,<dev index>.
                        // --device values like `pulse`, `default`, `jack` may be valid but there is no way to
                        // infer automatically what the mixer should be so they fail auto fallback
                        // so --alsa-mixer-device must be manually specified in those situations.
                        let start_index = device_name.find(':').unwrap_or_default();

                        let end_index = match device_name.find(',') {
                            Some(index) if index > start_index => index,
                            _ => device_name.len(),
                        };

                        let card = &device_name[start_index..end_index];

                        if card.starts_with(':') {
                            // mixers are assumed to be hw:CARD=<card name> or hw:<card index>.
                            "hw".to_owned() + card
                        } else {
                            error!(
                                "Could not find an alsa mixer for \"{}\", it must be specified with `--{}` / `-{}`",
                                &device.unwrap_or_default(),
                                ALSA_MIXER_DEVICE,
                                ALSA_MIXER_DEVICE_SHORT
                            );

                            exit(1);
                        }
                    }
                    None => {
                        error!(
                            "`--{}` / `-{}` or `--{}` / `-{}` \
                            must be specified when `--{}` / `-{}` is set to \"alsa\"",
                            DEVICE,
                            DEVICE_SHORT,
                            ALSA_MIXER_DEVICE,
                            ALSA_MIXER_DEVICE_SHORT,
                            MIXER_TYPE,
                            MIXER_TYPE_SHORT
                        );

                        exit(1);
                    }
                },
            }
        };

        #[cfg(not(feature = "alsa-backend"))]
        let device = mixer_default_config.device;

        #[cfg(feature = "alsa-backend")]
        let control = opt_str(ALSA_MIXER_CONTROL).unwrap_or(mixer_default_config.control);

        #[cfg(feature = "alsa-backend")]
        if control.is_empty() {
            empty_string_error_msg(ALSA_MIXER_CONTROL, ALSA_MIXER_CONTROL_SHORT);
        }

        #[cfg(not(feature = "alsa-backend"))]
        let control = mixer_default_config.control;

        let volume_range = opt_str(VOLUME_RANGE)
            .map(|range| match range.parse::<f64>() {
                Ok(value) if (VALID_VOLUME_RANGE).contains(&value) => value,
                _ => {
                    let valid_values = &format!(
                        "{} - {}",
                        VALID_VOLUME_RANGE.start(),
                        VALID_VOLUME_RANGE.end()
                    );

                    #[cfg(feature = "alsa-backend")]
                    let default_value = &format!(
                        "softvol - {}, alsa - what the control supports",
                        VolumeCtrl::DEFAULT_DB_RANGE
                    );

                    #[cfg(not(feature = "alsa-backend"))]
                    let default_value = &VolumeCtrl::DEFAULT_DB_RANGE.to_string();

                    invalid_error_msg(
                        VOLUME_RANGE,
                        VOLUME_RANGE_SHORT,
                        &range,
                        valid_values,
                        default_value,
                    );

                    exit(1);
                }
            })
            .unwrap_or_else(|| {
                if is_alsa_mixer {
                    0.0
                } else {
                    VolumeCtrl::DEFAULT_DB_RANGE
                }
            });

        let volume_ctrl = opt_str(VOLUME_CTRL)
            .as_deref()
            .map(|volume_ctrl| {
                VolumeCtrl::from_str_with_range(volume_ctrl, volume_range).unwrap_or_else(|_| {
                    invalid_error_msg(
                        VOLUME_CTRL,
                        VOLUME_CTRL_SHORT,
                        volume_ctrl,
                        "cubic, fixed, linear, log",
                        "log",
                    );

                    exit(1);
                })
            })
            .unwrap_or_else(|| VolumeCtrl::Log(volume_range));

        MixerConfig {
            device,
            control,
            index,
            volume_ctrl,
        }
    };

    let tmp_dir = opt_str(TEMP_DIR).map_or(SessionConfig::default().tmp_dir, |p| {
        let tmp_dir = PathBuf::from(p);
        if let Err(e) = create_dir_all(&tmp_dir) {
            error!("could not create or access specified tmp directory: {e}");
            exit(1);
        }
        tmp_dir
    });

    let enable_oauth = opt_present(ENABLE_OAUTH);

    let cache = {
        let volume_dir = opt_str(SYSTEM_CACHE)
            .or_else(|| opt_str(CACHE))
            .map(|p| p.into());

        let cred_dir = if opt_present(DISABLE_CREDENTIAL_CACHE) {
            None
        } else {
            volume_dir.clone()
        };

        let audio_dir = if opt_present(DISABLE_AUDIO_CACHE) {
            None
        } else {
            opt_str(CACHE)
                .as_ref()
                .map(|p| AsRef::<Path>::as_ref(p).join("files"))
        };

        let limit = if audio_dir.is_some() {
            opt_str(CACHE_SIZE_LIMIT)
                .as_deref()
                .map(parse_file_size)
                .map(|e| {
                    e.unwrap_or_else(|e| {
                        invalid_error_msg(
                            CACHE_SIZE_LIMIT,
                            CACHE_SIZE_LIMIT_SHORT,
                            &e.to_string(),
                            "",
                            "",
                        );

                        exit(1);
                    })
                })
        } else {
            None
        };

        if audio_dir.is_none() && opt_present(CACHE_SIZE_LIMIT) {
            warn!(
                "Without a `--{CACHE}` / `-{CACHE_SHORT}` path, and/or if the `--{DISABLE_AUDIO_CACHE}` / `-{DISABLE_AUDIO_CACHE_SHORT}` flag is set, `--{CACHE_SIZE_LIMIT}` / `-{CACHE_SIZE_LIMIT_SHORT}` has no effect."
            );
        }

        let cache = match Cache::new(cred_dir.clone(), volume_dir, audio_dir, limit) {
            Ok(cache) => Some(cache),
            Err(e) => {
                warn!("Cannot create cache: {e}");
                None
            }
        };

        if enable_oauth && (cache.is_none() || cred_dir.is_none()) {
            warn!("Credential caching is unavailable, but advisable when using OAuth login.");
        }

        cache
    };

    let credentials = {
        let cached_creds = cache.as_ref().and_then(Cache::credentials);

        if let Some(access_token) = opt_str(ACCESS_TOKEN) {
            if access_token.is_empty() {
                empty_string_error_msg(ACCESS_TOKEN, ACCESS_TOKEN_SHORT);
            }
            Some(Credentials::with_access_token(access_token))
        } else if let Some(username) = opt_str(USERNAME) {
            if username.is_empty() {
                empty_string_error_msg(USERNAME, USERNAME_SHORT);
            }
            if opt_present(PASSWORD) {
                error!(
                    "Invalid `--{PASSWORD}` / `-{PASSWORD_SHORT}`: Password authentication no longer supported, use OAuth"
                );
                exit(1);
            }
            match cached_creds {
                Some(creds) if Some(username) == creds.username => {
                    trace!("Using cached credentials for specified username.");
                    Some(creds)
                }
                _ => {
                    trace!("No cached credentials for specified username.");
                    None
                }
            }
        } else {
            if cached_creds.is_some() {
                trace!("Using cached credentials.");
            }
            cached_creds
        }
    };

    let no_discovery_reason = if !cfg!(any(
        feature = "with-libmdns",
        feature = "with-dns-sd",
        feature = "with-avahi"
    )) {
        Some("librespot compiled without zeroconf backend".to_owned())
    } else if opt_present(DISABLE_DISCOVERY) {
        Some(format!(
            "the `--{DISABLE_DISCOVERY}` / `-{DISABLE_DISCOVERY_SHORT}` flag set",
        ))
    } else {
        None
    };

    if credentials.is_none() && no_discovery_reason.is_some() && !enable_oauth {
        error!("Credentials are required if discovery and oauth login are disabled.");
        exit(1);
    }

    let oauth_port = if opt_present(OAUTH_PORT) {
        if !enable_oauth {
            warn!(
                "Without the `--{ENABLE_OAUTH}` / `-{ENABLE_OAUTH_SHORT}` flag set `--{OAUTH_PORT}` / `-{OAUTH_PORT_SHORT}` has no effect."
            );
        }
        opt_str(OAUTH_PORT)
            .map(|port| match port.parse::<u16>() {
                Ok(value) => {
                    if value > 0 {
                        Some(value)
                    } else {
                        None
                    }
                }
                _ => {
                    let valid_values = &format!("1 - {}", u16::MAX);
                    invalid_error_msg(OAUTH_PORT, OAUTH_PORT_SHORT, &port, valid_values, "");

                    exit(1);
                }
            })
            .unwrap_or(None)
    } else {
        Some(5588)
    };

    if let Some(reason) = no_discovery_reason.as_deref() {
        if opt_present(ZEROCONF_PORT) {
            warn!("With {reason} `--{ZEROCONF_PORT}` / `-{ZEROCONF_PORT_SHORT}` has no effect.");
        }
    }

    let zeroconf_port = if no_discovery_reason.is_none() {
        opt_str(ZEROCONF_PORT)
            .map(|port| match port.parse::<u16>() {
                Ok(value) if value != 0 => value,
                _ => {
                    let valid_values = &format!("1 - {}", u16::MAX);
                    invalid_error_msg(ZEROCONF_PORT, ZEROCONF_PORT_SHORT, &port, valid_values, "");

                    exit(1);
                }
            })
            .unwrap_or(0)
    } else {
        0
    };

    // #1046: not all connections are supplied an `autoplay` user attribute to run statelessly.
    // This knob allows for a manual override.
    let autoplay = match opt_str(AUTOPLAY) {
        Some(value) => match value.as_ref() {
            "on" => Some(true),
            "off" => Some(false),
            _ => {
                invalid_error_msg(
                    AUTOPLAY,
                    AUTOPLAY_SHORT,
                    &opt_str(AUTOPLAY).unwrap_or_default(),
                    "on, off",
                    "",
                );
                exit(1);
            }
        },
        None => SessionConfig::default().autoplay,
    };

    if let Some(reason) = no_discovery_reason.as_deref() {
        if opt_present(ZEROCONF_INTERFACE) {
            warn!(
                "With {} {} has no effect.",
                reason,
                format_flag(ZEROCONF_INTERFACE, ZEROCONF_INTERFACE_SHORT),
            );
        }
    }

    let zeroconf_ip: Vec<std::net::IpAddr> = if opt_present(ZEROCONF_INTERFACE) {
        if let Some(zeroconf_ip) = opt_str(ZEROCONF_INTERFACE) {
            zeroconf_ip
                .split(',')
                .map(|s| {
                    s.trim().parse::<std::net::IpAddr>().unwrap_or_else(|_| {
                        invalid_error_msg(
                            ZEROCONF_INTERFACE,
                            ZEROCONF_INTERFACE_SHORT,
                            s,
                            "IPv4 and IPv6 addresses",
                            "",
                        );
                        exit(1);
                    })
                })
                .collect()
        } else {
            warn!("Unable to use zeroconf-interface option, default to all interfaces.");
            vec![]
        }
    } else {
        vec![]
    };

    if let Some(reason) = no_discovery_reason.as_deref() {
        if opt_present(ZEROCONF_BACKEND) {
            warn!(
                "With {reason} `--{ZEROCONF_BACKEND}` / `-{ZEROCONF_BACKEND_SHORT}` has no effect."
            );
        }
    }

    let zeroconf_backend_name = opt_str(ZEROCONF_BACKEND);
    let zeroconf_backend = no_discovery_reason.is_none().then(|| {
        librespot::discovery::find(zeroconf_backend_name.as_deref()).unwrap_or_else(|_| {
            let available_backends: Vec<_> = librespot::discovery::BACKENDS
                .iter()
                .filter_map(|(id, launch_svc)| launch_svc.map(|_| *id))
                .collect();
            let default_backend = librespot::discovery::BACKENDS
                .iter()
                .find_map(|(id, launch_svc)| launch_svc.map(|_| *id))
                .unwrap_or("<none>");

            invalid_error_msg(
                ZEROCONF_BACKEND,
                ZEROCONF_BACKEND_SHORT,
                &zeroconf_backend_name.unwrap_or_default(),
                &available_backends.join(", "),
                default_backend,
            );

            exit(1);
        })
    });

    let local_file_directories = matches
        .opt_strs(LOCAL_FILE_DIR)
        .into_iter()
        .map(PathBuf::from)
        .collect::<Vec<_>>();

    let connect_config = {
        let connect_default_config = ConnectConfig::default();

        let name = opt_str(NAME);
        if matches!(name, Some(ref name) if name.is_empty()) {
            empty_string_error_msg(NAME, NAME_SHORT);
            exit(1);
        }

        #[cfg(feature = "pulseaudio-backend")]
        {
            if env::var("PULSE_PROP_application.name").is_err() {
                let op_pulseaudio_name = name
                    .as_ref()
                    .map(|name| format!("{} - {}", connect_default_config.name, name));

                let pulseaudio_name = op_pulseaudio_name
                    .as_deref()
                    .unwrap_or(&connect_default_config.name);

                set_env_var("PULSE_PROP_application.name", pulseaudio_name).await;
            }

            if env::var("PULSE_PROP_application.version").is_err() {
                set_env_var("PULSE_PROP_application.version", version::SEMVER).await;
            }

            if env::var("PULSE_PROP_application.icon_name").is_err() {
                set_env_var("PULSE_PROP_application.icon_name", "audio-x-generic").await;
            }

            if env::var("PULSE_PROP_application.process.binary").is_err() {
                set_env_var("PULSE_PROP_application.process.binary", "librespot").await;
            }

            if env::var("PULSE_PROP_stream.description").is_err() {
                set_env_var("PULSE_PROP_stream.description", "Spotify Connect endpoint").await;
            }

            if env::var("PULSE_PROP_media.software").is_err() {
                set_env_var("PULSE_PROP_media.software", "Spotify").await;
            }

            if env::var("PULSE_PROP_media.role").is_err() {
                set_env_var("PULSE_PROP_media.role", "music").await;
            }
        }

        let initial_volume = opt_str(INITIAL_VOLUME)
            .map(|initial_volume| {
                let volume = match initial_volume.parse::<u16>() {
                    Ok(value) if (VALID_INITIAL_VOLUME_RANGE).contains(&value) => value,
                    _ => {
                        let valid_values = &format!(
                            "{} - {}",
                            VALID_INITIAL_VOLUME_RANGE.start(),
                            VALID_INITIAL_VOLUME_RANGE.end()
                        );

                        #[cfg(feature = "alsa-backend")]
                        let default_value = &format!(
                            "{}, or the current value when the alsa mixer is used.",
                            connect_default_config.initial_volume
                        );

                        #[cfg(not(feature = "alsa-backend"))]
                        let default_value = &connect_default_config.initial_volume.to_string();

                        invalid_error_msg(
                            INITIAL_VOLUME,
                            INITIAL_VOLUME_SHORT,
                            &initial_volume,
                            valid_values,
                            default_value,
                        );

                        exit(1);
                    }
                };

                (volume as f32 / 100.0 * VolumeCtrl::MAX_VOLUME as f32) as u16
            })
            .or_else(|| {
                if is_alsa_mixer {
                    None
                } else {
                    cache.as_ref().and_then(Cache::volume)
                }
            });

        let device_type = opt_str(DEVICE_TYPE).as_deref().map(|device_type| {
            DeviceType::from_str(device_type).unwrap_or_else(|_| {
                invalid_error_msg(
                    DEVICE_TYPE,
                    DEVICE_TYPE_SHORT,
                    device_type,
                    "computer, tablet, smartphone, \
                        speaker, tv, avr, stb, audiodongle, \
                        gameconsole, castaudio, castvideo, \
                        automobile, smartwatch, chromebook, \
                        carthing",
                    DeviceType::default().into(),
                );

                exit(1);
            })
        });

        let volume_steps = opt_str(VOLUME_STEPS).map(|steps| match steps.parse::<u16>() {
            Ok(value) => value,
            _ => {
                let default_value = &connect_default_config.volume_steps.to_string();

                invalid_error_msg(
                    VOLUME_STEPS,
                    VOLUME_STEPS_SHORT,
                    &steps,
                    "a positive whole number <= 65535",
                    default_value,
                );

                exit(1);
            }
        });

        let is_group = opt_present(DEVICE_IS_GROUP);

        // use config defaults if not provided
        let name = name.unwrap_or(connect_default_config.name);
        let device_type = device_type.unwrap_or(connect_default_config.device_type);
        let initial_volume = initial_volume.unwrap_or(connect_default_config.initial_volume);
        let volume_steps = volume_steps.unwrap_or(connect_default_config.volume_steps);

        ConnectConfig {
            name,
            device_type,
            is_group,
            initial_volume,
            volume_steps,
            ..connect_default_config
        }
    };

    let session_config = SessionConfig {
        device_id: device_id(&connect_config.name),
        proxy: opt_str(PROXY).or_else(|| std::env::var("http_proxy").ok()).map(
            |s| {
                match Url::parse(&s) {
                    Ok(url) => {
                        if url.host().is_none() || url.port_or_known_default().is_none() {
                            error!("Invalid proxy url, only URLs on the format \"http(s)://host:port\" are allowed");
                            exit(1);
                        }

                        url
                    },
                    Err(e) => {
                        error!("Invalid proxy URL: \"{e}\", only URLs in the format \"http(s)://host:port\" are allowed");
                        exit(1);
                    }
                }
            },
        ),
        ap_port: opt_str(AP_PORT).map(|port| match port.parse::<u16>() {
            Ok(value) if value != 0 => value,
            _ => {
                let valid_values = &format!("1 - {}", u16::MAX);
                invalid_error_msg(AP_PORT, AP_PORT_SHORT, &port, valid_values, "");

                exit(1);
            }
        }),
		tmp_dir,
		autoplay,
		..SessionConfig::default()
    };

    let player_config = {
        let player_default_config = PlayerConfig::default();

        let bitrate = opt_str(BITRATE)
            .as_deref()
            .map(|bitrate| {
                Bitrate::from_str(bitrate).unwrap_or_else(|_| {
                    invalid_error_msg(BITRATE, BITRATE_SHORT, bitrate, "96, 160, 320", "160");
                    exit(1);
                })
            })
            .unwrap_or(player_default_config.bitrate);

        let gapless = !opt_present(DISABLE_GAPLESS);

        let normalisation = opt_present(ENABLE_VOLUME_NORMALISATION);

        let normalisation_method;
        let normalisation_type;
        let normalisation_pregain_db;
        let normalisation_threshold_dbfs;
        let normalisation_attack_cf;
        let normalisation_release_cf;
        let normalisation_knee_db;

        if !normalisation {
            for a in &[
                NORMALISATION_METHOD,
                NORMALISATION_GAIN_TYPE,
                NORMALISATION_PREGAIN,
                NORMALISATION_THRESHOLD,
                NORMALISATION_ATTACK,
                NORMALISATION_RELEASE,
                NORMALISATION_KNEE,
            ] {
                if opt_present(a) {
                    warn!(
                        "Without the `--{ENABLE_VOLUME_NORMALISATION}` / `-{ENABLE_VOLUME_NORMALISATION_SHORT}` flag normalisation options have no effect.",
                    );
                    break;
                }
            }

            normalisation_method = player_default_config.normalisation_method;
            normalisation_type = player_default_config.normalisation_type;
            normalisation_pregain_db = player_default_config.normalisation_pregain_db;
            normalisation_threshold_dbfs = player_default_config.normalisation_threshold_dbfs;
            normalisation_attack_cf = player_default_config.normalisation_attack_cf;
            normalisation_release_cf = player_default_config.normalisation_release_cf;
            normalisation_knee_db = player_default_config.normalisation_knee_db;
        } else {
            normalisation_method = opt_str(NORMALISATION_METHOD)
                .as_deref()
                .map(|method| {
                    NormalisationMethod::from_str(method).unwrap_or_else(|_| {
                        invalid_error_msg(
                            NORMALISATION_METHOD,
                            NORMALISATION_METHOD_SHORT,
                            method,
                            "basic, dynamic",
                            &format!("{:?}", player_default_config.normalisation_method),
                        );

                        exit(1);
                    })
                })
                .unwrap_or(player_default_config.normalisation_method);

            normalisation_type = opt_str(NORMALISATION_GAIN_TYPE)
                .as_deref()
                .map(|gain_type| {
                    NormalisationType::from_str(gain_type).unwrap_or_else(|_| {
                        invalid_error_msg(
                            NORMALISATION_GAIN_TYPE,
                            NORMALISATION_GAIN_TYPE_SHORT,
                            gain_type,
                            "track, album, auto",
                            &format!("{:?}", player_default_config.normalisation_type),
                        );

                        exit(1);
                    })
                })
                .unwrap_or(player_default_config.normalisation_type);

            normalisation_pregain_db = opt_str(NORMALISATION_PREGAIN)
                .map(|pregain| match pregain.parse::<f64>() {
                    Ok(value) if (VALID_NORMALISATION_PREGAIN_RANGE).contains(&value) => value,
                    _ => {
                        let valid_values = &format!(
                            "{} - {}",
                            VALID_NORMALISATION_PREGAIN_RANGE.start(),
                            VALID_NORMALISATION_PREGAIN_RANGE.end()
                        );

                        invalid_error_msg(
                            NORMALISATION_PREGAIN,
                            NORMALISATION_PREGAIN_SHORT,
                            &pregain,
                            valid_values,
                            &player_default_config.normalisation_pregain_db.to_string(),
                        );

                        exit(1);
                    }
                })
                .unwrap_or(player_default_config.normalisation_pregain_db);

            normalisation_threshold_dbfs = opt_str(NORMALISATION_THRESHOLD)
                .map(|threshold| match threshold.parse::<f64>() {
                    Ok(value) if (VALID_NORMALISATION_THRESHOLD_RANGE).contains(&value) => value,
                    _ => {
                        let valid_values = &format!(
                            "{} - {}",
                            VALID_NORMALISATION_THRESHOLD_RANGE.start(),
                            VALID_NORMALISATION_THRESHOLD_RANGE.end()
                        );

                        invalid_error_msg(
                            NORMALISATION_THRESHOLD,
                            NORMALISATION_THRESHOLD_SHORT,
                            &threshold,
                            valid_values,
                            &player_default_config
                                .normalisation_threshold_dbfs
                                .to_string(),
                        );

                        exit(1);
                    }
                })
                .unwrap_or(player_default_config.normalisation_threshold_dbfs);

            normalisation_attack_cf = opt_str(NORMALISATION_ATTACK)
                .map(|attack| match attack.parse::<u64>() {
                    Ok(value) if (VALID_NORMALISATION_ATTACK_RANGE).contains(&value) => {
                        duration_to_coefficient(Duration::from_millis(value))
                    }
                    _ => {
                        let valid_values = &format!(
                            "{} - {}",
                            VALID_NORMALISATION_ATTACK_RANGE.start(),
                            VALID_NORMALISATION_ATTACK_RANGE.end()
                        );

                        invalid_error_msg(
                            NORMALISATION_ATTACK,
                            NORMALISATION_ATTACK_SHORT,
                            &attack,
                            valid_values,
                            &coefficient_to_duration(player_default_config.normalisation_attack_cf)
                                .as_millis()
                                .to_string(),
                        );

                        exit(1);
                    }
                })
                .unwrap_or(player_default_config.normalisation_attack_cf);

            normalisation_release_cf = opt_str(NORMALISATION_RELEASE)
                .map(|release| match release.parse::<u64>() {
                    Ok(value) if (VALID_NORMALISATION_RELEASE_RANGE).contains(&value) => {
                        duration_to_coefficient(Duration::from_millis(value))
                    }
                    _ => {
                        let valid_values = &format!(
                            "{} - {}",
                            VALID_NORMALISATION_RELEASE_RANGE.start(),
                            VALID_NORMALISATION_RELEASE_RANGE.end()
                        );

                        invalid_error_msg(
                            NORMALISATION_RELEASE,
                            NORMALISATION_RELEASE_SHORT,
                            &release,
                            valid_values,
                            &coefficient_to_duration(
                                player_default_config.normalisation_release_cf,
                            )
                            .as_millis()
                            .to_string(),
                        );

                        exit(1);
                    }
                })
                .unwrap_or(player_default_config.normalisation_release_cf);

            normalisation_knee_db = opt_str(NORMALISATION_KNEE)
                .map(|knee| match knee.parse::<f64>() {
                    Ok(value) if (VALID_NORMALISATION_KNEE_RANGE).contains(&value) => value,
                    _ => {
                        let valid_values = &format!(
                            "{} - {}",
                            VALID_NORMALISATION_KNEE_RANGE.start(),
                            VALID_NORMALISATION_KNEE_RANGE.end()
                        );

                        invalid_error_msg(
                            NORMALISATION_KNEE,
                            NORMALISATION_KNEE_SHORT,
                            &knee,
                            valid_values,
                            &player_default_config.normalisation_knee_db.to_string(),
                        );

                        exit(1);
                    }
                })
                .unwrap_or(player_default_config.normalisation_knee_db);
        }

        let ditherer_name = opt_str(DITHER);
        let ditherer = match ditherer_name.as_deref() {
            Some(value) => match value {
                "none" => None,
                _ => match format {
                    AudioFormat::F64 | AudioFormat::F32 => {
                        error!("Dithering is not available with format: {format:?}.");
                        exit(1);
                    }
                    _ => Some(dither::find_ditherer(ditherer_name).unwrap_or_else(|| {
                        invalid_error_msg(
                            DITHER,
                            DITHER_SHORT,
                            &opt_str(DITHER).unwrap_or_default(),
                            "none, gpdf, tpdf, tpdf_hp for formats S16, S24, S24_3, S32, none for formats F32, F64",
                            "tpdf for formats S16, S24, S24_3 and none for formats S32, F32, F64",
                        );

                        exit(1);
                    })),
                },
            },
            None => match format {
                AudioFormat::S16 | AudioFormat::S24 | AudioFormat::S24_3 => {
                    player_default_config.ditherer
                }
                _ => None,
            },
        };

        #[cfg(feature = "passthrough-decoder")]
        let passthrough = opt_present(PASSTHROUGH);
        #[cfg(not(feature = "passthrough-decoder"))]
        let passthrough = false;

        PlayerConfig {
            bitrate,
            gapless,
            passthrough,
            normalisation,
            normalisation_type,
            normalisation_method,
            normalisation_pregain_db,
            normalisation_threshold_dbfs,
            normalisation_attack_cf,
            normalisation_release_cf,
            normalisation_knee_db,
            ditherer,
            position_update_interval: None,
            local_file_directories,
        }
    };

    let player_event_program = opt_str(ONEVENT);
    let emit_sink_events = opt_present(EMIT_SINK_EVENTS);

    Setup {
        format,
        backend,
        device,
        mixer,
        cache,
        player_config,
        session_config,
        connect_config,
        mixer_config,
        credentials,
        enable_oauth,
        oauth_port,
        zeroconf_port,
        player_event_program,
        emit_sink_events,
        zeroconf_ip,
        zeroconf_backend,
    }
}

// Initialize a static semaphore with only one permit, which is used to
// prevent setting environment variables from running in parallel.
static PERMIT: Semaphore = Semaphore::const_new(1);
async fn set_env_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V) {
    let permit = PERMIT
        .acquire()
        .await
        .expect("Failed to acquire semaphore permit");

    // SAFETY: This is safe because setting the environment variable will wait if the permit is
    // already acquired by other callers.
    unsafe { env::set_var(key, value) }

    // Drop the permit manually, so the compiler doesn't optimize it away as unused variable.
    drop(permit);
}

#[tokio::main(flavor = "current_thread")]
async fn main() {
    const RUST_BACKTRACE: &str = "RUST_BACKTRACE";
    const RECONNECT_RATE_LIMIT_WINDOW: Duration = Duration::from_secs(600);
    const DISCOVERY_RETRY_TIMEOUT: Duration = Duration::from_secs(10);
    const RECONNECT_RATE_LIMIT: usize = 5;

    if env::var(RUST_BACKTRACE).is_err() {
        set_env_var(RUST_BACKTRACE, "full").await;
    }

    let setup = get_setup().await;

    let mut last_credentials = None;
    let mut spirc: Option<Spirc> = None;
    let mut spirc_task: Option<Pin<_>> = None;
    let mut auto_connect_times: Vec<Instant> = vec![];
    let mut discovery = None;
    let mut connecting = false;
    let mut _event_handler: Option<EventHandler> = None;

    let mut session = Session::new(setup.session_config.clone(), setup.cache.clone());

    let mut sys = System::new();

    if let Some(zeroconf_backend) = setup.zeroconf_backend {
        // When started at boot as a service discovery may fail due to it
        // trying to bind to interfaces before the network is actually up.
        // This could be prevented in systemd by starting the service after
        // network-online.target but it requires that a wait-online.service is
        // also enabled which is not always the case since a wait-online.service
        // can potentially hang the boot process until it times out in certain situations.
        // This allows for discovery to retry every 10 secs in the 1st min of uptime
        // before giving up thus papering over the issue and not holding up the boot process.

        discovery = loop {
            let device_id = setup.session_config.device_id.clone();
            let client_id = setup.session_config.client_id.clone();

            match librespot::discovery::Discovery::builder(device_id, client_id)
                .name(setup.connect_config.name.clone())
                .device_type(setup.connect_config.device_type)
                .is_group(setup.connect_config.is_group)
                .port(setup.zeroconf_port)
                .zeroconf_ip(setup.zeroconf_ip.clone())
                .zeroconf_backend(zeroconf_backend)
                .launch()
            {
                Ok(d) => break Some(d),
                Err(e) => {
                    sys.refresh_processes(ProcessesToUpdate::All, true);

                    if System::uptime() <= 1 {
                        debug!("Retrying to initialise discovery: {e}");
                        tokio::time::sleep(DISCOVERY_RETRY_TIMEOUT).await;
                    } else {
                        debug!("System uptime > 1 min, not retrying to initialise discovery");
                        warn!("Could not initialise discovery: {e}");
                        break None;
                    }
                }
            }
        };
    }

    if let Some(credentials) = setup.credentials {
        last_credentials = Some(credentials);
        connecting = true;
    } else if setup.enable_oauth {
        let port_str = match setup.oauth_port {
            Some(port) => format!(":{port}"),
            _ => String::new(),
        };
        let client = OAuthClientBuilder::new(
            &setup.session_config.client_id,
            &format!("http://127.0.0.1{port_str}/login"),
            OAUTH_SCOPES.to_vec(),
        )
        .open_in_browser()
        .build()
        .unwrap_or_else(|e| {
            error!("Failed to create OAuth client: {e}");
            exit(1);
        });
        let oauth_token = client.get_access_token().unwrap_or_else(|e| {
            error!("Failed to get Spotify access token: {e}");
            exit(1);
        });
        last_credentials = Some(Credentials::with_access_token(oauth_token.access_token));
        connecting = true;
    } else if discovery.is_none() {
        error!(
            "Discovery is unavailable and no credentials provided. Authentication is not possible."
        );
        exit(1);
    }

    let mixer_config = setup.mixer_config.clone();
    let mixer = match (setup.mixer)(mixer_config) {
        Ok(mixer) => mixer,
        Err(why) => {
            error!("{why}");
            exit(1)
        }
    };
    let player_config = setup.player_config.clone();

    let soft_volume = mixer.get_soft_volume();
    let format = setup.format;
    let backend = setup.backend;
    let device = setup.device.clone();
    let player = Player::new(player_config, session.clone(), soft_volume, move || {
        (backend)(device, format)
    });

    if let Some(player_event_program) = setup.player_event_program.clone() {
        _event_handler = Some(EventHandler::new(
            player.get_player_event_channel(),
            &player_event_program,
        ));

        if setup.emit_sink_events {
            player.set_sink_event_callback(Some(Box::new(move |sink_status| {
                run_program_on_sink_events(sink_status, &player_event_program)
            })));
        }
    }

    loop {
        tokio::select! {
            credentials = async {
                match discovery.as_mut() {
                    Some(d) => d.next().await,
                    _ => None
                }
            }, if discovery.is_some() => {
                match credentials {
                    Some(credentials) => {
                        last_credentials = Some(credentials.clone());
                        auto_connect_times.clear();

                        if let Some(spirc) = spirc.take() {
                            if let Err(e) = spirc.shutdown() {
                                error!("error sending spirc shutdown message: {e}");
                            }
                        }
                        if let Some(spirc_task) = spirc_task.take() {
                            // Continue shutdown in its own task
                            tokio::spawn(spirc_task);
                        }
                        if !session.is_invalid() {
                            session.shutdown();
                        }

                        connecting = true;
                    },
                    None => {
                        error!("Discovery stopped unexpectedly");
                        exit(1);
                    }
                }
            },
            _ = async {}, if connecting && last_credentials.is_some() => {
                if session.is_invalid() {
                    session = Session::new(setup.session_config.clone(), setup.cache.clone());
                    player.set_session(session.clone());
                }

                let connect_config = setup.connect_config.clone();

                let (spirc_, spirc_task_) = match Spirc::new(connect_config,
                                                                session.clone(),
                                                                last_credentials.clone().unwrap_or_default(),
                                                                player.clone(),
                                                                mixer.clone()).await {
                    Ok((spirc_, spirc_task_)) => (spirc_, spirc_task_),
                    Err(e) => {
                        error!("could not initialize spirc: {e}");
                        exit(1);
                    }
                };
                spirc = Some(spirc_);
                spirc_task = Some(Box::pin(spirc_task_));

                connecting = false;
            },
            _ = async {
                if let Some(task) = spirc_task.as_mut() {
                    task.await;
                }
            }, if spirc_task.is_some() && !connecting => {
                spirc_task = None;

                warn!("Spirc shut down unexpectedly");

                let mut reconnect_exceeds_rate_limit = || {
                    auto_connect_times.retain(|&t| t.elapsed() < RECONNECT_RATE_LIMIT_WINDOW);
                    auto_connect_times.len() > RECONNECT_RATE_LIMIT
                };

                if last_credentials.is_some() && !reconnect_exceeds_rate_limit() {
                    auto_connect_times.push(Instant::now());
                    if !session.is_invalid() {
                        session.shutdown();
                    }
                    connecting = true;
                } else {
                    error!("Spirc shut down too often. Not reconnecting automatically.");
                    exit(1);
                }
            },
            _ = async {}, if player.is_invalid() => {
                error!("Player shut down unexpectedly");
                exit(1);
            },
            _ = tokio::signal::ctrl_c() => {
                break;
            },
            else => break,
        }
    }

    info!("Gracefully shutting down");

    let mut shutdown_tasks = tokio::task::JoinSet::new();

    // Shutdown spirc if necessary
    if let Some(spirc) = spirc {
        if let Err(e) = spirc.shutdown() {
            error!("error sending spirc shutdown message: {e}");
        }

        if let Some(spirc_task) = spirc_task {
            shutdown_tasks.spawn(spirc_task);
        }
    }

    if let Some(discovery) = discovery {
        shutdown_tasks.spawn(discovery.shutdown());
    }

    tokio::select! {
        _ = tokio::signal::ctrl_c() => (),
        _ = shutdown_tasks.join_all() => (),
    }
}