player.rs 20 KB

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