summaryrefslogtreecommitdiff
path: root/src/de/danoeh/antennapod/service/PlaybackService.java
blob: 2fa4e10d9cb6ac204fa7d79e8652f6df27604092 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
package de.danoeh.antennapod.service;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.RemoteControlClient;
import android.media.RemoteControlClient.MetadataEditor;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import de.danoeh.antennapod.AppConfig;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.activity.AudioplayerActivity;
import de.danoeh.antennapod.activity.VideoplayerActivity;
import de.danoeh.antennapod.feed.*;
import de.danoeh.antennapod.preferences.PlaybackPreferences;
import de.danoeh.antennapod.preferences.UserPreferences;
import de.danoeh.antennapod.receiver.MediaButtonReceiver;
import de.danoeh.antennapod.receiver.PlayerWidget;
import de.danoeh.antennapod.storage.DBReader;
import de.danoeh.antennapod.storage.DBTasks;
import de.danoeh.antennapod.storage.DBWriter;
import de.danoeh.antennapod.util.BitmapDecoder;
import de.danoeh.antennapod.util.QueueAccess;
import de.danoeh.antennapod.util.DuckType;
import de.danoeh.antennapod.util.flattr.FlattrUtils;
import de.danoeh.antennapod.util.playback.AudioPlayer;
import de.danoeh.antennapod.util.playback.IPlayer;
import de.danoeh.antennapod.util.playback.Playable;
import de.danoeh.antennapod.util.playback.Playable.PlayableException;
import de.danoeh.antennapod.util.playback.VideoPlayer;
import de.danoeh.antennapod.util.playback.PlaybackController;

/**
 * Controls the MediaPlayer that plays a FeedMedia-file
 */
public class PlaybackService extends Service {
    /**
     * Logging tag
     */
    private static final String TAG = "PlaybackService";

    /**
     * Parcelable of type Playable.
     */
    public static final String EXTRA_PLAYABLE = "PlaybackService.PlayableExtra";
    /**
     * True if media should be streamed.
     */
    public static final String EXTRA_SHOULD_STREAM = "extra.de.danoeh.antennapod.service.shouldStream";
    /**
     * True if playback should be started immediately after media has been
     * prepared.
     */
    public static final String EXTRA_START_WHEN_PREPARED = "extra.de.danoeh.antennapod.service.startWhenPrepared";

    public static final String EXTRA_PREPARE_IMMEDIATELY = "extra.de.danoeh.antennapod.service.prepareImmediately";

    public static final String ACTION_PLAYER_STATUS_CHANGED = "action.de.danoeh.antennapod.service.playerStatusChanged";
    private static final String AVRCP_ACTION_PLAYER_STATUS_CHANGED = "com.android.music.playstatechanged";

    public static final String ACTION_PLAYER_NOTIFICATION = "action.de.danoeh.antennapod.service.playerNotification";
    public static final String EXTRA_NOTIFICATION_CODE = "extra.de.danoeh.antennapod.service.notificationCode";
    public static final String EXTRA_NOTIFICATION_TYPE = "extra.de.danoeh.antennapod.service.notificationType";

    /**
     * If the PlaybackService receives this action, it will stop playback and
     * try to shutdown.
     */
    public static final String ACTION_SHUTDOWN_PLAYBACK_SERVICE = "action.de.danoeh.antennapod.service.actionShutdownPlaybackService";

    /**
     * If the PlaybackService receives this action, it will end playback of the
     * current episode and load the next episode if there is one available.
     */
    public static final String ACTION_SKIP_CURRENT_EPISODE = "action.de.danoeh.antennapod.service.skipCurrentEpisode";

    /**
     * Used in NOTIFICATION_TYPE_RELOAD.
     */
    public static final int EXTRA_CODE_AUDIO = 1;
    public static final int EXTRA_CODE_VIDEO = 2;

    public static final int NOTIFICATION_TYPE_ERROR = 0;
    public static final int NOTIFICATION_TYPE_INFO = 1;
    public static final int NOTIFICATION_TYPE_BUFFER_UPDATE = 2;

    /**
     * Receivers of this intent should update their information about the curently playing media
     */
    public static final int NOTIFICATION_TYPE_RELOAD = 3;
    /**
     * The state of the sleeptimer changed.
     */
    public static final int NOTIFICATION_TYPE_SLEEPTIMER_UPDATE = 4;
    public static final int NOTIFICATION_TYPE_BUFFER_START = 5;
    public static final int NOTIFICATION_TYPE_BUFFER_END = 6;
    /**
     * No more episodes are going to be played.
     */
    public static final int NOTIFICATION_TYPE_PLAYBACK_END = 7;

    /** 
     * Playback speed has changed
     * */
    public static final int NOTIFICATION_TYPE_PLAYBACK_SPEED_CHANGE = 8;
    
     /**
     * Returned by getPositionSafe() or getDurationSafe() if the playbackService
     * is in an invalid state.
     */
    public static final int INVALID_TIME = -1;

    /**
     * Is true if service is running.
     */
    public static boolean isRunning = false;

    private static final int NOTIFICATION_ID = 1;

	private volatile IPlayer player;
	private RemoteControlClient remoteControlClient;
    private AudioManager audioManager;
    private ComponentName mediaButtonReceiver;

    private volatile Playable media;

    /**
     * True if media should be streamed (Extracted from Intent Extra) .
     */
    private boolean shouldStream;

    private boolean startWhenPrepared;
    private PlayerStatus status;

    private PositionSaver positionSaver;
    private ScheduledFuture positionSaverFuture;

    private WidgetUpdateWorker widgetUpdater;
    private ScheduledFuture widgetUpdaterFuture;

    private SleepTimer sleepTimer;
    private Future sleepTimerFuture;

    private static final int SCHED_EX_POOL_SIZE = 3;
    private ScheduledThreadPoolExecutor schedExecutor;
    private ExecutorService dbLoaderExecutor;

    private volatile PlayerStatus statusBeforeSeek;

    private static boolean playingVideo;

    /**
     * True if mediaplayer was paused because it lost audio focus temporarily
     */
    private boolean pausedBecauseOfTransientAudiofocusLoss;

    private Thread chapterLoader;

    private final IBinder mBinder = new LocalBinder();

    private volatile List<FeedItem> queue;

    public class LocalBinder extends Binder {
        public PlaybackService getService() {
            return PlaybackService.this;
        }
    }

    @Override
    public boolean onUnbind(Intent intent) {
        if (AppConfig.DEBUG)
            Log.d(TAG, "Received onUnbind event");
        return super.onUnbind(intent);
    }

    /**
     * Returns an intent which starts an audio- or videoplayer, depending on the
     * type of media that is being played. If the playbackservice is not
     * running, the type of the last played media will be looked up.
     */
    public static Intent getPlayerActivityIntent(Context context) {
        if (isRunning) {
            if (playingVideo) {
                return new Intent(context, VideoplayerActivity.class);
            } else {
                return new Intent(context, AudioplayerActivity.class);
            }
        } else {
            if (PlaybackPreferences.getCurrentEpisodeIsVideo()) {
                return new Intent(context, VideoplayerActivity.class);
            } else {
                return new Intent(context, AudioplayerActivity.class);
            }
        }
    }

