-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathqueue_service.dart
1089 lines (948 loc) · 37.5 KB
/
queue_service.dart
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
import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'package:just_audio/just_audio.dart';
import 'package:audio_service/audio_service.dart';
import 'package:get_it/get_it.dart';
import 'package:logging/logging.dart';
import 'package:rxdart/rxdart.dart';
import 'package:uuid/uuid.dart';
import 'package:collection/collection.dart';
import 'package:finamp/models/finamp_models.dart';
import 'package:finamp/models/jellyfin_models.dart' as jellyfin_models;
import 'package:hive_flutter/hive_flutter.dart';
import 'finamp_user_helper.dart';
import 'jellyfin_api_helper.dart';
import 'finamp_settings_helper.dart';
import 'downloads_helper.dart';
import 'music_player_background_task.dart';
/// A track queueing service for Finamp.
class QueueService {
final _jellyfinApiHelper = GetIt.instance<JellyfinApiHelper>();
final _downloadsHelper = GetIt.instance<DownloadsHelper>();
final _audioHandler = GetIt.instance<MusicPlayerBackgroundTask>();
final _finampUserHelper = GetIt.instance<FinampUserHelper>();
final _queueServiceLogger = Logger("QueueService");
final _queuesBox = Hive.box<FinampStorableQueueInfo>("Queues");
// internal state
final List<FinampQueueItem> _queuePreviousTracks =
[]; // contains **all** items that have been played, including "next up"
FinampQueueItem? _currentTrack; // the currently playing track
final List<FinampQueueItem> _queueNextUp =
[]; // a temporary queue that gets appended to if the user taps "next up"
final List<FinampQueueItem> _queue = []; // contains all regular queue items
FinampQueueOrder _order = FinampQueueOrder(
items: [],
originalSource: QueueItemSource(
id: "",
name: const QueueItemSourceName(
type: QueueItemSourceNameType.preTranslated),
type: QueueItemSourceType.unknown),
linearOrder: [],
shuffledOrder: []); // contains all items that were at some point added to the regular queue, as well as their order when shuffle is enabled and disabled. This is used to loop the original queue once the end has been reached and "loop all" is enabled, **excluding** "next up" items and keeping the playback order.
FinampPlaybackOrder _playbackOrder = FinampPlaybackOrder.linear;
FinampLoopMode _loopMode = FinampLoopMode.none;
final _currentTrackStream = BehaviorSubject<FinampQueueItem?>.seeded(null);
final _queueStream = BehaviorSubject<FinampQueueInfo?>.seeded(null);
final _playbackOrderStream =
BehaviorSubject<FinampPlaybackOrder>.seeded(FinampPlaybackOrder.linear);
final _loopModeStream =
BehaviorSubject<FinampLoopMode>.seeded(FinampLoopMode.none);
// external queue state
// the audio source used by the player. The first X items of all internal queues are merged together into this source, so that all player features, like gapless playback, are supported
ConcatenatingAudioSource _queueAudioSource = ConcatenatingAudioSource(
children: [],
);
late ShuffleOrder _shuffleOrder;
int _queueAudioSourceIndex = 0;
// Flags for saving and loading saved queues
int _saveUpdateCycleCount = 0;
bool _saveUpdateImemdiate = false;
SavedQueueState _savedQueueState = SavedQueueState.preInit;
FinampStorableQueueInfo? _failedSavedQueue = null;
static const int _maxSavedQueues = 60;
QueueService() {
// _queueServiceLogger.level = Level.OFF;
final finampSettings = FinampSettingsHelper.finampSettings;
loopMode = finampSettings.loopMode;
_queueServiceLogger.info("Restored loop mode to $loopMode from settings");
_shuffleOrder = NextUpShuffleOrder(queueService: this);
_queueAudioSource = ConcatenatingAudioSource(
children: [],
shuffleOrder: _shuffleOrder,
);
_audioHandler.playbackState.listen((event) async {
// int indexDifference = (event.currentIndex ?? 0) - _queueAudioSourceIndex;
final previousIndex = _queueAudioSourceIndex;
_queueAudioSourceIndex = event.queueIndex ?? 0;
if (previousIndex != _queueAudioSourceIndex) {
int adjustedQueueIndex = (playbackOrder ==
FinampPlaybackOrder.shuffled &&
_queueAudioSource.shuffleIndices.isNotEmpty)
? _queueAudioSource.shuffleIndices.indexOf(_queueAudioSourceIndex)
: _queueAudioSourceIndex;
_queueServiceLogger.finer(
"Play queue index changed, new index: $adjustedQueueIndex (actual index: $_queueAudioSourceIndex)");
_queueFromConcatenatingAudioSource();
} else {
_saveUpdateImemdiate = true;
}
});
Stream.periodic(const Duration(seconds: 10)).listen((event) {
// Update once per minute in background, and up to once every ten seconds if
// pausing/seeking is occuring
// We also update on every track switch.
if (_saveUpdateCycleCount >= 5 || _saveUpdateImemdiate) {
if (_savedQueueState == SavedQueueState.pendingSave &&
!_audioHandler.paused) {
_savedQueueState = SavedQueueState.saving;
}
if (_savedQueueState == SavedQueueState.saving) {
_saveUpdateImemdiate = false;
_saveUpdateCycleCount = 0;
FinampStorableQueueInfo info = FinampStorableQueueInfo.fromQueueInfo(
getQueue(), _audioHandler.playbackPosition.inMilliseconds);
if (info.songCount != 0) {
_queuesBox.put("latest", info);
_queueServiceLogger.finest("Saved new periodic queue $info");
}
}
} else {
_saveUpdateCycleCount++;
}
});
// register callbacks
// _audioHandler.setQueueCallbacks(
// nextTrackCallback: _applyNextTrack,
// previousTrackCallback: _applyPreviousTrack,
// skipToIndexCallback: _applySkipToTrackByOffset,
// );
}
void _queueFromConcatenatingAudioSource() {
List<FinampQueueItem> allTracks = _audioHandler.effectiveSequence
?.map((e) => e.tag as FinampQueueItem)
.toList() ??
[];
int adjustedQueueIndex = (playbackOrder == FinampPlaybackOrder.shuffled &&
_queueAudioSource.shuffleIndices.isNotEmpty)
? _queueAudioSource.shuffleIndices.indexOf(_queueAudioSourceIndex)
: _queueAudioSourceIndex;
final previousTrack = _currentTrack;
final previousTracksPreviousLength = _queuePreviousTracks.length;
final nextUpPreviousLength = _queueNextUp.length;
final queuePreviousLength = _queue.length;
_queuePreviousTracks.clear();
_queueNextUp.clear();
_queue.clear();
bool canHaveNextUp = true;
// split the queue by old type
for (int i = 0; i < allTracks.length; i++) {
if (i < adjustedQueueIndex) {
_queuePreviousTracks.add(allTracks[i]);
if ([
QueueItemSourceType.nextUp,
QueueItemSourceType.nextUpAlbum,
QueueItemSourceType.nextUpPlaylist,
QueueItemSourceType.nextUpArtist
].contains(_queuePreviousTracks.last.source.type)) {
_queuePreviousTracks.last.source = QueueItemSource(
type: QueueItemSourceType.formerNextUp,
name: const QueueItemSourceName(
type: QueueItemSourceNameType.tracksFormerNextUp),
id: "former-next-up");
}
_queuePreviousTracks.last.type = QueueItemQueueType.previousTracks;
} else if (i == adjustedQueueIndex) {
_currentTrack = allTracks[i];
_currentTrack!.type = QueueItemQueueType.currentTrack;
} else {
if (allTracks[i].type == QueueItemQueueType.currentTrack &&
[
QueueItemSourceType.nextUp,
QueueItemSourceType.nextUpAlbum,
QueueItemSourceType.nextUpPlaylist,
QueueItemSourceType.nextUpArtist
].contains(allTracks[i].source.type)) {
_queue.add(allTracks[i]);
_queue.last.type = QueueItemQueueType.queue;
_queue.last.source = QueueItemSource(
type: QueueItemSourceType.formerNextUp,
name: const QueueItemSourceName(
type: QueueItemSourceNameType.tracksFormerNextUp),
id: "former-next-up");
canHaveNextUp = false;
} else if (allTracks[i].type == QueueItemQueueType.nextUp) {
if (canHaveNextUp) {
_queueNextUp.add(allTracks[i]);
_queueNextUp.last.type = QueueItemQueueType.nextUp;
} else {
_queue.add(allTracks[i]);
_queue.last.type = QueueItemQueueType.queue;
_queue.last.source = QueueItemSource(
type: QueueItemSourceType.formerNextUp,
name: const QueueItemSourceName(
type: QueueItemSourceNameType.tracksFormerNextUp),
id: "former-next-up");
}
} else {
_queue.add(allTracks[i]);
_queue.last.type = QueueItemQueueType.queue;
canHaveNextUp = false;
}
}
}
if (allTracks.isEmpty) {
_queueServiceLogger.fine("Queue is empty");
_currentTrack = null;
return;
}
refreshQueueStream();
_currentTrackStream.add(_currentTrack);
_audioHandler.mediaItem.add(_currentTrack?.item);
_audioHandler.queue.add(_queuePreviousTracks
.followedBy([_currentTrack!])
.followedBy(_queue)
.map((e) => e.item)
.toList());
if (_savedQueueState == SavedQueueState.saving) {
FinampStorableQueueInfo info =
FinampStorableQueueInfo.fromQueueInfo(getQueue(), null);
if (info.songCount != 0) {
_queuesBox.put("latest", info);
_queueServiceLogger.finest("Saved new rebuilt queue $info");
}
_saveUpdateImemdiate = false;
_saveUpdateCycleCount = 0;
}
// only log queue if there's a change
if (previousTrack?.id != _currentTrack?.id ||
previousTracksPreviousLength != _queuePreviousTracks.length ||
nextUpPreviousLength != _queueNextUp.length ||
queuePreviousLength != _queue.length) {
_logQueues(message: "(current)");
}
}
Future<void> performInitialQueueLoad() async {
if (_savedQueueState == SavedQueueState.preInit) {
try {
_savedQueueState = SavedQueueState.init;
var info = _queuesBox.get("latest");
if (info != null) {
// push latest into queue history
if (info.songCount != 0) {
await _queuesBox.put(info.creation.toString(), info);
}
var keys = _queuesBox.values
.map((x) => DateTime.fromMillisecondsSinceEpoch(x.creation))
.toList();
keys.sort();
_queueServiceLogger.finest("Stored queue dates: $keys");
if (keys.length > _maxSavedQueues) {
var extra = keys
.getRange(0, keys.length - _maxSavedQueues)
.map((e) => e.millisecondsSinceEpoch.toString());
_queueServiceLogger.finest("Deleting stored queues: $extra");
_queuesBox.deleteAll(extra);
}
if (FinampSettingsHelper.finampSettings.autoloadLastQueueOnStartup) {
await loadSavedQueue(info);
} else {
_savedQueueState = SavedQueueState.pendingSave;
}
}
} catch (e) {
_queueServiceLogger.severe(e);
rethrow;
}
}
}
Future<void> retryQueueLoad() async {
if (_savedQueueState == SavedQueueState.failed &&
_failedSavedQueue != null) {
await loadSavedQueue(_failedSavedQueue!);
}
}
Future<void> loadSavedQueue(FinampStorableQueueInfo info) async {
if (_savedQueueState == SavedQueueState.loading) {
return Future.error("A saved queue is currently loading");
}
// After loading queue, do not begin overwriting latest until the user modifies
// the queue or begins playback. This prevents saving unused queues that
// had loading errors or were immediately overwritten.
SavedQueueState? finalState = SavedQueueState.pendingSave;
try {
_savedQueueState = SavedQueueState.loading;
await stopPlayback();
refreshQueueStream();
List<String> allIds = info.previousTracks +
((info.currentTrack == null) ? [] : [info.currentTrack!]) +
info.nextUp +
info.queue;
List<String> uniqueIds = allIds.toSet().toList();
Map<String, jellyfin_models.BaseItemDto> idMap = {};
if (FinampSettingsHelper.finampSettings.isOffline) {
for (var id in uniqueIds) {
jellyfin_models.BaseItemDto? item =
_downloadsHelper.getDownloadedSong(id)?.song;
if (item != null) {
idMap[id] = item;
}
}
} else {
for (var slice in uniqueIds.slices(200)) {
List<jellyfin_models.BaseItemDto> itemList =
await _jellyfinApiHelper.getItems(itemIds: slice) ?? [];
for (var d2 in itemList) {
idMap[d2.id] = d2;
}
}
}
Map<String, List<jellyfin_models.BaseItemDto>> items = {
"previous":
info.previousTracks.map((e) => idMap[e]).whereNotNull().toList(),
"current":
[info.currentTrack].map((e) => idMap[e]).whereNotNull().toList(),
"next": info.nextUp.map((e) => idMap[e]).whereNotNull().toList(),
"queue": info.queue.map((e) => idMap[e]).whereNotNull().toList(),
};
sumLengths(int sum, Iterable val) => val.length + sum;
int loadedSongs = items.values.fold(0, sumLengths);
int droppedSongs = info.songCount - loadedSongs;
if (_savedQueueState != SavedQueueState.loading) {
finalState = null;
return Future.error("Loading of saved Queue was interrupted.");
}
await _replaceWholeQueue(
itemList: items["previous"]! + items["current"]! + items["queue"]!,
initialIndex: items["previous"]!.length,
beginPlaying: false,
source: info.source ??
QueueItemSource(
type: QueueItemSourceType.unknown,
name: const QueueItemSourceName(
type: QueueItemSourceNameType.savedQueue),
id: "savedqueue"));
Future<void> seekFuture = Future.value();
if ((info.currentTrackSeek ?? 0) > 5000) {
seekFuture = _audioHandler
.seek(Duration(milliseconds: (info.currentTrackSeek ?? 0) - 1000));
}
await addToNextUp(items: items["next"]!);
await seekFuture;
_queueServiceLogger.info("Loaded saved queue.");
if (loadedSongs == 0 && info.songCount > 0) {
finalState = SavedQueueState.failed;
_failedSavedQueue = info;
} else if (droppedSongs > 0) {
return Future.error(
"$droppedSongs songs in the Now Playing Queue could not be loaded.");
}
} finally {
if (finalState != null) {
_savedQueueState = finalState;
}
refreshQueueStream();
}
}
Future<void> startPlayback({
required List<jellyfin_models.BaseItemDto> items,
required QueueItemSource source,
FinampPlaybackOrder? order,
int? startingIndex,
}) async {
// _initialQueue = list; // save original PlaybackList for looping/restarting and meta info
if (startingIndex == null) {
if (order == FinampPlaybackOrder.shuffled) {
startingIndex = Random().nextInt(items.length);
} else {
startingIndex = 0;
}
}
if (_savedQueueState == SavedQueueState.saving) {
var info = _queuesBox.get("latest");
if (info != null && info.songCount != 0) {
await _queuesBox.put(info.creation.toString(), info);
}
}
_savedQueueState = SavedQueueState.saving;
await _replaceWholeQueue(
itemList: items,
source: source,
order: order,
initialIndex: startingIndex);
_queueServiceLogger
.info("Started playing '${source.name}' (${source.type})");
}
/// Replaces the queue with the given list of items. If startAtIndex is specified, Any items below it
/// will be ignored. This is used for when the user taps in the middle of an album to start from that point.
Future<void> _replaceWholeQueue(
{required List<jellyfin_models.BaseItemDto> itemList,
required QueueItemSource source,
required int initialIndex,
FinampPlaybackOrder? order,
bool beginPlaying = true}) async {
try {
if (initialIndex > itemList.length) {
return Future.error(
"initialIndex is bigger than the itemList! ($initialIndex > ${itemList.length})");
}
_queue.clear(); // empty queue
_queuePreviousTracks.clear();
_queueNextUp.clear();
_currentTrack = null;
List<FinampQueueItem> newItems = [];
List<int> newLinearOrder = [];
List<int> newShuffledOrder;
for (int i = 0; i < itemList.length; i++) {
jellyfin_models.BaseItemDto item = itemList[i];
try {
MediaItem mediaItem = await _generateMediaItem(item);
newItems.add(FinampQueueItem(
item: mediaItem,
source: source,
type: i == 0
? QueueItemQueueType.currentTrack
: QueueItemQueueType.queue,
));
newLinearOrder.add(i);
} catch (e) {
_queueServiceLogger.severe(e);
}
}
await _audioHandler.stop();
_queueAudioSource.clear();
// await _audioHandler.initializeAudioSource(_queueAudioSource);
List<AudioSource> audioSources = [];
for (final queueItem in newItems) {
audioSources.add(await _queueItemToAudioSource(queueItem));
}
await _queueAudioSource.addAll(audioSources);
// set first item in queue
_queueAudioSourceIndex = initialIndex;
if (_playbackOrder == FinampPlaybackOrder.shuffled) {
_queueAudioSourceIndex = _queueAudioSource.shuffleIndices[initialIndex];
}
_audioHandler.setNextInitialIndex(_queueAudioSourceIndex);
await _audioHandler.initializeAudioSource(_queueAudioSource);
newShuffledOrder = List.from(_queueAudioSource.shuffleIndices);
_order = FinampQueueOrder(
items: newItems,
originalSource: source,
linearOrder: newLinearOrder,
shuffledOrder: newShuffledOrder,
);
_queueServiceLogger.fine("Order items length: ${_order.items.length}");
// set playback order to trigger shuffle if necessary (fixes indices being wrong when starting with shuffle enabled)
if (order != null) {
playbackOrder = order;
}
// _queueStream.add(getQueue());
_queueFromConcatenatingAudioSource();
if (beginPlaying) {
await _audioHandler.play();
} else {
await _audioHandler.pause();
}
_audioHandler.nextInitialIndex = null;
} catch (e) {
_queueServiceLogger.severe(e);
return Future.error(e);
}
}
Future<void> stopPlayback() async {
queueServiceLogger.info("Stopping playback");
await _audioHandler.stop();
_queueAudioSource.clear();
_queueFromConcatenatingAudioSource();
return;
}
Future<void> addToQueue({
required List<jellyfin_models.BaseItemDto> items,
QueueItemSource? source,
}) async {
try {
if (_savedQueueState == SavedQueueState.pendingSave) {
_savedQueueState = SavedQueueState.saving;
}
List<FinampQueueItem> queueItems = [];
for (final item in items) {
queueItems.add(FinampQueueItem(
item: await _generateMediaItem(item),
source: source ?? _order.originalSource,
type: QueueItemQueueType.queue,
));
}
List<AudioSource> audioSources = [];
for (final item in queueItems) {
audioSources.add(await _queueItemToAudioSource(item));
_queueServiceLogger.fine(
"Added '${item.item.title}' to queue from '${source?.name}' (${source?.type})");
}
await _queueAudioSource.addAll(audioSources);
_queueFromConcatenatingAudioSource(); // update internal queues
} catch (e) {
_queueServiceLogger.severe(e);
return Future.error(e);
}
}
Future<void> addNext({
required List<jellyfin_models.BaseItemDto> items,
QueueItemSource? source,
}) async {
try {
if (_savedQueueState == SavedQueueState.pendingSave) {
_savedQueueState = SavedQueueState.saving;
}
List<FinampQueueItem> queueItems = [];
for (final item in items) {
queueItems.add(FinampQueueItem(
item: await _generateMediaItem(item),
source: source ??
QueueItemSource(
id: "next-up",
name: const QueueItemSourceName(
type: QueueItemSourceNameType.nextUp),
type: QueueItemSourceType.nextUp),
type: QueueItemQueueType.nextUp,
));
}
for (final queueItem in queueItems.reversed) {
int offset = min(_queueAudioSource.length, 1);
await _queueAudioSource.insert(_queueAudioSourceIndex + offset,
await _queueItemToAudioSource(queueItem));
_queueServiceLogger.fine(
"Appended '${queueItem.item.title}' to Next Up (index ${_queueAudioSourceIndex + offset})");
}
_queueFromConcatenatingAudioSource(); // update internal queues
} catch (e) {
_queueServiceLogger.severe(e);
return Future.error(e);
}
}
Future<void> addToNextUp({
required List<jellyfin_models.BaseItemDto> items,
QueueItemSource? source,
}) async {
try {
if (_savedQueueState == SavedQueueState.pendingSave) {
_savedQueueState = SavedQueueState.saving;
}
List<FinampQueueItem> queueItems = [];
for (final item in items) {
queueItems.add(FinampQueueItem(
item: await _generateMediaItem(item),
source: source ??
QueueItemSource(
id: "next-up",
name: const QueueItemSourceName(
type: QueueItemSourceNameType.nextUp),
type: QueueItemSourceType.nextUp),
type: QueueItemQueueType.nextUp,
));
}
_queueFromConcatenatingAudioSource(); // update internal queues
int offset = _queueNextUp.length + min(_queueAudioSource.length, 1);
for (final queueItem in queueItems) {
await _queueAudioSource.insert(_queueAudioSourceIndex + offset,
await _queueItemToAudioSource(queueItem));
_queueServiceLogger.fine(
"Appended '${queueItem.item.title}' to Next Up (index ${_queueAudioSourceIndex + offset})");
offset++;
}
_queueFromConcatenatingAudioSource(); // update internal queues
} catch (e) {
_queueServiceLogger.severe(e);
return Future.error(e);
}
}
Future<void> skipByOffset(int offset) async {
await _audioHandler.skipByOffset(offset);
}
Future<void> removeAtOffset(int offset) async {
final index = _playbackOrder == FinampPlaybackOrder.shuffled
? _queueAudioSource.shuffleIndices[
_queueAudioSource.shuffleIndices.indexOf((_queueAudioSourceIndex)) +
offset]
: (_queueAudioSourceIndex) + offset;
await _queueAudioSource.removeAt(index);
// await _audioHandler.removeQueueItemAt(index);
_queueFromConcatenatingAudioSource();
}
Future<void> reorderByOffset(int oldOffset, int newOffset) async {
_queueServiceLogger.fine(
"Reordering queue item at offset $oldOffset to offset $newOffset");
//!!! the player will automatically change the shuffle indices of the ConcatenatingAudioSource if shuffle is enabled, so we need to use the regular track index here
final oldIndex = _queueAudioSourceIndex + oldOffset;
final newIndex = oldOffset < newOffset
? _queueAudioSourceIndex + newOffset - 1
: _queueAudioSourceIndex + newOffset;
await _queueAudioSource.move(oldIndex, newIndex);
_queueFromConcatenatingAudioSource();
}
Future<void> clearNextUp() async {
// remove all items from Next Up
if (_queueNextUp.isNotEmpty) {
await _queueAudioSource.removeRange(_queueAudioSourceIndex + 1,
_queueAudioSourceIndex + 1 + _queueNextUp.length);
_queueNextUp.clear();
}
_queueFromConcatenatingAudioSource(); // update internal queues
}
FinampQueueInfo getQueue() {
return FinampQueueInfo(
previousTracks: _queuePreviousTracks,
currentTrack: _currentTrack,
queue: _queue,
nextUp: _queueNextUp,
source: _order.originalSource,
saveState: _savedQueueState,
);
}
BehaviorSubject<FinampQueueInfo?> getQueueStream() {
return _queueStream;
}
void refreshQueueStream() {
_queueStream.add(getQueue());
}
/// Returns the next [amount] QueueItems from Next Up and the regular queue.
/// The length of the returned list may be less than [amount] if there are not enough items in the queue
List<FinampQueueItem> getNextXTracksInQueue(int amount, {int reverse = 0}) {
List<FinampQueueItem> nextTracks = [];
if (_queuePreviousTracks.isNotEmpty && reverse > 0) {
nextTracks.addAll(_queuePreviousTracks.sublist(
max(0, _queuePreviousTracks.length - reverse),
_queuePreviousTracks.length));
}
if (_queueNextUp.isNotEmpty) {
nextTracks
.addAll(_queueNextUp.sublist(0, min(amount, _queueNextUp.length)));
amount -= _queueNextUp.length;
}
if (_queue.isNotEmpty && amount > 0) {
nextTracks.addAll(_queue.sublist(0, min(amount, _queue.length)));
}
return nextTracks;
}
BehaviorSubject<FinampPlaybackOrder> getPlaybackOrderStream() {
return _playbackOrderStream;
}
BehaviorSubject<FinampLoopMode> getLoopModeStream() {
return _loopModeStream;
}
BehaviorSubject<FinampQueueItem?> getCurrentTrackStream() {
return _currentTrackStream;
}
FinampQueueItem? getCurrentTrack() {
return _currentTrack;
}
set loopMode(FinampLoopMode mode) {
_loopMode = mode;
_loopModeStream.add(mode);
if (mode == FinampLoopMode.one) {
_audioHandler.setRepeatMode(AudioServiceRepeatMode.one);
} else if (mode == FinampLoopMode.all) {
_audioHandler.setRepeatMode(AudioServiceRepeatMode.all);
} else {
_audioHandler.setRepeatMode(AudioServiceRepeatMode.none);
}
FinampSettingsHelper.setLoopMode(loopMode);
_queueServiceLogger.fine(
"Loop mode set to ${FinampSettingsHelper.finampSettings.loopMode}");
}
FinampLoopMode get loopMode => _loopMode;
set playbackOrder(FinampPlaybackOrder order) {
_playbackOrder = order;
_queueServiceLogger.fine("Playback order set to $order");
_playbackOrderStream.add(order);
// update queue accordingly and generate new shuffled order if necessary
if (_playbackOrder == FinampPlaybackOrder.shuffled) {
_audioHandler.shuffle().then((_) => _audioHandler
.setShuffleMode(AudioServiceShuffleMode.all)
.then((_) => _queueFromConcatenatingAudioSource()));
} else {
_audioHandler
.setShuffleMode(AudioServiceShuffleMode.none)
.then((_) => _queueFromConcatenatingAudioSource());
}
}
FinampPlaybackOrder get playbackOrder => _playbackOrder;
void togglePlaybackOrder() {
if (_playbackOrder == FinampPlaybackOrder.shuffled) {
playbackOrder = FinampPlaybackOrder.linear;
} else {
playbackOrder = FinampPlaybackOrder.shuffled;
}
}
void toggleLoopMode() {
if (_loopMode == FinampLoopMode.all) {
loopMode = FinampLoopMode.one;
} else if (_loopMode == FinampLoopMode.one) {
loopMode = FinampLoopMode.none;
} else {
loopMode = FinampLoopMode.all;
}
}
Logger get queueServiceLogger => _queueServiceLogger;
void _logQueues({String message = ""}) {
// generate string for `_queue`
String queueString = "";
for (FinampQueueItem queueItem in _queuePreviousTracks) {
queueString += "${queueItem.item.title}, ";
}
queueString += "[[${_currentTrack?.item.title}]], ";
queueString += "{";
for (FinampQueueItem queueItem in _queueNextUp) {
queueString += "${queueItem.item.title}, ";
}
queueString += "} ";
for (FinampQueueItem queueItem in _queue) {
queueString += "${queueItem.item.title}, ";
}
// generate string for `_queueAudioSource`
// String queueAudioSourceString = "";
// queueAudioSourceString += "[${_queueAudioSource.sequence.first.toString()}], ";
// for (AudioSource queueItem in _queueAudioSource.sequence.sublist(1)) {
// queueAudioSourceString += "${queueItem.toString()}, ";
// }
// log queues
_queueServiceLogger.finer(
"Queue $message [${_queuePreviousTracks.length}-1-${_queueNextUp.length}-${_queue.length}]: $queueString");
// _queueServiceLogger.finer(
// "Audio Source Queue $message [${_queue.length}]: $queueAudioSourceString"
// )
}
Future<MediaItem> _generateMediaItem(jellyfin_models.BaseItemDto item) async {
const uuid = Uuid();
final downloadedSong = _downloadsHelper.getDownloadedSong(item.id);
final isDownloaded = downloadedSong == null
? false
: await _downloadsHelper.verifyDownloadedSong(downloadedSong);
return MediaItem(
id: uuid.v4(),
album: item.album ?? "unknown",
artist: item.artists?.join(", ") ?? item.albumArtist,
artUri: _downloadsHelper.getDownloadedImage(item)?.file.uri ??
_jellyfinApiHelper.getImageUrl(item: item),
title: item.name ?? "unknown",
extras: {
"itemJson": item.toJson(),
"shouldTranscode": FinampSettingsHelper.finampSettings.shouldTranscode,
"downloadedSongJson": isDownloaded
? (_downloadsHelper.getDownloadedSong(item.id))!.toJson()
: null,
"isOffline": FinampSettingsHelper.finampSettings.isOffline,
},
// Jellyfin returns microseconds * 10 for some reason
duration: Duration(
microseconds:
(item.runTimeTicks == null ? 0 : item.runTimeTicks! ~/ 10),
),
);
}
/// Syncs the list of MediaItems (_queue) with the internal queue of the player.
/// Called by onAddQueueItem and onUpdateQueue.
Future<AudioSource> _queueItemToAudioSource(FinampQueueItem queueItem) async {
if (queueItem.item.extras!["downloadedSongJson"] == null) {
// If DownloadedSong wasn't passed, we assume that the item is not
// downloaded.
// If offline, we throw an error so that we don't accidentally stream from
// the internet. See the big comment in _songUri() to see why this was
// passed in extras.
if (queueItem.item.extras!["isOffline"]) {
return Future.error(
"Offline mode enabled but downloaded song not found.");
} else {
if (queueItem.item.extras!["shouldTranscode"] == true) {
return HlsAudioSource(await _songUri(queueItem.item), tag: queueItem);
} else {
return AudioSource.uri(await _songUri(queueItem.item),
tag: queueItem);
}
}
} else {
// We have to deserialise this because Dart is stupid and can't handle
// sending classes through isolates.
final downloadedSong =
DownloadedSong.fromJson(queueItem.item.extras!["downloadedSongJson"]);
// Path verification and stuff is done in AudioServiceHelper, so this path
// should be valid.
final downloadUri = Uri.file(downloadedSong.file.path);
return AudioSource.uri(downloadUri, tag: queueItem);
}
}
Future<Uri> _songUri(MediaItem mediaItem) async {
// We need the platform to be Android or iOS to get device info
assert(Platform.isAndroid || Platform.isIOS,
"_songUri() only supports Android and iOS");
// When creating the MediaItem (usually in AudioServiceHelper), we specify
// whether or not to transcode. We used to pull from FinampSettings here,
// but since audio_service runs in an isolate (or at least, it does until
// 0.18), the value would be wrong if changed while a song was playing since
// Hive is bad at multi-isolate stuff.
final parsedBaseUrl = Uri.parse(_finampUserHelper.currentUser!.baseUrl);
List<String> builtPath = List.from(parsedBaseUrl.pathSegments);
Map<String, String> queryParameters =
Map.from(parsedBaseUrl.queryParameters);
// We include the user token as a query parameter because just_audio used to
// have issues with headers in HLS, and this solution still works fine
queryParameters["ApiKey"] = _finampUserHelper.currentUser!.accessToken;
if (mediaItem.extras!["shouldTranscode"]) {
builtPath.addAll([
"Audio",
mediaItem.extras!["itemJson"]["Id"],
"main.m3u8",
]);
queryParameters.addAll({
"audioCodec": "aac",
// Ideally we'd use 48kHz when the source is, realistically it doesn't
// matter too much
"audioSampleRate": "44100",
"maxAudioBitDepth": "16",
"audioBitRate":
FinampSettingsHelper.finampSettings.transcodeBitrate.toString(),
});
} else {
builtPath.addAll([
"Items",
mediaItem.extras!["itemJson"]["Id"],
"File",
]);
}
return Uri(
host: parsedBaseUrl.host,
port: parsedBaseUrl.port,
scheme: parsedBaseUrl.scheme,
userInfo: parsedBaseUrl.userInfo,
pathSegments: builtPath,
queryParameters: queryParameters,
);
}
}
class NextUpShuffleOrder extends ShuffleOrder {
final Random _random;
final QueueService? _queueService;
@override
List<int> indices = <int>[];
NextUpShuffleOrder({Random? random, QueueService? queueService})
: _random = random ?? Random(),
_queueService = queueService;
@override
void shuffle({int? initialIndex}) {
assert(initialIndex == null || indices.contains(initialIndex));
if (initialIndex == null) {
// will only be called manually, when replacing the whole queue
indices.shuffle(_random);
return;
}
indices.clear();
_queueService!._queueFromConcatenatingAudioSource();
FinampQueueInfo queueInfo = _queueService!.getQueue();
indices = List.generate(
queueInfo.previousTracks.length +
1 +
queueInfo.nextUp.length +
queueInfo.queue.length,
(i) => i);
if (indices.length <= 1) return;
indices.shuffle(_random);
_queueService!.queueServiceLogger.finest("initialIndex: $initialIndex");
// log indices
String indicesString = "";
for (int index in indices) {
indicesString += "$index, ";
}
_queueService!.queueServiceLogger
.finest("Shuffled indices: $indicesString");
_queueService!.queueServiceLogger
.finest("Current Track: ${queueInfo.currentTrack}");
int nextUpLength = 0;
if (_queueService != null) {
nextUpLength = queueInfo.nextUp.length;
}
const initialPos = 0; // current item will always be at the front
// move current track and next up tracks to the front, pushing all other tracks back while keeping their order
// remove current track and next up tracks from indices and save them in a separate list
List<int> currentTrackIndices = [];
for (int i = 0; i < 1 + nextUpLength; i++) {
currentTrackIndices
.add(indices.removeAt(indices.indexOf(initialIndex + i)));