-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathqueue.service.ts
More file actions
1481 lines (1272 loc) · 39.6 KB
/
Copy pathqueue.service.ts
File metadata and controls
1481 lines (1272 loc) · 39.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {
QueueOrigin,
Track,
PlaybackState,
PlaybackProgress,
PlaybackSettings,
} from "../types/index.ts";
import { getPlayerService } from "./player.service.ts";
import { getMusicService } from "./music.service.ts";
import { pushRecentTrackId, selectRadioCandidates } from "./radio.helpers.ts";
import { log } from "../utils/logger.ts";
type QueueChangeCallback = (queue: Track[]) => void;
type PlaybackStateCallback = (state: PlaybackState) => void;
type PlaybackProgressCallback = (progress: PlaybackProgress) => void;
type LyricsChangeCallback = (lyrics: any[]) => void;
type TrackLoadingCallback = (payload: {
track: Track | null;
message?: string;
}) => void;
type TrackReadyCallback = (track: Track) => void;
type PlayErrorCallback = (payload: {
error: string;
track: Track | null;
}) => void;
const PROGRESS_BROADCAST_INTERVAL_MS = 250;
const DEFAULT_PLAYBACK_SETTINGS: PlaybackSettings = {
crossfadeEnabled: true,
crossfadeDurationSeconds: 4,
volumeNormalizationEnabled: true,
};
const MIN_CROSSFADE_DURATION_SECONDS = 1;
const MAX_CROSSFADE_DURATION_SECONDS = 8;
const MIN_CROSSFADE_START_POSITION_SECONDS = 5;
const CROSSFADE_START_TOLERANCE_SECONDS = 0.35;
const MAX_CROSSFADE_TRIGGER_LEAD_SECONDS = 1;
class QueueService {
private static instance: QueueService | undefined;
private mixRequestId = 0;
private radioRequestId = 0;
private preloadRequestId = 0;
private queue: Track[] = [];
private currentTrack: Track | null = null;
private lastPlayedTrack: Track | null = null;
private currentPosition = 0;
private currentDuration = 0;
private isPaused = false;
private radioEnabled = false;
private playbackSettings: PlaybackSettings = {
...DEFAULT_PLAYBACK_SETTINGS,
};
private recentRadioTrackIds: string[] = [];
private radioFillPromise: Promise<void> | null = null;
private preloadPromise: Promise<boolean> | null = null;
private preloadTrackId: string | null = null;
private crossfadeStartedForTrackId: string | null = null;
private crossfadeTransitionPromise: Promise<void> | null = null;
private lastEofTimestamp = 0; // 記錄 EOF 時間,用於抑制假 pause 事件
private queueChangeCallbacks: QueueChangeCallback[] = [];
private stateChangeCallbacks: PlaybackStateCallback[] = [];
private progressChangeCallbacks: PlaybackProgressCallback[] = [];
private lyricsChangeCallbacks: LyricsChangeCallback[] = [];
private trackLoadingCallbacks: TrackLoadingCallback[] = [];
private trackReadyCallbacks: TrackReadyCallback[] = [];
private playErrorCallbacks: PlayErrorCallback[] = [];
private pendingProgressTimeout: ReturnType<typeof setTimeout> | null = null;
private lastProgressBroadcastAt = 0;
private lastProgressPayload: PlaybackProgress | null = null;
private constructor() {
// 監聽播放器事件
const player = getPlayerService();
player.onEvent((event) => {
let shouldBroadcastProgress = false;
let shouldBroadcastState = false;
if (event.timePos !== undefined) {
this.currentPosition = event.timePos;
shouldBroadcastProgress = true;
}
if (event.duration !== undefined) {
this.currentDuration = event.duration;
shouldBroadcastProgress = true;
}
// EOF 處理
if (event.eof === true) {
this.lastEofTimestamp = Date.now(); // 記錄 EOF 時間
log.info("Track ended, playing next...");
void this.playNext();
return;
}
// Pause 處理 - 抑制 EOF 後 2 秒內的假暫停
if (event.paused !== undefined) {
// mpv 進入 idle 模式時會發送 pause: true
// 抑制 EOF 後 2 秒內的 pause 事件,防止覆蓋 isPlaying 狀態
const timeSinceEof = Date.now() - this.lastEofTimestamp;
if (event.paused && timeSinceEof < 2000) {
log.debug("Ignoring pause event after EOF", {
timeSinceEof,
threshold: 2000,
});
return; // 直接返回,不處理也不廣播
}
this.isPaused = event.paused;
shouldBroadcastState = true;
shouldBroadcastProgress = true;
}
if (shouldBroadcastState) {
this.broadcastState();
}
if (shouldBroadcastProgress) {
this.broadcastProgress({ force: shouldBroadcastState });
void this.maybeStartCrossfade();
}
});
}
static getInstance(): QueueService {
if (!QueueService.instance) {
QueueService.instance = new QueueService();
}
return QueueService.instance;
}
static resetInstanceForTests(): void {
if (QueueService.instance) {
QueueService.instance.resetForTests();
}
QueueService.instance = undefined;
}
/**
* 註冊佇列變更回調
*/
onQueueChange(callback: QueueChangeCallback): void {
this.queueChangeCallbacks.push(callback);
}
/**
* 註冊播放狀態變更回調
*/
onStateChange(callback: PlaybackStateCallback): void {
this.stateChangeCallbacks.push(callback);
}
/**
* 註冊播放進度變更回調
*/
onProgressChange(callback: PlaybackProgressCallback): void {
this.progressChangeCallbacks.push(callback);
}
/**
* 註冊歌詞變更回調
*/
onLyricsChange(callback: LyricsChangeCallback): void {
this.lyricsChangeCallbacks.push(callback);
}
onTrackLoading(callback: TrackLoadingCallback): void {
this.trackLoadingCallbacks.push(callback);
}
onTrackReady(callback: TrackReadyCallback): void {
this.trackReadyCallbacks.push(callback);
}
onPlayError(callback: PlayErrorCallback): void {
this.playErrorCallbacks.push(callback);
}
/**
* 廣播佇列變更
*/
private broadcastQueueChange(): void {
for (const callback of this.queueChangeCallbacks) {
callback([...this.queue]);
}
}
/**
* 廣播狀態變更
*/
private broadcastState(): void {
const state = this.getState();
for (const callback of this.stateChangeCallbacks) {
callback(state);
}
}
private broadcastProgress(options: { force?: boolean } = {}): void {
const progress = this.getProgress();
const hasMeaningfulChange = !isSameProgress(
this.lastProgressPayload,
progress,
);
if (!hasMeaningfulChange) {
if (this.pendingProgressTimeout) {
clearTimeout(this.pendingProgressTimeout);
this.pendingProgressTimeout = null;
}
return;
}
const emit = () => {
this.pendingProgressTimeout = null;
const latestProgress = this.getProgress();
if (isSameProgress(this.lastProgressPayload, latestProgress)) {
return;
}
this.lastProgressPayload = latestProgress;
this.lastProgressBroadcastAt = Date.now();
for (const callback of this.progressChangeCallbacks) {
callback(latestProgress);
}
};
if (options.force) {
if (this.pendingProgressTimeout) {
clearTimeout(this.pendingProgressTimeout);
this.pendingProgressTimeout = null;
}
emit();
return;
}
const elapsed = Date.now() - this.lastProgressBroadcastAt;
if (elapsed >= PROGRESS_BROADCAST_INTERVAL_MS) {
emit();
return;
}
if (this.pendingProgressTimeout) {
return;
}
this.pendingProgressTimeout = setTimeout(
emit,
PROGRESS_BROADCAST_INTERVAL_MS - elapsed,
);
}
private broadcastPlayError(error: string, track: Track | null): void {
for (const callback of this.playErrorCallbacks) {
callback({ error, track });
}
}
private broadcastTrackLoading(track: Track | null, message?: string): void {
for (const callback of this.trackLoadingCallbacks) {
callback({ track, message });
}
}
private broadcastTrackReady(track: Track): void {
for (const callback of this.trackReadyCallbacks) {
callback(track);
}
}
private syncCurrentDurationFromPlayer(): boolean {
const activeDuration = getPlayerService().getActiveDuration();
if (
typeof activeDuration !== "number" ||
!Number.isFinite(activeDuration) ||
activeDuration <= 0 ||
this.currentDuration === activeDuration
) {
return false;
}
this.currentDuration = activeDuration;
return true;
}
/**
* 加入歌曲到播放清單
*/
async addToQueue(
track: Track,
options: { requestedBy?: Track["requestedBy"] } = {},
): Promise<void> {
const requester = this.resolveRequester(options.requestedBy, track);
const normalizedTrack = this.withRequester(track, requester);
this.insertManualTracks([normalizedTrack]);
log.info("Added to queue", {
videoId: normalizedTrack.videoId,
title: normalizedTrack.title,
artist: normalizedTrack.artist,
requestedBy: normalizedTrack.requestedBy?.profileId ?? null,
});
this.broadcastQueueChange();
// 如果目前沒有播放,自動開始播放
// 使用雙重檢查:currentTrack 為 null 且播放器未在播放
const playerIsPlaying = getPlayerService().isCurrentlyPlaying();
const shouldAutoPlay = this.currentTrack === null && !playerIsPlaying;
log.info("Auto-play check", {
currentTrack: this.currentTrack?.title ?? "null",
playerIsPlaying,
shouldAutoPlay,
queueLength: this.queue.length,
});
if (shouldAutoPlay) {
log.info("Auto-starting playback for newly added track");
await this.playNext();
return;
}
this.maybeHydrateRadioQueue();
void this.syncNextTrackPreload();
}
/**
* 創建混合播放清單
* 清空佇列,立即開始播放 Mix
*/
async createMixFromTrack(
baseTrack: Track,
options: { requestedBy?: Track["requestedBy"] } = {},
): Promise<Track[]> {
const requester = this.resolveRequester(options.requestedBy, baseTrack);
const normalizedBaseTrack = this.withRequester(baseTrack, requester);
log.info("Creating mix", {
baseTrack: normalizedBaseTrack.title,
requestedBy: normalizedBaseTrack.requestedBy?.profileId ?? null,
});
const mixRequestId = ++this.mixRequestId;
// 停止當前播放
await getPlayerService().stop();
this.clearPendingPreload();
this.resetCrossfadeState();
// 清空佇列
this.queue = [];
this.currentTrack = null;
this.currentPosition = 0;
this.currentDuration = 0;
this.isPaused = false;
this.broadcastQueueChange();
this.broadcastState();
// 先加入基礎歌曲
this.queue.push(this.withOrigin(normalizedBaseTrack, "mix"));
log.info("Mix created, starting playback", {
addedTracks: this.queue.length,
});
this.broadcastQueueChange();
// 先開始播放 base song,不等待推薦歌曲回來。
await this.playNext();
// 再背景補上推薦歌曲。
let mixTracks: Track[] = [];
try {
mixTracks = await getMusicService().getMixTracks(
normalizedBaseTrack.videoId,
10,
);
// 如果期間又建立了新的 mix,就丟棄舊結果避免污染 queue。
if (mixRequestId !== this.mixRequestId) {
log.info("Discarding stale mix tracks", {
baseTrack: normalizedBaseTrack.title,
mixRequestId,
currentMixRequestId: this.mixRequestId,
});
return [normalizedBaseTrack];
}
if (mixTracks.length > 0) {
const normalizedMixTracks = mixTracks.map((track) =>
this.withOrigin(this.withRequester(track, requester), "mix"),
);
this.queue.push(...normalizedMixTracks);
this.broadcastQueueChange();
void this.syncNextTrackPreload();
// 若 base song 已結束且播放器空閒,補上的 mix 要能自動接續播放。
if (this.currentTrack === null && !getPlayerService().isCurrentlyPlaying()) {
await this.playNext();
}
}
} catch (error) {
log.warn("Failed to get mix tracks, playing base track only", { error });
}
return [
normalizedBaseTrack,
...mixTracks.map((track) => this.withRequester(track, requester)),
];
}
/**
* 從播放清單移除歌曲
*/
removeFromQueue(index: number): void {
if (index >= 0 && index < this.queue.length) {
const removed = this.queue.splice(index, 1);
log.info("Removed from queue", { videoId: removed[0]?.videoId });
this.broadcastQueueChange();
this.broadcastState();
this.maybeHydrateRadioQueue();
void this.syncNextTrackPreload({ force: true });
}
}
/**
* 清空待播佇列,保留目前正在播放的歌曲
*/
clearQueue(): number {
const clearedCount = this.queue.length;
this.queue = [];
this.clearPendingPreload();
this.resetCrossfadeState();
if (clearedCount === 0) {
return 0;
}
log.info("Cleared queue", { clearedCount });
this.broadcastQueueChange();
this.broadcastState();
return clearedCount;
}
/**
* 重新排序播放清單
*/
reorderQueue(fromIndex: number, toIndex: number): void {
const isValidIndex = (index: number) =>
Number.isInteger(index) && index >= 0 && index < this.queue.length;
if (!isValidIndex(fromIndex) || !isValidIndex(toIndex)) {
throw new RangeError("Invalid queue index");
}
if (fromIndex === toIndex) {
return;
}
const [movedTrack] = this.queue.splice(fromIndex, 1);
this.queue.splice(toIndex, 0, movedTrack);
log.info("Reordered queue", {
videoId: movedTrack?.videoId,
fromIndex,
toIndex,
});
this.broadcastQueueChange();
this.broadcastState();
this.maybeHydrateRadioQueue();
void this.syncNextTrackPreload({ force: true });
}
/**
* 播放下一首
*/
async playNext(): Promise<void> {
log.info("playNext called", {
queueLength: this.queue.length,
currentTrack: this.currentTrack?.title ?? "null",
isPaused: this.isPaused,
});
this.resetCrossfadeState();
if (this.queue.length === 0) {
if (this.radioEnabled) {
this.broadcastTrackLoading(null, "正在準備下一首...");
}
const filled = await this.ensureRadioTracks({
immediatePlayback: true,
seedTrack: this.resolveAutoMixSeedTrack(),
});
if (filled && this.queue.length > 0) {
return this.playNext();
}
log.info("Queue is empty, stopping playback");
if (this.currentTrack) {
this.lastPlayedTrack = this.currentTrack;
this.rememberRecentlyPlayed(this.currentTrack.videoId);
}
this.clearPendingPreload();
this.currentTrack = null;
this.currentPosition = 0;
this.currentDuration = 0;
this.isPaused = false;
getPlayerService().stop();
this.broadcastState();
return;
}
const outgoingTrack = this.currentTrack;
const nextTrack = this.queue[0]!;
const player = getPlayerService();
if (outgoingTrack) {
this.lastPlayedTrack = outgoingTrack;
this.rememberRecentlyPlayed(outgoingTrack.videoId);
}
let activatedPreloaded = false;
if (player.isTrackPreloaded(nextTrack.videoId)) {
activatedPreloaded = await player.playPreloaded(nextTrack.videoId);
}
if (!activatedPreloaded && outgoingTrack) {
// 手動切歌時要先停止舊播放器,再切換 currentTrack,
// 否則舊歌在串流解析期間送出的 time-pos 會被誤標成新歌進度。
player.stop();
}
// 從佇列取出下一首
this.queue.shift();
this.preloadPromise = null;
this.preloadTrackId = null;
this.currentTrack = nextTrack;
this.currentPosition = 0;
this.currentDuration = nextTrack.duration;
this.isPaused = false;
if (activatedPreloaded) {
this.syncCurrentDurationFromPlayer();
}
log.info("Playing next track", { title: nextTrack.title });
// 廣播變更
this.broadcastQueueChange();
this.broadcastState();
this.maybeHydrateRadioQueue();
// 獲取並廣播歌詞
this.fetchAndBroadcastLyrics();
if (activatedPreloaded) {
this.broadcastProgress({ force: true });
this.broadcastTrackReady(nextTrack);
void this.syncNextTrackPreload({ force: true });
return;
}
this.broadcastTrackLoading(nextTrack);
try {
log.info("Fetching direct stream URL for playback", {
videoId: nextTrack.videoId,
});
const streamResult = await getMusicService().getStreamUrl(nextTrack.videoId);
log.info("Direct stream URL obtained", {
source: streamResult.source,
bitrate: streamResult.bitrate,
urlLength: streamResult.url.length,
});
await player.playUrl(streamResult.url, {
trackId: nextTrack.videoId,
});
const didSyncDuration = this.syncCurrentDurationFromPlayer();
log.info("Playback started successfully via direct stream URL", {
source: streamResult.source,
});
if (didSyncDuration) {
this.broadcastState();
this.broadcastProgress({ force: true });
}
this.broadcastTrackReady(nextTrack);
void this.syncNextTrackPreload({ force: true });
} catch (playError) {
// Fallback:若直連串流失敗,再退回 mpv 直接處理 YouTube URL。
log.warn("Direct stream playback failed, falling back to YouTube URL", {
error:
playError instanceof Error ? playError.message : String(playError),
stack: playError instanceof Error ? playError.stack : undefined,
videoId: nextTrack.videoId,
});
try {
await player.play(nextTrack.videoId);
const didSyncDuration = this.syncCurrentDurationFromPlayer();
log.info("Fallback playback started successfully via YouTube URL");
if (didSyncDuration) {
this.broadcastState();
this.broadcastProgress({ force: true });
}
this.broadcastTrackReady(nextTrack);
void this.syncNextTrackPreload({ force: true });
} catch (fallbackError) {
const errorMessage = `Failed to play track: ${nextTrack.title}. Error: ${fallbackError instanceof Error ? fallbackError.message : String(fallbackError)}`;
log.error("Both direct stream playback and YouTube URL fallback failed", {
playError:
playError instanceof Error ? playError.message : String(playError),
fallbackError:
fallbackError instanceof Error
? fallbackError.message
: String(fallbackError),
videoId: nextTrack.videoId,
trackTitle: nextTrack.title,
});
// 恢復佇列並重置狀態,避免歌曲因自動播放失敗而直接消失。
this.queue.unshift(nextTrack);
this.currentTrack = null;
this.currentPosition = 0;
this.currentDuration = 0;
this.isPaused = false;
this.broadcastQueueChange();
this.broadcastState();
this.broadcastPlayError(errorMessage, nextTrack);
void this.syncNextTrackPreload({ force: true });
// 拋出錯誤,讓調用者知道播放失敗
throw new Error(errorMessage);
}
}
}
/**
* 開始/恢復播放
*/
play(): void {
if (!this.currentTrack) {
log.debug("Ignoring play request without an active track");
return;
}
if (!this.isPaused && getPlayerService().isCurrentlyPlaying()) {
return;
}
this.isPaused = false;
getPlayerService().resume();
this.broadcastState();
this.broadcastProgress({ force: true });
void this.maybeStartCrossfade();
}
/**
* 暫停播放
*/
pause(): void {
if (!this.currentTrack) {
log.debug("Ignoring pause request without an active track");
return;
}
if (this.isPaused) {
return;
}
this.isPaused = true;
getPlayerService().pause();
this.broadcastState();
this.broadcastProgress({ force: true });
}
/**
* 暫停/繼續播放
*/
togglePlayPause(): void {
if (this.isPaused) {
this.play();
} else {
this.pause();
}
}
/**
* 跳過當前歌曲
*/
skip(): void {
log.info("Skipping current track");
void this.playNext();
}
setPlaybackSettings(
settings: Partial<PlaybackSettings>,
): PlaybackSettings {
const nextSettings = normalizePlaybackSettings({
...this.playbackSettings,
...settings,
});
if (arePlaybackSettingsEqual(this.playbackSettings, nextSettings)) {
return { ...this.playbackSettings };
}
const volumeNormalizationChanged =
this.playbackSettings.volumeNormalizationEnabled !==
nextSettings.volumeNormalizationEnabled;
this.playbackSettings = nextSettings;
this.broadcastState();
if (volumeNormalizationChanged) {
getPlayerService().setVolumeNormalizationEnabled(
nextSettings.volumeNormalizationEnabled,
);
}
void this.syncNextTrackPreload({ force: true });
return { ...this.playbackSettings };
}
enableRadio(): void {
if (this.radioEnabled) {
return;
}
this.radioEnabled = true;
this.broadcastState();
this.broadcastProgress({ force: true });
this.maybeHydrateRadioQueue({ force: true });
}
disableRadio(): void {
if (!this.radioEnabled) {
return;
}
this.radioEnabled = false;
this.broadcastState();
this.broadcastProgress({ force: true });
}
toggleRadio(): void {
if (this.radioEnabled) {
this.disableRadio();
return;
}
this.enableRadio();
}
/**
* 設定音量
*/
setVolume(volume: number): void {
getPlayerService().setVolume(volume);
this.broadcastState();
}
/**
* 跳轉到指定位置
*/
seekTo(position: number): void {
// 驗證輸入和邊界
if (!Number.isFinite(position) || position < 0) {
log.warn("Invalid seek position", { position });
return;
}
if (!this.currentTrack) {
log.warn("Cannot seek: no current track");
return;
}
// 限制在當前歌曲的 duration 範圍內
const clampedPosition =
Number.isFinite(this.currentDuration) && this.currentDuration > 0
? Math.min(position, this.currentDuration)
: position;
log.debug("Seeking to position", { position: clampedPosition });
this.currentPosition = clampedPosition;
getPlayerService().seek(clampedPosition);
this.broadcastProgress({ force: true });
this.crossfadeStartedForTrackId = null;
void this.maybeStartCrossfade();
}
/**
* 取得播放清單
*/
getQueue(): Track[] {
return [...this.queue];
}
/**
* 取得目前播放狀態
*/
getState(): PlaybackState {
return {
isPlaying: this.getIsPlaying(),
currentTrack: this.currentTrack,
position: this.currentPosition,
duration: this.currentDuration,
volume: getPlayerService().getVolume(),
queue: [...this.queue],
radioEnabled: this.radioEnabled,
lastPlayedTrack: this.lastPlayedTrack,
playbackSettings: { ...this.playbackSettings },
};
}
getProgress(): PlaybackProgress {
return {
trackId: this.currentTrack?.videoId ?? null,
position: this.currentPosition,
duration: this.currentDuration,
isPlaying: this.getIsPlaying(),
};
}
async replaceQueueWithTracks(
tracks: Track[],
origin: QueueOrigin = "playlist",
options: { requestedBy?: Track["requestedBy"] } = {},
): Promise<void> {
await getPlayerService().stop();
this.clearPendingPreload();
this.resetCrossfadeState();
const requester = this.resolveRequester(options.requestedBy, null, tracks);
this.queue = tracks.map((track) =>
this.withOrigin(this.withRequester(track, requester), origin),
);
this.currentTrack = null;
this.currentPosition = 0;
this.currentDuration = 0;
this.isPaused = false;
this.broadcastQueueChange();
this.broadcastState();
if (this.queue.length > 0) {
await this.playNext();
}
}
async appendTracksToQueue(
tracks: Track[],
origin: QueueOrigin = "playlist",
options: { requestedBy?: Track["requestedBy"] } = {},
): Promise<void> {
if (tracks.length === 0) {
return;
}
const requester = this.resolveRequester(options.requestedBy, null, tracks);
this.insertManualTracks(
tracks.map((track) =>
this.withOrigin(this.withRequester(track, requester), origin),
),
origin === "manual" || origin === "playlist",
);
this.broadcastQueueChange();
this.broadcastState();
const playerIsPlaying = getPlayerService().isCurrentlyPlaying();
const shouldAutoPlay = this.currentTrack === null && !playerIsPlaying;
if (shouldAutoPlay) {
await this.playNext();
return;
}
this.maybeHydrateRadioQueue();
void this.syncNextTrackPreload();
}
renameRequesterProfile(profileId: string, profileName: string): void {
const normalizedProfileId = profileId.trim();
const normalizedProfileName = profileName.trim();
if (!normalizedProfileId || !normalizedProfileName) {
return;
}
let didChange = false;
const renamedQueue = this.queue.map((track) => {
const nextTrack =
this.withRenamedRequester(
track,
normalizedProfileId,
normalizedProfileName,
) ?? track;
if (nextTrack !== track) {
didChange = true;
}
return nextTrack;
});
const renamedCurrentTrack = this.withRenamedRequester(
this.currentTrack,
normalizedProfileId,
normalizedProfileName,
);
const renamedLastPlayedTrack = this.withRenamedRequester(
this.lastPlayedTrack,
normalizedProfileId,
normalizedProfileName,
);
if (renamedCurrentTrack !== this.currentTrack) {
didChange = true;
}
if (renamedLastPlayedTrack !== this.lastPlayedTrack) {
didChange = true;
}
if (!didChange) {
return;
}
this.queue = renamedQueue;
this.currentTrack = renamedCurrentTrack;
this.lastPlayedTrack = renamedLastPlayedTrack;
this.broadcastQueueChange();
this.broadcastState();
void this.syncNextTrackPreload();
}
/**
* 取得歌詞
*/
async getLyrics() {
if (!this.currentTrack) {
return [];
}
const musicService = getMusicService();
return await musicService.getLyrics(
this.currentTrack.title,
this.currentTrack.artist,
this.currentTrack.duration,
);
}
/**
* 獲取並廣播歌詞(異步)
*/
private fetchAndBroadcastLyrics(): void {
// 使用異步方式獲取歌詞,避免阻塞播放
this.getLyrics()
.then((lyrics) => {
// 透過回調通知歌詞變更
for (const callback of this.lyricsChangeCallbacks) {
callback(lyrics);
}
log.debug("Lyrics broadcasted", { lyricsCount: lyrics.length });
})
.catch((error) => {
log.error("Failed to fetch lyrics", { error });
});
}
private resetCrossfadeState(): void {
this.crossfadeStartedForTrackId = null;
this.crossfadeTransitionPromise = null;
}
private clearPendingPreload(trackId?: string): void {
this.preloadRequestId += 1;
this.preloadPromise = null;
if (!trackId || this.preloadTrackId === trackId) {
this.preloadTrackId = null;
}
getPlayerService().cancelPreload(trackId);
}
private async syncNextTrackPreload(
options: { force?: boolean } = {},
): Promise<boolean> {
const nextTrack = this.queue[0] ?? null;
const player = getPlayerService();
if (!nextTrack) {
this.clearPendingPreload();
return false;
}
if (!options.force && player.isTrackPreloaded(nextTrack.videoId)) {