    /**
     * Same as getPlayerActivityIntent(context), but here the type of activity
     * depends on the FeedMedia that is provided as an argument.
     */
    public static Intent getPlayerActivityIntent(Context context, Playable media) {
        MediaType mt = media.getMediaType();
        if (mt == MediaType.VIDEO) {
            return new Intent(context, VideoplayerActivity.class);
        } else {
            return new Intent(context, AudioplayerActivity.class);
        }
    }

    @SuppressLint("NewApi")
    @Override
    public void onCreate() {
        super.onCreate();
        if (AppConfig.DEBUG)
            Log.d(TAG, "Service created.");
        isRunning = true;
        pausedBecauseOfTransientAudiofocusLoss = false;
        status = PlayerStatus.STOPPED;
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        schedExecutor = new ScheduledThreadPoolExecutor(SCHED_EX_POOL_SIZE,
                new ThreadFactory() {

                    @Override
                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r);
                        t.setPriority(Thread.MIN_PRIORITY);
                        return t;
                    }
                }, new RejectedExecutionHandler() {

            @Override
            public void rejectedExecution(Runnable r,
                                          ThreadPoolExecutor executor) {
                Log.w(TAG, "SchedEx rejected submission of new task");
            }
        }
        );
        dbLoaderExecutor = Executors.newSingleThreadExecutor();

        mediaButtonReceiver = new ComponentName(getPackageName(),
                MediaButtonReceiver.class.getName());
        audioManager.registerMediaButtonEventReceiver(mediaButtonReceiver);
        if (android.os.Build.VERSION.SDK_INT >= 14) {
            audioManager
                    .registerRemoteControlClient(setupRemoteControlClient());
        }
        registerReceiver(headsetDisconnected, new IntentFilter(
                Intent.ACTION_HEADSET_PLUG));
        registerReceiver(shutdownReceiver, new IntentFilter(
                ACTION_SHUTDOWN_PLAYBACK_SERVICE));
        registerReceiver(audioBecomingNoisy, new IntentFilter(
                AudioManager.ACTION_AUDIO_BECOMING_NOISY));
        registerReceiver(skipCurrentEpisodeReceiver, new IntentFilter(
                ACTION_SKIP_CURRENT_EPISODE));
        EventDistributor.getInstance().register(eventDistributorListener);
        loadQueue();
    }

    private IPlayer createMediaPlayer() {
        if (player != null) {
            player.release();
        }
        IPlayer player;
        if (media == null || media.getMediaType() == MediaType.VIDEO) {
            player = new VideoPlayer();
        } else {
            player = new AudioPlayer(this);
        }
        return createMediaPlayer(player);
    }

	private IPlayer createMediaPlayer(IPlayer mp) {
		if (mp != null && media != null) {
			if (media.getMediaType() == MediaType.AUDIO) {
				((AudioPlayer) mp).setOnPreparedListener(audioPreparedListener);
				((AudioPlayer) mp)
						.setOnCompletionListener(audioCompletionListener);
				((AudioPlayer) mp)
						.setOnSeekCompleteListener(audioSeekCompleteListener);
				((AudioPlayer) mp).setOnErrorListener(audioErrorListener);
				((AudioPlayer) mp)
						.setOnBufferingUpdateListener(audioBufferingUpdateListener);
				((AudioPlayer) mp).setOnInfoListener(audioInfoListener);
			} else {
				((VideoPlayer) mp).setOnPreparedListener(videoPreparedListener);
				((VideoPlayer) mp)
						.setOnCompletionListener(videoCompletionListener);
				((VideoPlayer) mp)
						.setOnSeekCompleteListener(videoSeekCompleteListener);
				((VideoPlayer) mp).setOnErrorListener(videoErrorListener);
				((VideoPlayer) mp)
						.setOnBufferingUpdateListener(videoBufferingUpdateListener);
				((VideoPlayer) mp).setOnInfoListener(videoInfoListener);
			}
		}
		return mp;
	}

    @SuppressLint("NewApi")
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (AppConfig.DEBUG)
            Log.d(TAG, "Service is about to be destroyed");
        isRunning = false;
        if (chapterLoader != null) {
            chapterLoader.interrupt();
        }
        disableSleepTimer();
        unregisterReceiver(headsetDisconnected);
        unregisterReceiver(shutdownReceiver);
        unregisterReceiver(audioBecomingNoisy);
        unregisterReceiver(skipCurrentEpisodeReceiver);
        EventDistributor.getInstance().unregister(eventDistributorListener);
        if (android.os.Build.VERSION.SDK_INT >= 14) {
            audioManager.unregisterRemoteControlClient(remoteControlClient);
        }
        audioManager.unregisterMediaButtonEventReceiver(mediaButtonReceiver);
        audioManager.abandonAudioFocus(audioFocusChangeListener);
        player.release();
        stopWidgetUpdater();
        updateWidget();
    }

    @Override
    public IBinder onBind(Intent intent) {
        if (AppConfig.DEBUG)
            Log.d(TAG, "Received onBind event");
        return mBinder;
    }

    private final EventDistributor.EventListener eventDistributorListener = new EventDistributor.EventListener() {
        @Override
        public void update(EventDistributor eventDistributor, Integer arg) {
            if ((EventDistributor.QUEUE_UPDATE & arg) != 0) {
                loadQueue();
            }
        }
    };

    private final OnAudioFocusChangeListener audioFocusChangeListener = new OnAudioFocusChangeListener() {

        @Override
        public void onAudioFocusChange(int focusChange) {
            switch (focusChange) {
                case AudioManager.AUDIOFOCUS_LOSS:
                    if (AppConfig.DEBUG)
                        Log.d(TAG, "Lost audio focus");
                    pause(true, false);
                    stopSelf();
                    break;
                case AudioManager.AUDIOFOCUS_GAIN:
                    if (AppConfig.DEBUG)
                        Log.d(TAG, "Gained audio focus");
                    if (pausedBecauseOfTransientAudiofocusLoss) {
                        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                                AudioManager.ADJUST_RAISE, 0);
                        play();
                    }
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    if (status == PlayerStatus.PLAYING) {
                        if (!UserPreferences.shouldPauseForFocusLoss()) {
                            if (AppConfig.DEBUG)
                                Log.d(TAG, "Lost audio focus temporarily. Ducking...");
                            audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                                    AudioManager.ADJUST_LOWER, 0);
                            pausedBecauseOfTransientAudiofocusLoss = true;
                        } else {
                            if (AppConfig.DEBUG)
                                Log.d(TAG, "Lost audio focus temporarily. Could duck, but won't, pausing...");
                            pause(false, false);
                            pausedBecauseOfTransientAudiofocusLoss = true;
                        }
                    }
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    if (status == PlayerStatus.PLAYING) {
                        if (AppConfig.DEBUG)
                            Log.d(TAG, "Lost audio focus temporarily. Pausing...");
                        pause(false, false);
                        pausedBecauseOfTransientAudiofocusLoss = true;
                    }
            }
        }
    };

    /**
     * 1. Check type of intent
     * 1.1 Keycode -> handle keycode -> done
     * 1.2 Playable -> Step 2
     * 2. Handle playable
     * 2.1 Check current status
     * 2.1.1 Not playing -> play new playable
     * 2.1.2 Playing, new playable is the same -> play if playback is currently paused
     * 2.1.3 Playing, new playable different -> Stop playback of old media
     *
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        if (AppConfig.DEBUG)
            Log.d(TAG, "OnStartCommand called");
        final int keycode = intent.getIntExtra(MediaButtonReceiver.EXTRA_KEYCODE, -1);
        final Playable playable = intent.getParcelableExtra(EXTRA_PLAYABLE);
        if (keycode == -1 && playable == null) {
            Log.e(TAG, "PlaybackService was started with no arguments");
            stopSelf();
        }

        if (keycode != -1) {
            if (AppConfig.DEBUG)
                Log.d(TAG, "Received media button event");
            handleKeycode(keycode);
        } else {
            boolean playbackType = intent.getBooleanExtra(EXTRA_SHOULD_STREAM,
                    true);
            if (media == null) {
                media = playable;
                shouldStream = playbackType;
                startWhenPrepared = intent.getBooleanExtra(
                        EXTRA_START_WHEN_PREPARED, false);
                initMediaplayer(intent.getBooleanExtra(EXTRA_PREPARE_IMMEDIATELY, false));
                sendNotificationBroadcast(NOTIFICATION_TYPE_RELOAD, 0);
            }
            if (media != null) {
                if (!playable.getIdentifier().equals(media.getIdentifier())) {
                    // different media or different playback type
                    pause(true, false);
                    player.reset();
                    media = playable;
                    shouldStream = playbackType;
                    startWhenPrepared = intent.getBooleanExtra(EXTRA_START_WHEN_PREPARED, false);
                    initMediaplayer(intent.getBooleanExtra(EXTRA_PREPARE_IMMEDIATELY, false));
                    sendNotificationBroadcast(NOTIFICATION_TYPE_RELOAD, 0);
                } else {
                    // same media and same playback type
                    if (status == PlayerStatus.PAUSED) {
                        play();
                    }
                }
            }
        }

        return Service.START_NOT_STICKY;
    }

	/** Handles media button events */
	private void handleKeycode(int keycode) {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Handling keycode: " + keycode);
		switch (keycode) {
		case KeyEvent.KEYCODE_HEADSETHOOK:
		case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
			if (status == PlayerStatus.PLAYING) {
				pause(true, true);
			} else if (status == PlayerStatus.PAUSED) {
				play();
			} else if (status == PlayerStatus.PREPARING) {
				setStartWhenPrepared(!startWhenPrepared);
			} else if (status == PlayerStatus.INITIALIZED) {
				startWhenPrepared = true;
				prepare();
			}
			break;
		case KeyEvent.KEYCODE_MEDIA_PLAY:
			if (status == PlayerStatus.PAUSED) {
				play();
			} else if (status == PlayerStatus.INITIALIZED) {
				startWhenPrepared = true;
				prepare();
			}
			break;
		case KeyEvent.KEYCODE_MEDIA_PAUSE:
			if (status == PlayerStatus.PLAYING) {
				pause(true, true);
			}
			break;
		case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: {
			seekDelta(PlaybackController.DEFAULT_SEEK_DELTA);
			break;
		}
		case KeyEvent.KEYCODE_MEDIA_REWIND: {
			seekDelta(-PlaybackController.DEFAULT_SEEK_DELTA);
			break;
 		  }
		}
	}

    /**
     * Called by a mediaplayer Activity as soon as it has prepared its
     * mediaplayer.
     */
    public void setVideoSurface(SurfaceHolder sh) {
        if (AppConfig.DEBUG)
            Log.d(TAG, "Setting display");
        player.setDisplay(null);
        player.setDisplay(sh);
        if (status == PlayerStatus.STOPPED
                || status == PlayerStatus.AWAITING_VIDEO_SURFACE) {
            try {
                InitTask initTask = new InitTask() {

                    @Override
                    protected void onPostExecute(Playable result) {
                        if (status == PlayerStatus.INITIALIZING) {
                            if (result != null) {
                                try {
                                    if (shouldStream) {
                                        player.setDataSource(media
                                                .getStreamUrl());
                                        setStatus(PlayerStatus.PREPARING);
                                        player.prepareAsync();
                                    } else {
                                        player.setDataSource(media
                                                .getLocalMediaUrl());
                                        setStatus(PlayerStatus.PREPARING);
                                        player.prepareAsync();
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            } else {
                                setStatus(PlayerStatus.ERROR);
                                sendBroadcast(new Intent(
                                        ACTION_SHUTDOWN_PLAYBACK_SERVICE));
                            }
                        }
                    }

                    @Override
                    protected void onPreExecute() {
                        setStatus(PlayerStatus.INITIALIZING);
                    }

                };
                initTask.executeAsync(media);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * Called when the surface holder of the mediaplayer has to be changed.
     */
    private void resetVideoSurface() {
        if (AppConfig.DEBUG)
            Log.d(TAG, "Resetting video surface");
        cancelPositionSaver();
        player.setDisplay(null);
        player.reset();
        player = createMediaPlayer();
        status = PlayerStatus.STOPPED;
    }

	public void notifyVideoSurfaceAbandoned() {
		resetVideoSurface();
        if (media != null) {
            initMediaplayer(true);
        }
	}

    /**
     * Called after service has extracted the media it is supposed to play.
     *
     * @param prepareImmediately True if service should prepare playback after it has been initialized
     */
    private void initMediaplayer(final boolean prepareImmediately) {
        if (AppConfig.DEBUG)
            Log.d(TAG, "Setting up media player");
        try {
            MediaType mediaType = media.getMediaType();
            player = createMediaPlayer();
            if (mediaType == MediaType.AUDIO) {
                if (AppConfig.DEBUG)
                    Log.d(TAG, "Mime type is audio");

                InitTask initTask = new InitTask() {

                    @Override
                    protected void onPostExecute(Playable result) {
                        // check if state of service has changed. If it has
                        // changed, assume that loaded metadata is not needed
                        // anymore.
                        if (status == PlayerStatus.INITIALIZING) {
                            if (result != null) {
                                playingVideo = false;
                                try {
                                    if (shouldStream) {
                                        player.setDataSource(media
                                                .getStreamUrl());
                                    } else if (media.localFileAvailable()) {
                                        player.setDataSource(media
                                                .getLocalMediaUrl());
                                    }

                                    if (prepareImmediately) {
                                        setStatus(PlayerStatus.PREPARING);
                                        player.prepareAsync();
                                    } else {
                                        setStatus(PlayerStatus.INITIALIZED);
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    media = null;
                                    setStatus(PlayerStatus.ERROR);
                                    sendBroadcast(new Intent(
                                            ACTION_SHUTDOWN_PLAYBACK_SERVICE));
                                }
                            } else {
                                Log.e(TAG, "InitTask could not load metadata");
                                media = null;
                                setStatus(PlayerStatus.ERROR);
                                sendBroadcast(new Intent(
                                        ACTION_SHUTDOWN_PLAYBACK_SERVICE));
                            }
                        } else {
                            if (AppConfig.DEBUG)
                                Log.d(TAG,
                                        "Status of player has changed during initialization. Stopping init process.");
                        }
                    }

                    @Override
                    protected void onPreExecute() {
                        setStatus(PlayerStatus.INITIALIZING);
                    }

                };
                initTask.executeAsync(media);
            } else if (mediaType == MediaType.VIDEO) {
                if (AppConfig.DEBUG)
                    Log.d(TAG, "Mime type is video");
                playingVideo = true;
                setStatus(PlayerStatus.AWAITING_VIDEO_SURFACE);
                player.setScreenOnWhilePlaying(true);
            }

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }

	private void setupPositionSaver() {
		if (positionSaverFuture == null
				|| (positionSaverFuture.isCancelled() || positionSaverFuture
						.isDone())) {

			positionSaver = new PositionSaver();
			positionSaverFuture = schedExecutor.scheduleAtFixedRate(
					positionSaver, PositionSaver.WAITING_INTERVALL,
					PositionSaver.WAITING_INTERVALL, TimeUnit.MILLISECONDS);
		}
	}

	private void cancelPositionSaver() {
		if (positionSaverFuture != null) {
			boolean result = positionSaverFuture.cancel(true);
			if (AppConfig.DEBUG)
				Log.d(TAG, "PositionSaver cancelled. Result: " + result);
		}
	}

    private final com.aocate.media.MediaPlayer.OnPreparedListener audioPreparedListener = new com.aocate.media.MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(com.aocate.media.MediaPlayer mp) {
            genericOnPrepared(mp);
        }
    };

    private final android.media.MediaPlayer.OnPreparedListener videoPreparedListener = new android.media.MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(android.media.MediaPlayer mp) {
            genericOnPrepared(mp);
        }
    };

    private final void genericOnPrepared(Object inObj) {
        IPlayer mp = DuckType.coerce(inObj).to(IPlayer.class);
        if (AppConfig.DEBUG)
            Log.d(TAG, "Resource prepared");
        mp.seekTo(media.getPosition());
        if (media.getDuration() == 0) {
            if (AppConfig.DEBUG)
                Log.d(TAG, "Setting duration of media");
            media.setDuration(mp.getDuration());
        }
        setStatus(PlayerStatus.PREPARED);
        if (chapterLoader != null) {
            chapterLoader.interrupt();
        }
        chapterLoader = new Thread() {
            @Override
            public void run() {
                if (AppConfig.DEBUG)
                    Log.d(TAG, "Chapter loader started");
                if (media != null && media.getChapters() == null) {
                    media.loadChapterMarks();
                    if (!isInterrupted() && media.getChapters() != null) {
                        sendNotificationBroadcast(NOTIFICATION_TYPE_RELOAD,
                                0);
                    }
                }
                if (AppConfig.DEBUG)
                    Log.d(TAG, "Chapter loader stopped");
            }
        };
        chapterLoader.start();

        if (startWhenPrepared) {
            play();
        }
    }

    private final com.aocate.media.MediaPlayer.OnSeekCompleteListener audioSeekCompleteListener = new com.aocate.media.MediaPlayer.OnSeekCompleteListener() {
        @Override
        public void onSeekComplete(com.aocate.media.MediaPlayer mp) {
            genericSeekCompleteListener();
        }
    };

    private final android.media.MediaPlayer.OnSeekCompleteListener videoSeekCompleteListener = new android.media.MediaPlayer.OnSeekCompleteListener() {
        @Override
        public void onSeekComplete(android.media.MediaPlayer mp) {
            genericSeekCompleteListener();
        }
    };

    private final void genericSeekCompleteListener() {
        if (status == PlayerStatus.SEEKING) {
            setStatus(statusBeforeSeek);
        }
    }

    private final com.aocate.media.MediaPlayer.OnInfoListener audioInfoListener = new com.aocate.media.MediaPlayer.OnInfoListener() {
        @Override
        public boolean onInfo(com.aocate.media.MediaPlayer mp, int what,
                              int extra) {
            return genericInfoListener(what);
        }
    };

    private final android.media.MediaPlayer.OnInfoListener videoInfoListener = new android.media.MediaPlayer.OnInfoListener() {
        @Override
        public boolean onInfo(android.media.MediaPlayer mp, int what, int extra) {
            return genericInfoListener(what);
        }
    };

    private boolean genericInfoListener(int what) {
        switch (what) {
            case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                sendNotificationBroadcast(NOTIFICATION_TYPE_BUFFER_START, 0);
                return true;
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                sendNotificationBroadcast(NOTIFICATION_TYPE_BUFFER_END, 0);
                return true;
            default:
                return false;
        }
    }

    private final com.aocate.media.MediaPlayer.OnErrorListener audioErrorListener = new com.aocate.media.MediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(com.aocate.media.MediaPlayer mp, int what,
                               int extra) {
            return genericOnError(mp, what, extra);
        }
    };

    private final android.media.MediaPlayer.OnErrorListener videoErrorListener = new android.media.MediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(android.media.MediaPlayer mp, int what, int extra) {
            return genericOnError(mp, what, extra);
        }
    };

    private boolean genericOnError(Object inObj, int what, int extra) {
        final String TAG = "PlaybackService.onErrorListener";
        Log.w(TAG, "An error has occured: " + what + " " + extra);
        IPlayer mp = DuckType.coerce(inObj).to(IPlayer.class);
        if (mp.isPlaying()) {
            pause(true, true);
        }
        sendNotificationBroadcast(NOTIFICATION_TYPE_ERROR, what);
        setCurrentlyPlayingMedia(PlaybackPreferences.NO_MEDIA_PLAYING);
        stopSelf();
        return true;
    }

    private final com.aocate.media.MediaPlayer.OnCompletionListener audioCompletionListener = new com.aocate.media.MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(com.aocate.media.MediaPlayer mp) {
            genericOnCompletion();
        }
    };

    private final android.media.MediaPlayer.OnCompletionListener videoCompletionListener = new android.media.MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(android.media.MediaPlayer mp) {
            genericOnCompletion();
        }
    };

    private void genericOnCompletion() {
        endPlayback(true);
    }

    private final com.aocate.media.MediaPlayer.OnBufferingUpdateListener audioBufferingUpdateListener = new com.aocate.media.MediaPlayer.OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(com.aocate.media.MediaPlayer mp,
                                      int percent) {
            genericOnBufferingUpdate(percent);
        }
    };

    private final android.media.MediaPlayer.OnBufferingUpdateListener videoBufferingUpdateListener = new android.media.MediaPlayer.OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(android.media.MediaPlayer mp, int percent) {
            genericOnBufferingUpdate(percent);
        }
    };

    private void genericOnBufferingUpdate(int percent) {
        sendNotificationBroadcast(NOTIFICATION_TYPE_BUFFER_UPDATE, percent);
    }

    private void endPlayback(boolean playNextEpisode) {
        if (AppConfig.DEBUG)
            Log.d(TAG, "Playback ended");
        audioManager.abandonAudioFocus(audioFocusChangeListener);

        // Save state
        cancelPositionSaver();

        boolean isInQueue = false;
        FeedItem nextItem = null;

        if (media instanceof FeedMedia) {
            FeedItem item = ((FeedMedia) media).getItem();
            DBWriter.markItemRead(PlaybackService.this, item, true, true);
            nextItem = DBTasks.getQueueSuccessorOfItem(this, item.getId(), queue);
            isInQueue = media instanceof FeedMedia
                    && QueueAccess.ItemListAccess(queue).contains(((FeedMedia) media).getItem().getId());
            if (isInQueue) {
                DBWriter.removeQueueItem(PlaybackService.this, item.getId(), true);
            }
            DBWriter.addItemToPlaybackHistory(PlaybackService.this, (FeedMedia) media);
            long autoDeleteMediaId = ((FeedComponent) media).getId();
            if (shouldStream) {
                autoDeleteMediaId = -1;
            }
        }

        // Load next episode if previous episode was in the queue and if there
        // is an episode in the queue left.
        // Start playback immediately if continuous playback is enabled
        boolean loadNextItem = isInQueue && nextItem != null;
        playNextEpisode = playNextEpisode && loadNextItem
                && UserPreferences.isFollowQueue();
        if (loadNextItem) {
            if (AppConfig.DEBUG)
                Log.d(TAG, "Loading next item in queue");
            media = nextItem.getMedia();
        }
        final boolean prepareImmediately;
        if (playNextEpisode) {
            if (AppConfig.DEBUG)
                Log.d(TAG, "Playback of next episode will start immediately.");
            prepareImmediately = startWhenPrepared = true;
        } else {
            if (AppConfig.DEBUG)
                Log.d(TAG, "No more episodes available to play");
            media = null;
            prepareImmediately = startWhenPrepared = false;
            stopForeground(true);
            stopWidgetUpdater();
        }

        int notificationCode = 0;
        if (media != null) {
            shouldStream = !media.localFileAvailable();
            if (media.getMediaType() == MediaType.AUDIO) {
                notificationCode = EXTRA_CODE_AUDIO;
                playingVideo = false;
            } else if (media.getMediaType() == MediaType.VIDEO) {
                notificationCode = EXTRA_CODE_VIDEO;
            }
        }
        writePlaybackPreferences();
        if (media != null) {
            resetVideoSurface();
            refreshRemoteControlClientState();
            initMediaplayer(prepareImmediately);

            sendNotificationBroadcast(NOTIFICATION_TYPE_RELOAD,
                    notificationCode);
        } else {
            sendNotificationBroadcast(NOTIFICATION_TYPE_PLAYBACK_END, 0);
            stopSelf();
        }
    }

	public void setSleepTimer(long waitingTime) {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Setting sleep timer to " + Long.toString(waitingTime)
					+ " milliseconds");
		if (sleepTimerFuture != null) {
			sleepTimerFuture.cancel(true);
		}
		sleepTimer = new SleepTimer(waitingTime);
		sleepTimerFuture = schedExecutor.submit(sleepTimer);
		sendNotificationBroadcast(NOTIFICATION_TYPE_SLEEPTIMER_UPDATE, 0);
	}

	public void disableSleepTimer() {
		if (sleepTimerFuture != null) {
			if (AppConfig.DEBUG)
				Log.d(TAG, "Disabling sleep timer");
			sleepTimerFuture.cancel(true);
			sendNotificationBroadcast(NOTIFICATION_TYPE_SLEEPTIMER_UPDATE, 0);
		}
	}

	/**
	 * Saves the current position and pauses playback. Note that, if audiofocus
	 * is abandoned, the lockscreen controls will also disapear.
	 *
	 * @param abandonFocus
	 *            is true if the service should release audio focus
	 * @param reinit
	 *            is true if service should reinit after pausing if the media
	 *            file is being streamed
	 */
	public void pause(boolean abandonFocus, boolean reinit) {
		if (player.isPlaying()) {
			if (AppConfig.DEBUG)
				Log.d(TAG, "Pausing playback.");
			player.pause();
			cancelPositionSaver();
			saveCurrentPosition();
			setStatus(PlayerStatus.PAUSED);
			if (abandonFocus) {
				audioManager.abandonAudioFocus(audioFocusChangeListener);
				pausedBecauseOfTransientAudiofocusLoss = false;
				disableSleepTimer();
			}
			stopWidgetUpdater();
			stopForeground(true);
			if (shouldStream && reinit) {
				reinit();
			}
		}
	}

	/** Pauses playback and destroys service. Recommended for video playback. */
	public void stop() {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Stopping playback");
		if (status == PlayerStatus.PREPARED || status == PlayerStatus.PAUSED
				|| status == PlayerStatus.STOPPED
				|| status == PlayerStatus.PLAYING) {
			player.stop();
		}
		setCurrentlyPlayingMedia(PlaybackPreferences.NO_MEDIA_PLAYING);
		stopSelf();
	}

	/**
	 * Prepared media player for playback if the service is in the INITALIZED
	 * state.
	 */
	public void prepare() {
		if (status == PlayerStatus.INITIALIZED) {
			if (AppConfig.DEBUG)
				Log.d(TAG, "Preparing media player");
			setStatus(PlayerStatus.PREPARING);
			player.prepareAsync();
		}
	}

	/** Resets the media player and moves into INITIALIZED state. */
	public void reinit() {
		player.reset();
		player = createMediaPlayer(player);
		initMediaplayer(false);
	}

	@SuppressLint("NewApi")
	public void play() {
		if (status == PlayerStatus.PAUSED || status == PlayerStatus.PREPARED
				|| status == PlayerStatus.STOPPED) {
			int focusGained = audioManager.requestAudioFocus(
					audioFocusChangeListener, AudioManager.STREAM_MUSIC,
					AudioManager.AUDIOFOCUS_GAIN);

			if (focusGained == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
				if (AppConfig.DEBUG)
					Log.d(TAG, "Audiofocus successfully requested");
				if (AppConfig.DEBUG)
					Log.d(TAG, "Resuming/Starting playback");
				writePlaybackPreferences();

				setSpeed(Float.parseFloat(UserPreferences.getPlaybackSpeed()));
				player.start();
				if (status != PlayerStatus.PAUSED) {
					player.seekTo((int) media.getPosition());
				}
				setStatus(PlayerStatus.PLAYING);
				setupPositionSaver();
				setupWidgetUpdater();
				setupNotification();
				pausedBecauseOfTransientAudiofocusLoss = false;
				if (android.os.Build.VERSION.SDK_INT >= 14) {
					audioManager
							.registerRemoteControlClient(remoteControlClient);
				}
				audioManager
						.registerMediaButtonEventReceiver(mediaButtonReceiver);
				media.onPlaybackStart();
			} else {
				if (AppConfig.DEBUG)
					Log.d(TAG, "Failed to request Audiofocus");
			}
		}
	}

	private void writePlaybackPreferences() {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Writing playback preferences");

		SharedPreferences.Editor editor = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext()).edit();
		if (media != null) {
			editor.putLong(PlaybackPreferences.PREF_CURRENTLY_PLAYING_MEDIA,
					media.getPlayableType());
			editor.putBoolean(
					PlaybackPreferences.PREF_CURRENT_EPISODE_IS_STREAM,
					shouldStream);
			editor.putBoolean(
					PlaybackPreferences.PREF_CURRENT_EPISODE_IS_VIDEO,
					playingVideo);
			if (media instanceof FeedMedia) {
				FeedMedia fMedia = (FeedMedia) media;
				editor.putLong(
						PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEED_ID,
						fMedia.getItem().getFeed().getId());
				editor.putLong(
						PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEEDMEDIA_ID,
						fMedia.getId());
			} else {
				editor.putLong(
						PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEED_ID,
						PlaybackPreferences.NO_MEDIA_PLAYING);
				editor.putLong(
						PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEEDMEDIA_ID,
						PlaybackPreferences.NO_MEDIA_PLAYING);
			}
			media.writeToPreferences(editor);
		} else {
			editor.putLong(PlaybackPreferences.PREF_CURRENTLY_PLAYING_MEDIA,
					PlaybackPreferences.NO_MEDIA_PLAYING);
			editor.putLong(PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEED_ID,
					PlaybackPreferences.NO_MEDIA_PLAYING);
			editor.putLong(
					PlaybackPreferences.PREF_CURRENTLY_PLAYING_FEEDMEDIA_ID,
					PlaybackPreferences.NO_MEDIA_PLAYING);
		}

		editor.commit();
	}

	private void setStatus(PlayerStatus newStatus) {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Setting status to " + newStatus);
		status = newStatus;
		sendBroadcast(new Intent(ACTION_PLAYER_STATUS_CHANGED));
		updateWidget();
		refreshRemoteControlClientState();
		bluetoothNotifyChange();
	}

	/** Send ACTION_PLAYER_STATUS_CHANGED without changing the status attribute. */
	private void postStatusUpdateIntent() {
		setStatus(status);
	}

	private void sendNotificationBroadcast(int type, int code) {
		Intent intent = new Intent(ACTION_PLAYER_NOTIFICATION);
		intent.putExtra(EXTRA_NOTIFICATION_TYPE, type);
		intent.putExtra(EXTRA_NOTIFICATION_CODE, code);
		sendBroadcast(intent);
	}

	/** Used by setupNotification to load notification data in another thread. */
	private AsyncTask<Void, Void, Void> notificationSetupTask;

	/** Prepares notification and starts the service in the foreground. */
	@SuppressLint("NewApi")
	private void setupNotification() {
		final PendingIntent pIntent = PendingIntent.getActivity(this, 0,
				PlaybackService.getPlayerActivityIntent(this),
				PendingIntent.FLAG_UPDATE_CURRENT);

		if (notificationSetupTask != null) {
			notificationSetupTask.cancel(true);
		}
		notificationSetupTask = new AsyncTask<Void, Void, Void>() {
			Bitmap icon = null;

			@Override
			protected Void doInBackground(Void... params) {
				if (AppConfig.DEBUG)
					Log.d(TAG, "Starting background work");
				if (android.os.Build.VERSION.SDK_INT >= 11) {
					if (media != null && media != null) {
						int iconSize = getResources().getDimensionPixelSize(
								android.R.dimen.notification_large_icon_width);
						icon = BitmapDecoder
								.decodeBitmapFromWorkerTaskResource(iconSize,
										media);
					}

				}
				if (icon == null) {
					icon = BitmapFactory.decodeResource(getResources(),
							R.drawable.ic_stat_antenna);
				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				if (!isCancelled() && status == PlayerStatus.PLAYING
						&& media != null) {
					String contentText = media.getFeedTitle();
					String contentTitle = media.getEpisodeTitle();
					Notification notification = null;
					if (android.os.Build.VERSION.SDK_INT >= 16) {
						Intent pauseButtonIntent = new Intent(
								PlaybackService.this, PlaybackService.class);
						pauseButtonIntent.putExtra(
								MediaButtonReceiver.EXTRA_KEYCODE,
								KeyEvent.KEYCODE_MEDIA_PAUSE);
						PendingIntent pauseButtonPendingIntent = PendingIntent
								.getService(PlaybackService.this, 0,
										pauseButtonIntent,
										PendingIntent.FLAG_UPDATE_CURRENT);
						Notification.Builder notificationBuilder = new Notification.Builder(
								PlaybackService.this)
								.setContentTitle(contentTitle)
								.setContentText(contentText)
								.setOngoing(true)
								.setContentIntent(pIntent)
								.setLargeIcon(icon)
								.setSmallIcon(R.drawable.ic_stat_antenna)
								.addAction(android.R.drawable.ic_media_pause,
										getString(R.string.pause_label),
										pauseButtonPendingIntent);
						notification = notificationBuilder.build();
					} else {
						NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
								PlaybackService.this)
								.setContentTitle(contentTitle)
								.setContentText(contentText).setOngoing(true)
								.setContentIntent(pIntent).setLargeIcon(icon)
								.setSmallIcon(R.drawable.ic_stat_antenna);
						notification = notificationBuilder.getNotification();
					}
					startForeground(NOTIFICATION_ID, notification);
					if (AppConfig.DEBUG)
						Log.d(TAG, "Notification set up");
				}
			}

		};
		if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
			notificationSetupTask
					.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		} else {
			notificationSetupTask.execute();
		}

	}

	/**
	 * Seek a specific position from the current position
	 *
	 * @param delta
	 *            offset from current position (positive or negative)
	 * */
	public void seekDelta(int delta) {
		int position = getCurrentPositionSafe();
		if (position != INVALID_TIME) {
			seek(player.getCurrentPosition() + delta);
		}
	}

	public void seek(int i) {
		saveCurrentPosition();
		if (status == PlayerStatus.INITIALIZED
				|| status == PlayerStatus.INITIALIZING
				|| status == PlayerStatus.PREPARING) {
			media.setPosition(i);
			setStartWhenPrepared(true);
			prepare();
		} else {
			if (AppConfig.DEBUG)
				Log.d(TAG, "Seeking position " + i);
			if (shouldStream) {
				if (status != PlayerStatus.SEEKING) {
					statusBeforeSeek = status;
				}
				setStatus(PlayerStatus.SEEKING);
			}
			player.seekTo(i);
		}
	}

	public void seekToChapter(Chapter chapter) {
		seek((int) chapter.getStart());
	}

	/** Saves the current position of the media file to the DB */
	private synchronized void saveCurrentPosition() {
		int position = getCurrentPositionSafe();
		if (position != INVALID_TIME) {
			if (AppConfig.DEBUG)
				Log.d(TAG, "Saving current position to " + position);
			media.saveCurrentPosition(PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext()),
					position);
		}
	}

	private void stopWidgetUpdater() {
		if (widgetUpdaterFuture != null) {
			if (AppConfig.DEBUG)
				Log.d(TAG, "Stopping widgetUpdateWorker");
			widgetUpdaterFuture.cancel(true);
		}
		sendBroadcast(new Intent(PlayerWidget.STOP_WIDGET_UPDATE));
	}

	@SuppressLint("NewApi")
	private void setupWidgetUpdater() {
		if (widgetUpdaterFuture == null
				|| (widgetUpdaterFuture.isCancelled() || widgetUpdaterFuture
						.isDone())) {
			widgetUpdater = new WidgetUpdateWorker();
			widgetUpdaterFuture = schedExecutor.scheduleAtFixedRate(
					widgetUpdater, WidgetUpdateWorker.NOTIFICATION_INTERVALL,
					WidgetUpdateWorker.NOTIFICATION_INTERVALL,
					TimeUnit.MILLISECONDS);
		}
	}

	private void updateWidget() {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Sending widget update request");
		PlaybackService.this.sendBroadcast(new Intent(
				PlayerWidget.FORCE_WIDGET_UPDATE));
	}

	public boolean sleepTimerActive() {
		return sleepTimer != null && sleepTimer.isWaiting();
	}

	public long getSleepTimerTimeLeft() {
		if (sleepTimerActive()) {
			return sleepTimer.getWaitingTime();
		} else {
			return 0;
		}
	}

	@SuppressLint("NewApi")
	private RemoteControlClient setupRemoteControlClient() {
		Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
		mediaButtonIntent.setComponent(mediaButtonReceiver);
		PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(
				getApplicationContext(), 0, mediaButtonIntent, 0);
		remoteControlClient = new RemoteControlClient(mediaPendingIntent);
		int controlFlags;
		if (android.os.Build.VERSION.SDK_INT < 16) {
			controlFlags = RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
					| RemoteControlClient.FLAG_KEY_MEDIA_NEXT;
		} else {
			controlFlags = RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE;
		}
		remoteControlClient.setTransportControlFlags(controlFlags);
		return remoteControlClient;
	}

	/** Refresh player status and metadata. */
	@SuppressLint("NewApi")
	private void refreshRemoteControlClientState() {
		if (android.os.Build.VERSION.SDK_INT >= 14) {
			if (remoteControlClient != null) {
				switch (status) {
				case PLAYING:
					remoteControlClient
							.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);
					break;
				case PAUSED:
				case INITIALIZED:
					remoteControlClient
							.setPlaybackState(RemoteControlClient.PLAYSTATE_PAUSED);
					break;
				case STOPPED:
					remoteControlClient
							.setPlaybackState(RemoteControlClient.PLAYSTATE_STOPPED);
					break;
				case ERROR:
					remoteControlClient
							.setPlaybackState(RemoteControlClient.PLAYSTATE_ERROR);
					break;
				default:
					remoteControlClient
							.setPlaybackState(RemoteControlClient.PLAYSTATE_BUFFERING);
				}
				if (media != null) {
					MetadataEditor editor = remoteControlClient
							.editMetadata(false);
					editor.putString(MediaMetadataRetriever.METADATA_KEY_TITLE,
							media.getEpisodeTitle());

					editor.putString(MediaMetadataRetriever.METADATA_KEY_ALBUM,
							media.getFeedTitle());

					editor.apply();
				}
				if (AppConfig.DEBUG)
					Log.d(TAG, "RemoteControlClient state was refreshed");
			}
		}
	}

	private void bluetoothNotifyChange() {
		boolean isPlaying = false;

		if (status == PlayerStatus.PLAYING) {
			isPlaying = true;
		}

        if (media != null) {
		    Intent i = new Intent(AVRCP_ACTION_PLAYER_STATUS_CHANGED);
		    i.putExtra("id", 1);
		    i.putExtra("artist", "");
		    i.putExtra("album", media.getFeedTitle());
		    i.putExtra("track", media.getEpisodeTitle());
		    i.putExtra("playing", isPlaying);
            if (queue != null) {
                i.putExtra("ListSize", queue.size());
            }
            i.putExtra("duration", media.getDuration());
		    i.putExtra("position", media.getPosition());
		    sendBroadcast(i);
        }
	}

	/**
	 * Pauses playback when the headset is disconnected and the preference is
	 * set
	 */
	private BroadcastReceiver headsetDisconnected = new BroadcastReceiver() {
		private static final String TAG = "headsetDisconnected";
		private static final int UNPLUGGED = 0;

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
				int state = intent.getIntExtra("state", -1);
				if (state != -1) {
					if (AppConfig.DEBUG)
						Log.d(TAG, "Headset plug event. State is " + state);
					if (state == UNPLUGGED && status == PlayerStatus.PLAYING) {
						if (AppConfig.DEBUG)
							Log.d(TAG, "Headset was unplugged during playback.");
						pauseIfPauseOnDisconnect();
					}
				} else {
					Log.e(TAG, "Received invalid ACTION_HEADSET_PLUG intent");
				}
			}
		}
	};

	private BroadcastReceiver audioBecomingNoisy = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// sound is about to change, eg. bluetooth -> speaker
			if (AppConfig.DEBUG)
				Log.d(TAG, "Pausing playback because audio is becoming noisy");
			pauseIfPauseOnDisconnect();
		}
		// android.media.AUDIO_BECOMING_NOISY
	};

	/** Pauses playback if PREF_PAUSE_ON_HEADSET_DISCONNECT was set to true. */
	private void pauseIfPauseOnDisconnect() {
		if (UserPreferences.isPauseOnHeadsetDisconnect()
				&& status == PlayerStatus.PLAYING) {
			pause(true, true);
		}
	}

	private BroadcastReceiver shutdownReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(ACTION_SHUTDOWN_PLAYBACK_SERVICE)) {
				schedExecutor.shutdownNow();
				stop();
				media = null;
			}
		}

	};

	private BroadcastReceiver skipCurrentEpisodeReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(ACTION_SKIP_CURRENT_EPISODE)) {

				if (AppConfig.DEBUG)
					Log.d(TAG, "Received SKIP_CURRENT_EPISODE intent");
				if (media != null) {
					setStatus(PlayerStatus.STOPPED);
					endPlayback(true);
				}
			}
		}
    };

	/** Periodically saves the position of the media file */
	class PositionSaver implements Runnable {
		public static final int WAITING_INTERVALL = 5000;

		@Override
		public void run() {
			if (player != null && player.isPlaying()) {
				try {
					saveCurrentPosition();
				} catch (IllegalStateException e) {
					Log.w(TAG,
							"saveCurrentPosition was called in illegal state");
				}
			}
		}
	}

	/** Notifies the player widget in the specified intervall */
	class WidgetUpdateWorker implements Runnable {
		private static final int NOTIFICATION_INTERVALL = 1000;

		@Override
		public void run() {
			if (PlaybackService.isRunning) {
				updateWidget();
			}
		}
	}

	/** Sleeps for a given time and then pauses playback. */
	class SleepTimer implements Runnable {
		private static final String TAG = "SleepTimer";
		private static final long UPDATE_INTERVALL = 1000L;
		private volatile long waitingTime;
		private boolean isWaiting;

		public SleepTimer(long waitingTime) {
			super();
			this.waitingTime = waitingTime;
		}

		@Override
		public void run() {
			isWaiting = true;
			if (AppConfig.DEBUG)
				Log.d(TAG, "Starting");
			while (waitingTime > 0) {
				try {
					Thread.sleep(UPDATE_INTERVALL);
					waitingTime -= UPDATE_INTERVALL;

					if (waitingTime <= 0) {
						if (AppConfig.DEBUG)
							Log.d(TAG, "Waiting completed");
						if (status == PlayerStatus.PLAYING) {
							if (AppConfig.DEBUG)
								Log.d(TAG, "Pausing playback");
							pause(true, true);
						}
						postExecute();
					}
				} catch (InterruptedException e) {
					Log.d(TAG, "Thread was interrupted while waiting");
					break;
				}
			}
			postExecute();
		}

		protected void postExecute() {
			isWaiting = false;
			sendNotificationBroadcast(NOTIFICATION_TYPE_SLEEPTIMER_UPDATE, 0);
		}

		public long getWaitingTime() {
			return waitingTime;
		}

		public boolean isWaiting() {
			return isWaiting;
		}

	}

	public static boolean isPlayingVideo() {
		return playingVideo;
	}

	public boolean isShouldStream() {
		return shouldStream;
	}

	public PlayerStatus getStatus() {
		return status;
	}

	public Playable getMedia() {
		return media;
	}

	public IPlayer getPlayer() {
		return player;
	}

	public boolean isStartWhenPrepared() {
		return startWhenPrepared;
	}

	public void setStartWhenPrepared(boolean startWhenPrepared) {
		this.startWhenPrepared = startWhenPrepared;
		postStatusUpdateIntent();
	}

	public boolean canSetSpeed() {
		if (player != null && media != null && media.getMediaType() == MediaType.AUDIO) {
			return ((AudioPlayer) player).canSetSpeed();
		}
		return false;
	}

	public boolean canSetPitch() {
		if (player != null && media != null && media.getMediaType() == MediaType.AUDIO) {
			return ((AudioPlayer) player).canSetPitch();
		}
		return false;
	}

	public void setSpeed(float speed) {
		if (media != null && media.getMediaType() == MediaType.AUDIO) {
			AudioPlayer audioPlayer = (AudioPlayer) player;
			if (audioPlayer.canSetSpeed()) {
				audioPlayer.setPlaybackSpeed((float) speed);
				if (AppConfig.DEBUG)
					Log.d(TAG, "Playback speed was set to " + speed);
				sendNotificationBroadcast(
						NOTIFICATION_TYPE_PLAYBACK_SPEED_CHANGE, 0);
			}
		}
	}

	public void setPitch(float pitch) {
		if (media != null && media.getMediaType() == MediaType.AUDIO) {
			AudioPlayer audioPlayer = (AudioPlayer) player;
			if (audioPlayer.canSetPitch()) {
				audioPlayer.setPlaybackPitch((float) pitch);
			}
		}
	}

	public float getCurrentPlaybackSpeed() {
		if (media.getMediaType() == MediaType.AUDIO
				&& player instanceof AudioPlayer) {
			AudioPlayer audioPlayer = (AudioPlayer) player;
			if (audioPlayer.canSetSpeed()) {
				return audioPlayer.getCurrentSpeedMultiplier();
			}
		}
		return -1;
	}

	/**
	 * call getDuration() on mediaplayer or return INVALID_TIME if player is in
	 * an invalid state. This method should be used instead of calling
	 * getDuration() directly to avoid an error.
	 */
	public int getDurationSafe() {
		if (status != null && player != null) {
			switch (status) {
			case PREPARED:
			case PLAYING:
			case PAUSED:
			case SEEKING:
				try {
					return player.getDuration();
				} catch (IllegalStateException e) {
					e.printStackTrace();
					return INVALID_TIME;
				}
			default:
				return INVALID_TIME;
			}
		} else {
			return INVALID_TIME;
		}
	}

	/**
	 * call getCurrentPosition() on mediaplayer or return INVALID_TIME if player
	 * is in an invalid state. This method should be used instead of calling
	 * getCurrentPosition() directly to avoid an error.
	 */
	public int getCurrentPositionSafe() {
		if (status != null && player != null) {
			switch (status) {
			case PREPARED:
			case PLAYING:
			case PAUSED:
			case SEEKING:
				return player.getCurrentPosition();
			default:
				return INVALID_TIME;
			}
		} else {
			return INVALID_TIME;
		}
	}

	private void setCurrentlyPlayingMedia(long id) {
		SharedPreferences.Editor editor = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext()).edit();
		editor.putLong(PlaybackPreferences.PREF_CURRENTLY_PLAYING_MEDIA, id);
		editor.commit();
	}

	private static class InitTask extends AsyncTask<Playable, Void, Playable> {
		private Playable playable;
		public PlayableException exception;

		@Override
		protected Playable doInBackground(Playable... params) {
			if (params[0] == null) {
				throw new IllegalArgumentException("Playable must not be null");
			}
			playable = params[0];

			try {
				playable.loadMetadata();
			} catch (PlayableException e) {
				e.printStackTrace();
				exception = e;
				return null;
			}
			return playable;
		}

		@SuppressLint("NewApi")
		public void executeAsync(Playable playable) {
			FlattrUtils.hasToken();
			if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
				executeOnExecutor(THREAD_POOL_EXECUTOR, playable);
			} else {
				execute(playable);
			}
		}

	}

    private void loadQueue() {
        dbLoaderExecutor.submit(new QueueLoaderTask());
    }

    private class QueueLoaderTask implements Runnable {
        @Override
        public void run() {
            List<FeedItem> queueRef = DBReader.getQueue(PlaybackService.this);
            queue = queueRef;
        }
    }
}