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
|
/*
This file is part of Subsonic.
Subsonic is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Subsonic is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Subsonic. If not, see <http://www.gnu.org/licenses/>.
Copyright 2009 (C) Sindre Mehus
*/
package github.daneren2005.subphonic.service;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
import github.daneren2005.subphonic.audiofx.EqualizerController;
import github.daneren2005.subphonic.audiofx.VisualizerController;
import github.daneren2005.subphonic.domain.MusicDirectory;
import github.daneren2005.subphonic.domain.PlayerState;
import github.daneren2005.subphonic.domain.RepeatMode;
import github.daneren2005.subphonic.util.CancellableTask;
import github.daneren2005.subphonic.util.LRUCache;
import github.daneren2005.subphonic.util.ShufflePlayBuffer;
import github.daneren2005.subphonic.util.SimpleServiceBinder;
import github.daneren2005.subphonic.util.Util;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import static github.daneren2005.subphonic.domain.PlayerState.*;
/**
* @author Sindre Mehus
* @version $Id$
*/
public class DownloadServiceImpl extends Service implements DownloadService {
private static final String TAG = DownloadServiceImpl.class.getSimpleName();
public static final String CMD_PLAY = "github.daneren2005.subphonic.CMD_PLAY";
public static final String CMD_TOGGLEPAUSE = "github.daneren2005.subphonic.CMD_TOGGLEPAUSE";
public static final String CMD_PAUSE = "github.daneren2005.subphonic.CMD_PAUSE";
public static final String CMD_STOP = "github.daneren2005.subphonic.CMD_STOP";
public static final String CMD_PREVIOUS = "github.daneren2005.subphonic.CMD_PREVIOUS";
public static final String CMD_NEXT = "github.daneren2005.subphonic.CMD_NEXT";
private final IBinder binder = new SimpleServiceBinder<DownloadService>(this);
private MediaPlayer mediaPlayer;
private final List<DownloadFile> downloadList = new ArrayList<DownloadFile>();
private final Handler handler = new Handler();
private final DownloadServiceLifecycleSupport lifecycleSupport = new DownloadServiceLifecycleSupport(this);
private final ShufflePlayBuffer shufflePlayBuffer = new ShufflePlayBuffer(this);
private final LRUCache<MusicDirectory.Entry, DownloadFile> downloadFileCache = new LRUCache<MusicDirectory.Entry, DownloadFile>(100);
private final List<DownloadFile> cleanupCandidates = new ArrayList<DownloadFile>();
private final Scrobbler scrobbler = new Scrobbler();
private final JukeboxService jukeboxService = new JukeboxService(this);
private DownloadFile currentPlaying;
private DownloadFile currentDownloading;
private CancellableTask bufferTask;
private PlayerState playerState = IDLE;
private boolean shufflePlay;
private long revision;
private static DownloadService instance;
private String suggestedPlaylistName;
private PowerManager.WakeLock wakeLock;
private boolean keepScreenOn = false;
private static boolean equalizerAvailable;
private static boolean visualizerAvailable;
private EqualizerController equalizerController;
private VisualizerController visualizerController;
private boolean showVisualization;
private boolean jukeboxEnabled;
static {
try {
EqualizerController.checkAvailable();
equalizerAvailable = true;
} catch (Throwable t) {
equalizerAvailable = false;
}
}
static {
try {
VisualizerController.checkAvailable();
visualizerAvailable = true;
} catch (Throwable t) {
visualizerAvailable = false;
}
}
@Override
public void onCreate() {
super.onCreate();
mediaPlayer = new MediaPlayer();
mediaPlayer.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
return false;
}
});
if (equalizerAvailable) {
equalizerController = new EqualizerController(this, mediaPlayer);
if (!equalizerController.isAvailable()) {
equalizerController = null;
} else {
equalizerController.loadSettings();
}
}
if (visualizerAvailable) {
visualizerController = new VisualizerController(this, mediaPlayer);
if (!visualizerController.isAvailable()) {
visualizerController = null;
}
}
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
wakeLock.setReferenceCounted(false);
instance = this;
lifecycleSupport.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
lifecycleSupport.onStart(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
lifecycleSupport.onDestroy();
mediaPlayer.release();
shufflePlayBuffer.shutdown();
if (equalizerController != null) {
equalizerController.release();
}
if (visualizerController != null) {
visualizerController.release();
}
instance = null;
}
public static DownloadService getInstance() {
return instance;
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
@Override
public synchronized void download(List<MusicDirectory.Entry> songs, boolean save, boolean autoplay, boolean playNext) {
shufflePlay = false;
int offset = 1;
if (songs.isEmpty()) {
return;
}
if (playNext) {
if (autoplay && getCurrentPlayingIndex() >= 0) {
offset = 0;
}
for (MusicDirectory.Entry song : songs) {
DownloadFile downloadFile = new DownloadFile(this, song, save);
downloadList.add(getCurrentPlayingIndex() + offset, downloadFile);
offset++;
}
revision++;
} else {
for (MusicDirectory.Entry song : songs) {
DownloadFile downloadFile = new DownloadFile(this, song, save);
downloadList.add(downloadFile);
}
revision++;
}
updateJukeboxPlaylist();
if (autoplay) {
play(0);
} else {
if (currentPlaying == null) {
currentPlaying = downloadList.get(0);
}
checkDownloads();
}
lifecycleSupport.serializeDownloadQueue();
}
private void updateJukeboxPlaylist() {
if (jukeboxEnabled) {
jukeboxService.updatePlaylist();
}
}
public void restore(List<MusicDirectory.Entry> songs, int currentPlayingIndex, int currentPlayingPosition) {
download(songs, false, false, false);
if (currentPlayingIndex != -1) {
play(currentPlayingIndex, false);
if (currentPlaying.isCompleteFileAvailable()) {
doPlay(currentPlaying, currentPlayingPosition, false);
}
}
}
@Override
public synchronized void setShufflePlayEnabled(boolean enabled) {
if (shufflePlay == enabled) {
return;
}
shufflePlay = enabled;
if (shufflePlay) {
clear();
checkDownloads();
}
}
@Override
public synchronized boolean isShufflePlayEnabled() {
return shufflePlay;
}
@Override
public synchronized void shuffle() {
Collections.shuffle(downloadList);
if (currentPlaying != null) {
downloadList.remove(getCurrentPlayingIndex());
downloadList.add(0, currentPlaying);
}
revision++;
lifecycleSupport.serializeDownloadQueue();
updateJukeboxPlaylist();
}
@Override
public RepeatMode getRepeatMode() {
return Util.getRepeatMode(this);
}
@Override
public void setRepeatMode(RepeatMode repeatMode) {
Util.setRepeatMode(this, repeatMode);
}
@Override
public boolean getKeepScreenOn() {
return keepScreenOn;
}
@Override
public void setKeepScreenOn(boolean keepScreenOn) {
this.keepScreenOn = keepScreenOn;
}
@Override
public boolean getShowVisualization() {
return showVisualization;
}
@Override
public void setShowVisualization(boolean showVisualization) {
this.showVisualization = showVisualization;
}
@Override
public synchronized DownloadFile forSong(MusicDirectory.Entry song) {
for (DownloadFile downloadFile : downloadList) {
if (downloadFile.getSong().equals(song)) {
return downloadFile;
}
}
DownloadFile downloadFile = downloadFileCache.get(song);
if (downloadFile == null) {
downloadFile = new DownloadFile(this, song, false);
downloadFileCache.put(song, downloadFile);
}
return downloadFile;
}
@Override
public synchronized void clear() {
clear(true);
}
@Override
public synchronized void clearIncomplete() {
reset();
Iterator<DownloadFile> iterator = downloadList.iterator();
while (iterator.hasNext()) {
DownloadFile downloadFile = iterator.next();
if (!downloadFile.isCompleteFileAvailable()) {
iterator.remove();
}
}
lifecycleSupport.serializeDownloadQueue();
updateJukeboxPlaylist();
}
@Override
public synchronized int size() {
return downloadList.size();
}
public synchronized void clear(boolean serialize) {
reset();
downloadList.clear();
revision++;
if (currentDownloading != null) {
currentDownloading.cancelDownload();
currentDownloading = null;
}
setCurrentPlaying(null, false);
if (serialize) {
lifecycleSupport.serializeDownloadQueue();
}
updateJukeboxPlaylist();
}
@Override
public synchronized void remove(DownloadFile downloadFile) {
if (downloadFile == currentDownloading) {
currentDownloading.cancelDownload();
currentDownloading = null;
}
if (downloadFile == currentPlaying) {
reset();
setCurrentPlaying(null, false);
}
downloadList.remove(downloadFile);
revision++;
lifecycleSupport.serializeDownloadQueue();
updateJukeboxPlaylist();
}
@Override
public synchronized void delete(List<MusicDirectory.Entry> songs) {
for (MusicDirectory.Entry song : songs) {
forSong(song).delete();
}
}
@Override
public synchronized void unpin(List<MusicDirectory.Entry> songs) {
for (MusicDirectory.Entry song : songs) {
forSong(song).unpin();
}
}
synchronized void setCurrentPlaying(int currentPlayingIndex, boolean showNotification) {
try {
setCurrentPlaying(downloadList.get(currentPlayingIndex), showNotification);
} catch (IndexOutOfBoundsException x) {
// Ignored
}
}
synchronized void setCurrentPlaying(DownloadFile currentPlaying, boolean showNotification) {
this.currentPlaying = currentPlaying;
if (currentPlaying != null) {
Util.broadcastNewTrackInfo(this, currentPlaying.getSong());
} else {
Util.broadcastNewTrackInfo(this, null);
}
if (currentPlaying != null && showNotification) {
Util.showPlayingNotification(this, this, handler, currentPlaying.getSong());
} else {
Util.hidePlayingNotification(this, this, handler);
}
}
@Override
public synchronized int getCurrentPlayingIndex() {
return downloadList.indexOf(currentPlaying);
}
@Override
public DownloadFile getCurrentPlaying() {
return currentPlaying;
}
@Override
public DownloadFile getCurrentDownloading() {
return currentDownloading;
}
@Override
public synchronized List<DownloadFile> getDownloads() {
return new ArrayList<DownloadFile>(downloadList);
}
/** Plays either the current song (resume) or the first/next one in queue. */
public synchronized void play()
{
int current = getCurrentPlayingIndex();
if (current == -1) {
play(0);
} else {
play(current);
}
}
@Override
public synchronized void play(int index) {
play(index, true);
}
private synchronized void play(int index, boolean start) {
if (index < 0 || index >= size()) {
reset();
setCurrentPlaying(null, false);
} else {
setCurrentPlaying(index, start);
checkDownloads();
if (start) {
if (jukeboxEnabled) {
jukeboxService.skip(getCurrentPlayingIndex(), 0);
setPlayerState(STARTED);
} else {
bufferAndPlay();
}
}
}
}
/** Plays or resumes the playback, depending on the current player state. */
public synchronized void togglePlayPause()
{
if (playerState == PAUSED || playerState == COMPLETED) {
start();
} else if (playerState == STOPPED || playerState == IDLE) {
play();
} else if (playerState == STARTED) {
pause();
}
}
@Override
public synchronized void seekTo(int position) {
try {
if (jukeboxEnabled) {
jukeboxService.skip(getCurrentPlayingIndex(), position / 1000);
} else {
mediaPlayer.seekTo(position);
}
} catch (Exception x) {
handleError(x);
}
}
@Override
public synchronized void previous() {
int index = getCurrentPlayingIndex();
if (index == -1) {
return;
}
// Restart song if played more than five seconds.
if (getPlayerPosition() > 5000 || index == 0) {
play(index);
} else {
play(index - 1);
}
}
@Override
public synchronized void next() {
int index = getCurrentPlayingIndex();
if (index != -1) {
play(index + 1);
}
}
private void onSongCompleted() {
int index = getCurrentPlayingIndex();
if (index != -1) {
switch (getRepeatMode()) {
case OFF:
play(index + 1);
break;
case ALL:
play((index + 1) % size());
break;
case SINGLE:
play(index);
break;
default:
break;
}
}
}
@Override
public synchronized void pause() {
try {
if (playerState == STARTED) {
if (jukeboxEnabled) {
jukeboxService.stop();
} else {
mediaPlayer.pause();
}
setPlayerState(PAUSED);
}
} catch (Exception x) {
handleError(x);
}
}
@Override
public synchronized void start() {
try {
if (jukeboxEnabled) {
jukeboxService.start();
} else {
mediaPlayer.start();
}
setPlayerState(STARTED);
} catch (Exception x) {
handleError(x);
}
}
@Override
public synchronized void reset() {
if (bufferTask != null) {
bufferTask.cancel();
}
try {
mediaPlayer.reset();
setPlayerState(IDLE);
} catch (Exception x) {
handleError(x);
}
}
@Override
public synchronized int getPlayerPosition() {
try {
if (playerState == IDLE || playerState == DOWNLOADING || playerState == PREPARING) {
return 0;
}
if (jukeboxEnabled) {
return jukeboxService.getPositionSeconds() * 1000;
} else {
return mediaPlayer.getCurrentPosition();
}
} catch (Exception x) {
handleError(x);
return 0;
}
}
@Override
public synchronized int getPlayerDuration() {
if (currentPlaying != null) {
Integer duration = currentPlaying.getSong().getDuration();
if (duration != null) {
return duration * 1000;
}
}
if (playerState != IDLE && playerState != DOWNLOADING && playerState != PlayerState.PREPARING) {
try {
return mediaPlayer.getDuration();
} catch (Exception x) {
handleError(x);
}
}
return 0;
}
@Override
public PlayerState getPlayerState() {
return playerState;
}
synchronized void setPlayerState(PlayerState playerState) {
Log.i(TAG, this.playerState.name() + " -> " + playerState.name() + " (" + currentPlaying + ")");
if (playerState == PAUSED) {
lifecycleSupport.serializeDownloadQueue();
}
boolean show = this.playerState == PAUSED && playerState == PlayerState.STARTED;
boolean hide = this.playerState == STARTED && playerState == PlayerState.PAUSED;
Util.broadcastPlaybackStatusChange(this, playerState);
this.playerState = playerState;
if (show) {
Util.showPlayingNotification(this, this, handler, currentPlaying.getSong());
} else if (hide) {
Util.hidePlayingNotification(this, this, handler);
}
if (playerState == STARTED) {
scrobbler.scrobble(this, currentPlaying, false);
} else if (playerState == COMPLETED) {
scrobbler.scrobble(this, currentPlaying, true);
}
}
@Override
public void setSuggestedPlaylistName(String name) {
this.suggestedPlaylistName = name;
}
@Override
public String getSuggestedPlaylistName() {
return suggestedPlaylistName;
}
@Override
public EqualizerController getEqualizerController() {
return equalizerController;
}
@Override
public VisualizerController getVisualizerController() {
return visualizerController;
}
@Override
public boolean isJukeboxEnabled() {
return jukeboxEnabled;
}
@Override
public void setJukeboxEnabled(boolean jukeboxEnabled) {
this.jukeboxEnabled = jukeboxEnabled;
jukeboxService.setEnabled(jukeboxEnabled);
if (jukeboxEnabled) {
reset();
// Cancel current download, if necessary.
if (currentDownloading != null) {
currentDownloading.cancelDownload();
}
}
}
@Override
public void adjustJukeboxVolume(boolean up) {
jukeboxService.adjustVolume(up);
}
private synchronized void bufferAndPlay() {
reset();
bufferTask = new BufferTask(currentPlaying, 0);
bufferTask.start();
}
private synchronized void doPlay(final DownloadFile downloadFile, int position, boolean start) {
// TODO: Start play at curr pos on rebuffer instead of restart
try {
final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile() : downloadFile.getPartialFile();
downloadFile.updateModificationDate();
mediaPlayer.setOnCompletionListener(null);
mediaPlayer.reset();
setPlayerState(IDLE);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(file.getPath());
setPlayerState(PREPARING);
mediaPlayer.prepare();
setPlayerState(PREPARED);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
// Acquire a temporary wakelock, since when we return from
// this callback the MediaPlayer will release its wakelock
// and allow the device to go to sleep.
wakeLock.acquire(60000);
setPlayerState(COMPLETED);
// If COMPLETED and not playing partial file, we are *really" finished
// with the song and can move on to the next.
if (!file.equals(downloadFile.getPartialFile())) {
onSongCompleted();
return;
}
// If file is not completely downloaded, restart the playback from the current position.
int pos = mediaPlayer.getCurrentPosition();
synchronized (DownloadServiceImpl.this) {
// Work-around for apparent bug on certain phones: If close (less than ten seconds) to the end
// of the song, skip to the next rather than restarting it.
Integer duration = downloadFile.getSong().getDuration() == null ? null : downloadFile.getSong().getDuration() * 1000;
if (duration != null) {
if (Math.abs(duration - pos) < 10000) {
Log.i(TAG, "Skipping restart from " + pos + " of " + duration);
onSongCompleted();
return;
}
}
Log.i(TAG, "Requesting restart from " + pos + " of " + duration);
reset();
bufferTask = new BufferTask(downloadFile, pos);
bufferTask.start();
}
}
});
if (position != 0) {
Log.i(TAG, "Restarting player from position " + position);
mediaPlayer.seekTo(position);
}
if (start) {
mediaPlayer.start();
setPlayerState(STARTED);
} else {
setPlayerState(PAUSED);
}
lifecycleSupport.serializeDownloadQueue();
} catch (Exception x) {
handleError(x);
}
}
private void handleError(Exception x) {
Log.w(TAG, "Media player error: " + x, x);
mediaPlayer.reset();
setPlayerState(IDLE);
}
protected synchronized void checkDownloads() {
if (!Util.isExternalStoragePresent() || !lifecycleSupport.isExternalStorageAvailable()) {
return;
}
if (shufflePlay) {
checkShufflePlay();
}
if (jukeboxEnabled || !Util.isNetworkConnected(this)) {
return;
}
if (downloadList.isEmpty()) {
return;
}
// Need to download current playing?
if (currentPlaying != null &&
currentPlaying != currentDownloading &&
!currentPlaying.isCompleteFileAvailable()) {
// Cancel current download, if necessary.
if (currentDownloading != null) {
currentDownloading.cancelDownload();
}
currentDownloading = currentPlaying;
currentDownloading.download();
cleanupCandidates.add(currentDownloading);
}
// Find a suitable target for download.
else if (currentDownloading == null || currentDownloading.isWorkDone() || currentDownloading.isFailed()) {
int n = size();
if (n == 0) {
return;
}
int preloaded = 0;
int start = currentPlaying == null ? 0 : getCurrentPlayingIndex();
int i = start;
do {
DownloadFile downloadFile = downloadList.get(i);
if (!downloadFile.isWorkDone()) {
if (downloadFile.shouldSave() || preloaded < Util.getPreloadCount(this)) {
currentDownloading = downloadFile;
currentDownloading.download();
cleanupCandidates.add(currentDownloading);
break;
}
} else if (currentPlaying != downloadFile) {
preloaded++;
}
i = (i + 1) % n;
} while (i != start);
}
// Delete obsolete .partial and .complete files.
cleanup();
}
private synchronized void checkShufflePlay() {
final int listSize = 20;
boolean wasEmpty = downloadList.isEmpty();
long revisionBefore = revision;
// First, ensure that list is at least 20 songs long.
int size = size();
if (size < listSize) {
for (MusicDirectory.Entry song : shufflePlayBuffer.get(listSize - size)) {
DownloadFile downloadFile = new DownloadFile(this, song, false);
downloadList.add(downloadFile);
revision++;
}
}
int currIndex = currentPlaying == null ? 0 : getCurrentPlayingIndex();
// Only shift playlist if playing song #5 or later.
if (currIndex > 4) {
int songsToShift = currIndex - 2;
for (MusicDirectory.Entry song : shufflePlayBuffer.get(songsToShift)) {
downloadList.add(new DownloadFile(this, song, false));
downloadList.get(0).cancelDownload();
downloadList.remove(0);
revision++;
}
}
if (revisionBefore != revision) {
updateJukeboxPlaylist();
}
if (wasEmpty && !downloadList.isEmpty()) {
play(0);
}
}
public long getDownloadListUpdateRevision() {
return revision;
}
private synchronized void cleanup() {
Iterator<DownloadFile> iterator = cleanupCandidates.iterator();
while (iterator.hasNext()) {
DownloadFile downloadFile = iterator.next();
if (downloadFile != currentPlaying && downloadFile != currentDownloading) {
if (downloadFile.cleanup()) {
iterator.remove();
}
}
}
}
private class BufferTask extends CancellableTask {
private static final int BUFFER_LENGTH_SECONDS = 5;
private final DownloadFile downloadFile;
private final int position;
private final long expectedFileSize;
private final File partialFile;
public BufferTask(DownloadFile downloadFile, int position) {
this.downloadFile = downloadFile;
this.position = position;
partialFile = downloadFile.getPartialFile();
// Calculate roughly how many bytes BUFFER_LENGTH_SECONDS corresponds to.
int bitRate = downloadFile.getBitRate();
long byteCount = Math.max(100000, bitRate * 1024 / 8 * BUFFER_LENGTH_SECONDS);
// Find out how large the file should grow before resuming playback.
expectedFileSize = partialFile.length() + byteCount;
}
@Override
public void execute() {
setPlayerState(DOWNLOADING);
while (!bufferComplete()) {
Util.sleepQuietly(1000L);
if (isCancelled()) {
return;
}
}
doPlay(downloadFile, position, true);
}
private boolean bufferComplete() {
boolean completeFileAvailable = downloadFile.isCompleteFileAvailable();
long size = partialFile.length();
Log.i(TAG, "Buffering " + partialFile + " (" + size + "/" + expectedFileSize + ", " + completeFileAvailable + ")");
return completeFileAvailable || size >= expectedFileSize;
}
@Override
public String toString() {
return "BufferTask (" + downloadFile + ")";
}
}
}
|