forked from RelistenNet/gapless.js
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
630 lines (501 loc) · 15.9 KB
/
index.ts
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
enum PlaybackType {
html5,
webaudio,
}
enum PlaybackLoadingState {
none,
loading,
loaded,
}
export interface QueueOptions {
onProgress?: () => void;
onEnded?: () => void;
onPlayNextTrack?: () => void;
onPlayPreviousTrack?: () => void;
onStartNewTrack?: () => void;
webAudioIsDisabled?: boolean;
fetchMode?: 'cors' | 'no-cors' | 'same-origin';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
debug?: ((message: string, ...optionalParams: any[]) => void) | null;
numberOfTracksToPreload?: number;
}
interface QueueState {
volume: number;
currentTrackIndex: number;
webAudioIsDisabled: boolean;
}
interface QueueProps<TTrack> {
onProgress?: (track: Track<TTrack>) => void;
onEnded?: () => void;
onPlayNextTrack?: (track: Track<TTrack>) => void;
onPlayPreviousTrack?: (track: Track<TTrack>) => void;
onStartNewTrack?: (track: Track<TTrack>) => void;
}
interface WithWebkitAudioContext {
webkitAudioContext: AudioContext;
}
const AudioContext = globalThis.AudioContext || ((globalThis as unknown) as WithWebkitAudioContext).webkitAudioContext;
export class Queue<TTrackMetadata> {
private props: QueueProps<TTrackMetadata>;
private numberOfTracksToPreload: number;
public readonly tracks: Track<TTrackMetadata>[] = [];
public state: QueueState;
public readonly fetchMode?: 'cors' | 'no-cors' | 'same-origin';
public constructor({ onProgress, onEnded, onPlayNextTrack, onPlayPreviousTrack, onStartNewTrack, webAudioIsDisabled = false, numberOfTracksToPreload = 2, fetchMode = 'cors' }: QueueOptions = {}) {
this.props = {
onProgress,
onEnded,
onPlayNextTrack,
onPlayPreviousTrack,
onStartNewTrack,
};
this.fetchMode = fetchMode;
this.numberOfTracksToPreload = numberOfTracksToPreload;
this.state = {
volume: 1,
currentTrackIndex: 0,
webAudioIsDisabled,
};
}
public addTrack({ trackUrl, metadata = {} as TTrackMetadata }: { trackUrl: string; metadata: TTrackMetadata }): void {
this.tracks.push(
// eslint-disable-next-line @typescript-eslint/no-use-before-define
new Track({
trackUrl,
metadata,
index: this.tracks.length,
queue: this,
}),
);
}
public removeTrack(track: Track<TTrackMetadata>): void {
const index = this.tracks.indexOf(track);
this.tracks.splice(index, 1);
}
public async togglePlayPause(): Promise<void> {
if (this.currentTrack) {
await this.currentTrack.togglePlayPause();
}
}
public async play(): Promise<void> {
if (this.currentTrack) {
await this.currentTrack.play();
}
}
public pause(): void {
if (this.currentTrack) {
this.currentTrack.pause();
}
}
public async playPrevious(): Promise<void> {
this.resetCurrentTrack();
this.state.currentTrackIndex = Math.max(this.state.currentTrackIndex - 1, 0);
this.resetCurrentTrack();
if (this.currentTrack) {
await this.play();
if (this.props.onStartNewTrack) {
this.props.onStartNewTrack(this.currentTrack);
}
if (this.props.onPlayPreviousTrack) {
this.props.onPlayPreviousTrack(this.currentTrack);
}
}
}
public async playNext(): Promise<void> {
this.resetCurrentTrack();
this.state.currentTrackIndex += 1;
this.resetCurrentTrack();
if (this.currentTrack) {
await this.play();
if (this.props.onStartNewTrack) {
this.props.onStartNewTrack(this.currentTrack);
}
if (this.props.onPlayNextTrack) {
this.props.onPlayNextTrack(this.currentTrack);
}
}
}
public resetCurrentTrack(): void {
if (this.currentTrack) {
this.currentTrack.seek(0);
this.currentTrack.pause();
}
}
public pauseAll(): void {
for (const track of this.tracks) {
track.pause();
}
}
public async gotoTrack(trackIndex: number, playImmediately = false): Promise<void> {
this.pauseAll();
this.state.currentTrackIndex = trackIndex;
this.resetCurrentTrack();
if (playImmediately && this.currentTrack) {
await this.play();
if (this.props.onStartNewTrack) {
this.props.onStartNewTrack(this.currentTrack);
}
}
}
public loadTrack(trackIndex: number, useHtmlAudioPreloading = false): void {
// only preload if song is within the next 2
if (this.state.currentTrackIndex + this.numberOfTracksToPreload <= trackIndex) {
return;
}
const track = this.tracks[trackIndex];
if (track) {
track.preload(useHtmlAudioPreloading);
}
}
// Internal - Used by the track to notify when it has ended
public notifyTrackEnded(): void {
if (this.props.onEnded) {
this.props.onEnded();
}
}
// Internal - Used by the track to notify when progress has updated
public notifyTrackProgressUpdated(): void {
if (this.props.onProgress && this.currentTrack) {
this.props.onProgress(this.currentTrack);
}
}
public get currentTrack(): Track<TTrackMetadata> | undefined {
if (this.state.currentTrackIndex < this.tracks.length) {
return this.tracks[this.state.currentTrackIndex];
}
return undefined;
}
public get nextTrack(): Track<TTrackMetadata> {
return this.tracks[this.state.currentTrackIndex + 1];
}
public disableWebAudio(): void {
this.state.webAudioIsDisabled = true;
}
public setVolume(volume: number): void {
if (volume < 0) {
volume = 0;
} else if (volume > 1) {
volume = 1;
}
this.state.volume = volume;
for (const track of this.tracks) {
track.setVolume(volume);
}
}
}
interface TrackOptions<TTrackMetadata> {
trackUrl: string;
queue: Queue<TTrackMetadata>;
index: number;
metadata: TTrackMetadata;
}
interface LimitedTrackState {
playbackType: PlaybackType;
webAudioLoadingState: PlaybackLoadingState;
}
interface TrackState extends LimitedTrackState {
isPaused: boolean;
currentTime: number;
duration: number;
index: number;
}
export class Track<TTrackMetadata> {
private playbackType: PlaybackType;
private webAudioLoadingState: PlaybackLoadingState;
private loadedHead: boolean;
private queue: Queue<TTrackMetadata>;
private audio: HTMLAudioElement;
private audioContext: AudioContext;
private gainNode: GainNode;
private webAudioStartedPlayingAt: number;
private webAudioPausedAt: number;
private webAudioPausedDuration: number;
private audioBuffer: AudioBuffer | null;
private bufferSourceNode: AudioBufferSourceNode;
public metadata: TTrackMetadata;
public index: number;
public trackUrl: string;
public constructor({ trackUrl, queue, index, metadata }: TrackOptions<TTrackMetadata>) {
// playback type state
this.playbackType = PlaybackType.html5;
this.webAudioLoadingState = PlaybackLoadingState.none;
this.loadedHead = false;
// basic inputs from Queue
this.index = index;
this.queue = queue;
this.trackUrl = trackUrl;
this.metadata = metadata;
// this.onEnded = this.onEnded.bind(this);
// this.onProgress = this.onProgress.bind(this);
// HTML5 Audio
this.audio = new Audio();
this.audio.onerror = (e: Event | string): void => {
this.debug('audioOnError', e);
};
this.audio.onended = (): void => {
this.notifyTrackEnd();
};
this.audio.controls = false;
this.audio.volume = this.queue.state.volume;
this.audio.preload = 'none';
this.audio.src = trackUrl;
// this.audio.onprogress = () => this.debug(this.index, this.audio.buffered)
// WebAudio
this.audioContext = new AudioContext();
this.gainNode = this.audioContext.createGain();
this.gainNode.gain.value = this.queue.state.volume;
this.webAudioStartedPlayingAt = 0;
this.webAudioPausedDuration = 0;
this.webAudioPausedAt = 0;
this.audioBuffer = null;
this.bufferSourceNode = this.audioContext.createBufferSource();
this.bufferSourceNode.onended = (): void => {
this.notifyTrackEnd();
};
}
public pause(): void {
this.debug('pause');
if (this.isUsingWebAudio) {
if (this.bufferSourceNode.playbackRate.value === 0) {
return;
}
this.webAudioPausedAt = this.audioContext.currentTime;
this.bufferSourceNode.playbackRate.value = 0;
this.gainNode.disconnect(this.audioContext.destination);
} else {
this.audio.pause();
}
}
public async play(): Promise<void> {
this.debug('play');
if (this.audioBuffer) {
// if we've already set up the buffer just set playbackRate to 1
if (this.isUsingWebAudio) {
if (this.bufferSourceNode.playbackRate.value === 1) {
return;
}
if (this.webAudioPausedAt) {
this.webAudioPausedDuration += this.audioContext.currentTime - this.webAudioPausedAt;
}
// use seek to avoid bug where track wouldn't play properly
// if paused for longer than length of track
// TODO: fix bug -- must be related to bufferSourceNode
this.seek(this.currentTime);
// was paused, now force play
this.connectGainNode();
this.bufferSourceNode.playbackRate.value = 1;
this.webAudioPausedAt = 0;
} else {
// otherwise set the bufferSourceNode buffer and switch to WebAudio
this.switchToWebAudio();
}
// Try to preload the next track
this.queue.loadTrack(this.index + 1);
} else {
this.audio.preload = 'auto';
await this.audio.play();
if (!this.queue.state.webAudioIsDisabled) {
// Fire and forget
this.loadHEAD()
.then(() => {
void this.loadBuffer();
return true;
})
.catch(() => undefined);
}
}
this.onProgress();
}
public async togglePlayPause(): Promise<void> {
if (this.isPaused) {
await this.play();
} else {
this.pause();
}
}
public preload(useHtmlAudioPreloading = false): void {
this.debug('preload', useHtmlAudioPreloading);
if (useHtmlAudioPreloading) {
this.audio.preload = 'auto';
} else if (!this.audioBuffer && !this.queue.state.webAudioIsDisabled) {
// Fire and forget
this.loadHEAD()
.then(() => {
void this.loadBuffer();
return true;
})
.catch(() => undefined);
}
}
// TODO: add checks for to > duration or null or negative (duration - to)
public seek(to = 0): void {
if (this.isUsingWebAudio) {
this.seekBufferSourceNode(to);
} else {
this.audio.currentTime = to;
}
this.onProgress();
}
public connectGainNode(): void {
this.gainNode.connect(this.audioContext.destination);
}
public setVolume(volume: number): void {
this.audio.volume = volume;
if (this.gainNode) {
this.gainNode.gain.value = volume;
}
}
// getter helpers
public get isUsingWebAudio(): boolean {
return this.playbackType === PlaybackType.webaudio;
}
public get isPaused(): boolean {
if (this.isUsingWebAudio) {
return this.bufferSourceNode.playbackRate.value === 0;
}
return this.audio.paused;
}
public get currentTime(): number {
if (this.isUsingWebAudio) {
return this.audioContext.currentTime - this.webAudioStartedPlayingAt - this.webAudioPausedDuration;
}
return this.audio.currentTime;
}
public get duration(): number {
if (this.isUsingWebAudio && this.audioBuffer) {
return this.audioBuffer.duration;
}
return this.audio.duration;
}
public get isActiveTrack(): boolean {
return this.queue.currentTrack?.index === this.index;
}
public get isLoaded(): boolean {
return this.webAudioLoadingState === PlaybackLoadingState.loaded;
}
public get state(): LimitedTrackState {
return {
playbackType: this.playbackType,
webAudioLoadingState: this.webAudioLoadingState,
};
}
public get completeState(): TrackState {
return {
playbackType: this.playbackType,
webAudioLoadingState: this.webAudioLoadingState,
isPaused: this.isPaused,
currentTime: this.currentTime,
duration: this.duration,
index: this.index,
};
}
private async loadHEAD(): Promise<void> {
if (this.loadedHead) {
return;
}
const { redirected, url } = await fetch(this.trackUrl, {
method: 'HEAD',
mode: this.queue.fetchMode,
});
if (redirected) {
this.trackUrl = url;
}
this.loadedHead = true;
}
private async loadBuffer(): Promise<void> {
try {
if (this.webAudioLoadingState !== PlaybackLoadingState.none) {
return;
}
this.webAudioLoadingState = PlaybackLoadingState.loading;
const response = await fetch(this.trackUrl, {
mode: this.queue.fetchMode,
});
const buffer = await response.arrayBuffer();
this.audioBuffer = await this.audioContext.decodeAudioData(buffer);
this.webAudioLoadingState = PlaybackLoadingState.loaded;
this.bufferSourceNode.buffer = this.audioBuffer;
this.bufferSourceNode.connect(this.gainNode);
// try to preload next track
this.queue.loadTrack(this.index + 1);
// if we loaded the active track, switch to web audio
if (this.isActiveTrack) {
this.switchToWebAudio();
}
} catch (ex) {
this.debug(`Error fetching buffer: ${this.trackUrl}`, ex);
}
}
private switchToWebAudio(): void {
// if we've switched tracks, don't switch to web audio
if (!this.isActiveTrack || !this.audioBuffer) {
return;
}
this.debug('switch to web audio', this.currentTime, this.isPaused, this.audio.duration - this.audioBuffer.duration);
// if currentTime === 0, this is a new track, so play it
// otherwise we're hitting this mid-track which may
// happen in the middle of a paused track
if (this.currentTime && this.isPaused) {
this.bufferSourceNode.playbackRate.value = 0;
} else {
this.bufferSourceNode.playbackRate.value = 1;
}
this.connectGainNode();
this.webAudioStartedPlayingAt = this.audioContext.currentTime - this.currentTime;
// TODO: slight blip, could be improved
this.bufferSourceNode.start(0, this.currentTime);
this.audio.pause();
this.playbackType = PlaybackType.webaudio;
}
private seekBufferSourceNode(to: number): void {
const wasPaused = this.isPaused;
this.bufferSourceNode.onended = null;
this.bufferSourceNode.stop();
this.bufferSourceNode = this.audioContext.createBufferSource();
this.bufferSourceNode.buffer = this.audioBuffer;
this.bufferSourceNode.connect(this.gainNode);
this.bufferSourceNode.onended = (): void => {
this.notifyTrackEnd();
};
this.webAudioStartedPlayingAt = this.audioContext.currentTime - to;
this.webAudioPausedDuration = 0;
this.bufferSourceNode.start(0, to);
if (wasPaused) {
this.connectGainNode();
this.pause();
}
}
// basic event handlers
private notifyTrackEnd(): void {
this.debug('onEnded');
// Fire and forget
void this.queue.playNext();
this.queue.notifyTrackEnded();
}
private onProgress(): void {
if (!this.isActiveTrack) {
return;
}
const durationRemainingInSeconds = this.duration - this.currentTime;
const { nextTrack } = this.queue;
// if in last 25 seconds and next track hasn't loaded yet, load next track using HtmlAudio
if (durationRemainingInSeconds <= 25 && nextTrack && !nextTrack.isLoaded) {
this.queue.loadTrack(this.index + 1, true);
}
this.queue.notifyTrackProgressUpdated();
// if we're paused, we still want to send one final onProgress call
// and then bow out, hence this being at the end of the function
if (this.isPaused) {
return;
}
window.requestAnimationFrame((): void => {
this.onProgress();
});
}
// debug helper
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private debug(message: string, ...optionalParams: any[]): void {
// eslint-disable-next-line no-console
console.log(`${this.index}:${message}`, ...optionalParams, this.state);
}
}