main.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. #[macro_use] extern crate log;
  2. extern crate env_logger;
  3. extern crate futures;
  4. extern crate getopts;
  5. extern crate librespot;
  6. extern crate tokio_core;
  7. extern crate tokio_io;
  8. extern crate tokio_signal;
  9. use env_logger::LogBuilder;
  10. use futures::{Future, Async, Poll, Stream};
  11. use std::env;
  12. use std::io::{self, stderr, Write};
  13. use std::path::PathBuf;
  14. use std::process::exit;
  15. use std::str::FromStr;
  16. use tokio_core::reactor::{Handle, Core};
  17. use tokio_io::IoStream;
  18. use std::mem;
  19. use librespot::core::authentication::{get_credentials, Credentials};
  20. use librespot::core::cache::Cache;
  21. use librespot::core::config::{Bitrate, DeviceType, PlayerConfig, SessionConfig, ConnectConfig};
  22. use librespot::core::session::Session;
  23. use librespot::core::version;
  24. use librespot::audio_backend::{self, Sink, BACKENDS};
  25. use librespot::discovery::{discovery, DiscoveryStream};
  26. use librespot::mixer::{self, Mixer};
  27. use librespot::player::Player;
  28. use librespot::spirc::{Spirc, SpircTask};
  29. fn usage(program: &str, opts: &getopts::Options) -> String {
  30. let brief = format!("Usage: {} [options]", program);
  31. opts.usage(&brief)
  32. }
  33. fn setup_logging(verbose: bool) {
  34. let mut builder = LogBuilder::new();
  35. match env::var("RUST_LOG") {
  36. Ok(config) => {
  37. builder.parse(&config);
  38. builder.init().unwrap();
  39. if verbose {
  40. warn!("`--verbose` flag overidden by `RUST_LOG` environment variable");
  41. }
  42. }
  43. Err(_) => {
  44. if verbose {
  45. builder.parse("mdns=info,librespot=trace");
  46. } else {
  47. builder.parse("mdns=info,librespot=info");
  48. }
  49. builder.init().unwrap();
  50. }
  51. }
  52. }
  53. fn list_backends() {
  54. println!("Available Backends : ");
  55. for (&(name, _), idx) in BACKENDS.iter().zip(0..) {
  56. if idx == 0 {
  57. println!("- {} (default)", name);
  58. } else {
  59. println!("- {}", name);
  60. }
  61. }
  62. }
  63. #[derive(Clone)]
  64. struct Setup {
  65. backend: fn(Option<String>) -> Box<Sink>,
  66. device: Option<String>,
  67. mixer: fn() -> Box<Mixer>,
  68. cache: Option<Cache>,
  69. player_config: PlayerConfig,
  70. session_config: SessionConfig,
  71. connect_config: ConnectConfig,
  72. credentials: Option<Credentials>,
  73. enable_discovery: bool,
  74. zeroconf_port: u16,
  75. }
  76. fn setup(args: &[String]) -> Setup {
  77. let mut opts = getopts::Options::new();
  78. opts.optopt("c", "cache", "Path to a directory where files will be cached.", "CACHE")
  79. .optflag("", "disable-audio-cache", "Disable caching of the audio data.")
  80. .reqopt("n", "name", "Device name", "NAME")
  81. .optopt("", "device-type", "Displayed device type", "DEVICE_TYPE")
  82. .optopt("b", "bitrate", "Bitrate (96, 160 or 320). Defaults to 160", "BITRATE")
  83. .optopt("", "onstart", "Run PROGRAM when playback is about to begin.", "PROGRAM")
  84. .optopt("", "onstop", "Run PROGRAM when playback has ended.", "PROGRAM")
  85. .optflag("v", "verbose", "Enable verbose output")
  86. .optopt("u", "username", "Username to sign in with", "USERNAME")
  87. .optopt("p", "password", "Password", "PASSWORD")
  88. .optflag("", "disable-discovery", "Disable discovery mode")
  89. .optopt("", "backend", "Audio backend to use. Use '?' to list options", "BACKEND")
  90. .optopt("", "device", "Audio device to use. Use '?' to list options", "DEVICE")
  91. .optopt("", "mixer", "Mixer to use", "MIXER")
  92. .optopt("", "initial-volume", "Initial volume in %, once connected (must be from 0 to 100)", "VOLUME")
  93. .optopt("z", "zeroconf-port", "The port the internal server advertised over zeroconf uses.", "ZEROCONF_PORT");
  94. let matches = match opts.parse(&args[1..]) {
  95. Ok(m) => m,
  96. Err(f) => {
  97. writeln!(stderr(), "error: {}\n{}", f.to_string(), usage(&args[0], &opts)).unwrap();
  98. exit(1);
  99. }
  100. };
  101. let verbose = matches.opt_present("verbose");
  102. setup_logging(verbose);
  103. info!("librespot {} ({}). Built on {}. Build ID: {}",
  104. version::short_sha(),
  105. version::commit_date(),
  106. version::short_now(),
  107. version::build_id());
  108. let backend_name = matches.opt_str("backend");
  109. if backend_name == Some("?".into()) {
  110. list_backends();
  111. exit(0);
  112. }
  113. let backend = audio_backend::find(backend_name)
  114. .expect("Invalid backend");
  115. let device = matches.opt_str("device");
  116. let mixer_name = matches.opt_str("mixer");
  117. let mixer = mixer::find(mixer_name.as_ref())
  118. .expect("Invalid mixer");
  119. let initial_volume: i32;
  120. if matches.opt_present("initial-volume") && matches.opt_str("initial-volume").unwrap().parse::<i32>().is_ok() {
  121. let iv = matches.opt_str("initial-volume").unwrap().parse::<i32>().unwrap();
  122. match iv {
  123. iv if iv >= 0 && iv <= 100 => { initial_volume = iv * 0xFFFF / 100 }
  124. _ => {
  125. debug!("Volume needs to be a value from 0-100; set volume level to 50%");
  126. initial_volume = 0x8000;
  127. }
  128. }
  129. } else {
  130. initial_volume = 0x8000;
  131. }
  132. let zeroconf_port: u16;
  133. if matches.opt_present("zeroconf-port") && matches.opt_str("zeroconf-port").unwrap().parse::<u16>().is_ok() {
  134. let z = matches.opt_str("zeroconf-port").unwrap().parse::<u16>().unwrap();
  135. match z {
  136. z if z >= 1024 => { zeroconf_port = z }
  137. _ => { zeroconf_port = 0 }
  138. }
  139. } else {
  140. zeroconf_port = 0
  141. }
  142. let name = matches.opt_str("name").unwrap();
  143. let use_audio_cache = !matches.opt_present("disable-audio-cache");
  144. let cache = matches.opt_str("c").map(|cache_location| {
  145. Cache::new(PathBuf::from(cache_location), use_audio_cache)
  146. });
  147. let credentials = {
  148. let cached_credentials = cache.as_ref().and_then(Cache::credentials);
  149. get_credentials(
  150. matches.opt_str("username"),
  151. matches.opt_str("password"),
  152. cached_credentials
  153. )
  154. };
  155. let session_config = {
  156. let device_id = librespot::core::session::device_id(&name);
  157. SessionConfig {
  158. user_agent: version::version_string(),
  159. device_id: device_id,
  160. }
  161. };
  162. let player_config = {
  163. let bitrate = matches.opt_str("b").as_ref()
  164. .map(|bitrate| Bitrate::from_str(bitrate).expect("Invalid bitrate"))
  165. .unwrap_or(Bitrate::default());
  166. PlayerConfig {
  167. bitrate: bitrate,
  168. onstart: matches.opt_str("onstart"),
  169. onstop: matches.opt_str("onstop"),
  170. }
  171. };
  172. let connect_config = {
  173. let device_type = matches.opt_str("device-type").as_ref()
  174. .map(|device_type| DeviceType::from_str(device_type).expect("Invalid device type"))
  175. .unwrap_or(DeviceType::default());
  176. ConnectConfig {
  177. name: name,
  178. device_type: device_type,
  179. volume: initial_volume,
  180. }
  181. };
  182. let enable_discovery = !matches.opt_present("disable-discovery");
  183. Setup {
  184. backend: backend,
  185. cache: cache,
  186. session_config: session_config,
  187. player_config: player_config,
  188. connect_config: connect_config,
  189. credentials: credentials,
  190. device: device,
  191. enable_discovery: enable_discovery,
  192. zeroconf_port: zeroconf_port,
  193. mixer: mixer,
  194. }
  195. }
  196. struct Main {
  197. cache: Option<Cache>,
  198. player_config: PlayerConfig,
  199. session_config: SessionConfig,
  200. connect_config: ConnectConfig,
  201. backend: fn(Option<String>) -> Box<Sink>,
  202. device: Option<String>,
  203. mixer: fn() -> Box<Mixer>,
  204. handle: Handle,
  205. discovery: Option<DiscoveryStream>,
  206. signal: IoStream<()>,
  207. spirc: Option<Spirc>,
  208. spirc_task: Option<SpircTask>,
  209. connect: Box<Future<Item=Session, Error=io::Error>>,
  210. shutdown: bool,
  211. }
  212. impl Main {
  213. fn new(handle: Handle, setup: Setup) -> Main {
  214. let mut task = Main {
  215. handle: handle.clone(),
  216. cache: setup.cache,
  217. session_config: setup.session_config,
  218. player_config: setup.player_config,
  219. connect_config: setup.connect_config,
  220. backend: setup.backend,
  221. device: setup.device,
  222. mixer: setup.mixer,
  223. connect: Box::new(futures::future::empty()),
  224. discovery: None,
  225. spirc: None,
  226. spirc_task: None,
  227. shutdown: false,
  228. signal: Box::new(tokio_signal::ctrl_c(&handle).flatten_stream()),
  229. };
  230. if setup.enable_discovery {
  231. let config = task.connect_config.clone();
  232. let device_id = task.session_config.device_id.clone();
  233. task.discovery = Some(discovery(&handle, config, device_id, setup.zeroconf_port).unwrap());
  234. }
  235. if let Some(credentials) = setup.credentials {
  236. task.credentials(credentials);
  237. }
  238. task
  239. }
  240. fn credentials(&mut self, credentials: Credentials) {
  241. let config = self.session_config.clone();
  242. let handle = self.handle.clone();
  243. let connection = Session::connect(config, credentials, self.cache.clone(), handle);
  244. self.connect = connection;
  245. self.spirc = None;
  246. let task = mem::replace(&mut self.spirc_task, None);
  247. if let Some(task) = task {
  248. self.handle.spawn(task);
  249. }
  250. }
  251. }
  252. impl Future for Main {
  253. type Item = ();
  254. type Error = ();
  255. fn poll(&mut self) -> Poll<(), ()> {
  256. loop {
  257. let mut progress = false;
  258. if let Some(Async::Ready(Some(creds))) = self.discovery.as_mut().map(|d| d.poll().unwrap()) {
  259. if let Some(ref spirc) = self.spirc {
  260. spirc.shutdown();
  261. }
  262. self.credentials(creds);
  263. progress = true;
  264. }
  265. if let Async::Ready(session) = self.connect.poll().unwrap() {
  266. self.connect = Box::new(futures::future::empty());
  267. let device = self.device.clone();
  268. let mixer = (self.mixer)();
  269. let player_config = self.player_config.clone();
  270. let connect_config = self.connect_config.clone();
  271. let audio_filter = mixer.get_audio_filter();
  272. let backend = self.backend;
  273. let player = Player::new(player_config, session.clone(), audio_filter, move || {
  274. (backend)(device)
  275. });
  276. let (spirc, spirc_task) = Spirc::new(connect_config, session, player, mixer);
  277. self.spirc = Some(spirc);
  278. self.spirc_task = Some(spirc_task);
  279. progress = true;
  280. }
  281. if let Async::Ready(Some(())) = self.signal.poll().unwrap() {
  282. if !self.shutdown {
  283. if let Some(ref spirc) = self.spirc {
  284. spirc.shutdown();
  285. }
  286. self.shutdown = true;
  287. } else {
  288. return Ok(Async::Ready(()));
  289. }
  290. progress = true;
  291. }
  292. if let Some(ref mut spirc_task) = self.spirc_task {
  293. if let Async::Ready(()) = spirc_task.poll().unwrap() {
  294. if self.shutdown {
  295. return Ok(Async::Ready(()));
  296. } else {
  297. panic!("Spirc shut down unexpectedly");
  298. }
  299. }
  300. }
  301. if !progress {
  302. return Ok(Async::NotReady);
  303. }
  304. }
  305. }
  306. }
  307. fn main() {
  308. let mut core = Core::new().unwrap();
  309. let handle = core.handle();
  310. let args: Vec<String> = std::env::args().collect();
  311. core.run(Main::new(handle, setup(&args))).unwrap()
  312. }