player.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. use byteorder::{LittleEndian, ReadBytesExt};
  2. use futures;
  3. use futures::sync::oneshot;
  4. use futures::{future, Future};
  5. use std;
  6. use std::borrow::Cow;
  7. use std::io::{Read, Result, Seek, SeekFrom};
  8. use std::mem;
  9. use std::sync::mpsc::{RecvError, RecvTimeoutError, TryRecvError};
  10. use std::thread;
  11. use std::time::Duration;
  12. use config::{Bitrate, PlayerConfig};
  13. use core::session::Session;
  14. use core::spotify_id::SpotifyId;
  15. use audio::{AudioDecrypt, AudioFile};
  16. use audio::{VorbisDecoder, VorbisPacket};
  17. use audio_backend::Sink;
  18. use metadata::{FileFormat, Metadata, Track};
  19. use mixer::AudioFilter;
  20. pub struct Player {
  21. commands: Option<std::sync::mpsc::Sender<PlayerCommand>>,
  22. thread_handle: Option<thread::JoinHandle<()>>,
  23. }
  24. struct PlayerInternal {
  25. session: Session,
  26. config: PlayerConfig,
  27. commands: std::sync::mpsc::Receiver<PlayerCommand>,
  28. state: PlayerState,
  29. sink: Box<Sink>,
  30. sink_running: bool,
  31. audio_filter: Option<Box<AudioFilter + Send>>,
  32. event_sender: futures::sync::mpsc::UnboundedSender<PlayerEvent>,
  33. }
  34. enum PlayerCommand {
  35. Load(SpotifyId, bool, u32, oneshot::Sender<()>),
  36. Play,
  37. Pause,
  38. Stop,
  39. Seek(u32),
  40. }
  41. #[derive(Debug, Clone)]
  42. pub enum PlayerEvent {
  43. Started {
  44. track_id: SpotifyId,
  45. },
  46. Changed {
  47. old_track_id: SpotifyId,
  48. new_track_id: SpotifyId,
  49. },
  50. Stopped {
  51. track_id: SpotifyId,
  52. },
  53. }
  54. type PlayerEventChannel = futures::sync::mpsc::UnboundedReceiver<PlayerEvent>;
  55. #[derive(Clone, Copy, Debug)]
  56. struct NormalisationData {
  57. track_gain_db: f32,
  58. track_peak: f32,
  59. album_gain_db: f32,
  60. album_peak: f32,
  61. }
  62. impl NormalisationData {
  63. fn parse_from_file<T: Read + Seek>(mut file: T) -> Result<NormalisationData> {
  64. const SPOTIFY_NORMALIZATION_HEADER_START_OFFSET: u64 = 144;
  65. file.seek(SeekFrom::Start(SPOTIFY_NORMALIZATION_HEADER_START_OFFSET))
  66. .unwrap();
  67. let track_gain_db = file.read_f32::<LittleEndian>().unwrap();
  68. let track_peak = file.read_f32::<LittleEndian>().unwrap();
  69. let album_gain_db = file.read_f32::<LittleEndian>().unwrap();
  70. let album_peak = file.read_f32::<LittleEndian>().unwrap();
  71. let r = NormalisationData {
  72. track_gain_db: track_gain_db,
  73. track_peak: track_peak,
  74. album_gain_db: album_gain_db,
  75. album_peak: album_peak,
  76. };
  77. Ok(r)
  78. }
  79. fn get_factor(config: &PlayerConfig, data: NormalisationData) -> f32 {
  80. let mut normalisation_factor =
  81. f32::powf(10.0, (data.track_gain_db + config.normalisation_pregain) / 20.0);
  82. if normalisation_factor * data.track_peak > 1.0 {
  83. warn!("Reducing normalisation factor to prevent clipping. Please add negative pregain to avoid.");
  84. normalisation_factor = 1.0 / data.track_peak;
  85. }
  86. debug!("Normalisation Data: {:?}", data);
  87. debug!("Applied normalisation factor: {}", normalisation_factor);
  88. normalisation_factor
  89. }
  90. }
  91. impl Player {
  92. pub fn new<F>(
  93. config: PlayerConfig,
  94. session: Session,
  95. audio_filter: Option<Box<AudioFilter + Send>>,
  96. sink_builder: F,
  97. ) -> (Player, PlayerEventChannel)
  98. where
  99. F: FnOnce() -> Box<Sink> + Send + 'static,
  100. {
  101. let (cmd_tx, cmd_rx) = std::sync::mpsc::channel();
  102. let (event_sender, event_receiver) = futures::sync::mpsc::unbounded();
  103. let handle = thread::spawn(move || {
  104. debug!("new Player[{}]", session.session_id());
  105. let internal = PlayerInternal {
  106. session: session,
  107. config: config,
  108. commands: cmd_rx,
  109. state: PlayerState::Stopped,
  110. sink: sink_builder(),
  111. sink_running: false,
  112. audio_filter: audio_filter,
  113. event_sender: event_sender,
  114. };
  115. internal.run();
  116. });
  117. (
  118. Player {
  119. commands: Some(cmd_tx),
  120. thread_handle: Some(handle),
  121. },
  122. event_receiver,
  123. )
  124. }
  125. fn command(&self, cmd: PlayerCommand) {
  126. self.commands.as_ref().unwrap().send(cmd).unwrap();
  127. }
  128. pub fn load(
  129. &self,
  130. track: SpotifyId,
  131. start_playing: bool,
  132. position_ms: u32,
  133. ) -> oneshot::Receiver<()> {
  134. let (tx, rx) = oneshot::channel();
  135. self.command(PlayerCommand::Load(track, start_playing, position_ms, tx));
  136. rx
  137. }
  138. pub fn play(&self) {
  139. self.command(PlayerCommand::Play)
  140. }
  141. pub fn pause(&self) {
  142. self.command(PlayerCommand::Pause)
  143. }
  144. pub fn stop(&self) {
  145. self.command(PlayerCommand::Stop)
  146. }
  147. pub fn seek(&self, position_ms: u32) {
  148. self.command(PlayerCommand::Seek(position_ms));
  149. }
  150. }
  151. impl Drop for Player {
  152. fn drop(&mut self) {
  153. debug!("Shutting down player thread ...");
  154. self.commands = None;
  155. if let Some(handle) = self.thread_handle.take() {
  156. match handle.join() {
  157. Ok(_) => (),
  158. Err(_) => error!("Player thread panicked!"),
  159. }
  160. }
  161. }
  162. }
  163. type Decoder = VorbisDecoder<Subfile<AudioDecrypt<AudioFile>>>;
  164. enum PlayerState {
  165. Stopped,
  166. Paused {
  167. track_id: SpotifyId,
  168. decoder: Decoder,
  169. end_of_track: oneshot::Sender<()>,
  170. normalisation_factor: f32,
  171. },
  172. Playing {
  173. track_id: SpotifyId,
  174. decoder: Decoder,
  175. end_of_track: oneshot::Sender<()>,
  176. normalisation_factor: f32,
  177. },
  178. EndOfTrack {
  179. track_id: SpotifyId,
  180. },
  181. Invalid,
  182. }
  183. impl PlayerState {
  184. fn is_playing(&self) -> bool {
  185. use self::PlayerState::*;
  186. match *self {
  187. Stopped | EndOfTrack { .. } | Paused { .. } => false,
  188. Playing { .. } => true,
  189. Invalid => panic!("invalid state"),
  190. }
  191. }
  192. fn decoder(&mut self) -> Option<&mut Decoder> {
  193. use self::PlayerState::*;
  194. match *self {
  195. Stopped | EndOfTrack { .. } => None,
  196. Paused { ref mut decoder, .. } | Playing { ref mut decoder, .. } => Some(decoder),
  197. Invalid => panic!("invalid state"),
  198. }
  199. }
  200. fn playing_to_end_of_track(&mut self) {
  201. use self::PlayerState::*;
  202. match mem::replace(self, Invalid) {
  203. Playing {
  204. track_id,
  205. end_of_track,
  206. ..
  207. } => {
  208. let _ = end_of_track.send(());
  209. *self = EndOfTrack { track_id };
  210. }
  211. _ => panic!("Called playing_to_end_of_track in non-playing state."),
  212. }
  213. }
  214. fn paused_to_playing(&mut self) {
  215. use self::PlayerState::*;
  216. match ::std::mem::replace(self, Invalid) {
  217. Paused {
  218. track_id,
  219. decoder,
  220. end_of_track,
  221. normalisation_factor,
  222. } => {
  223. *self = Playing {
  224. track_id: track_id,
  225. decoder: decoder,
  226. end_of_track: end_of_track,
  227. normalisation_factor: normalisation_factor,
  228. };
  229. }
  230. _ => panic!("invalid state"),
  231. }
  232. }
  233. fn playing_to_paused(&mut self) {
  234. use self::PlayerState::*;
  235. match ::std::mem::replace(self, Invalid) {
  236. Playing {
  237. track_id,
  238. decoder,
  239. end_of_track,
  240. normalisation_factor,
  241. } => {
  242. *self = Paused {
  243. track_id: track_id,
  244. decoder: decoder,
  245. end_of_track: end_of_track,
  246. normalisation_factor: normalisation_factor,
  247. };
  248. }
  249. _ => panic!("invalid state"),
  250. }
  251. }
  252. }
  253. impl PlayerInternal {
  254. fn run(mut self) {
  255. loop {
  256. let cmd = if self.state.is_playing() {
  257. if self.sink_running {
  258. match self.commands.try_recv() {
  259. Ok(cmd) => Some(cmd),
  260. Err(TryRecvError::Empty) => None,
  261. Err(TryRecvError::Disconnected) => return,
  262. }
  263. } else {
  264. match self.commands.recv_timeout(Duration::from_secs(5)) {
  265. Ok(cmd) => Some(cmd),
  266. Err(RecvTimeoutError::Timeout) => None,
  267. Err(RecvTimeoutError::Disconnected) => return,
  268. }
  269. }
  270. } else {
  271. match self.commands.recv() {
  272. Ok(cmd) => Some(cmd),
  273. Err(RecvError) => return,
  274. }
  275. };
  276. if let Some(cmd) = cmd {
  277. self.handle_command(cmd);
  278. }
  279. if self.state.is_playing() && !self.sink_running {
  280. self.start_sink();
  281. }
  282. if self.sink_running {
  283. let mut current_normalisation_factor: f32 = 1.0;
  284. let packet = if let PlayerState::Playing {
  285. ref mut decoder,
  286. normalisation_factor,
  287. ..
  288. } = self.state
  289. {
  290. current_normalisation_factor = normalisation_factor;
  291. Some(decoder.next_packet().expect("Vorbis error"))
  292. } else {
  293. None
  294. };
  295. if let Some(packet) = packet {
  296. self.handle_packet(packet, current_normalisation_factor);
  297. }
  298. }
  299. }
  300. }
  301. fn start_sink(&mut self) {
  302. match self.sink.start() {
  303. Ok(()) => self.sink_running = true,
  304. Err(err) => error!("Could not start audio: {}", err),
  305. }
  306. }
  307. fn stop_sink_if_running(&mut self) {
  308. if self.sink_running {
  309. self.stop_sink();
  310. }
  311. }
  312. fn stop_sink(&mut self) {
  313. self.sink.stop().unwrap();
  314. self.sink_running = false;
  315. }
  316. fn handle_packet(&mut self, packet: Option<VorbisPacket>, normalisation_factor: f32) {
  317. match packet {
  318. Some(mut packet) => {
  319. if packet.data().len() > 0 {
  320. if let Some(ref editor) = self.audio_filter {
  321. editor.modify_stream(&mut packet.data_mut())
  322. };
  323. if self.config.normalisation && normalisation_factor != 1.0 {
  324. for x in packet.data_mut().iter_mut() {
  325. *x = (*x as f32 * normalisation_factor) as i16;
  326. }
  327. }
  328. if let Err(err) = self.sink.write(&packet.data()) {
  329. error!("Could not write audio: {}", err);
  330. self.stop_sink();
  331. }
  332. }
  333. }
  334. None => {
  335. self.stop_sink();
  336. self.state.playing_to_end_of_track();
  337. }
  338. }
  339. }
  340. fn handle_command(&mut self, cmd: PlayerCommand) {
  341. debug!("command={:?}", cmd);
  342. match cmd {
  343. PlayerCommand::Load(track_id, play, position, end_of_track) => {
  344. if self.state.is_playing() {
  345. self.stop_sink_if_running();
  346. }
  347. match self.load_track(track_id, position as i64) {
  348. Some((decoder, normalisation_factor)) => {
  349. if play {
  350. match self.state {
  351. PlayerState::Playing {
  352. track_id: old_track_id,
  353. ..
  354. }
  355. | PlayerState::EndOfTrack {
  356. track_id: old_track_id,
  357. ..
  358. } => self.send_event(PlayerEvent::Changed {
  359. old_track_id: old_track_id,
  360. new_track_id: track_id,
  361. }),
  362. _ => self.send_event(PlayerEvent::Started { track_id }),
  363. }
  364. self.start_sink();
  365. self.state = PlayerState::Playing {
  366. track_id: track_id,
  367. decoder: decoder,
  368. end_of_track: end_of_track,
  369. normalisation_factor: normalisation_factor,
  370. };
  371. } else {
  372. self.state = PlayerState::Paused {
  373. track_id: track_id,
  374. decoder: decoder,
  375. end_of_track: end_of_track,
  376. normalisation_factor: normalisation_factor,
  377. };
  378. match self.state {
  379. PlayerState::Playing {
  380. track_id: old_track_id,
  381. ..
  382. }
  383. | PlayerState::EndOfTrack {
  384. track_id: old_track_id,
  385. ..
  386. } => self.send_event(PlayerEvent::Changed {
  387. old_track_id: old_track_id,
  388. new_track_id: track_id,
  389. }),
  390. _ => (),
  391. }
  392. self.send_event(PlayerEvent::Stopped { track_id });
  393. }
  394. }
  395. None => {
  396. let _ = end_of_track.send(());
  397. }
  398. }
  399. }
  400. PlayerCommand::Seek(position) => {
  401. if let Some(decoder) = self.state.decoder() {
  402. match decoder.seek(position as i64) {
  403. Ok(_) => (),
  404. Err(err) => error!("Vorbis error: {:?}", err),
  405. }
  406. } else {
  407. warn!("Player::seek called from invalid state");
  408. }
  409. }
  410. PlayerCommand::Play => {
  411. if let PlayerState::Paused { track_id, .. } = self.state {
  412. self.state.paused_to_playing();
  413. self.send_event(PlayerEvent::Started { track_id });
  414. self.start_sink();
  415. } else {
  416. warn!("Player::play called from invalid state");
  417. }
  418. }
  419. PlayerCommand::Pause => {
  420. if let PlayerState::Playing { track_id, .. } = self.state {
  421. self.state.playing_to_paused();
  422. self.stop_sink_if_running();
  423. self.send_event(PlayerEvent::Stopped { track_id });
  424. } else {
  425. warn!("Player::pause called from invalid state");
  426. }
  427. }
  428. PlayerCommand::Stop => match self.state {
  429. PlayerState::Playing { track_id, .. }
  430. | PlayerState::Paused { track_id, .. }
  431. | PlayerState::EndOfTrack { track_id } => {
  432. self.stop_sink_if_running();
  433. self.send_event(PlayerEvent::Stopped { track_id });
  434. self.state = PlayerState::Stopped;
  435. }
  436. PlayerState::Stopped => {
  437. warn!("Player::stop called from invalid state");
  438. }
  439. PlayerState::Invalid => panic!("invalid state"),
  440. },
  441. }
  442. }
  443. fn send_event(&mut self, event: PlayerEvent) {
  444. let _ = self.event_sender.unbounded_send(event.clone());
  445. }
  446. fn find_available_alternative<'a>(&self, track: &'a Track) -> Option<Cow<'a, Track>> {
  447. if track.available {
  448. Some(Cow::Borrowed(track))
  449. } else {
  450. let alternatives = track
  451. .alternatives
  452. .iter()
  453. .map(|alt_id| Track::get(&self.session, *alt_id));
  454. let alternatives = future::join_all(alternatives).wait().unwrap();
  455. alternatives.into_iter().find(|alt| alt.available).map(Cow::Owned)
  456. }
  457. }
  458. fn load_track(&self, track_id: SpotifyId, position: i64) -> Option<(Decoder, f32)> {
  459. let track = Track::get(&self.session, track_id).wait().unwrap();
  460. info!(
  461. "Loading track \"{}\" with Spotify URI \"spotify:track:{}\"",
  462. track.name,
  463. track_id.to_base62()
  464. );
  465. let track = match self.find_available_alternative(&track) {
  466. Some(track) => track,
  467. None => {
  468. warn!("Track \"{}\" is not available", track.name);
  469. return None;
  470. }
  471. };
  472. let format = match self.config.bitrate {
  473. Bitrate::Bitrate96 => FileFormat::OGG_VORBIS_96,
  474. Bitrate::Bitrate160 => FileFormat::OGG_VORBIS_160,
  475. Bitrate::Bitrate320 => FileFormat::OGG_VORBIS_320,
  476. };
  477. let file_id = match track.files.get(&format) {
  478. Some(&file_id) => file_id,
  479. None => {
  480. warn!("Track \"{}\" is not available in format {:?}", track.name, format);
  481. return None;
  482. }
  483. };
  484. let key = self.session
  485. .audio_key()
  486. .request(track.id, file_id)
  487. .wait()
  488. .unwrap();
  489. let encrypted_file = AudioFile::open(&self.session, file_id).wait().unwrap();
  490. let mut decrypted_file = AudioDecrypt::new(key, encrypted_file);
  491. let normalisation_factor = match NormalisationData::parse_from_file(&mut decrypted_file) {
  492. Ok(normalisation_data) => NormalisationData::get_factor(&self.config, normalisation_data),
  493. Err(_) => {
  494. warn!("Unable to extract normalisation data, using default value.");
  495. 1.0 as f32
  496. }
  497. };
  498. let audio_file = Subfile::new(decrypted_file, 0xa7);
  499. let mut decoder = VorbisDecoder::new(audio_file).unwrap();
  500. match decoder.seek(position) {
  501. Ok(_) => (),
  502. Err(err) => error!("Vorbis error: {:?}", err),
  503. }
  504. info!("Track \"{}\" loaded", track.name);
  505. Some((decoder, normalisation_factor))
  506. }
  507. }
  508. impl Drop for PlayerInternal {
  509. fn drop(&mut self) {
  510. debug!("drop Player[{}]", self.session.session_id());
  511. }
  512. }
  513. impl ::std::fmt::Debug for PlayerCommand {
  514. fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
  515. match *self {
  516. PlayerCommand::Load(track, play, position, _) => f.debug_tuple("Load")
  517. .field(&track)
  518. .field(&play)
  519. .field(&position)
  520. .finish(),
  521. PlayerCommand::Play => f.debug_tuple("Play").finish(),
  522. PlayerCommand::Pause => f.debug_tuple("Pause").finish(),
  523. PlayerCommand::Stop => f.debug_tuple("Stop").finish(),
  524. PlayerCommand::Seek(position) => f.debug_tuple("Seek").field(&position).finish(),
  525. }
  526. }
  527. }
  528. struct Subfile<T: Read + Seek> {
  529. stream: T,
  530. offset: u64,
  531. }
  532. impl<T: Read + Seek> Subfile<T> {
  533. pub fn new(mut stream: T, offset: u64) -> Subfile<T> {
  534. stream.seek(SeekFrom::Start(offset)).unwrap();
  535. Subfile {
  536. stream: stream,
  537. offset: offset,
  538. }
  539. }
  540. }
  541. impl<T: Read + Seek> Read for Subfile<T> {
  542. fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
  543. self.stream.read(buf)
  544. }
  545. }
  546. impl<T: Read + Seek> Seek for Subfile<T> {
  547. fn seek(&mut self, mut pos: SeekFrom) -> Result<u64> {
  548. pos = match pos {
  549. SeekFrom::Start(offset) => SeekFrom::Start(offset + self.offset),
  550. x => x,
  551. };
  552. let newpos = try!(self.stream.seek(pos));
  553. if newpos > self.offset {
  554. Ok(newpos - self.offset)
  555. } else {
  556. Ok(0)
  557. }
  558. }
  559. }