main.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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_signal;
  12. extern crate url;
  13. use crypto::digest::Digest;
  14. use crypto::sha1::Sha1;
  15. use env_logger::LogBuilder;
  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};
  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. let mut h = Sha1::new();
  42. h.input_str(name);
  43. h.result_str()
  44. }
  45. fn usage(program: &str, opts: &getopts::Options) -> String {
  46. let brief = format!("Usage: {} [options]", program);
  47. opts.usage(&brief)
  48. }
  49. fn setup_logging(verbose: bool) {
  50. let mut builder = LogBuilder::new();
  51. match env::var("RUST_LOG") {
  52. Ok(config) => {
  53. builder.parse(&config);
  54. builder.init().unwrap();
  55. if verbose {
  56. warn!("`--verbose` flag overidden by `RUST_LOG` environment variable");
  57. }
  58. }
  59. Err(_) => {
  60. if verbose {
  61. builder.parse("mdns=info,librespot=trace");
  62. } else {
  63. builder.parse("mdns=info,librespot=info");
  64. }
  65. builder.init().unwrap();
  66. }
  67. }
  68. }
  69. fn list_backends() {
  70. println!("Available Backends : ");
  71. for (&(name, _), idx) in BACKENDS.iter().zip(0..) {
  72. if idx == 0 {
  73. println!("- {} (default)", name);
  74. } else {
  75. println!("- {}", name);
  76. }
  77. }
  78. }
  79. #[derive(Clone)]
  80. struct Setup {
  81. backend: fn(Option<String>) -> Box<Sink>,
  82. device: Option<String>,
  83. mixer: fn() -> Box<Mixer>,
  84. cache: Option<Cache>,
  85. player_config: PlayerConfig,
  86. session_config: SessionConfig,
  87. connect_config: ConnectConfig,
  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. .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. }
  242. };
  243. let player_config = {
  244. let bitrate = matches
  245. .opt_str("b")
  246. .as_ref()
  247. .map(|bitrate| Bitrate::from_str(bitrate).expect("Invalid bitrate"))
  248. .unwrap_or(Bitrate::default());
  249. PlayerConfig {
  250. bitrate: bitrate,
  251. normalisation: matches.opt_present("enable-volume-normalisation"),
  252. normalisation_pregain: matches
  253. .opt_str("normalisation-pregain")
  254. .map(|pregain| pregain.parse::<f32>().expect("Invalid pregain float value"))
  255. .unwrap_or(PlayerConfig::default().normalisation_pregain),
  256. }
  257. };
  258. let connect_config = {
  259. let device_type = matches
  260. .opt_str("device-type")
  261. .as_ref()
  262. .map(|device_type| DeviceType::from_str(device_type).expect("Invalid device type"))
  263. .unwrap_or(DeviceType::default());
  264. ConnectConfig {
  265. name: name,
  266. device_type: device_type,
  267. volume: initial_volume,
  268. linear_volume: matches.opt_present("linear-volume"),
  269. }
  270. };
  271. let enable_discovery = !matches.opt_present("disable-discovery");
  272. Setup {
  273. backend: backend,
  274. cache: cache,
  275. session_config: session_config,
  276. player_config: player_config,
  277. connect_config: connect_config,
  278. credentials: credentials,
  279. device: device,
  280. enable_discovery: enable_discovery,
  281. zeroconf_port: zeroconf_port,
  282. mixer: mixer,
  283. player_event_program: matches.opt_str("onevent"),
  284. }
  285. }
  286. struct Main {
  287. cache: Option<Cache>,
  288. player_config: PlayerConfig,
  289. session_config: SessionConfig,
  290. connect_config: ConnectConfig,
  291. backend: fn(Option<String>) -> Box<Sink>,
  292. device: Option<String>,
  293. mixer: fn() -> Box<Mixer>,
  294. handle: Handle,
  295. discovery: Option<DiscoveryStream>,
  296. signal: IoStream<()>,
  297. spirc: Option<Spirc>,
  298. spirc_task: Option<SpircTask>,
  299. connect: Box<Future<Item = Session, Error = io::Error>>,
  300. shutdown: bool,
  301. player_event_channel: Option<UnboundedReceiver<PlayerEvent>>,
  302. player_event_program: Option<String>,
  303. }
  304. impl Main {
  305. fn new(handle: Handle, setup: Setup) -> Main {
  306. let mut task = Main {
  307. handle: handle.clone(),
  308. cache: setup.cache,
  309. session_config: setup.session_config,
  310. player_config: setup.player_config,
  311. connect_config: setup.connect_config,
  312. backend: setup.backend,
  313. device: setup.device,
  314. mixer: setup.mixer,
  315. connect: Box::new(futures::future::empty()),
  316. discovery: None,
  317. spirc: None,
  318. spirc_task: None,
  319. shutdown: false,
  320. signal: Box::new(tokio_signal::ctrl_c(&handle).flatten_stream()),
  321. player_event_channel: None,
  322. player_event_program: setup.player_event_program,
  323. };
  324. if setup.enable_discovery {
  325. let config = task.connect_config.clone();
  326. let device_id = task.session_config.device_id.clone();
  327. task.discovery = Some(discovery(&handle, config, device_id, setup.zeroconf_port).unwrap());
  328. }
  329. if let Some(credentials) = setup.credentials {
  330. task.credentials(credentials);
  331. }
  332. task
  333. }
  334. fn credentials(&mut self, credentials: Credentials) {
  335. let config = self.session_config.clone();
  336. let handle = self.handle.clone();
  337. let connection = Session::connect(config, credentials, self.cache.clone(), handle);
  338. self.connect = connection;
  339. self.spirc = None;
  340. let task = mem::replace(&mut self.spirc_task, None);
  341. if let Some(task) = task {
  342. self.handle.spawn(task);
  343. }
  344. }
  345. }
  346. impl Future for Main {
  347. type Item = ();
  348. type Error = ();
  349. fn poll(&mut self) -> Poll<(), ()> {
  350. loop {
  351. let mut progress = false;
  352. if let Some(Async::Ready(Some(creds))) = self.discovery.as_mut().map(|d| d.poll().unwrap()) {
  353. if let Some(ref spirc) = self.spirc {
  354. spirc.shutdown();
  355. }
  356. self.credentials(creds);
  357. progress = true;
  358. }
  359. if let Async::Ready(session) = self.connect.poll().unwrap() {
  360. self.connect = Box::new(futures::future::empty());
  361. let device = self.device.clone();
  362. let mixer = (self.mixer)();
  363. let player_config = self.player_config.clone();
  364. let connect_config = self.connect_config.clone();
  365. let audio_filter = mixer.get_audio_filter();
  366. let backend = self.backend;
  367. let (player, event_channel) =
  368. Player::new(player_config, session.clone(), audio_filter, move || {
  369. (backend)(device)
  370. });
  371. let (spirc, spirc_task) = Spirc::new(connect_config, session, player, mixer);
  372. self.spirc = Some(spirc);
  373. self.spirc_task = Some(spirc_task);
  374. self.player_event_channel = Some(event_channel);
  375. progress = true;
  376. }
  377. if let Async::Ready(Some(())) = self.signal.poll().unwrap() {
  378. trace!("Ctrl-C received");
  379. if !self.shutdown {
  380. if let Some(ref spirc) = self.spirc {
  381. spirc.shutdown();
  382. }
  383. self.shutdown = true;
  384. } else {
  385. return Ok(Async::Ready(()));
  386. }
  387. progress = true;
  388. }
  389. if let Some(ref mut spirc_task) = self.spirc_task {
  390. if let Async::Ready(()) = spirc_task.poll().unwrap() {
  391. if self.shutdown {
  392. return Ok(Async::Ready(()));
  393. } else {
  394. panic!("Spirc shut down unexpectedly");
  395. }
  396. }
  397. }
  398. if let Some(ref mut player_event_channel) = self.player_event_channel {
  399. if let Async::Ready(Some(event)) = player_event_channel.poll().unwrap() {
  400. if let Some(ref program) = self.player_event_program {
  401. run_program_on_events(event, program);
  402. }
  403. }
  404. }
  405. if !progress {
  406. return Ok(Async::NotReady);
  407. }
  408. }
  409. }
  410. }
  411. fn main() {
  412. if env::var("RUST_BACKTRACE").is_err() {
  413. env::set_var("RUST_BACKTRACE", "full")
  414. }
  415. let mut core = Core::new().unwrap();
  416. let handle = core.handle();
  417. let args: Vec<String> = std::env::args().collect();
  418. core.run(Main::new(handle, setup(&args))).unwrap()
  419. }