forked from librespot-org/librespot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
2077 lines (1869 loc) · 70.6 KB
/
main.rs
File metadata and controls
2077 lines (1869 loc) · 70.6 KB
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
use data_encoding::HEXLOWER;
use futures_util::StreamExt;
use log::{debug, error, info, trace, warn};
use sha1::{Digest, Sha1};
use std::{
env,
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 url::Url;
use librespot::{
connect::{config::ConnectConfig, spirc::Spirc},
core::{
authentication::Credentials, cache::Cache, config::DeviceType, version, Session,
SessionConfig,
},
discovery::DnsSdServiceBuilder,
playback::{
audio_backend::{self, SinkBuilder, BACKENDS},
config::{
AudioFormat, Bitrate, NormalisationMethod, NormalisationType, PlayerConfig, VolumeCtrl,
},
dither,
mixer::{self, MixerConfig, MixerFn},
player::{coefficient_to_duration, duration_to_coefficient, Player},
},
};
#[cfg(feature = "alsa-backend")]
use librespot::playback::mixer::alsamixer::AlsaMixer;
mod player_event_handler;
use player_event_handler::{run_program_on_sink_events, EventHandler};
#[cfg(feature = "with-mpris")]
mod mpris_event_handler;
#[cfg(feature = "with-mpris")]
use mpris_event_handler::MprisEventHandler;
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>,
}
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 ZEROCONF_PORT: &str = "zeroconf-port";
const ZEROCONF_INTERFACE: &str = "zeroconf-interface";
const ZEROCONF_BACKEND: &str = "zeroconf-backend";
// 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 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
// 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.";
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(
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"
);
#[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];