-
Notifications
You must be signed in to change notification settings - Fork 653
/
Copy pathplayer.rs
1711 lines (1556 loc) · 56.3 KB
/
player.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use byteorder::{LittleEndian, ReadBytesExt};
use futures;
use futures::{future, Async, Future, Poll, Stream};
use std;
use std::borrow::Cow;
use std::cmp::max;
use std::io::{Read, Result, Seek, SeekFrom};
use std::mem;
use std::thread;
use std::time::{Duration, Instant};
use crate::config::{Bitrate, PlayerConfig};
use librespot_core::session::Session;
use librespot_core::spotify_id::SpotifyId;
use librespot_core::util::SeqGenerator;
use crate::audio::{AudioDecrypt, AudioFile, StreamLoaderController};
use crate::audio::{VorbisDecoder, VorbisPacket};
use crate::audio::{
READ_AHEAD_BEFORE_PLAYBACK_ROUNDTRIPS, READ_AHEAD_BEFORE_PLAYBACK_SECONDS,
READ_AHEAD_DURING_PLAYBACK_ROUNDTRIPS, READ_AHEAD_DURING_PLAYBACK_SECONDS,
};
use crate::audio_backend::Sink;
use crate::metadata::{AudioItem, FileFormat};
use crate::mixer::AudioFilter;
const PRELOAD_NEXT_TRACK_BEFORE_END_DURATION_MS: u32 = 30000;
pub struct Player {
commands: Option<futures::sync::mpsc::UnboundedSender<PlayerCommand>>,
thread_handle: Option<thread::JoinHandle<()>>,
play_request_id_generator: SeqGenerator<u64>,
}
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum SinkStatus {
Running,
Closed,
TemporarilyClosed,
}
pub type SinkEventCallback = Box<dyn Fn(SinkStatus) + Send>;
struct PlayerInternal {
session: Session,
config: PlayerConfig,
commands: futures::sync::mpsc::UnboundedReceiver<PlayerCommand>,
state: PlayerState,
preload: PlayerPreload,
sink: Box<dyn Sink>,
sink_status: SinkStatus,
sink_event_callback: Option<SinkEventCallback>,
audio_filter: Option<Box<dyn AudioFilter + Send>>,
event_senders: Vec<futures::sync::mpsc::UnboundedSender<PlayerEvent>>,
}
enum PlayerCommand {
Load {
track_id: SpotifyId,
play_request_id: u64,
play: bool,
position_ms: u32,
},
Preload {
track_id: SpotifyId,
},
Play,
Pause,
Stop,
Seek(u32),
AddEventSender(futures::sync::mpsc::UnboundedSender<PlayerEvent>),
SetSinkEventCallback(Option<SinkEventCallback>),
EmitVolumeSetEvent(u16),
}
#[derive(Debug, Clone)]
pub enum PlayerEvent {
// Fired when the player is stopped (e.g. by issuing a "stop" command to the player).
Stopped {
play_request_id: u64,
track_id: SpotifyId,
},
// The player started working on playback of a track while it was in a stopped state.
// This is always immediately followed up by a "Loading" or "Playing" event.
Started {
play_request_id: u64,
track_id: SpotifyId,
position_ms: u32,
},
// Same as started but in the case that the player already had a track loaded.
// The player was either playing the loaded track or it was paused.
Changed {
old_track_id: SpotifyId,
new_track_id: SpotifyId,
},
// The player is delayed by loading a track.
Loading {
play_request_id: u64,
track_id: SpotifyId,
position_ms: u32,
},
// The player is preloading a track.
Preloading {
track_id: SpotifyId,
},
// The player is playing a track.
// This event is issued at the start of playback of whenever the position must be communicated
// because it is out of sync. This includes:
// start of a track
// un-pausing
// after a seek
// after a buffer-underrun
Playing {
play_request_id: u64,
track_id: SpotifyId,
position_ms: u32,
duration_ms: u32,
},
// The player entered a paused state.
Paused {
play_request_id: u64,
track_id: SpotifyId,
position_ms: u32,
duration_ms: u32,
},
// The player thinks it's a good idea to issue a preload command for the next track now.
// This event is intended for use within spirc.
TimeToPreloadNextTrack {
play_request_id: u64,
track_id: SpotifyId,
},
// The player reached the end of a track.
// This event is intended for use within spirc. Spirc will respond by issuing another command
// which will trigger another event (e.g. Changed or Stopped)
EndOfTrack {
play_request_id: u64,
track_id: SpotifyId,
},
// The player was unable to load the requested track.
Unavailable {
play_request_id: u64,
track_id: SpotifyId,
},
// The mixer volume was set to a new level.
VolumeSet {
volume: u16,
},
}
impl PlayerEvent {
pub fn get_play_request_id(&self) -> Option<u64> {
use PlayerEvent::*;
match self {
Loading {
play_request_id, ..
}
| Unavailable {
play_request_id, ..
}
| Started {
play_request_id, ..
}
| Playing {
play_request_id, ..
}
| TimeToPreloadNextTrack {
play_request_id, ..
}
| EndOfTrack {
play_request_id, ..
}
| Paused {
play_request_id, ..
}
| Stopped {
play_request_id, ..
} => Some(*play_request_id),
Changed { .. } | Preloading { .. } | VolumeSet { .. } => None,
}
}
}
pub type PlayerEventChannel = futures::sync::mpsc::UnboundedReceiver<PlayerEvent>;
#[derive(Clone, Copy, Debug)]
struct NormalisationData {
track_gain_db: f32,
track_peak: f32,
album_gain_db: f32,
album_peak: f32,
}
impl NormalisationData {
fn parse_from_file<T: Read + Seek>(mut file: T) -> Result<NormalisationData> {
const SPOTIFY_NORMALIZATION_HEADER_START_OFFSET: u64 = 144;
file.seek(SeekFrom::Start(SPOTIFY_NORMALIZATION_HEADER_START_OFFSET))
.unwrap();
let track_gain_db = file.read_f32::<LittleEndian>().unwrap();
let track_peak = file.read_f32::<LittleEndian>().unwrap();
let album_gain_db = file.read_f32::<LittleEndian>().unwrap();
let album_peak = file.read_f32::<LittleEndian>().unwrap();
let r = NormalisationData {
track_gain_db: track_gain_db,
track_peak: track_peak,
album_gain_db: album_gain_db,
album_peak: album_peak,
};
Ok(r)
}
fn get_factor(config: &PlayerConfig, data: NormalisationData) -> f32 {
let mut normalisation_factor = f32::powf(
10.0,
(data.track_gain_db + config.normalisation_pregain) / 20.0,
);
if normalisation_factor * data.track_peak > 1.0 {
warn!("Reducing normalisation factor to prevent clipping. Please add negative pregain to avoid.");
normalisation_factor = 1.0 / data.track_peak;
}
debug!("Normalisation Data: {:?}", data);
debug!("Applied normalisation factor: {}", normalisation_factor);
normalisation_factor
}
}
impl Player {
pub fn new<F>(
config: PlayerConfig,
session: Session,
audio_filter: Option<Box<dyn AudioFilter + Send>>,
sink_builder: F,
) -> (Player, PlayerEventChannel)
where
F: FnOnce() -> Box<dyn Sink> + Send + 'static,
{
let (cmd_tx, cmd_rx) = futures::sync::mpsc::unbounded();
let (event_sender, event_receiver) = futures::sync::mpsc::unbounded();
let handle = thread::spawn(move || {
debug!("new Player[{}]", session.session_id());
let internal = PlayerInternal {
session: session,
config: config,
commands: cmd_rx,
state: PlayerState::Stopped,
preload: PlayerPreload::None,
sink: sink_builder(),
sink_status: SinkStatus::Closed,
sink_event_callback: None,
audio_filter: audio_filter,
event_senders: [event_sender].to_vec(),
};
// While PlayerInternal is written as a future, it still contains blocking code.
// It must be run by using wait() in a dedicated thread.
let _ = internal.wait();
debug!("PlayerInternal thread finished.");
});
(
Player {
commands: Some(cmd_tx),
thread_handle: Some(handle),
play_request_id_generator: SeqGenerator::new(0),
},
event_receiver,
)
}
fn command(&self, cmd: PlayerCommand) {
self.commands.as_ref().unwrap().unbounded_send(cmd).unwrap();
}
pub fn load(&mut self, track_id: SpotifyId, start_playing: bool, position_ms: u32) -> u64 {
let play_request_id = self.play_request_id_generator.get();
self.command(PlayerCommand::Load {
track_id,
play_request_id,
play: start_playing,
position_ms,
});
play_request_id
}
pub fn preload(&self, track_id: SpotifyId) {
self.command(PlayerCommand::Preload { track_id });
}
pub fn play(&self) {
self.command(PlayerCommand::Play)
}
pub fn pause(&self) {
self.command(PlayerCommand::Pause)
}
pub fn stop(&self) {
self.command(PlayerCommand::Stop)
}
pub fn seek(&self, position_ms: u32) {
self.command(PlayerCommand::Seek(position_ms));
}
pub fn get_player_event_channel(&self) -> PlayerEventChannel {
let (event_sender, event_receiver) = futures::sync::mpsc::unbounded();
self.command(PlayerCommand::AddEventSender(event_sender));
event_receiver
}
pub fn get_end_of_track_future(&self) -> Box<dyn Future<Item = (), Error = ()>> {
let result = self
.get_player_event_channel()
.filter(|event| match event {
PlayerEvent::EndOfTrack { .. } | PlayerEvent::Stopped { .. } => true,
_ => false,
})
.into_future()
.map_err(|_| ())
.map(|_| ());
Box::new(result)
}
pub fn set_sink_event_callback(&self, callback: Option<SinkEventCallback>) {
self.command(PlayerCommand::SetSinkEventCallback(callback));
}
pub fn emit_volume_set_event(&self, volume: u16) {
self.command(PlayerCommand::EmitVolumeSetEvent(volume));
}
}
impl Drop for Player {
fn drop(&mut self) {
debug!("Shutting down player thread ...");
self.commands = None;
if let Some(handle) = self.thread_handle.take() {
match handle.join() {
Ok(_) => (),
Err(_) => error!("Player thread panicked!"),
}
}
}
}
struct PlayerLoadedTrackData {
decoder: Decoder,
normalisation_factor: f32,
stream_loader_controller: StreamLoaderController,
bytes_per_second: usize,
duration_ms: u32,
stream_position_pcm: u64,
}
enum PlayerPreload {
None,
Loading {
track_id: SpotifyId,
loader: Box<dyn Future<Item = PlayerLoadedTrackData, Error = ()>>,
},
Ready {
track_id: SpotifyId,
loaded_track: PlayerLoadedTrackData,
},
}
type Decoder = VorbisDecoder<Subfile<AudioDecrypt<AudioFile>>>;
enum PlayerState {
Stopped,
Loading {
track_id: SpotifyId,
play_request_id: u64,
start_playback: bool,
loader: Box<dyn Future<Item = PlayerLoadedTrackData, Error = ()>>,
},
Paused {
track_id: SpotifyId,
play_request_id: u64,
decoder: Decoder,
normalisation_factor: f32,
stream_loader_controller: StreamLoaderController,
bytes_per_second: usize,
duration_ms: u32,
stream_position_pcm: u64,
suggested_to_preload_next_track: bool,
},
Playing {
track_id: SpotifyId,
play_request_id: u64,
decoder: Decoder,
normalisation_factor: f32,
stream_loader_controller: StreamLoaderController,
bytes_per_second: usize,
duration_ms: u32,
stream_position_pcm: u64,
reported_nominal_start_time: Option<Instant>,
suggested_to_preload_next_track: bool,
},
EndOfTrack {
track_id: SpotifyId,
play_request_id: u64,
loaded_track: PlayerLoadedTrackData,
},
Invalid,
}
impl PlayerState {
fn is_playing(&self) -> bool {
use self::PlayerState::*;
match *self {
Stopped | EndOfTrack { .. } | Paused { .. } | Loading { .. } => false,
Playing { .. } => true,
Invalid => panic!("invalid state"),
}
}
#[allow(dead_code)]
fn is_stopped(&self) -> bool {
use self::PlayerState::*;
match *self {
Stopped => true,
_ => false,
}
}
fn is_loading(&self) -> bool {
use self::PlayerState::*;
match *self {
Loading { .. } => true,
_ => false,
}
}
fn decoder(&mut self) -> Option<&mut Decoder> {
use self::PlayerState::*;
match *self {
Stopped | EndOfTrack { .. } | Loading { .. } => None,
Paused {
ref mut decoder, ..
}
| Playing {
ref mut decoder, ..
} => Some(decoder),
Invalid => panic!("invalid state"),
}
}
fn stream_loader_controller(&mut self) -> Option<&mut StreamLoaderController> {
use self::PlayerState::*;
match *self {
Stopped | EndOfTrack { .. } | Loading { .. } => None,
Paused {
ref mut stream_loader_controller,
..
}
| Playing {
ref mut stream_loader_controller,
..
} => Some(stream_loader_controller),
Invalid => panic!("invalid state"),
}
}
fn playing_to_end_of_track(&mut self) {
use self::PlayerState::*;
match mem::replace(self, Invalid) {
Playing {
track_id,
play_request_id,
decoder,
duration_ms,
bytes_per_second,
normalisation_factor,
stream_loader_controller,
stream_position_pcm,
..
} => {
*self = EndOfTrack {
track_id,
play_request_id,
loaded_track: PlayerLoadedTrackData {
decoder,
duration_ms,
bytes_per_second,
normalisation_factor,
stream_loader_controller,
stream_position_pcm,
},
};
}
_ => panic!("Called playing_to_end_of_track in non-playing state."),
}
}
fn paused_to_playing(&mut self) {
use self::PlayerState::*;
match ::std::mem::replace(self, Invalid) {
Paused {
track_id,
play_request_id,
decoder,
normalisation_factor,
stream_loader_controller,
duration_ms,
bytes_per_second,
stream_position_pcm,
suggested_to_preload_next_track,
} => {
*self = Playing {
track_id,
play_request_id,
decoder,
normalisation_factor,
stream_loader_controller,
duration_ms,
bytes_per_second,
stream_position_pcm,
reported_nominal_start_time: None,
suggested_to_preload_next_track,
};
}
_ => panic!("invalid state"),
}
}
fn playing_to_paused(&mut self) {
use self::PlayerState::*;
match ::std::mem::replace(self, Invalid) {
Playing {
track_id,
play_request_id,
decoder,
normalisation_factor,
stream_loader_controller,
duration_ms,
bytes_per_second,
stream_position_pcm,
reported_nominal_start_time: _,
suggested_to_preload_next_track,
} => {
*self = Paused {
track_id,
play_request_id,
decoder,
normalisation_factor,
stream_loader_controller,
duration_ms,
bytes_per_second,
stream_position_pcm,
suggested_to_preload_next_track,
};
}
_ => panic!("invalid state"),
}
}
}
struct PlayerTrackLoader {
session: Session,
config: PlayerConfig,
}
impl PlayerTrackLoader {
fn find_available_alternative<'a>(&self, audio: &'a AudioItem) -> Option<Cow<'a, AudioItem>> {
if audio.available {
Some(Cow::Borrowed(audio))
} else {
if let Some(alternatives) = &audio.alternatives {
let alternatives = alternatives
.iter()
.map(|alt_id| AudioItem::get_audio_item(&self.session, *alt_id));
let alternatives = future::join_all(alternatives).wait().unwrap();
alternatives
.into_iter()
.find(|alt| alt.available)
.map(Cow::Owned)
} else {
None
}
}
}
fn stream_data_rate(&self, format: FileFormat) -> usize {
match format {
FileFormat::OGG_VORBIS_96 => 12 * 1024,
FileFormat::OGG_VORBIS_160 => 20 * 1024,
FileFormat::OGG_VORBIS_320 => 40 * 1024,
FileFormat::MP3_256 => 32 * 1024,
FileFormat::MP3_320 => 40 * 1024,
FileFormat::MP3_160 => 20 * 1024,
FileFormat::MP3_96 => 12 * 1024,
FileFormat::MP3_160_ENC => 20 * 1024,
FileFormat::MP4_128_DUAL => 16 * 1024,
FileFormat::OTHER3 => 40 * 1024, // better some high guess than nothing
FileFormat::AAC_160 => 20 * 1024,
FileFormat::AAC_320 => 40 * 1024,
FileFormat::MP4_128 => 16 * 1024,
FileFormat::OTHER5 => 40 * 1024, // better some high guess than nothing
}
}
fn load_track(&self, spotify_id: SpotifyId, position_ms: u32) -> Option<PlayerLoadedTrackData> {
let audio = match AudioItem::get_audio_item(&self.session, spotify_id).wait() {
Ok(audio) => audio,
Err(_) => {
error!("Unable to load audio item.");
return None;
}
};
info!("Loading <{}> with Spotify URI <{}>", audio.name, audio.uri);
let audio = match self.find_available_alternative(&audio) {
Some(audio) => audio,
None => {
warn!("<{}> is not available", audio.uri);
return None;
}
};
assert!(audio.duration >= 0);
let duration_ms = audio.duration as u32;
// (Most) podcasts seem to support only 96 bit Vorbis, so fall back to it
let formats = match self.config.bitrate {
Bitrate::Bitrate96 => [
FileFormat::OGG_VORBIS_96,
FileFormat::OGG_VORBIS_160,
FileFormat::OGG_VORBIS_320,
],
Bitrate::Bitrate160 => [
FileFormat::OGG_VORBIS_160,
FileFormat::OGG_VORBIS_96,
FileFormat::OGG_VORBIS_320,
],
Bitrate::Bitrate320 => [
FileFormat::OGG_VORBIS_320,
FileFormat::OGG_VORBIS_160,
FileFormat::OGG_VORBIS_96,
],
};
let format = formats
.iter()
.find(|format| audio.files.contains_key(format))
.unwrap();
let file_id = match audio.files.get(&format) {
Some(&file_id) => file_id,
None => {
warn!("<{}> in not available in format {:?}", audio.name, format);
return None;
}
};
let bytes_per_second = self.stream_data_rate(*format);
let play_from_beginning = position_ms == 0;
let key = self.session.audio_key().request(spotify_id, file_id);
let encrypted_file = AudioFile::open(
&self.session,
file_id,
bytes_per_second,
play_from_beginning,
);
let encrypted_file = match encrypted_file.wait() {
Ok(encrypted_file) => encrypted_file,
Err(_) => {
error!("Unable to load encrypted file.");
return None;
}
};
let mut stream_loader_controller = encrypted_file.get_stream_loader_controller();
if play_from_beginning {
// No need to seek -> we stream from the beginning
stream_loader_controller.set_stream_mode();
} else {
// we need to seek -> we set stream mode after the initial seek.
stream_loader_controller.set_random_access_mode();
}
let key = match key.wait() {
Ok(key) => key,
Err(_) => {
error!("Unable to load decryption key");
return None;
}
};
let mut decrypted_file = AudioDecrypt::new(key, encrypted_file);
let normalisation_factor = match NormalisationData::parse_from_file(&mut decrypted_file) {
Ok(normalisation_data) => {
NormalisationData::get_factor(&self.config, normalisation_data)
}
Err(_) => {
warn!("Unable to extract normalisation data, using default value.");
1.0 as f32
}
};
let audio_file = Subfile::new(decrypted_file, 0xa7);
let mut decoder = VorbisDecoder::new(audio_file).unwrap();
if position_ms != 0 {
match decoder.seek(position_ms as i64) {
Ok(_) => (),
Err(err) => error!("Vorbis error: {:?}", err),
}
stream_loader_controller.set_stream_mode();
}
let stream_position_pcm = PlayerInternal::position_ms_to_pcm(position_ms);
info!("<{}> ({} ms) loaded", audio.name, audio.duration);
Some(PlayerLoadedTrackData {
decoder,
normalisation_factor,
stream_loader_controller,
bytes_per_second,
duration_ms,
stream_position_pcm,
})
}
}
impl Future for PlayerInternal {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<(), ()> {
// While this is written as a future, it still contains blocking code.
// It must be run on its own thread.
loop {
let mut all_futures_completed_or_not_ready = true;
// process commands that were sent to us
let cmd = match self.commands.poll() {
Ok(Async::Ready(None)) => return Ok(Async::Ready(())), // client has disconnected - shut down.
Ok(Async::Ready(Some(cmd))) => {
all_futures_completed_or_not_ready = false;
Some(cmd)
}
Ok(Async::NotReady) => None,
Err(_) => None,
};
if let Some(cmd) = cmd {
self.handle_command(cmd);
}
// Handle loading of a new track to play
if let PlayerState::Loading {
ref mut loader,
track_id,
start_playback,
play_request_id,
} = self.state
{
match loader.poll() {
Ok(Async::Ready(loaded_track)) => {
self.start_playback(
track_id,
play_request_id,
loaded_track,
start_playback,
);
if let PlayerState::Loading { .. } = self.state {
panic!("The state wasn't changed by start_playback()");
}
}
Ok(Async::NotReady) => (),
Err(_) => {
warn!("Unable to load <{:?}>\nSkipping to next track", track_id);
assert!(self.state.is_loading());
self.send_event(PlayerEvent::EndOfTrack {
track_id,
play_request_id,
})
}
}
}
// handle pending preload requests.
if let PlayerPreload::Loading {
ref mut loader,
track_id,
} = self.preload
{
match loader.poll() {
Ok(Async::Ready(loaded_track)) => {
self.send_event(PlayerEvent::Preloading { track_id });
self.preload = PlayerPreload::Ready {
track_id,
loaded_track,
};
}
Ok(Async::NotReady) => (),
Err(_) => {
debug!("Unable to preload {:?}", track_id);
self.preload = PlayerPreload::None;
// Let Spirc know that the track was unavailable.
if let PlayerState::Playing {
play_request_id, ..
}
| PlayerState::Paused {
play_request_id, ..
} = self.state
{
self.send_event(PlayerEvent::Unavailable {
track_id,
play_request_id,
});
}
}
}
}
if self.state.is_playing() {
self.ensure_sink_running();
if let PlayerState::Playing {
track_id,
play_request_id,
ref mut decoder,
normalisation_factor,
ref mut stream_position_pcm,
ref mut reported_nominal_start_time,
duration_ms,
..
} = self.state
{
let packet = decoder.next_packet().expect("Vorbis error");
if let Some(ref packet) = packet {
*stream_position_pcm =
*stream_position_pcm + (packet.data().len() / 2) as u64;
let stream_position_millis = Self::position_pcm_to_ms(*stream_position_pcm);
let notify_about_position = match *reported_nominal_start_time {
None => true,
Some(reported_nominal_start_time) => {
// only notify if we're behind. If we're ahead it's probably due to a buffer of the backend and we;re actually in time.
let lag = (Instant::now() - reported_nominal_start_time).as_millis()
as i64
- stream_position_millis as i64;
if lag > 1000 {
true
} else {
false
}
}
};
if notify_about_position {
*reported_nominal_start_time = Some(
Instant::now()
- Duration::from_millis(stream_position_millis as u64),
);
self.send_event(PlayerEvent::Playing {
track_id,
play_request_id,
position_ms: stream_position_millis as u32,
duration_ms,
});
}
}
self.handle_packet(packet, normalisation_factor);
} else {
unreachable!();
};
}
if let PlayerState::Playing {
track_id,
play_request_id,
duration_ms,
stream_position_pcm,
ref mut stream_loader_controller,
ref mut suggested_to_preload_next_track,
..
}
| PlayerState::Paused {
track_id,
play_request_id,
duration_ms,
stream_position_pcm,
ref mut stream_loader_controller,
ref mut suggested_to_preload_next_track,
..
} = self.state
{
if (!*suggested_to_preload_next_track)
&& ((duration_ms as i64 - Self::position_pcm_to_ms(stream_position_pcm) as i64)
< PRELOAD_NEXT_TRACK_BEFORE_END_DURATION_MS as i64)
&& stream_loader_controller.range_to_end_available()
{
*suggested_to_preload_next_track = true;
self.send_event(PlayerEvent::TimeToPreloadNextTrack {
track_id,
play_request_id,
});
}
}
if self.session.is_invalid() {
return Ok(Async::Ready(()));
}
if (!self.state.is_playing()) && all_futures_completed_or_not_ready {
return Ok(Async::NotReady);
}
}
}
}
impl PlayerInternal {
fn position_pcm_to_ms(position_pcm: u64) -> u32 {
(position_pcm * 10 / 441) as u32
}
fn position_ms_to_pcm(position_ms: u32) -> u64 {
position_ms as u64 * 441 / 10
}
fn ensure_sink_running(&mut self) {
if self.sink_status != SinkStatus::Running {
trace!("== Starting sink ==");
if let Some(callback) = &mut self.sink_event_callback {
callback(SinkStatus::Running);
}
match self.sink.start() {
Ok(()) => self.sink_status = SinkStatus::Running,
Err(err) => error!("Could not start audio: {}", err),
}
}
}
fn ensure_sink_stopped(&mut self, temporarily: bool) {
match self.sink_status {
SinkStatus::Running => {
trace!("== Stopping sink ==");
self.sink.stop().unwrap();
self.sink_status = if temporarily {
SinkStatus::TemporarilyClosed
} else {
SinkStatus::Closed
};
if let Some(callback) = &mut self.sink_event_callback {
callback(self.sink_status);
}
}
SinkStatus::TemporarilyClosed => {
if !temporarily {
self.sink_status = SinkStatus::Closed;
if let Some(callback) = &mut self.sink_event_callback {
callback(SinkStatus::Closed);
}
}
}
SinkStatus::Closed => (),
}
}
fn handle_player_stop(&mut self) {
match self.state {
PlayerState::Playing {
track_id,
play_request_id,
..
}
| PlayerState::Paused {
track_id,
play_request_id,
..
}
| PlayerState::EndOfTrack {
track_id,
play_request_id,
..
}
| PlayerState::Loading {
track_id,
play_request_id,
..
} => {