main.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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};
  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() -> Box<Mixer>,
  83. cache: Option<Cache>,
  84. player_config: PlayerConfig,
  85. session_config: SessionConfig,
  86. connect_config: ConnectConfig,
  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",
  130. "DEVICE",
  131. )
  132. .optopt("", "mixer", "Mixer to use", "MIXER")
  133. .optopt(
  134. "",
  135. "initial-volume",
  136. "Initial volume in %, once connected (must be from 0 to 100)",
  137. "VOLUME",
  138. )
  139. .optopt(
  140. "",
  141. "zeroconf-port",
  142. "The port the internal server advertised over zeroconf uses.",
  143. "ZEROCONF_PORT",
  144. )
  145. .optflag(
  146. "",
  147. "enable-volume-normalisation",
  148. "Play all tracks at the same volume",
  149. )
  150. .optopt(
  151. "",
  152. "normalisation-pregain",
  153. "Pregain (dB) applied by volume normalisation",
  154. "PREGAIN",
  155. )
  156. .optflag(
  157. "",
  158. "linear-volume",
  159. "increase volume linear instead of logarithmic.",
  160. );
  161. let matches = match opts.parse(&args[1..]) {
  162. Ok(m) => m,
  163. Err(f) => {
  164. writeln!(stderr(), "error: {}\n{}", f.to_string(), usage(&args[0], &opts)).unwrap();
  165. exit(1);
  166. }
  167. };
  168. let verbose = matches.opt_present("verbose");
  169. setup_logging(verbose);
  170. info!(
  171. "librespot {} ({}). Built on {}. Build ID: {}",
  172. version::short_sha(),
  173. version::commit_date(),
  174. version::short_now(),
  175. version::build_id()
  176. );
  177. let backend_name = matches.opt_str("backend");
  178. if backend_name == Some("?".into()) {
  179. list_backends();
  180. exit(0);
  181. }
  182. let backend = audio_backend::find(backend_name).expect("Invalid backend");
  183. let device = matches.opt_str("device");
  184. let mixer_name = matches.opt_str("mixer");
  185. let mixer = mixer::find(mixer_name.as_ref()).expect("Invalid mixer");
  186. let use_audio_cache = !matches.opt_present("disable-audio-cache");
  187. let cache = matches
  188. .opt_str("c")
  189. .map(|cache_location| Cache::new(PathBuf::from(cache_location), use_audio_cache));
  190. let initial_volume = matches
  191. .opt_str("initial-volume")
  192. .map(|volume| {
  193. let volume = volume.parse::<u16>().unwrap();
  194. if volume > 100 {
  195. panic!("Initial volume must be in the range 0-100");
  196. }
  197. (volume as i32 * 0xFFFF / 100) as u16
  198. })
  199. .or_else(|| cache.as_ref().and_then(Cache::volume))
  200. .unwrap_or(0x8000);
  201. let zeroconf_port = matches
  202. .opt_str("zeroconf-port")
  203. .map(|port| port.parse::<u16>().unwrap())
  204. .unwrap_or(0);
  205. let name = matches.opt_str("name").unwrap();
  206. let credentials = {
  207. let cached_credentials = cache.as_ref().and_then(Cache::credentials);
  208. let password = |username: &String| -> String {
  209. write!(stderr(), "Password for {}: ", username).unwrap();
  210. stderr().flush().unwrap();
  211. rpassword::read_password().unwrap()
  212. };
  213. get_credentials(
  214. matches.opt_str("username"),
  215. matches.opt_str("password"),
  216. cached_credentials,
  217. password,
  218. )
  219. };
  220. let session_config = {
  221. let device_id = device_id(&name);
  222. SessionConfig {
  223. user_agent: version::version_string(),
  224. device_id: device_id,
  225. proxy: matches.opt_str("proxy").or(std::env::var("http_proxy").ok()).map(
  226. |s| {
  227. match Url::parse(&s) {
  228. Ok(url) => {
  229. if url.host().is_none() || url.port().is_none() {
  230. panic!("Invalid proxy url, only urls on the format \"http://host:port\" are allowed");
  231. }
  232. if url.scheme() != "http" {
  233. panic!("Only unsecure http:// proxies are supported");
  234. }
  235. url
  236. },
  237. Err(err) => panic!("Invalid proxy url: {}, only urls on the format \"http://host:port\" are allowed", err)
  238. }
  239. },
  240. ),
  241. ap_port: matches
  242. .opt_str("ap-port")
  243. .map(|port| port.parse::<u16>().expect("Invalid port")),
  244. }
  245. };
  246. let player_config = {
  247. let bitrate = matches
  248. .opt_str("b")
  249. .as_ref()
  250. .map(|bitrate| Bitrate::from_str(bitrate).expect("Invalid bitrate"))
  251. .unwrap_or(Bitrate::default());
  252. PlayerConfig {
  253. bitrate: bitrate,
  254. normalisation: matches.opt_present("enable-volume-normalisation"),
  255. normalisation_pregain: matches
  256. .opt_str("normalisation-pregain")
  257. .map(|pregain| pregain.parse::<f32>().expect("Invalid pregain float value"))
  258. .unwrap_or(PlayerConfig::default().normalisation_pregain),
  259. }
  260. };
  261. let connect_config = {
  262. let device_type = matches
  263. .opt_str("device-type")
  264. .as_ref()
  265. .map(|device_type| DeviceType::from_str(device_type).expect("Invalid device type"))
  266. .unwrap_or(DeviceType::default());
  267. ConnectConfig {
  268. name: name,
  269. device_type: device_type,
  270. volume: initial_volume,
  271. linear_volume: matches.opt_present("linear-volume"),
  272. }
  273. };
  274. let enable_discovery = !matches.opt_present("disable-discovery");
  275. Setup {
  276. backend: backend,
  277. cache: cache,
  278. session_config: session_config,
  279. player_config: player_config,
  280. connect_config: connect_config,
  281. credentials: credentials,
  282. device: device,
  283. enable_discovery: enable_discovery,
  284. zeroconf_port: zeroconf_port,
  285. mixer: mixer,
  286. player_event_program: matches.opt_str("onevent"),
  287. }
  288. }
  289. struct Main {
  290. cache: Option<Cache>,
  291. player_config: PlayerConfig,
  292. session_config: SessionConfig,
  293. connect_config: ConnectConfig,
  294. backend: fn(Option<String>) -> Box<Sink>,
  295. device: Option<String>,
  296. mixer: fn() -> Box<Mixer>,
  297. handle: Handle,
  298. discovery: Option<DiscoveryStream>,
  299. signal: IoStream<()>,
  300. spirc: Option<Spirc>,
  301. spirc_task: Option<SpircTask>,
  302. connect: Box<Future<Item = Session, Error = io::Error>>,
  303. shutdown: bool,
  304. player_event_channel: Option<UnboundedReceiver<PlayerEvent>>,
  305. player_event_program: Option<String>,
  306. }
  307. impl Main {
  308. fn new(handle: Handle, setup: Setup) -> Main {
  309. let mut task = Main {
  310. handle: handle.clone(),
  311. cache: setup.cache,
  312. session_config: setup.session_config,
  313. player_config: setup.player_config,
  314. connect_config: setup.connect_config,
  315. backend: setup.backend,
  316. device: setup.device,
  317. mixer: setup.mixer,
  318. connect: Box::new(futures::future::empty()),
  319. discovery: None,
  320. spirc: None,
  321. spirc_task: None,
  322. shutdown: false,
  323. signal: Box::new(tokio_signal::ctrl_c(&handle).flatten_stream()),
  324. player_event_channel: None,
  325. player_event_program: setup.player_event_program,
  326. };
  327. if setup.enable_discovery {
  328. let config = task.connect_config.clone();
  329. let device_id = task.session_config.device_id.clone();
  330. task.discovery = Some(discovery(&handle, config, device_id, setup.zeroconf_port).unwrap());
  331. }
  332. if let Some(credentials) = setup.credentials {
  333. task.credentials(credentials);
  334. }
  335. task
  336. }
  337. fn credentials(&mut self, credentials: Credentials) {
  338. let config = self.session_config.clone();
  339. let handle = self.handle.clone();
  340. let connection = Session::connect(config, credentials, self.cache.clone(), handle);
  341. self.connect = connection;
  342. self.spirc = None;
  343. let task = mem::replace(&mut self.spirc_task, None);
  344. if let Some(task) = task {
  345. self.handle.spawn(task);
  346. }
  347. }
  348. }
  349. impl Future for Main {
  350. type Item = ();
  351. type Error = ();
  352. fn poll(&mut self) -> Poll<(), ()> {
  353. loop {
  354. let mut progress = false;
  355. if let Some(Async::Ready(Some(creds))) = self.discovery.as_mut().map(|d| d.poll().unwrap()) {
  356. if let Some(ref spirc) = self.spirc {
  357. spirc.shutdown();
  358. }
  359. self.credentials(creds);
  360. progress = true;
  361. }
  362. if let Async::Ready(session) = self.connect.poll().unwrap() {
  363. self.connect = Box::new(futures::future::empty());
  364. let device = self.device.clone();
  365. let mixer = (self.mixer)();
  366. let player_config = self.player_config.clone();
  367. let connect_config = self.connect_config.clone();
  368. let audio_filter = mixer.get_audio_filter();
  369. let backend = self.backend;
  370. let (player, event_channel) =
  371. Player::new(player_config, session.clone(), audio_filter, move || {
  372. (backend)(device)
  373. });
  374. let (spirc, spirc_task) = Spirc::new(connect_config, session, player, mixer);
  375. self.spirc = Some(spirc);
  376. self.spirc_task = Some(spirc_task);
  377. self.player_event_channel = Some(event_channel);
  378. progress = true;
  379. }
  380. if let Async::Ready(Some(())) = self.signal.poll().unwrap() {
  381. trace!("Ctrl-C received");
  382. if !self.shutdown {
  383. if let Some(ref spirc) = self.spirc {
  384. spirc.shutdown();
  385. }
  386. self.shutdown = true;
  387. } else {
  388. return Ok(Async::Ready(()));
  389. }
  390. progress = true;
  391. }
  392. if let Some(ref mut spirc_task) = self.spirc_task {
  393. if let Async::Ready(()) = spirc_task.poll().unwrap() {
  394. if self.shutdown {
  395. return Ok(Async::Ready(()));
  396. } else {
  397. panic!("Spirc shut down unexpectedly");
  398. }
  399. }
  400. }
  401. if let Some(ref mut player_event_channel) = self.player_event_channel {
  402. if let Async::Ready(Some(event)) = player_event_channel.poll().unwrap() {
  403. if let Some(ref program) = self.player_event_program {
  404. let child = run_program_on_events(event, program)
  405. .expect("program failed to start")
  406. .map(|status| if !status.success() {
  407. error!("child exited with status {:?}", status.code());
  408. })
  409. .map_err(|e| error!("failed to wait on child process: {}", e));
  410. self.handle.spawn(child);
  411. }
  412. }
  413. }
  414. if !progress {
  415. return Ok(Async::NotReady);
  416. }
  417. }
  418. }
  419. }
  420. fn main() {
  421. if env::var("RUST_BACKTRACE").is_err() {
  422. env::set_var("RUST_BACKTRACE", "full")
  423. }
  424. let mut core = Core::new().unwrap();
  425. let handle = core.handle();
  426. let args: Vec<String> = std::env::args().collect();
  427. core.run(Main::new(handle, setup(&args))).unwrap()
  428. }