-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamplayer.ts
More file actions
419 lines (315 loc) · 11.3 KB
/
streamplayer.ts
File metadata and controls
419 lines (315 loc) · 11.3 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
import { TypedEmitter } from "./typedEventTarget.js"
import { CompanionAd, MyStats, SocketMeta } from "./types.js"
export * from "./types.js"
//@ts-ignore
const AudioContext = globalThis.AudioContext || globalThis.webkitAudioContext
const sleep = (time: number) => {
return new Promise((resolve) => {
setTimeout(resolve, time)
})
}
const noCache = () => {
return Math.random().toString().slice(2)
}
interface HistoryEntryRaw {
LiveStreamId: string
InsertDate: string
MetaArtist: string
MetaSong: string
MetaTitle: string
}
export interface Meta {
title: string
artist: string
cover: any
time: Date
companionAd: CompanionAd | null
}
export interface Options {
/**
* @deprecated covers is deprecated, please use your own way to lookup covers from the metadatas
*/
covers?: {
URL?: string
fallback?: string
} | null
aggregator: string
useMediaSession?: boolean
queryParams?: Record<string, string>
sendLocationUpdates?: boolean
}
interface MetaEvents {
currentchange: Meta
historychange: Meta[]
ended: void
}
type FullOptions = Required<Options>
type DefaultOptions = Omit<FullOptions, "aggregator">
const defaultOptions: DefaultOptions = {
useMediaSession: true,
queryParams: {},
covers: null,
sendLocationUpdates: false
}
/**
* StreamPlayer emits two events:
* - `currentchange`: when the current song changes
* - `historychange`: when the history changes
*/
export class StreamPlayer extends TypedEmitter<MetaEvents> {
private ctx = new AudioContext()
private gain = this.ctx.createGain()
private analyzer = this.ctx.createAnalyser()
private streamurl: string = ""
private getSocketurl: ((id: string) => string) | null = null
private historyurl: string = ""
private statsurl: string = ""
public edge: string = ""
private initialization: Promise<void>
private audio: HTMLAudioElement | null = null
private src: MediaElementAudioSourceNode | null = null
private lbRes: Response | null = null
get response() {
return this.lbRes
}
private options: FullOptions
public history: Meta[] = []
public static loadbalancer = "frontend.streamonkey.net"
private async initURLs() {
const lbURL = new URL(`https://${StreamPlayer.loadbalancer}/${this.channel}`)
Object.entries(this.options.queryParams).forEach(([k, v]) => lbURL.searchParams.set(k, v))
lbURL.searchParams.set("aggregator", this.options.aggregator)
this.historyurl = `https://${StreamPlayer.loadbalancer}/${this.channel}/history`
this.lbRes = await fetch(lbURL.toString(), { method: "HEAD" })
this.streamurl = this.lbRes.url
const edgeURL = new URL(this.streamurl)
this.edge = edgeURL.host
this.getSocketurl = (id) => `wss://${this.edge}/wstitleupdate/${id}`
this.statsurl = `https://${this.edge}/${this.channel}/mystats`
}
/**
*
* @param channel the channel to connect to
* @param options
*/
constructor(private channel: string, options: Options) {
super()
if (!options.aggregator) {
throw new Error("options.aggregator must be set!")
}
this.options = Object.assign(defaultOptions, options)
this.initialization = this.initURLs()
this.analyzer.fftSize = Math.pow(2, 10)
this.analyzer.maxDecibels = 0
this.analyzer.minDecibels = -70
this.analyzer.smoothingTimeConstant = 0.85 // dampen the animation
this.gain.gain.value = 1
this.getHistory()
this.setMediaSession()
}
private _playing = false
/**
* get the playing state
*/
public get playing() {
return this._playing
}
private currentSessionID: Promise<string> | null = null
/**
* start the playback of the stream
* @param time the time of the stream to start at, if omitted will start at live
* @returns
*/
public async play(time?: Date) {
if (this.playing) return
// this check is necessary for safari, because it doesn't support await for creating an <audio> element
// if omitted, the playback will not start in safari
if (this.streamurl == "") {
await this.initialization
}
// resume asynchronously to prevent safari playback not starting with "await"
this.ctx.resume()
this.audio = document.createElement("audio")
document.body.append(this.audio)
this.audio.style.display = "none"
this.audio.crossOrigin = "use-credentials"
let url = new URL(this.streamurl)
if (time) {
const codec = "aacp"
url.pathname = `/${this.channel}/stream/${codec}/${time.getUTCFullYear()}/${time.getUTCMonth() + 1}/${time.getUTCDate()}/${time.getUTCHours()}/${time.getUTCMinutes()}/${time.getUTCSeconds()}`
}
url.searchParams.set("nocache", noCache())
this.audio.src = url.toString()
this.audio.volume = 1
this.src = this.ctx.createMediaElementSource(this.audio)
this.src.connect(this.gain).connect(this.analyzer).connect(this.ctx.destination)
// connect the websocket only after the audio is loaded
this.audio.addEventListener("loadeddata", () => {
this.currentSessionID = this.getSessionStats().then(v => v.SessionId)
this.connectWebsocket().catch(() => { })
this.startLocationUpdates()
})
this.audio.addEventListener("ended", () => {
this.dispatchEvent("ended")
this.stop()
})
this.audio.play()
this._playing = true
this.setMediaSession()
}
/**
* stop the playback of the stream
* can be restarted afterwards
* @returns
*/
public stop() {
if (!this._playing) return
this.socket?.close()
this.audio?.pause()
this.src?.disconnect()
this.audio?.remove()
this.audio = null
this.src = null
this._playing = false
}
private socket: WebSocket | null = null
private setMediaSession() {
if (this.options.useMediaSession && "mediaSession" in navigator && navigator.mediaSession) {
navigator.mediaSession.setActionHandler("play", () => this.play())
navigator.mediaSession.setActionHandler("pause", () => this.stop())
navigator.mediaSession.setActionHandler("stop", () => this.stop())
}
}
public async getSessionStats(): Promise<MyStats> {
await this.initialization
if (!this._playing) throw new Error("Not playing")
const res = await fetch(this.statsurl, {
mode: "cors",
credentials: "include"
})
const json: MyStats = await res.json()
return json
}
private connectWebsocket = async () => {
this.socket?.close()
if (!this.playing || this.getSocketurl == null || this.currentSessionID == null) return
const sessionID = await this.currentSessionID
this.socket = new WebSocket(this.getSocketurl(sessionID))
this.socket.onerror = async () => {
this.socket?.close()
console.log("retrying connection")
await sleep(2000)
this.connectWebsocket()
}
this.socket.addEventListener("message", async (e: MessageEvent<string>) => {
const json: SocketMeta = JSON.parse(e.data)
const cover = await this.getCoverURL(json.title, json.artist)
this.dispatchEvent("currentchange", {
artist: json.artist,
cover,
title: json.title,
time: new Date(),
companionAd: json.companion_ad,
})
this.getHistory()
if (this.options.useMediaSession) {
navigator.mediaSession!.metadata = new MediaMetadata({
title: json.title,
artist: json.artist,
artwork: cover ? [
{ src: cover },
] : undefined
})
}
})
}
/**
* @deprecated covers is deprecated, please use your own way to lookup covers from the metadatas
*/
private getCoverURL = async (title: string, artist: string) => {
console.warn("streamonkey-player StreamPlayer: getCoverURL is deprecated, please use your own way to lookup covers from the metadatas")
if (!this.options.covers) {
return null
}
if (!this.options.covers.URL) {
return this.options.covers.fallback
}
let url
try {
url = new URL(this.options.covers.URL)
} catch (e) {
url = new URL(this.options.covers.URL, location.origin)
}
url.searchParams.set("title", title)
url.searchParams.set("artist", artist)
const res = await fetch(url.toString())
if (res.status != 200) {
return this.options.covers.fallback
} else {
return await res.text()
}
}
private async getHistory() {
await this.initialization
const res = await fetch(this.historyurl)
let hist: HistoryEntryRaw[] = await res.json()
if (!Array.isArray(hist)) {
this.history = []
return
}
this.history = await Promise.all(hist.map(async (v, i) => {
// only get the cover for the last 40 songs. The whole history can reach easily up to 400 songs
const cover = i < 40 ? await this.getCoverURL(v.MetaSong, v.MetaArtist) : undefined
return {
title: v.MetaSong,
artist: v.MetaArtist,
cover: cover,
time: new Date(v.InsertDate),
companionAd: null,
}
}))
this.dispatchEvent("historychange", this.history)
}
/**
* set a new volume for the stream (range 0-1)
*/
set volume(vol: number) {
this.gain.gain.value = vol
}
/**
* get the current volume of the stream (range 0-1)
*/
get volume() {
return this.gain.gain.value
}
/**
* Fill the given array with the current spectrum data
* @param data a Uint8Array to which the fftdata will be written
*/
fft(data: Uint8Array) {
this.analyzer.getByteFrequencyData(data)
}
private startLocationUpdates() {
if (!this.options.sendLocationUpdates) return
const send = () => {
navigator.geolocation.getCurrentPosition(async pos => {
const url = new URL(this.statsurl)
if (!this.currentSessionID) return
const sessionID = await this.currentSessionID
url.pathname = `/updatelocation/${sessionID}/${pos.coords.latitude}/${pos.coords.longitude}/`
const res = await fetch(url.toString(), {
method: "GET"
})
// 304 is sent on too frequent updates
if (res.status == 200 || res.status == 304) {
setTimeout(send, 10000)
}
}, () => { }, {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0,
})
}
send()
}
}