main.rs 17 KB

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