forked from LMS-Community/slimserver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamingController.pm
More file actions
2453 lines (1944 loc) · 72.7 KB
/
Copy pathStreamingController.pm
File metadata and controls
2453 lines (1944 loc) · 72.7 KB
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
package Slim::Player::StreamingController;
# Logitech Media Server Copyright 2001-2020 Logitech.
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License,
# version 2.
use bytes;
use strict;
use Scalar::Util qw(blessed weaken);
use Slim::Utils::Log;
use Slim::Utils::Misc;
use Slim::Utils::Prefs;
use Slim::Player::Song;
use Slim::Player::ReplayGain;
my $log = logger('player.source');
my $synclog = logger('player.sync');
my $prefs = preferences('server');
# Streaming state
use constant IDLE => 0;
use constant STREAMING => 1;
use constant STREAMOUT => 2;
use constant TRACKWAIT => 3; # Waiting for next track info to be ready and all players ready-to-stream
my $i = 0;
my @StreamingStateName = ('IDLE', 'STREAMING', 'STREAMOUT', 'TRACKWAIT');
my %StreamingStateNameMap = map { $_ => $i++ } @StreamingStateName;
# Playing state (audio)
use constant STOPPED => 0;
use constant BUFFERING => 1;
use constant WAITING_TO_SYNC => 2;
use constant PLAYING => 3;
use constant PAUSED => 4;
$i = 0;
my @PlayingStateName = ('STOPPED', 'BUFFERING', 'WAITING_TO_SYNC', 'PLAYING', 'PAUSED');
my %PlayingStateNameMap = map { $_ => $i++ } @PlayingStateName;
use constant FADEVOLUME => 0.3125;
sub new {
my ($class, $client) = @_;
my $self = {
masterId => $client->id(),
players => [],
allPlayers => [$client],
# State
streamingState => IDLE,
playingState => STOPPED,
rebuffering => 0,
lastStateChange => 0,
# Streaming control
songqueue => [],
songStreamController => undef,
nextCheckSyncTime => 0,
resumeTime => undef, # elapsed time when paused
# Sync management
syncgroupid => undef,
frameData => undef, # array of (stream-byte-offset, stream-time-offset) tuples
initialStreamBuffer => undef, # cache of initially-streamed data to calculate rate
# Track management
nextTrack => undef, # a Song
nextTrackCallbackId => 0,
consecutiveErrors => 0,
};
if ($client->power) {
push @{$self->{'players'}}, $client;
weaken( $self->{players}->[0] );
}
weaken( $self->{allPlayers}->[0] );
bless $self, $class;
return $self;
}
# What we have here is a state table with a number of handlers, one named handler
# to cover each precondition/action/end-state combination. The handler functions
# are after the table.
#
# I am not convinced that the table is either the most efficient
# implementation of this state machine, nor the the most comprehensible.
# An alternate approach would be to evaluate the constriants and execute the
# actions & state-changes directly from the inbound-event functions. Whether it
# makes sense to change to this remains to be seen. But for the moment, use of
# the jump table gives more opportunities to find and fix unanticipated event-state
# combinations.
my @ValidStates = (
# IDLE STREAMING STREAMOUT TRACKWAIT
[ 1, 0, 0, 1], # STOPPED
[ 0, 1, 1, 0], # BUFFERING
[ 0, 1, 1, 0], # WAITING_TO_SYNC
[ 1, 1, 1, 1], # PLAYING
[ 1, 1, 1, 1], # PAUSED
);
my %stateTable = ( # stateTable[event][playState][streamingState]
# IDLE STREAMING STREAMOUT TRACKWAIT
Stop =>
[ [ \&_NoOp, \&_BadState, \&_BadState, \&_Stop], # STOPPED
[ \&_BadState, \&_Stop, \&_Stop, \&_BadState], # BUFFERING
[ \&_BadState, \&_Stop, \&_Stop, \&_BadState], # WAITING_TO_SYNC
[ \&_Stop, \&_Stop, \&_Stop, \&_Stop], # PLAYING
[ \&_Stop, \&_Stop, \&_Stop, \&_Stop], # PAUSED
],
Play =>
[ [ \&_StopGetNext, \&_BadState, \&_BadState, \&_StopGetNext], # STOPPED
[ \&_BadState, \&_StopGetNext, \&_StopGetNext, \&_BadState], # BUFFERING
[ \&_BadState, \&_StopGetNext, \&_StopGetNext, \&_BadState], # WAITING_TO_SYNC
[ \&_StopGetNext, \&_StopGetNext, \&_StopGetNext, \&_StopGetNext], # PLAYING
[ \&_StopGetNext, \&_StopGetNext, \&_StopGetNext, \&_StopGetNext], # PAUSED
],
ContinuePlay =>
[ [ \&_Stop, \&_BadState, \&_BadState, \&_StopGetNext], # STOPPED
[ \&_BadState, \&_StopGetNext, \&_StopGetNext, \&_BadState], # BUFFERING
[ \&_BadState, \&_StopGetNext, \&_StopGetNext, \&_BadState], # WAITING_TO_SYNC
[ \&_Continue, \&_Continue, \&_Continue, \&_PlayIfReady], # PLAYING
[ \&_Stop, \&_Stop, \&_Stop, \&_Stop], # PAUSED
],
Pause =>
[ [ \&_Invalid, \&_BadState, \&_BadState, \&_NoOp], # STOPPED
[ \&_BadState, \&_NoOp, \&_NoOp, \&_BadState], # BUFFERING
[ \&_BadState, \&_NoOp, \&_NoOp, \&_BadState], # WAITING_TO_SYNC
[ \&_Pause, \&_Pause, \&_Pause, \&_Pause], # PLAYING
[ \&_JumpOrResume,\&_Resume, \&_Resume, \&_Resume], # PAUSED
],
Resume =>
[ [ \&_Invalid, \&_BadState, \&_BadState, \&_Invalid], # STOPPED
[ \&_BadState, \&_Invalid, \&_Invalid, \&_BadState], # BUFFERING
[ \&_BadState, \&_Invalid, \&_Invalid, \&_BadState], # WAITING_TO_SYNC
[ \&_Invalid, \&_Invalid, \&_Invalid, \&_Invalid], # PLAYING
[ \&_JumpOrResume,\&_Resume, \&_Resume, \&_Resume], # PAUSED
],
Flush =>
[ [ \&_Invalid, \&_BadState, \&_BadState, \&_Invalid], # STOPPED
[ \&_BadState, \&_Invalid, \&_Invalid, \&_BadState], # BUFFERING
[ \&_BadState, \&_Invalid, \&_Invalid, \&_BadState], # WAITING_TO_SYNC
[ \&_Invalid, \&_FlushGetNext,\&_FlushGetNext,\&_Invalid], # PLAYING
[ \&_Invalid, \&_FlushGetNext,\&_FlushGetNext,\&_Invalid], # PAUSED
],
Skip =>
[ [ \&_StopGetNext, \&_BadState, \&_BadState, \&_NoOp], # STOPPED
[ \&_BadState, \&_Skip, \&_Skip, \&_BadState], # BUFFERING
[ \&_BadState, \&_Skip, \&_Skip, \&_BadState], # WAITING_TO_SYNC
[ \&_StopGetNext, \&_Skip, \&_Skip, \&_Skip], # PLAYING
[ \&_StopGetNext, \&_Skip, \&_Skip, \&_Skip], # PAUSED
],
JumpToTime =>
[ [ \&_Invalid, \&_BadState, \&_BadState, \&_Invalid], # STOPPED
[ \&_BadState, \&_JumpToTime, \&_JumpToTime, \&_BadState], # BUFFERING
[ \&_BadState, \&_JumpToTime, \&_JumpToTime, \&_BadState], # WAITING_TO_SYNC
[ \&_JumpToTime, \&_JumpToTime, \&_JumpToTime, \&_JumpToTime], # PLAYING
[ \&_JumpPaused, \&_JumpPaused, \&_JumpPaused, \&_JumpPaused], # PAUSED
],
NextTrackReady =>
[ [ \&_NoOp, \&_BadState, \&_BadState, \&_Stream], # STOPPED
[ \&_BadState, \&_Invalid, \&_Invalid, \&_BadState], # BUFFERING
[ \&_BadState, \&_Invalid, \&_Invalid, \&_BadState], # WAITING_TO_SYNC
[ \&_Invalid, \&_Invalid, \&_Invalid, \&_StreamIfReady], # PLAYING
[ \&_Invalid, \&_Invalid, \&_Invalid, \&_StreamIfReady], # PAUSED
],
NextTrackError =>
[ [ \&_Invalid, \&_BadState, \&_BadState, \&_NextIfMore], # STOPPED
[ \&_BadState, \&_Invalid, \&_Invalid, \&_BadState], # BUFFERING
[ \&_BadState, \&_Invalid, \&_Invalid, \&_BadState], # WAITING_TO_SYNC
[ \&_Invalid, \&_Invalid, \&_Invalid, \&_NextIfMore], # PLAYING
[ \&_Invalid, \&_Invalid, \&_Invalid, \&_NextIfMore], # PAUSED
],
LocalEndOfStream =>
[ [ \&_Invalid, \&_BadState, \&_BadState, \&_Invalid], # STOPPED
[ \&_BadState, \&_Streamout, \&_Invalid, \&_BadState], # BUFFERING
[ \&_BadState, \&_Streamout, \&_Invalid, \&_BadState], # WAITING_TO_SYNC
[ \&_Invalid, \&_Streamout, \&_Invalid, \&_Invalid], # PLAYING
[ \&_Invalid, \&_Streamout, \&_Invalid, \&_Invalid], # PAUSED
],
BufferReady =>
[ [ \&_Invalid, \&_BadState, \&_BadState, \&_Invalid], # STOPPED
[ \&_BadState, \&_WaitToSync, \&_WaitToSync, \&_BadState], # BUFFERING
[ \&_BadState, \&_StartIfReady,\&_StartIfReady,\&_BadState], # WAITING_TO_SYNC
[ \&_Invalid, \&_Invalid, \&_Invalid, \&_Invalid], # PLAYING
[ \&_Invalid, \&_Invalid, \&_Invalid, \&_Invalid], # PAUSED
],
Started =>
[ [ \&_Invalid, \&_BadState, \&_BadState, \&_Invalid], # STOPPED
[ \&_BadState, \&_Playing, \&_Playing, \&_BadState], # BUFFERING
[ \&_BadState, \&_Invalid, \&_Invalid, \&_BadState], # WAITING_TO_SYNC
[ \&_Playing, \&_Playing, \&_Playing, \&_PlayAndStream], # PLAYING
[ \&_Invalid, \&_Playing, \&_Playing, \&_PlayAndStream], # PAUSED
],
StreamingFailed =>
[ [ \&_Invalid, \&_BadState, \&_BadState, \&_Invalid], # STOPPED
[ \&_BadState, \&_StopNextIfMore, \&_StopNextIfMore, \&_BadState], # BUFFERING
[ \&_BadState, \&_StopNextIfMore, \&_StopNextIfMore, \&_BadState], # WAITING_TO_SYNC
[ \&_Invalid, \&_SyncStopNext, \&_SyncStopNext, \&_Invalid], # PLAYING
[ \&_Invalid, \&_Stop, \&_Stop, \&_Invalid], # PAUSED
],
EndOfStream =>
[ [ \&_NoOp, \&_BadState, \&_BadState, \&_NoOp], # STOPPED
[ \&_BadState, \&_StartStreamout,\&_Start, \&_BadState], # BUFFERING; _Start in Streamout to counter Bug 9125
[ \&_BadState, \&_StartStreamout,\&_Start, \&_BadState], # WAITING_TO_SYNC
[ \&_Invalid, \&_AutoStart, \&_AutoStart, \&_Invalid], # PLAYING
[ \&_Invalid, \&_Streamout, \&_NoOp, \&_Invalid], # PAUSED
],
ReadyToStream =>
[ [ \&_Invalid, \&_BadState, \&_BadState, \&_Invalid], # STOPPED
[ \&_BadState, \&_NoOp, \&_Invalid, \&_BadState], # BUFFERING
[ \&_BadState, \&_Invalid, \&_Invalid, \&_BadState], # WAITING_TO_SYNC
[ \&_NoOp, \&_NextIfMore, \&_RetryOrNext, \&_StreamIfReady], # PLAYING
[ \&_NoOp, \&_NextIfMore, \&_NextIfMore, \&_StreamIfReady], # PAUSED
],
Stopped =>
[ [ \&_Invalid, \&_BadState, \&_BadState, \&_NoOp], # STOPPED
[ \&_BadState, \&_NoOp, \&_NoOp, \&_BadState], # BUFFERING
[ \&_BadState, \&_Invalid, \&_Invalid, \&_BadState], # WAITING_TO_SYNC
[ \&_Stopped, \&_Buffering, \&_Buffering, \&_PlayIfReady], # PLAYING
[ \&_Stopped, \&_Buffering, \&_Buffering, \&_Stopped], # PAUSED
],
OutputUnderrun =>
[ [ \&_NoOp, \&_BadState, \&_BadState, \&_NoOp], # STOPPED
[ \&_BadState, \&_NoOp, \&_NoOp, \&_BadState], # BUFFERING
[ \&_BadState, \&_Invalid, \&_Invalid, \&_BadState], # WAITING_TO_SYNC
[ \&_Invalid, \&_Rebuffer, \&_Rebuffer, \&_Invalid], # PLAYING
[ \&_NoOp, \&_NoOp, \&_NoOp, \&_NoOp], # PAUSED
],
StatusHeartbeat =>
[ [ \&_NoOp, \&_BadState, \&_BadState, \&_NoOp], # STOPPED
[ \&_BadState, \&_NoOp, \&_NoOp, \&_BadState], # BUFFERING
[ \&_BadState, \&_StartIfReady,\&_StartIfReady,\&_BadState], # WAITING_TO_SYNC
[ \&_CheckSync, \&_CheckSync, \&_CheckSync, \&_CheckSync], # PLAYING
[ \&_NoOp, \&_CheckPaused, \&_CheckPaused, \&_NoOp], # PAUSED
],
);
####################################################################
# Actions
sub _eventAction {
my ($self, $event, $params) = @_;
my $action = $stateTable{$event}[$self->{'playingState'}][$self->{'streamingState'}];
if (!defined $action) {
$log->error(sprintf("%s: %s in state %s-%s -> undefined",
$self->{'masterId'},
$event,
$PlayingStateName[$self->{'playingState'}], $StreamingStateName[$self->{'streamingState'}]));
return;
}
my $curPlayingState;
my $curStreamingState;
if (main::DEBUGLOG && $log->is_debug) {
$curPlayingState = $PlayingStateName[$self->{'playingState'}];
$curStreamingState = $StreamingStateName[$self->{'streamingState'}];
$log->debug(
sprintf("%s: %s in %s-%s -> %s",
$self->{'masterId'},
$event,
$curPlayingState, $curStreamingState,
Slim::Utils::PerlRunTime::realNameForCodeRef($action))
);
if ($params) {
my $s = "params:";
foreach my $p (keys %$params) {
$s .= " $p => " . (defined $params->{$p} ? $params->{$p} : 'undef');
}
$log->debug($s);
}
}
my $result = $action->(@_);
if (!$ValidStates[$self->{'playingState'}][$self->{'streamingState'}]) {
$log->error(sprintf("%s: %s with action %s resulted in invalid state %s-%s",
$self->{'masterId'},
$event,
main::DEBUGLOG ? Slim::Utils::PerlRunTime::realNameForCodeRef($action) : 'unk',
$PlayingStateName[$self->{'playingState'}], $StreamingStateName[$self->{'streamingState'}])
);
}
elsif ( main::DEBUGLOG && $log->is_debug ) {
my $newPlayingState = $PlayingStateName[$self->{'playingState'}];
my $newStreamingState = $StreamingStateName[$self->{'streamingState'}];
if ( $newPlayingState ne $curPlayingState || $newStreamingState ne $curStreamingState ) {
$log->debug( sprintf("%s: %s - new state %s-%s",
$self->{'masterId'},
$event,
$newPlayingState, $newStreamingState,
) );
}
}
return $result;
}
sub _NoOp {}
sub _BadState {
my ($self, $event) = @_;
$log->error(sprintf("%s: event %s received while in invalid state %s-%s", $self->{'masterId'}, $event,
$PlayingStateName[$self->{'playingState'}], $StreamingStateName[$self->{'streamingState'}]));
logBacktrace('') if $log->is_warn;
}
sub _Invalid {
my ($self, $event) = @_;
$log->warn(sprintf("%s: event %s received while in invalid state %s-%s", $self->{'masterId'}, $event,
$PlayingStateName[$self->{'playingState'}], $StreamingStateName[$self->{'streamingState'}]));
logBacktrace('') if $log->is_warn;
}
sub _Buffering {_setPlayingState($_[0], BUFFERING);}
sub _Playing {
my ($self) = @_;
# need to fade-in here and not in _Stream due to potential buffering delay
if ($self->{'fadeActive'}) {
foreach my $player (@{$self->{'players'}}) {
$player->fade_volume($prefs->client($self->master)->get('fadeInDuration'));
}
}
$self->{'fadeActive'} = undef;
# bug 10681 - don't actually change the state if we are rebuffering
# as there can be a race condition between output buffer underrun and
# track-start events especially, but not exclusively when synced.
# We still advance the track information.
if (!$self->{'rebuffering'}) {
_setPlayingState($self, PLAYING);
}
$self->{'consecutiveErrors'} = 0;
my $queue = $self->{'songqueue'};
my $last_song = $self->playingSong();
while (defined($last_song)
&& ($last_song->status() == Slim::Player::Song::STATUS_PLAYING
|| $last_song->status() == Slim::Player::Song::STATUS_FAILED
|| $last_song->status() == Slim::Player::Song::STATUS_FINISHED)
&& scalar(@$queue) > 1)
{
main::INFOLOG && $log->info("Song " . $last_song->index() . " is not longer in the queue");
pop @{$queue};
$last_song = $queue->[-1];
}
if (defined($last_song)) {
main::INFOLOG && $log->info("Song " . $last_song->index() . " has now started playing");
$last_song->setStatus(Slim::Player::Song::STATUS_PLAYING);
$last_song->retryData(undef); # we are playing so we must be done retrying
}
# Update a few timestamps
# trackStartTime is used to signal the buffering status message to stop
# currentPlaylistChangeTime signals the web to refresh the playlist
my $time = Time::HiRes::time();
$self->master()->trackStartTime( $time );
$self->master()->currentPlaylistChangeTime( $time );
Slim::Player::Playlist::refreshPlaylist($self->master());
if ( $last_song ) {
Slim::Control::Request::notifyFromArray($self->master(),
[
'playlist',
'newsong',
Slim::Music::Info::standardTitle(
$self->master(),
$last_song->currentTrack()
),
$last_song->index()
]
);
}
if ( main::INFOLOG && $log->is_info ) {
$log->info("Song queue is now " . join(',', map { $_->index() } @$queue));
}
}
sub _Stopped {
_setPlayingState( $_[0], STOPPED );
_notifyStopped( $_[0] );
}
sub _notifyStopped {
my ($self, $suppressNotifications) = @_;
# This was previously commented out, for bug 7781,
# because some plugins (Alarm) don't like extra stop events.
# This broke important notifications for Jive.
# Other changes mean that that this can be reinstated.
Slim::Control::Request::notifyFromArray( $self->master(), ['playlist', 'stop'] ) unless $suppressNotifications;
foreach my $player ( @{ $self->{'players'} } ) {
if ($player->can('onStop')) {
$player->onStop();
}
}
}
sub _Streamout {_setStreamingState($_[0], STREAMOUT);}
sub _CheckPaused { # only called when PAUSED
my ($self, $event, $params) = @_;
return if ! $self->isPaused(); # safety check
my $song = $self->playingSong();
if ( $song
&& $song->currentTrackHandler()->isRemote()
&& $self->master()->usage() > 0.98)
{
if ($song->canSeek() && defined $self->{'resumeTime'}) {
# Bug 10645: stop only the streaming if there is a chance to restart
main::INFOLOG && $log->info("Stopping remote stream upon full buffer when paused (resume time: $self->{'resumeTime'})");
_pauseStreaming($self, $song);
} elsif (!$song->duration()) {
# Bug 7620: stop remote radio streams if they have been paused long enough for the buffer to fill.
# Assume unknown duration means radio and so we shuould stop now
main::INFOLOG && $log->info("Stopping remote stream upon full buffer when paused (no resume)");
_Stop(@_);
}
# else - (bug 14230) just leave it paused and if the remote source disconnects then pick up the pieces later
}
}
sub _pauseStreaming {
my ($self, $playingSong) = @_;
if ($self->{'streamingState'} == IDLE) {
return;
}
foreach my $player (@{$self->{'players'}}) {
_stopClient($player);
}
if ($self->{'songStreamController'}) {
$self->{'songStreamController'}->close();
$self->{'songStreamController'} = undef;
}
_setStreamingState($self, IDLE);
$playingSong->setStatus(Slim::Player::Song::STATUS_READY);
# clear streamingSong if not same as playingSong
if ($playingSong != $self->{'songqueue'}->[0]) {
shift @{$self->{'songqueue'}};
}
}
use constant CHECK_SYNC_INTERVAL => 0.950;
use constant MIN_DEVIATION_ADJUST => 0.010;
use constant MAX_DEVIATION_ADJUST => 10.000;
use constant PLAYPOINT_RECENT_THRESHOLD => 3.0;
sub _CheckSync {
my ($self, $event, $params) = @_;
# check to see if resynchronization is necessary
return unless scalar @{ $self->{'players'} } > 1;
my $now = Time::HiRes::time();
return if $now < $self->{'nextCheckSyncTime'};
$self->{'nextCheckSyncTime'} = $now + CHECK_SYNC_INTERVAL;
# need a recent play-point from all players in the group, otherwise give up
my $recentThreshold = $now - PLAYPOINT_RECENT_THRESHOLD;
my @playerPlayPoints;
foreach my $player (@{ $self->{'players'} }) {
next unless ( $player->isPlayer()
&& $prefs->client($player)->get('maintainSync') );
my $playPoint = $player->playPoint();
if ( !defined $playPoint ) {
if ( main::DEBUGLOG && $synclog->is_debug ) {$synclog->debug( $player->id() . " bailing as no playPoint" );}
return;
}
if ( $playPoint->[0] > $recentThreshold ) {
push(@playerPlayPoints,
[
$player,
$playPoint->[1] + $prefs->client($player)->get('playDelay') / 1000
]
);
}
else {
if ( main::DEBUGLOG && $synclog->is_debug ) {
$synclog->debug( $player->id() . " bailing as playPoint too old: "
. ( $now - $playPoint->[0] ) . "s" );
}
return;
}
}
return unless scalar(@playerPlayPoints);
if ( main::DEBUGLOG && $synclog->is_debug ) {
my $first = $playerPlayPoints[0][1];
my $str = sprintf( "%s: %.3f", $playerPlayPoints[0][0]->id(), $first );
foreach ( @playerPlayPoints[ 1 .. $#playerPlayPoints ] ) {
$str .= sprintf( ", %s: %+5d",
$_->[0]->id(), ( $_->[1] - $first ) * 1000 );
}
$synclog->debug("playPoints: $str");
}
# sort the play-points by decreasing apparent-start-time
@playerPlayPoints = sort { $b->[1] <=> $a->[1] } @playerPlayPoints;
# clean up the list of stored frame data
# (do this now, so that it does not delay critial timers when using pauseFor())
main::SB1SLIMP3SYNC && Slim::Player::SB1SliMP3Sync::purgeOldFrames( $self->frameData(),
$recentThreshold - $playerPlayPoints[0][1] );
# find the reference player - the most-behind that does not support skipAhead
my $reference;
for ( $reference = 0 ; $reference < $#playerPlayPoints ; $reference++ ) {
last unless $playerPlayPoints[$reference][0]->can('skipAhead');
}
my $referenceTime = $playerPlayPoints[$reference][1];
# my $referenceMinAdjust = $prefs->client($playerPlayPoints[$reference][0])->get('minSyncAdjust')/1000;
# tell each player that is out-of-sync with the reference to adjust
for ( my $i = 0 ; $i < @playerPlayPoints ; $i++ ) {
next if ( $i == $reference );
my $player = $playerPlayPoints[$i][0];
my $delta = abs( $playerPlayPoints[$i][1] - $referenceTime );
next if (
$delta > MAX_DEVIATION_ADJUST
|| $delta < MIN_DEVIATION_ADJUST
|| $delta < $prefs->client($player)->get('minSyncAdjust') / 1000
# || $delta < $referenceMinAdjust
);
if ( $i < $reference ) {
if ( main::INFOLOG && $synclog->is_info ) {
$synclog->info(sprintf("%s resync: skipAhead %dms", $player->id(), $delta * 1000));
}
$player->skipAhead($delta);
$self->{'nextCheckSyncTime'} += 1;
}
else {
# bug 6864: SB1s cannot reliably pause without skipping frames, so we don't try
if ( $player->can('pauseForInterval') ) {
if ( main::INFOLOG && $synclog->is_info ) {
$synclog->info(sprintf("%s resync: pauseFor %dms", $player->id(), $delta * 1000));
}
$player->pauseForInterval($delta);
$self->{'nextCheckSyncTime'} += $delta;
}
}
}
}
sub _Stop { # stop -> Stopped, Idle
my ($self, $event, $params, $suppressNotifications) = @_;
# bug 10458 - try to avoding unnecessary notifications
$suppressNotifications = 1 unless ( $self->isPlaying() || $self->isPaused() );
if ( !$suppressNotifications && $self->playingSong() && ( $self->isPlaying(1) || $self->isPaused() ) ) {
my $song = $self->playingSong();
my $handler = $song->currentTrackHandler();
if ($handler->can('onStop')) {
$handler->onStop($song);
}
}
foreach my $player (@{$self->{'players'}}) {
_stopClient($player);
}
my $queue = $self->{'songqueue'};
while (scalar @$queue > 1) {shift @$queue;}
$queue->[0]->setStatus(Slim::Player::Song::STATUS_FINISHED) if scalar @$queue;
if (main::INFOLOG && $log->is_info && scalar @$queue) {
$log->info("Song queue is now " . join(',', map { $_->index() } @$queue));
}
if ($self->{'songStreamController'}) {
$self->{'songStreamController'}->close();
$self->{'songStreamController'} = undef;
}
_setPlayingState($self, STOPPED);
_setStreamingState($self, IDLE);
_notifyStopped($self, $suppressNotifications);
}
sub _stopClient {
my ($client) = @_;
$client->stop;
@{$client->chunks} = ();
$client->closeStream();
}
sub _getNextTrack { # getNextTrack -> TrackWait
my ($self, $params, $ifMoreTracks) = @_;
if ($self->{'consecutiveErrors'} > Slim::Player::Playlist::count(master($self))) {
$log->warn("Giving up because of too many consecutive errors: " . $self->{'consecutiveErrors'});
return;
}
my $index = $params->{'index'};
my $song = $params->{'song'};
my $id = ++$self->{'nextTrackCallbackId'};
$self->{'nextTrack'} = undef;
if (!$song) {
# If we have an existing playlist song then we ask it for the next song.
if (!defined($index) && ($song = $self->streamingSong()) && $song->isPlaylist()) {
$song = $song->clonePlaylistSong(); # returns undef at end of playlist
} else {
$song = undef;
}
}
if (!$song) {
# Otherwise, we use the repeat mode to decide which playlist entry to ask for.
unless (defined($index)) {
my $oldIndex = $params->{'errorSong'}
? $params->{'errorSong'}->index()
: $params->{'errorIndex'};
$index = nextsong($self, $oldIndex);
}
if (!defined($index)) {
if ($ifMoreTracks) {
return; # got to end of playlist & no repeat & no force play
} else {
$index = 0;
}
}
my $seekdata = $params->{'seekdata'};
$song = Slim::Player::Song->new($self, $index, $seekdata);
if (!$song) {
_setStreamingState($self, TRACKWAIT);
_nextTrackError($self, $id, $index);
return;
}
}
_setStreamingState($self, TRACKWAIT);
# Bug 10841: Put the song on the queue now even if it might get removed again later
# so that player displays can be correct while scanning a remote track
my $queue = $self->{'songqueue'};
unshift @$queue, $song unless scalar @$queue && $queue->[0] == $song;
while (scalar @$queue &&
($queue->[-1]->status() == Slim::Player::Song::STATUS_FAILED ||
$queue->[-1]->status() == Slim::Player::Song::STATUS_FINISHED)
)
{
pop @$queue;
}
_showTrackwaitStatus($self, $song);
$song->getNextSong (
sub { # success
_nextTrackReady($self, $id, $song);
},
sub { # fail
_nextTrackError($self, $id, $song, @_);
}
);
}
sub _showTrackwaitStatus {
my ($self, $song) = @_;
# Show getting-track-info message if still in TRACKWAIT & STOPPED
if ($self->{'playingState'} == STOPPED && $self->{'streamingState'} == TRACKWAIT) {
my $handler = $song->currentTrackHandler();
my $remoteMeta = $handler->can('getMetadataFor')
? $handler->getMetadataFor($self->master(), $song->currentTrack()->url)
: {};
my $icon = $song->icon();
my $message;
if (!$song->isRemote) {
$message = 'NOW_PLAYING';
$remoteMeta = undef;
} else {
$message = $song->isPlaylist() ? 'GETTING_TRACK_DETAILS' : 'GETTING_STREAM_INFO';
}
_playersMessage($self, $song->currentTrack->url, $remoteMeta , $message, $icon, 0, 30);
}
}
sub _nextTrackReady {
my ($self, $id, $song, $params) = @_;
if ($self->{'nextTrackCallbackId'} != $id) {
main::INFOLOG && $log->info($self->{'masterId'} . ": discarding unexpected nextTrackCallbackId $id, expected " .
$self->{'nextTrackCallbackId'});
$song->setStatus(Slim::Player::Song::STATUS_FINISHED) if (blessed $song);
return;
}
$self->{'nextTrack'} = $song;
main::INFOLOG && $log->info($self->{'masterId'} . ": nextTrack will be index ". $song->index());
_eventAction($self, 'NextTrackReady', $params);
}
sub _nextTrackError {
my ($self, $id, $songOrIndex, @error) = @_;
if ($self->{'nextTrackCallbackId'} != $id) {return;}
my ($song, $index);
if (blessed $songOrIndex) {
$song = $songOrIndex;
$song->setStatus(Slim::Player::Song::STATUS_FAILED);
} else {
$index = $songOrIndex;
}
_errorOpening($self, $song ? $song->currentTrack()->url : undef, @error);
_eventAction($self, 'NextTrackError', {error => \@error, errorSong => $song, errorIndex => $index});
}
sub _errorOpening {
my ($self, $songUrl, $error, $url) = @_;
$self->{'consecutiveErrors'}++;
$error ||= 'PROBLEM_OPENING';
$url ||= $songUrl;
_playersMessage($self, $url, {}, $error, undef, 1, 5, 'isError');
}
sub _playersMessage {
my ($self, $url, $remoteMeta, $message, $icon, $block, $duration, $isError) = @_;
$block = 0 unless defined $block;
$duration = 10 unless defined $duration;
my $master = $self->master();
# Check with the protocol handler to see if it wants to suppress certain messages
if ( my $song = $self->streamingSong() || $self->playingSong() ) {
my $handler = $song->currentTrackHandler();
if ( $handler->can('suppressPlayersMessage') ) {
return if $handler->suppressPlayersMessage($master, $song, $message);
}
}
my $line1 = (uc($message) eq $message) ? $master->string($message) : $message;
main::INFOLOG && $log->info("$line1: $url");
my $iconType = $icon && Slim::Music::Info::isRemoteURL($icon) ? 'icon' : 'icon-id';
$icon ||= 0;
# don't pass remoteMeta if it does not contain a title so getCurrentTitle can extract from db
if ($remoteMeta && ref $remoteMeta eq 'HASH' && !$remoteMeta->{'title'}) {
$remoteMeta = undef;
}
foreach my $client (@{$self->{'players'}}) {
my ($lines, $overlay);
my $line2 = Slim::Music::Info::getCurrentTitle($client, $url, 0, $remoteMeta) || $url;
# use full now playing display if NOW_PLAYING message to get overlay
if ($message eq 'NOW_PLAYING' && $client->can('currentSongLines')) {
my $songLines = $client->currentSongLines();
$lines = $songLines->{'line'};
$overlay = $songLines->{'overlay'};
} else {
$lines = [ $line1, $line2 ];
}
my $screen = Slim::Buttons::Common::msgOnScreen2($client) ? 'screen2' : 'screen1';
# Show an error message
$client->showBriefly( {
$screen => { line => $lines, overlay => $overlay },
jive => {
type => ($isError ? 'popupplay' : 'song'),
text => [ $line1, $line2 ],
$iconType => Slim::Web::ImageProxy::proxiedImage($icon),
duration => $duration * 1000
},
}, {
scroll => 1,
firstline => 1,
block => $block,
duration => $duration,
} );
}
}
# nextsong is for figuring out what the next song will be.
sub nextsong {
my ($self, $currsong) = @_;
my $streamingSong = streamingSong($self);
$currsong = $streamingSong ? $streamingSong->index() : 0 unless defined $currsong;
my $client = master($self);
my $playlistCount = Slim::Player::Playlist::count($client);
if (!$playlistCount) {return undef;}
my $repeat = Slim::Player::Playlist::repeat($client);
if ($self->{'consecutiveErrors'} >= 2) {
if ($playlistCount == 1) {
$log->warn("Giving up because of too many consecutive errors: " . $self->{'consecutiveErrors'});
return undef;
} elsif ($repeat == 1) {
$repeat = 2; # skip this track anyway after two errors
}
}
if ( $repeat == 1 ) {
return $currsong;
}
# Allow one full cycle of the playlist + 1 track
if ($self->{'consecutiveErrors'} > $playlistCount) {
$log->warn("Giving up because of too many consecutive errors: " . $self->{'consecutiveErrors'});
return undef;
}
my $nextsong = $currsong + 1;
if ($nextsong >= $playlistCount) {
# play the next song and start over if necessary
if (Slim::Player::Playlist::shuffle($client) &&
$repeat == 2 &&
$prefs->get('reshuffleOnRepeat')) {
Slim::Player::Playlist::reshuffle($client, 1);
$client->currentPlaylistUpdateTime(Time::HiRes::time()); # bug 17643
}
$nextsong = 0;
}
main::INFOLOG && $log->info("The next song is number $nextsong, was $currsong");
if (!$repeat && $nextsong == 0) {$nextsong = undef;}
return $nextsong;
}
# FIXME - this algorithm is not safe enough.
# (a) It may be that the Track object does not have a duration available for fixed-length stream
# better checks in place now represented by Song::isLive;
# (b) It may be that the duration is only a guess and not good enough for resuming.
#
# If we are playing a remote stream and it ends prematurely, either because it is radio
# (no specific duration) or we have played less than expected, then try to restart.
# We have to have played at least 10 seconds and there must be at least 10 seconds more expected
# in order to try to restart.
#
sub _RetryOrNext { # -> Idle; IF [shouldretry && canretry] THEN continue
# ELSIF [moreTracks] THEN getNextTrack -> TrackWait ENDIF
my ($self, $event, $params) = @_;
_setStreamingState($self, IDLE);
my $song = streamingSong($self);
my $elapsed = playingSongElapsed($self);
if ($song == playingSong($self)
&& $song->isRemote()
&& $elapsed > 10) # have we managed to play at least 10s?
{
if (!$song->duration() && $song->isLive()) { # unknown duration => assume radio
main::INFOLOG && $log->is_info && $log->info('Attempting to re-stream ', $song->currentTrack()->url, ' after time ', $elapsed);
$song->retryData({ count => 0, start => Time::HiRes::time()});
_Stream($self, $event, {song => $song});
return;
} else {
my $duration = $song->duration();
my $bufferSize = master($self)->bufferSize;
my $streambitrate = $song->streambitrate();
if (main::DEBUGLOG && $log->is_debug) {
$log->debug("Elapsed: " . $elapsed);
$log->debug("Duration: " . $duration);
$log->debug("bufferSize: " . $bufferSize);
$log->debug("songbitrate: " . $song->bitrate());
$log->debug("streambitrate: " . $streambitrate);
}
# check we have more than buffer left to play.
if (!$elapsed || !$duration || !$bufferSize || !$streambitrate ||
!($elapsed < $duration) || ($duration - $elapsed) < (($bufferSize * 8) / $streambitrate)) {
if ( main::DEBUGLOG && $log->is_debug ) {$log->debug("Will not retry - no player sync or track is within buffer length end.")};
} else {
# get seek data from protocol handler.
if ( main::DEBUGLOG && $log->is_debug ) {$log->debug("Getting seek data from protocol handler.")};
my $seekdata = $song->getSeekData($elapsed);
main::INFOLOG && $log->is_info && $log->info("Restarting playback at time offset: ". $elapsed);
_Stream($self, undef, {song => $song, seekdata => $seekdata, reconnect => 1});
return;
}
}
}
_getNextTrack($self, $params, 1);
}
sub _Continue {
my ($self, $event, $params) = @_;
my $song = $params->{'song'};
my $bytesReceived = $params->{'bytesReceived'};
my $seekdata;
if ($bytesReceived) {
$seekdata = $song->getSeekDataByPosition($bytesReceived);
}
if ($seekdata && $seekdata->{'streamComplete'}) {
main::INFOLOG && $log->is_info && $log->info("stream already complete at offset $bytesReceived");
_Streamout($self);
} elsif ($seekdata && $bytesReceived) {
main::INFOLOG && $log->is_info && $log->info("Restarting stream at offset $bytesReceived");
_Stream($self, $event, {song => $song, seekdata => $seekdata, reconnect => 1});
if ($song == playingSong($self)) {
$song->setStatus(Slim::Player::Song::STATUS_PLAYING);
}
} else {
# This handles resuming after reboot with the caveat that if connection has been lost (no reboot)
# while playing and before reception of next song's 1st byte, we'll resume the current song
main::INFOLOG && $log->is_info && $log->info("Restarting playback at time offset: ". $self->playingSongElapsed());
_JumpToTime($self, $event, {newtime => $self->playingSongElapsed(), restartIfNoSeek => 1});
}
}
sub _StopGetNext { # stop, getNextTrack -> Stopped, TrackWait
my ($self, $event, $params) = @_;
_Stop(@_);
_getNextTrack($self, $params);
}
sub _Skip {
my ($self, $event, $params) = @_;
my $currentSong = $self->streamingSong();
my $handler = $currentSong->currentTrackHandler();
my $url = $currentSong->currentTrack()->url;
if ($handler->can('canDoAction') && !$handler->canDoAction($self->master(), $url, 'stop')) {
main::INFOLOG && $log->info("Skip for $url disallowed by protocol handler");
return;
}