main.rs 15 KB

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