main.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. use futures::sync::mpsc::UnboundedReceiver;
  2. use futures::{Async, Future, Poll, Stream};
  3. use sha1::{Digest, Sha1};
  4. use log::{error, info, trace, warn};
  5. use std::env;
  6. use std::io::{self, stderr, Write};
  7. use std::mem;
  8. use std::path::PathBuf;
  9. use std::process::exit;
  10. use std::str::FromStr;
  11. use tokio_core::reactor::{Core, Handle};
  12. use tokio_io::IoStream;
  13. use url::Url;
  14. use librespot::core::authentication::{get_credentials, Credentials};
  15. use librespot::core::cache::Cache;
  16. use librespot::core::config::{ConnectConfig, DeviceType, SessionConfig};
  17. use librespot::core::session::Session;
  18. use librespot::core::version;
  19. use librespot::connect::discovery::{discovery, DiscoveryStream};
  20. use librespot::connect::spirc::{Spirc, SpircTask};
  21. use librespot::playback::audio_backend::{self, Sink, BACKENDS};
  22. use librespot::playback::config::{Bitrate, PlayerConfig};
  23. use librespot::playback::mixer::{self, Mixer, MixerConfig};
  24. use librespot::playback::player::{Player, PlayerEvent};
  25. mod player_event_handler;
  26. use crate::player_event_handler::run_program_on_events;
  27. fn device_id(name: &str) -> String {
  28. hex::encode(Sha1::digest(name.as_bytes()))
  29. }
  30. fn usage(program: &str, opts: &getopts::Options) -> String {
  31. let brief = format!("Usage: {} [options]", program);
  32. opts.usage(&brief)
  33. }
  34. fn setup_logging(verbose: bool) {
  35. let mut builder = env_logger::Builder::new();
  36. match env::var("RUST_LOG") {
  37. Ok(config) => {
  38. builder.parse_filters(&config);
  39. builder.init();
  40. if verbose {
  41. warn!("`--verbose` flag overidden by `RUST_LOG` environment variable");
  42. }
  43. }
  44. Err(_) => {
  45. if verbose {
  46. builder.parse_filters("mdns=info,librespot=trace");
  47. } else {
  48. builder.parse_filters("mdns=info,librespot=info");
  49. }
  50. builder.init();
  51. }
  52. }
  53. }
  54. fn list_backends() {
  55. println!("Available Backends : ");
  56. for (&(name, _), idx) in BACKENDS.iter().zip(0..) {
  57. if idx == 0 {
  58. println!("- {} (default)", name);
  59. } else {
  60. println!("- {}", name);
  61. }
  62. }
  63. }
  64. #[derive(Clone)]
  65. struct Setup {
  66. backend: fn(Option<String>) -> Box<dyn Sink>,
  67. device: Option<String>,
  68. mixer: fn(Option<MixerConfig>) -> Box<dyn Mixer>,
  69. cache: Option<Cache>,
  70. player_config: PlayerConfig,
  71. session_config: SessionConfig,
  72. connect_config: ConnectConfig,
  73. mixer_config: MixerConfig,
  74. credentials: Option<Credentials>,
  75. enable_discovery: bool,
  76. zeroconf_port: u16,
  77. player_event_program: Option<String>,
  78. }
  79. fn setup(args: &[String]) -> Setup {
  80. let mut opts = getopts::Options::new();
  81. opts.optopt(
  82. "c",
  83. "cache",
  84. "Path to a directory where files will be cached.",
  85. "CACHE",
  86. ).optflag("", "disable-audio-cache", "Disable caching of the audio data.")
  87. .reqopt("n", "name", "Device name", "NAME")
  88. .optopt("", "device-type", "Displayed device type", "DEVICE_TYPE")
  89. .optopt(
  90. "b",
  91. "bitrate",
  92. "Bitrate (96, 160 or 320). Defaults to 160",
  93. "BITRATE",
  94. )
  95. .optopt(
  96. "",
  97. "onevent",
  98. "Run PROGRAM when playback is about to begin.",
  99. "PROGRAM",
  100. )
  101. .optflag("v", "verbose", "Enable verbose output")
  102. .optopt("u", "username", "Username to sign in with", "USERNAME")
  103. .optopt("p", "password", "Password", "PASSWORD")
  104. .optopt("", "proxy", "HTTP proxy to use when connecting", "PROXY")
  105. .optopt("", "ap-port", "Connect to AP with specified port. If no AP with that port are present fallback AP will be used. Available ports are usually 80, 443 and 4070", "AP_PORT")
  106. .optflag("", "disable-discovery", "Disable discovery mode")
  107. .optopt(
  108. "",
  109. "backend",
  110. "Audio backend to use. Use '?' to list options",
  111. "BACKEND",
  112. )
  113. .optopt(
  114. "",
  115. "device",
  116. "Audio device to use. Use '?' to list options if using portaudio or alsa",
  117. "DEVICE",
  118. )
  119. .optopt("", "mixer", "Mixer to use (alsa or softmixer)", "MIXER")
  120. .optopt(
  121. "m",
  122. "mixer-name",
  123. "Alsa mixer name, e.g \"PCM\" or \"Master\". Defaults to 'PCM'",
  124. "MIXER_NAME",
  125. )
  126. .optopt(
  127. "",
  128. "mixer-card",
  129. "Alsa mixer card, e.g \"hw:0\" or similar from `aplay -l`. Defaults to 'default' ",
  130. "MIXER_CARD",
  131. )
  132. .optopt(
  133. "",
  134. "mixer-index",
  135. "Alsa mixer index, Index of the cards mixer. Defaults to 0",
  136. "MIXER_INDEX",
  137. )
  138. .optopt(
  139. "",
  140. "initial-volume",
  141. "Initial volume in %, once connected (must be from 0 to 100)",
  142. "VOLUME",
  143. )
  144. .optopt(
  145. "",
  146. "zeroconf-port",
  147. "The port the internal server advertised over zeroconf uses.",
  148. "ZEROCONF_PORT",
  149. )
  150. .optflag(
  151. "",
  152. "enable-volume-normalisation",
  153. "Play all tracks at the same volume",
  154. )
  155. .optopt(
  156. "",
  157. "normalisation-pregain",
  158. "Pregain (dB) applied by volume normalisation",
  159. "PREGAIN",
  160. )
  161. .optflag(
  162. "",
  163. "linear-volume",
  164. "increase volume linear instead of logarithmic.",
  165. )
  166. .optflag(
  167. "",
  168. "autoplay",
  169. "autoplay similar songs when your music ends.",
  170. );
  171. let matches = match opts.parse(&args[1..]) {
  172. Ok(m) => m,
  173. Err(f) => {
  174. writeln!(stderr(), "error: {}\n{}", f.to_string(), usage(&args[0], &opts)).unwrap();
  175. exit(1);
  176. }
  177. };
  178. let verbose = matches.opt_present("verbose");
  179. setup_logging(verbose);
  180. info!(
  181. "librespot {} ({}). Built on {}. Build ID: {}",
  182. version::short_sha(),
  183. version::commit_date(),
  184. version::short_now(),
  185. version::build_id()
  186. );
  187. let backend_name = matches.opt_str("backend");
  188. if backend_name == Some("?".into()) {
  189. list_backends();
  190. exit(0);
  191. }
  192. let backend = audio_backend::find(backend_name).expect("Invalid backend");
  193. let device = matches.opt_str("device");
  194. if device == Some("?".into()) {
  195. backend(device);
  196. exit(0);
  197. }
  198. let mixer_name = matches.opt_str("mixer");
  199. let mixer = mixer::find(mixer_name.as_ref()).expect("Invalid mixer");
  200. let mixer_config = MixerConfig {
  201. card: matches.opt_str("mixer-card").unwrap_or(String::from("default")),
  202. mixer: matches.opt_str("mixer-name").unwrap_or(String::from("PCM")),
  203. index: matches
  204. .opt_str("mixer-index")
  205. .map(|index| index.parse::<u32>().unwrap())
  206. .unwrap_or(0),
  207. };
  208. let use_audio_cache = !matches.opt_present("disable-audio-cache");
  209. let cache = matches
  210. .opt_str("c")
  211. .map(|cache_location| Cache::new(PathBuf::from(cache_location), use_audio_cache));
  212. let initial_volume = matches
  213. .opt_str("initial-volume")
  214. .map(|volume| {
  215. let volume = volume.parse::<u16>().unwrap();
  216. if volume > 100 {
  217. panic!("Initial volume must be in the range 0-100");
  218. }
  219. (volume as i32 * 0xFFFF / 100) as u16
  220. })
  221. .or_else(|| cache.as_ref().and_then(Cache::volume))
  222. .unwrap_or(0x8000);
  223. let zeroconf_port = matches
  224. .opt_str("zeroconf-port")
  225. .map(|port| port.parse::<u16>().unwrap())
  226. .unwrap_or(0);
  227. let name = matches.opt_str("name").unwrap();
  228. let credentials = {
  229. let cached_credentials = cache.as_ref().and_then(Cache::credentials);
  230. let password = |username: &String| -> String {
  231. write!(stderr(), "Password for {}: ", username).unwrap();
  232. stderr().flush().unwrap();
  233. rpassword::read_password().unwrap()
  234. };
  235. get_credentials(
  236. matches.opt_str("username"),
  237. matches.opt_str("password"),
  238. cached_credentials,
  239. password,
  240. )
  241. };
  242. let session_config = {
  243. let device_id = device_id(&name);
  244. SessionConfig {
  245. user_agent: version::version_string(),
  246. device_id: device_id,
  247. proxy: matches.opt_str("proxy").or(std::env::var("http_proxy").ok()).map(
  248. |s| {
  249. match Url::parse(&s) {
  250. Ok(url) => {
  251. if url.host().is_none() || url.port().is_none() {
  252. panic!("Invalid proxy url, only urls on the format \"http://host:port\" are allowed");
  253. }
  254. if url.scheme() != "http" {
  255. panic!("Only unsecure http:// proxies are supported");
  256. }
  257. url
  258. },
  259. Err(err) => panic!("Invalid proxy url: {}, only urls on the format \"http://host:port\" are allowed", err)
  260. }
  261. },
  262. ),
  263. ap_port: matches
  264. .opt_str("ap-port")
  265. .map(|port| port.parse::<u16>().expect("Invalid port")),
  266. }
  267. };
  268. let player_config = {
  269. let bitrate = matches
  270. .opt_str("b")
  271. .as_ref()
  272. .map(|bitrate| Bitrate::from_str(bitrate).expect("Invalid bitrate"))
  273. .unwrap_or(Bitrate::default());
  274. PlayerConfig {
  275. bitrate: bitrate,
  276. normalisation: matches.opt_present("enable-volume-normalisation"),
  277. normalisation_pregain: matches
  278. .opt_str("normalisation-pregain")
  279. .map(|pregain| pregain.parse::<f32>().expect("Invalid pregain float value"))
  280. .unwrap_or(PlayerConfig::default().normalisation_pregain),
  281. }
  282. };
  283. let connect_config = {
  284. let device_type = matches
  285. .opt_str("device-type")
  286. .as_ref()
  287. .map(|device_type| DeviceType::from_str(device_type).expect("Invalid device type"))
  288. .unwrap_or(DeviceType::default());
  289. ConnectConfig {
  290. name: name,
  291. device_type: device_type,
  292. volume: initial_volume,
  293. linear_volume: matches.opt_present("linear-volume"),
  294. autoplay: matches.opt_present("autoplay"),
  295. }
  296. };
  297. let enable_discovery = !matches.opt_present("disable-discovery");
  298. Setup {
  299. backend: backend,
  300. cache: cache,
  301. session_config: session_config,
  302. player_config: player_config,
  303. connect_config: connect_config,
  304. credentials: credentials,
  305. device: device,
  306. enable_discovery: enable_discovery,
  307. zeroconf_port: zeroconf_port,
  308. mixer: mixer,
  309. mixer_config: mixer_config,
  310. player_event_program: matches.opt_str("onevent"),
  311. }
  312. }
  313. struct Main {
  314. cache: Option<Cache>,
  315. player_config: PlayerConfig,
  316. session_config: SessionConfig,
  317. connect_config: ConnectConfig,
  318. backend: fn(Option<String>) -> Box<dyn Sink>,
  319. device: Option<String>,
  320. mixer: fn(Option<MixerConfig>) -> Box<dyn Mixer>,
  321. mixer_config: MixerConfig,
  322. handle: Handle,
  323. discovery: Option<DiscoveryStream>,
  324. signal: IoStream<()>,
  325. spirc: Option<Spirc>,
  326. spirc_task: Option<SpircTask>,
  327. connect: Box<dyn Future<Item = Session, Error = io::Error>>,
  328. shutdown: bool,
  329. player_event_channel: Option<UnboundedReceiver<PlayerEvent>>,
  330. player_event_program: Option<String>,
  331. }
  332. impl Main {
  333. fn new(handle: Handle, setup: Setup) -> Main {
  334. let mut task = Main {
  335. handle: handle.clone(),
  336. cache: setup.cache,
  337. session_config: setup.session_config,
  338. player_config: setup.player_config,
  339. connect_config: setup.connect_config,
  340. backend: setup.backend,
  341. device: setup.device,
  342. mixer: setup.mixer,
  343. mixer_config: setup.mixer_config,
  344. connect: Box::new(futures::future::empty()),
  345. discovery: None,
  346. spirc: None,
  347. spirc_task: None,
  348. shutdown: false,
  349. signal: Box::new(tokio_signal::ctrl_c().flatten_stream()),
  350. player_event_channel: None,
  351. player_event_program: setup.player_event_program,
  352. };
  353. if setup.enable_discovery {
  354. let config = task.connect_config.clone();
  355. let device_id = task.session_config.device_id.clone();
  356. task.discovery = Some(discovery(&handle, config, device_id, setup.zeroconf_port).unwrap());
  357. }
  358. if let Some(credentials) = setup.credentials {
  359. task.credentials(credentials);
  360. }
  361. task
  362. }
  363. fn credentials(&mut self, credentials: Credentials) {
  364. let config = self.session_config.clone();
  365. let handle = self.handle.clone();
  366. let connection = Session::connect(config, credentials, self.cache.clone(), handle);
  367. self.connect = connection;
  368. self.spirc = None;
  369. let task = mem::replace(&mut self.spirc_task, None);
  370. if let Some(task) = task {
  371. self.handle.spawn(task);
  372. }
  373. }
  374. }
  375. impl Future for Main {
  376. type Item = ();
  377. type Error = ();
  378. fn poll(&mut self) -> Poll<(), ()> {
  379. loop {
  380. let mut progress = false;
  381. if let Some(Async::Ready(Some(creds))) = self.discovery.as_mut().map(|d| d.poll().unwrap()) {
  382. if let Some(ref spirc) = self.spirc {
  383. spirc.shutdown();
  384. }
  385. self.credentials(creds);
  386. progress = true;
  387. }
  388. if let Async::Ready(session) = self.connect.poll().unwrap() {
  389. self.connect = Box::new(futures::future::empty());
  390. let mixer_config = self.mixer_config.clone();
  391. let mixer = (self.mixer)(Some(mixer_config));
  392. let player_config = self.player_config.clone();
  393. let connect_config = self.connect_config.clone();
  394. let audio_filter = mixer.get_audio_filter();
  395. let backend = self.backend;
  396. let device = self.device.clone();
  397. let (player, event_channel) =
  398. Player::new(player_config, session.clone(), audio_filter, move || {
  399. (backend)(device)
  400. });
  401. let (spirc, spirc_task) = Spirc::new(connect_config, session, player, mixer);
  402. self.spirc = Some(spirc);
  403. self.spirc_task = Some(spirc_task);
  404. self.player_event_channel = Some(event_channel);
  405. progress = true;
  406. }
  407. if let Async::Ready(Some(())) = self.signal.poll().unwrap() {
  408. trace!("Ctrl-C received");
  409. if !self.shutdown {
  410. if let Some(ref spirc) = self.spirc {
  411. spirc.shutdown();
  412. } else {
  413. return Ok(Async::Ready(()));
  414. }
  415. self.shutdown = true;
  416. } else {
  417. return Ok(Async::Ready(()));
  418. }
  419. progress = true;
  420. }
  421. if let Some(ref mut spirc_task) = self.spirc_task {
  422. if let Async::Ready(()) = spirc_task.poll().unwrap() {
  423. if self.shutdown {
  424. return Ok(Async::Ready(()));
  425. } else {
  426. panic!("Spirc shut down unexpectedly");
  427. }
  428. }
  429. }
  430. if let Some(ref mut player_event_channel) = self.player_event_channel {
  431. if let Async::Ready(Some(event)) = player_event_channel.poll().unwrap() {
  432. if let Some(ref program) = self.player_event_program {
  433. let child = run_program_on_events(event, program)
  434. .expect("program failed to start")
  435. .map(|status| {
  436. if !status.success() {
  437. error!("child exited with status {:?}", status.code());
  438. }
  439. })
  440. .map_err(|e| error!("failed to wait on child process: {}", e));
  441. self.handle.spawn(child);
  442. }
  443. }
  444. }
  445. if !progress {
  446. return Ok(Async::NotReady);
  447. }
  448. }
  449. }
  450. }
  451. fn main() {
  452. if env::var("RUST_BACKTRACE").is_err() {
  453. env::set_var("RUST_BACKTRACE", "full")
  454. }
  455. let mut core = Core::new().unwrap();
  456. let handle = core.handle();
  457. let args: Vec<String> = std::env::args().collect();
  458. core.run(Main::new(handle, setup(&args))).unwrap()
  459. }