main.rs 17 KB

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