@supr-design/flux-player 0.0.0-stage → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1930 @@
1
+ //#region packages/core/dist/src/PlayerState.js
2
+ var e = class {
3
+ state;
4
+ bus;
5
+ constructor(e) {
6
+ this.bus = e, this.state = this.getDefaultState();
7
+ }
8
+ getDefaultState() {
9
+ return {
10
+ status: "idle",
11
+ currentTime: 0,
12
+ duration: NaN,
13
+ paused: !0,
14
+ ended: !1,
15
+ buffering: !1,
16
+ muted: !1,
17
+ volume: 1,
18
+ playbackRate: 1,
19
+ buffered: [],
20
+ selectedQuality: "auto",
21
+ availableQualities: [],
22
+ selectedSubtitle: null,
23
+ availableSubtitles: [],
24
+ selectedAudioTrack: "default",
25
+ availableAudioTracks: [],
26
+ engineType: "none",
27
+ readyState: 0,
28
+ error: null,
29
+ isLive: !1,
30
+ isDvr: !1,
31
+ source: null
32
+ };
33
+ }
34
+ get snapshot() {
35
+ return {
36
+ ...this.state,
37
+ buffered: this.state.buffered.map((e) => ({ ...e })),
38
+ availableQualities: this.state.availableQualities.map((e) => ({ ...e })),
39
+ availableSubtitles: this.state.availableSubtitles.map((e) => ({ ...e })),
40
+ availableAudioTracks: this.state.availableAudioTracks.map((e) => ({ ...e })),
41
+ source: this.state.source ? { ...this.state.source } : null
42
+ };
43
+ }
44
+ reset() {
45
+ let e = this.state.volume, t = this.state.muted;
46
+ this.state = this.getDefaultState(), this.state.volume = e, this.state.muted = t, this.notify();
47
+ }
48
+ update(e) {
49
+ let t = !1;
50
+ for (let n of Object.keys(e)) this.state[n] !== e[n] && (this.state[n] = e[n], t = !0, this.bus.emit(`state:${n}`, e[n]));
51
+ t && this.notify();
52
+ }
53
+ notify() {
54
+ this.bus.emit("state:change", this.snapshot);
55
+ }
56
+ }, t = class {
57
+ listeners = /* @__PURE__ */ new Map();
58
+ on(e, t) {
59
+ return this.listeners.has(e) || this.listeners.set(e, []), this.listeners.get(e).push(t), () => this.off(e, t);
60
+ }
61
+ off(e, t) {
62
+ let n = this.listeners.get(e);
63
+ if (!n) return;
64
+ let r = n.indexOf(t);
65
+ r > -1 && n.splice(r, 1);
66
+ }
67
+ emit(e, ...t) {
68
+ let n = this.listeners.get(e);
69
+ if (n) for (let r of [...n]) try {
70
+ r(...t);
71
+ } catch (t) {
72
+ console.error(`Error in event listener for ${e}:`, t);
73
+ }
74
+ }
75
+ clear() {
76
+ this.listeners.clear();
77
+ }
78
+ }, n = class {
79
+ engines = [];
80
+ register(e) {
81
+ this.engines.find((t) => t.id === e.id) || this.engines.push(e);
82
+ }
83
+ getEngines() {
84
+ return this.engines;
85
+ }
86
+ findEngineForSource(e, t) {
87
+ if (e && e !== "auto") return this.engines.find((t) => t.canPlayType(e)) || null;
88
+ for (let e of this.engines) if (e.canPlaySource(t)) return e;
89
+ return null;
90
+ }
91
+ }, r = [
92
+ {
93
+ pattern: /application\/(vnd\.apple\.mpegurl|x-mpegurl)/i,
94
+ type: "hls"
95
+ },
96
+ {
97
+ pattern: /application\/dash\+xml/i,
98
+ type: "dash"
99
+ },
100
+ {
101
+ pattern: /video\/mp4/i,
102
+ type: "mp4"
103
+ },
104
+ {
105
+ pattern: /video\/webm/i,
106
+ type: "webm"
107
+ }
108
+ ];
109
+ function i(e) {
110
+ if (!e) return "auto";
111
+ for (let t of r) if (t.pattern.test(e)) return t.type;
112
+ return "auto";
113
+ }
114
+ function a(e) {
115
+ try {
116
+ let t = new URL(e);
117
+ return `${t.pathname}${t.search}`.toLowerCase();
118
+ } catch {
119
+ return e.toLowerCase();
120
+ }
121
+ }
122
+ function o(e, t) {
123
+ let n = i(t);
124
+ if (n !== "auto") return n;
125
+ let r = a(e);
126
+ return r.includes(".m3u8") ? "hls" : r.includes(".mpd") ? "dash" : r.includes(".webm") ? "webm" : r.includes(".mp4") ? "mp4" : /(format|type)=(m3u8|hls)/i.test(r) ? "hls" : /(format|type)=(mpd|dash)/i.test(r) ? "dash" : "auto";
127
+ }
128
+ //#endregion
129
+ //#region packages/core/dist/src/Preroll.js
130
+ function s(e, t, n) {
131
+ let r = e.parentElement;
132
+ if (!r || n.aborted) return Promise.resolve("cancelled");
133
+ let i = getComputedStyle(r).position === "static", a = r.style.position;
134
+ i && (r.style.position = "relative");
135
+ let o = document.createElement("div");
136
+ o.style.cssText = "position:absolute;inset:0;z-index:100;background:black;color:white";
137
+ let s = document.createElement("video");
138
+ s.style.cssText = "width:100%;height:100%;object-fit:contain", s.playsInline = !0, s.muted = e.muted, s.volume = e.volume, s.controls = !0, s.setAttribute("aria-label", "Advertisement");
139
+ let c = document.createElement("span");
140
+ return c.textContent = "Advertisement", c.style.cssText = "position:absolute;top:12px;left:12px;background:#151515;padding:4px 8px;font:13px sans-serif;pointer-events:none", o.append(s, c), r.append(o), new Promise((e) => {
141
+ let c = !1, l, u = (t) => {
142
+ c || (c = !0, clearTimeout(l), n.removeEventListener("abort", d), s.onended = s.onerror = s.onwaiting = s.onplaying = null, s.pause(), s.removeAttribute("src"), s.load(), o.remove(), i && (r.style.position = a), e(t));
143
+ }, d = () => u("cancelled"), f = () => {
144
+ clearTimeout(l), l = window.setTimeout(() => u("failed"), 1e4);
145
+ };
146
+ s.onended = () => u("ended"), s.onerror = () => u("failed"), s.onwaiting = f, s.onplaying = () => clearTimeout(l), n.addEventListener("abort", d, { once: !0 }), f(), s.src = t, s.play().catch(() => u("failed"));
147
+ });
148
+ }
149
+ //#endregion
150
+ //#region packages/core/dist/src/index.js
151
+ var c = class {
152
+ bus;
153
+ state;
154
+ registry;
155
+ currentEngine = null;
156
+ currentVideoElement = null;
157
+ cleans = [];
158
+ generation = 0;
159
+ adSource;
160
+ pendingMidrolls = [];
161
+ adController;
162
+ adPlayback;
163
+ cancelAd() {
164
+ this.adController?.abort(), this.adPlayback = void 0, this.adController = void 0;
165
+ }
166
+ pendingSeekTime = null;
167
+ performance = {
168
+ startupMode: "balanced",
169
+ startupStrategy: "balanced",
170
+ startupBufferSeconds: 1.2,
171
+ manifestFastPath: !1
172
+ };
173
+ abr = {
174
+ startupProfile: "balanced",
175
+ upgradeAggression: "medium",
176
+ rebufferSafetyBias: "medium"
177
+ };
178
+ constructor() {
179
+ this.bus = new t(), this.state = new e(this.bus), this.registry = new n();
180
+ }
181
+ attachVideo(e) {
182
+ this.currentVideoElement = e, this.currentEngine && this.currentEngine.attach(e);
183
+ }
184
+ setPerformance(e) {
185
+ this.performance = {
186
+ startupMode: e?.startupMode ?? "balanced",
187
+ startupStrategy: e?.startupStrategy ?? "balanced",
188
+ startupBufferSeconds: e?.startupBufferSeconds ?? 1.2,
189
+ manifestFastPath: e?.manifestFastPath ?? !1
190
+ }, this.bus.emit("performance:updated", this.performance);
191
+ }
192
+ setAbr(e) {
193
+ this.abr = {
194
+ startupProfile: e?.startupProfile ?? "balanced",
195
+ upgradeAggression: e?.upgradeAggression ?? "medium",
196
+ rebufferSafetyBias: e?.rebufferSafetyBias ?? "medium"
197
+ }, this.bus.emit("abr:updated", this.abr);
198
+ }
199
+ getStartupReadiness() {
200
+ return this.currentEngine?.getStartupReadiness?.() ?? null;
201
+ }
202
+ async load(e) {
203
+ let t = ++this.generation;
204
+ this.cancelAd(), this.adSource = e.preroll?.src, this.pendingMidrolls = (e.midrolls || []).filter((e) => Number.isFinite(e.at) && e.at > 0 && e.src).sort((e, t) => e.at - t.at), this.bus.emit("startup:mode", {
205
+ mode: this.performance.startupMode,
206
+ startupBufferSeconds: this.performance.startupBufferSeconds
207
+ });
208
+ let n = o(e.src, e.mimeType), r = e.type && e.type !== "auto" ? e.type : n;
209
+ this.state.update({
210
+ currentTime: 0,
211
+ duration: NaN,
212
+ readyState: 0,
213
+ error: null,
214
+ paused: !0,
215
+ ended: !1,
216
+ buffering: !1,
217
+ selectedQuality: "auto",
218
+ availableQualities: [],
219
+ selectedSubtitle: null,
220
+ availableSubtitles: [],
221
+ selectedAudioTrack: "default",
222
+ availableAudioTracks: [],
223
+ isLive: !1,
224
+ isDvr: !1,
225
+ status: "loading",
226
+ source: {
227
+ src: e.src,
228
+ adBreakTimes: [...this.adSource ? [0] : [], ...this.pendingMidrolls.map((e) => e.at)],
229
+ requestedType: r,
230
+ detectedType: n,
231
+ mimeType: e.mimeType || null,
232
+ title: e.title || null,
233
+ poster: e.poster || null,
234
+ thumbnailVtt: e.thumbnailVtt || null
235
+ }
236
+ });
237
+ let i = { ...e };
238
+ delete i.drm, this.bus.emit("source_loading", i);
239
+ let a = r, s = this.registry.findEngineForSource(a, e.src);
240
+ if (!s || e.drm && s.id !== "dash") {
241
+ let t = {
242
+ code: "NO_ENGINE",
243
+ message: e.drm ? "Configured DRM requires DASH playback" : "No engine found for source",
244
+ engine: "core",
245
+ recoverable: !1
246
+ };
247
+ throw this.state.update({
248
+ error: t,
249
+ status: "error"
250
+ }), this.bus.emit("error", t), Error(t.message);
251
+ }
252
+ if (this.currentEngine) {
253
+ if (await this.currentEngine.destroy(), t !== this.generation) return;
254
+ this.unbindEngine();
255
+ }
256
+ this.currentEngine = s, this.currentEngine.setRuntimeConfig?.({
257
+ performance: this.performance,
258
+ abr: this.abr
259
+ }), this.pendingSeekTime = null, this.currentVideoElement && (e.muted !== void 0 && (this.currentVideoElement.muted = e.muted), this.currentEngine.attach(this.currentVideoElement)), this.bindEngine(this.currentEngine), this.state.update({ engineType: s.id });
260
+ try {
261
+ if (await this.currentEngine.load(e), t !== this.generation) return;
262
+ this.bus.emit("source_loaded", i);
263
+ let n = this.getState();
264
+ this.state.update({ status: n.paused ? "paused" : "playing" }), e.autoplay && this.play().catch((e) => console.warn("Autoplay failed", e));
265
+ } catch (e) {
266
+ if (t !== this.generation) return;
267
+ let n = {
268
+ code: "LOAD_ERROR",
269
+ message: e?.message || "Unknown loading error",
270
+ engine: s.id,
271
+ recoverable: !1
272
+ };
273
+ throw this.state.update({
274
+ error: n,
275
+ status: "error",
276
+ buffering: !1
277
+ }), this.bus.emit("error", n), e;
278
+ }
279
+ }
280
+ bindEngine(e) {
281
+ this.cleans.forEach((e) => e()), this.cleans = [
282
+ e.on("play", () => {
283
+ this.state.update({
284
+ paused: !1,
285
+ ended: !1,
286
+ status: "playing"
287
+ }), this.bus.emit("play");
288
+ }),
289
+ e.on("playing", () => {
290
+ this.state.update({
291
+ paused: !1,
292
+ readyState: 4,
293
+ buffering: !1,
294
+ ended: !1,
295
+ status: "playing"
296
+ }), this.bus.emit("playing");
297
+ }),
298
+ e.on("pause", () => {
299
+ let e = this.getState();
300
+ this.state.update({
301
+ paused: !0,
302
+ status: e.ended ? "ended" : "paused"
303
+ }), this.bus.emit("pause");
304
+ }),
305
+ e.on("ended", () => {
306
+ this.state.update({
307
+ paused: !0,
308
+ ended: !0,
309
+ buffering: !1,
310
+ status: "ended"
311
+ }), this.bus.emit("ended");
312
+ }),
313
+ e.on("seeked", ({ currentTime: e }) => {
314
+ this.state.update({
315
+ currentTime: e,
316
+ buffering: !1,
317
+ status: this.getState().paused ? "paused" : "playing"
318
+ }), this.pendingSeekTime !== null && (this.bus.emit("seek_complete", e), this.pendingSeekTime = null);
319
+ }),
320
+ e.on("timeupdate", ({ currentTime: t }) => {
321
+ this.state.update({ currentTime: t });
322
+ let n = this.pendingMidrolls[0];
323
+ n && t >= n.at && !this.currentVideoElement?.paused && !this.adPlayback && (this.pendingMidrolls.shift(), this.adSource = n.src, e.pause(), this.play().catch((t) => this.bus.emit("error", {
324
+ code: "AD_RESUME_FAILED",
325
+ message: String(t),
326
+ engine: e.id
327
+ })));
328
+ }),
329
+ e.on("durationchange", ({ duration: e, isLive: t = e === Infinity }) => {
330
+ this.state.update({
331
+ duration: e,
332
+ isLive: t,
333
+ isDvr: t && !!this.currentVideoElement?.seekable.length
334
+ });
335
+ }),
336
+ e.on("volumechange", ({ volume: e, muted: t }) => this.state.update({
337
+ volume: e,
338
+ muted: t
339
+ })),
340
+ e.on("ratechange", ({ playbackRate: e }) => this.state.update({ playbackRate: e })),
341
+ e.on("progress", ({ buffered: e }) => this.state.update({ buffered: e })),
342
+ e.on("qualitychange", ({ level: e }) => this.state.update({ selectedQuality: e })),
343
+ e.on("trackschange", ({ qualities: e, subtitles: t, audioTracks: n }) => {
344
+ this.state.update({
345
+ availableQualities: e,
346
+ availableSubtitles: t,
347
+ availableAudioTracks: n
348
+ });
349
+ }),
350
+ e.on("telemetry", (t) => {
351
+ this.bus.emit("telemetry", {
352
+ engine: e.id,
353
+ ...t || {}
354
+ });
355
+ }),
356
+ e.on("error", ({ error: e }) => {
357
+ if (e?.recoverable) {
358
+ this.state.update({ error: null }), this.bus.emit("error", e);
359
+ return;
360
+ }
361
+ this.state.update({
362
+ error: e,
363
+ status: "error",
364
+ buffering: !1
365
+ }), this.bus.emit("error", e);
366
+ }),
367
+ e.on("ready", () => {
368
+ this.state.update({
369
+ readyState: 4,
370
+ buffering: !1,
371
+ status: this.getState().paused ? "ready" : "playing"
372
+ }), this.bus.emit("ready");
373
+ }),
374
+ e.on("waiting", () => {
375
+ this.state.update({
376
+ readyState: 2,
377
+ buffering: !0,
378
+ status: "buffering"
379
+ }), this.bus.emit("waiting");
380
+ })
381
+ ];
382
+ }
383
+ unbindEngine() {
384
+ this.cleans.forEach((e) => e()), this.cleans = [];
385
+ }
386
+ async play() {
387
+ if (!this.currentEngine) throw Error("No engine loaded");
388
+ if (this.bus.emit("playback_requested"), this.adPlayback) return this.adPlayback;
389
+ if (this.adSource && this.currentVideoElement) {
390
+ let e = this.adSource;
391
+ this.adSource = void 0, this.bus.emit("ad:started");
392
+ let t = new AbortController();
393
+ return this.adController = t, this.adPlayback = s(this.currentVideoElement, e, t.signal).then(async (e) => {
394
+ t.signal.aborted || (this.bus.emit("ad:" + e), await this.playContent());
395
+ }).finally(() => {
396
+ this.adController === t && this.cancelAd();
397
+ }), this.adPlayback;
398
+ }
399
+ return this.playContent();
400
+ }
401
+ async playContent() {
402
+ let e = this.generation;
403
+ await this.currentEngine?.play(), e === this.generation && (this.state.update({
404
+ paused: !1,
405
+ ended: !1,
406
+ status: "playing"
407
+ }), this.bus.emit("playback_started"));
408
+ }
409
+ pause() {
410
+ this.cancelAd(), this.currentEngine?.pause();
411
+ let e = this.getState();
412
+ this.state.update({
413
+ paused: !0,
414
+ status: e.ended ? "ended" : "paused"
415
+ });
416
+ }
417
+ async destroy() {
418
+ ++this.generation, this.cancelAd(), this.unbindEngine(), this.currentEngine &&= (await this.currentEngine.destroy(), null), this.bus.clear();
419
+ }
420
+ seek(e) {
421
+ this.pendingSeekTime = e, this.bus.emit("seek_start", e), this.currentEngine?.seek(e);
422
+ }
423
+ setVolume(e) {
424
+ this.currentEngine?.setVolume(e);
425
+ }
426
+ setMuted(e) {
427
+ this.currentEngine?.setMuted(e);
428
+ }
429
+ setPlaybackRate(e) {
430
+ this.currentEngine?.setPlaybackRate(e);
431
+ }
432
+ setQuality(e) {
433
+ this.currentEngine?.setQuality(e), this.state.update({ selectedQuality: e });
434
+ }
435
+ setSubtitle(e) {
436
+ this.currentEngine?.setSubtitle(e), this.state.update({ selectedSubtitle: e });
437
+ }
438
+ setAudioTrack(e) {
439
+ this.currentEngine?.setAudioTrack(e), this.state.update({ selectedAudioTrack: e });
440
+ }
441
+ getState() {
442
+ return this.state.snapshot;
443
+ }
444
+ getStats() {
445
+ return this.state.snapshot;
446
+ }
447
+ on(e, t) {
448
+ return this.bus.on(e, t);
449
+ }
450
+ }, l = class {
451
+ id = "native";
452
+ isNative = !0;
453
+ video = null;
454
+ listeners = /* @__PURE__ */ new Map();
455
+ domListeners = [];
456
+ canPlayType(e) {
457
+ return [
458
+ "mp4",
459
+ "webm",
460
+ "ogg"
461
+ ].includes(e);
462
+ }
463
+ canPlaySource(e) {
464
+ let t = e.toLowerCase();
465
+ return t.includes(".mp4") || t.includes(".webm") || t.includes(".ogg");
466
+ }
467
+ attach(e) {
468
+ this.video = e, this.bindDomEvents();
469
+ }
470
+ bindDomEvents() {
471
+ if (!this.video) return;
472
+ this.unbindDomEvents();
473
+ let e = (e, t, n = () => void 0) => {
474
+ let r = (e) => {
475
+ let r = n(e);
476
+ this.emit(t, r);
477
+ };
478
+ this.video.addEventListener(e, r), this.domListeners.push({
479
+ event: e,
480
+ handler: r
481
+ });
482
+ };
483
+ e("play", "play"), e("pause", "pause"), e("playing", "playing"), e("ended", "ended"), e("waiting", "waiting"), e("seeked", "seeked", () => ({ currentTime: this.video.currentTime })), e("canplay", "ready"), e("timeupdate", "timeupdate", () => ({ currentTime: this.video.currentTime })), e("durationchange", "durationchange", () => ({ duration: this.video.duration })), e("volumechange", "volumechange", () => ({
484
+ volume: this.video.volume,
485
+ muted: this.video.muted
486
+ })), e("ratechange", "ratechange", () => ({ playbackRate: this.video.playbackRate })), e("progress", "progress", () => {
487
+ let e = [], t = this.video.buffered;
488
+ for (let n = 0; n < t.length; n++) e.push({
489
+ start: t.start(n),
490
+ end: t.end(n)
491
+ });
492
+ return { buffered: e };
493
+ }), e("error", "error", () => {
494
+ let e = this.video.error;
495
+ return { error: {
496
+ code: e?.code?.toString() || "UNKNOWN",
497
+ message: e?.message || "Media Error",
498
+ engine: this.id,
499
+ recoverable: !1,
500
+ originalError: e
501
+ } };
502
+ });
503
+ }
504
+ unbindDomEvents() {
505
+ this.video && (this.domListeners.forEach(({ event: e, handler: t }) => {
506
+ this.video.removeEventListener(e, t);
507
+ }), this.domListeners = []);
508
+ }
509
+ async load(e) {
510
+ if (!this.video) throw Error("Video element not attached");
511
+ this.video.poster = e.poster || "", this.video.src = e.src, this.video.load();
512
+ }
513
+ async play() {
514
+ await this.video?.play();
515
+ }
516
+ pause() {
517
+ this.video?.pause();
518
+ }
519
+ async destroy() {
520
+ this.unbindDomEvents(), this.video && (this.video.src = "", this.video.removeAttribute("src")), this.video = null, this.listeners.clear();
521
+ }
522
+ seek(e) {
523
+ this.video && (this.video.currentTime = e);
524
+ }
525
+ setVolume(e) {
526
+ this.video && (this.video.volume = e);
527
+ }
528
+ setMuted(e) {
529
+ this.video && (this.video.muted = e);
530
+ }
531
+ setPlaybackRate(e) {
532
+ this.video && (this.video.playbackRate = e);
533
+ }
534
+ setQuality(e) {
535
+ console.warn("Quality switching not supported in native engine");
536
+ }
537
+ setSubtitle(e) {}
538
+ setAudioTrack(e) {}
539
+ on(e, t) {
540
+ let n = e;
541
+ return this.listeners.has(n) || this.listeners.set(n, []), this.listeners.get(n).push(t), () => this.off(e, t);
542
+ }
543
+ off(e, t) {
544
+ let n = e, r = this.listeners.get(n);
545
+ if (!r) return;
546
+ let i = r.indexOf(t);
547
+ i > -1 && r.splice(i, 1);
548
+ }
549
+ emit(e, t) {
550
+ let n = e, r = this.listeners.get(n);
551
+ if (r) for (let e of [...r]) e(t);
552
+ }
553
+ }, u = {
554
+ play: "<svg viewBox=\"0 0 24 24\"><path d=\"M8 5v14l11-7z\"/></svg>",
555
+ replay: "<svg viewBox=\"0 0 24 24\"><path d=\"M12 5V2L7 7l5 5V9c3.31 0 6 2.69 6 6a6 6 0 0 1-10.24 4.24l-1.42 1.42A8 8 0 1 0 20 15c0-4.42-3.58-8-8-8z\"/></svg>",
556
+ pause: "<svg viewBox=\"0 0 24 24\"><path d=\"M6 19h4V5H6v14zm8-14v14h4V5h-4z\"/></svg>",
557
+ mute: "<svg viewBox=\"0 0 24 24\"><path d=\"M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z\"/></svg>",
558
+ volume: "<svg viewBox=\"0 0 24 24\"><path d=\"M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z\"/></svg>",
559
+ fullscreen: "<svg viewBox=\"0 0 24 24\"><path d=\"M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z\"/></svg>",
560
+ fullscreenExit: "<svg viewBox=\"0 0 24 24\"><path d=\"M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z\"/></svg>",
561
+ pip: "<svg viewBox=\"0 0 24 24\"><path d=\"M19 7H5v10h14V7zm2-2v14H3V5h18zm-9 7h7v5h-7v-5z\"/></svg>",
562
+ settings: "<svg viewBox=\"0 0 24 24\"><path d=\"M19.14,12.94c0.04-0.3,0.06-0.61,0.06-0.94c0-0.32-0.02-0.64-0.06-0.94l2.03-1.58c0.18-0.14,0.23-0.41,0.12-0.61 l-1.92-3.32c-0.12-0.22-0.37-0.29-0.59-0.22l-2.39,0.96c-0.5-0.38-1.03-0.7-1.62-0.94L14.4,2.81c-0.04-0.24-0.24-0.41-0.48-0.41 h-3.84c-0.24,0-0.43,0.17-0.47,0.41L9.25,5.35C8.66,5.59,8.12,5.92,7.63,6.29L5.24,5.33c-0.22-0.08-0.47,0-0.59,0.22L2.73,8.87 C2.62,9.08,2.66,9.34,2.86,9.48l2.03,1.58C4.84,11.36,4.8,11.69,4.8,12s0.02,0.64,0.06,0.94l-2.03,1.58 c-0.18,0.14-0.23,0.41-0.12,0.61l1.92,3.32c0.12,0.22,0.37,0.29,0.59,0.22l2.39-0.96c0.5,0.38,1.03,0.7,1.62,0.94l0.36,2.54 c0.05,0.24,0.24,0.41,0.48,0.41h3.84c0.24,0,0.43-0.17,0.47-0.41l0.36-2.54c0.59-0.24,1.13-0.56,1.62-0.94l2.39,0.96 c0.22,0.08,0.47,0,0.59-0.22l1.92-3.32c0.12-0.22,0.07-0.49-0.12-0.61L19.14,12.94z M12,15.6c-1.98,0-3.6-1.62-3.6-3.6 s1.62-3.6,3.6-3.6s3.6,1.62,3.6,3.6S13.98,15.6,12,15.6z\"/></svg>"
563
+ }, d = class {
564
+ player;
565
+ target;
566
+ handler;
567
+ constructor(e, t) {
568
+ this.player = e, this.target = t, this.handler = this.handleKey.bind(this), this.target.addEventListener("keydown", this.handler), this.target.tabIndex = 0;
569
+ }
570
+ handleKey(e) {
571
+ let t = document.activeElement?.tagName.toLowerCase();
572
+ if (e.defaultPrevented || t === "input" || t === "textarea" || t === "button" && e.key === " ") return;
573
+ let n = !1;
574
+ switch (e.key) {
575
+ case " ":
576
+ case "k":
577
+ case "K":
578
+ n = !0, this.togglePlay();
579
+ break;
580
+ case "ArrowLeft":
581
+ n = !0, this.seekRelative(-5);
582
+ break;
583
+ case "ArrowRight":
584
+ n = !0, this.seekRelative(5);
585
+ break;
586
+ case "m":
587
+ case "M":
588
+ n = !0, this.toggleMute();
589
+ break;
590
+ case "f":
591
+ case "F":
592
+ n = !0, this.toggleFullscreen();
593
+ break;
594
+ case "c":
595
+ case "C":
596
+ n = !0, this.toggleCaptions();
597
+ break;
598
+ }
599
+ n && (e.preventDefault(), e.stopPropagation());
600
+ }
601
+ togglePlay() {
602
+ this.player.getState().paused ? this.player.play().catch(() => {}) : this.player.pause();
603
+ }
604
+ seekRelative(e) {
605
+ let t = this.player.getState();
606
+ this.player.seek(Math.max(0, Math.min(t.duration || 0, t.currentTime + e)));
607
+ }
608
+ toggleMute() {
609
+ let e = this.player.getState();
610
+ this.player.setMuted(!e.muted);
611
+ }
612
+ toggleFullscreen() {
613
+ document.fullscreenElement ? document.exitFullscreen().catch(() => {}) : this.target.requestFullscreen().catch(() => {});
614
+ }
615
+ toggleCaptions() {
616
+ this.player.getState().selectedSubtitle ? this.player.setSubtitle(null) : this.player.setSubtitle("0");
617
+ }
618
+ destroy() {
619
+ this.target.removeEventListener("keydown", this.handler);
620
+ }
621
+ }, f = class {
622
+ static makeClickable(e, t) {
623
+ e.setAttribute("role", "button"), e.tabIndex = 0, e.addEventListener("click", t), e.addEventListener("keydown", (e) => {
624
+ (e.key === "Enter" || e.key === " ") && (e.preventDefault(), t());
625
+ });
626
+ }
627
+ }, p = {
628
+ colors: {
629
+ background: "#09090b",
630
+ surface: "rgba(9, 9, 11, 0.7)",
631
+ surfaceElevated: "rgba(39, 39, 42, 0.8)",
632
+ overlayGradientEnd: "rgba(0, 0, 0, 0.7)",
633
+ overlayError: "rgba(0, 0, 0, 0.8)",
634
+ menuBackground: "rgba(15, 15, 15, 0.9)",
635
+ menuBorder: "rgba(255, 255, 255, 0.1)",
636
+ menuHover: "rgba(255, 255, 255, 0.1)",
637
+ menuActive: "rgba(59, 130, 246, 0.1)",
638
+ buffered: "rgba(255, 255, 255, 0.4)",
639
+ textPrimary: "#fafafa",
640
+ textSecondary: "#a1a1aa",
641
+ brandPrimary: "#3b82f6",
642
+ danger: "#ef4444",
643
+ focus: "rgba(59, 130, 246, 0.5)"
644
+ },
645
+ radius: {
646
+ sm: "4px",
647
+ md: "8px",
648
+ lg: "12px",
649
+ pill: "9999px"
650
+ },
651
+ spacing: {
652
+ xs: "4px",
653
+ sm: "8px",
654
+ md: "16px",
655
+ lg: "24px"
656
+ },
657
+ typography: {
658
+ fontFamily: "\"Inter\", \"Roboto\", \"Outfit\", sans-serif",
659
+ fontSizeSm: "12px",
660
+ fontSizeMd: "14px",
661
+ fontSizeLg: "16px",
662
+ fontWeightMedium: "500",
663
+ fontWeightBold: "700"
664
+ },
665
+ control: {
666
+ height: "40px",
667
+ iconSize: "24px"
668
+ }
669
+ }, m = {
670
+ colors: {
671
+ background: "#ffffff",
672
+ surface: "rgba(255, 255, 255, 0.8)",
673
+ surfaceElevated: "rgba(244, 244, 245, 0.9)",
674
+ overlayGradientEnd: "rgba(0, 0, 0, 0.35)",
675
+ overlayError: "rgba(255, 255, 255, 0.95)",
676
+ menuBackground: "rgba(255, 255, 255, 0.95)",
677
+ menuBorder: "rgba(9, 9, 11, 0.1)",
678
+ menuHover: "rgba(9, 9, 11, 0.06)",
679
+ menuActive: "rgba(37, 99, 235, 0.12)",
680
+ buffered: "rgba(9, 9, 11, 0.25)",
681
+ textPrimary: "#09090b",
682
+ textSecondary: "#71717a",
683
+ brandPrimary: "#2563eb",
684
+ danger: "#dc2626",
685
+ focus: "rgba(37, 99, 235, 0.4)"
686
+ },
687
+ radius: p.radius,
688
+ spacing: p.spacing,
689
+ typography: p.typography,
690
+ control: p.control
691
+ };
692
+ function h(e, t) {
693
+ if (!t) return e;
694
+ let n = JSON.parse(JSON.stringify(e));
695
+ for (let e of Object.keys(t)) typeof t[e] == "object" ? n[e] = {
696
+ ...n[e],
697
+ ...t[e]
698
+ } : n[e] = t[e];
699
+ return n;
700
+ }
701
+ function g(e, t = "flux-player") {
702
+ let n = "";
703
+ for (let [r, i] of Object.entries(e)) if (typeof i == "object") for (let [e, a] of Object.entries(i)) n += `--${t}-${r}-${e}: ${a};\n`;
704
+ return n;
705
+ }
706
+ function _(e, t) {
707
+ let n = p;
708
+ typeof t == "string" ? t === "light" && (n = m) : n = h(t.base === "light" ? m : p, t), g(n), e.setAttribute("style", e.getAttribute("style") || "");
709
+ for (let [t, r] of Object.entries(n)) if (typeof r == "object") for (let [n, i] of Object.entries(r)) e.style.setProperty(`--flux-player-${t}-${n}`, i);
710
+ }
711
+ //#endregion
712
+ //#region packages/ui-default/dist/src/DefaultUI.js
713
+ var v = class {
714
+ player;
715
+ container;
716
+ videoEl;
717
+ wrapper;
718
+ overlay;
719
+ spinner;
720
+ bigPlay;
721
+ replayBtn;
722
+ errorPanel;
723
+ errorTextEl;
724
+ extraButtons;
725
+ playBtn;
726
+ muteBtn;
727
+ pipBtn;
728
+ fullscreenBtn;
729
+ timeDisplay;
730
+ liveBadge;
731
+ progressFill;
732
+ bufferedFill;
733
+ markerSignature = "";
734
+ timeline;
735
+ timelineThumbnailPreview;
736
+ timelineThumbnailImage;
737
+ volumeSlider;
738
+ settingsBtn;
739
+ settingsMenu;
740
+ menuOpen = !1;
741
+ uiPaused = !0;
742
+ isDragging = !1;
743
+ uiConfig;
744
+ iconOverrides;
745
+ renderedIcons = /* @__PURE__ */ new Map();
746
+ cleans = [];
747
+ domCleans = [];
748
+ idleTimeout;
749
+ fullscreenChangeHandler = null;
750
+ pipSupported = !1;
751
+ controlElements = [];
752
+ controlFocusIndex = 0;
753
+ menuItems = [];
754
+ menuFocusIndex = 0;
755
+ thumbnailVttUrl = null;
756
+ thumbnailCues = [];
757
+ thumbnailFetchAbort = null;
758
+ subtitleDisplay;
759
+ subtitleTrackListeners = /* @__PURE__ */ new Map();
760
+ activeSourceToken = null;
761
+ resetUiForSourceChange(e) {
762
+ let t = `${e.source?.src || ""}|${this.resolveThumbnailVttUrl(e) || ""}`;
763
+ if (t !== this.activeSourceToken) {
764
+ this.activeSourceToken = t, this.thumbnailFetchAbort?.abort(), this.thumbnailFetchAbort = null, this.thumbnailVttUrl = null, this.thumbnailCues = [], this.hideTimelineThumbnail(), this.timelineThumbnailImage.removeAttribute("src"), this.subtitleDisplay.innerHTML = "";
765
+ for (let [e, t] of this.subtitleTrackListeners.entries()) e.removeEventListener("cuechange", t);
766
+ this.subtitleTrackListeners.clear();
767
+ for (let e = 0; e < this.videoEl.textTracks.length; e++) this.videoEl.textTracks[e].mode = "disabled", this.bindSubtitleTrack(this.videoEl.textTracks[e]);
768
+ }
769
+ }
770
+ constructor(e, t, n = {}) {
771
+ if (this.player = e, this.uiConfig = n, this.iconOverrides = { ...n.icons }, typeof t == "string") {
772
+ let e = document.querySelector(t);
773
+ if (!e) throw Error(`Target ${t} not found`);
774
+ this.container = e;
775
+ } else this.container = t;
776
+ this.videoEl = document.createElement("video"), this.videoEl.className = "flux-player-video", this.player.attachVideo(this.videoEl), this.render(), this.bindEvents(), this.updateState(this.player.getState());
777
+ }
778
+ render() {
779
+ this.container.innerHTML = "", this.wrapper = document.createElement("div"), this.wrapper.className = "flux-player-wrapper", this.wrapper.appendChild(this.videoEl), this.spinner = document.createElement("div"), this.spinner.className = "flux-player-spinner", this.wrapper.appendChild(this.spinner), this.bigPlay = document.createElement("div"), this.bigPlay.className = "flux-player-big-play", this.bigPlay.setAttribute("aria-label", "Play"), this.renderIcon(this.bigPlay, "play"), this.wrapper.appendChild(this.bigPlay), f.makeClickable(this.bigPlay, () => this.handlePrimaryAction()), this.replayBtn = document.createElement("div"), this.replayBtn.className = "flux-player-replay flux-hidden", this.replayBtn.setAttribute("aria-label", "Replay"), this.renderIcon(this.replayBtn, "replay"), this.wrapper.appendChild(this.replayBtn), f.makeClickable(this.replayBtn, () => this.replay()), this.errorPanel = document.createElement("div"), this.errorPanel.className = "flux-player-error flux-hidden", this.errorPanel.innerHTML = "<div class=\"flux-player-error-title\">Playback Error</div>", this.errorTextEl = document.createElement("div"), this.errorTextEl.className = "flux-player-error-text", this.errorPanel.appendChild(this.errorTextEl), this.wrapper.appendChild(this.errorPanel), this.overlay = document.createElement("div"), this.overlay.className = "flux-player-overlay";
780
+ let e = document.createElement("div");
781
+ e.className = "flux-player-controls", this.timeline = document.createElement("div"), this.timeline.className = "flux-player-timeline", this.timeline.setAttribute("role", "slider"), this.timeline.setAttribute("aria-label", "Seek timeline"), this.timeline.tabIndex = -1, this.bufferedFill = document.createElement("div"), this.bufferedFill.className = "flux-player-timeline-buffered", this.progressFill = document.createElement("div"), this.progressFill.className = "flux-player-timeline-progress", this.timelineThumbnailPreview = document.createElement("div"), this.timelineThumbnailPreview.className = "flux-player-thumbnail-preview flux-hidden", this.timelineThumbnailImage = document.createElement("img"), this.timelineThumbnailImage.className = "flux-player-thumbnail-image", this.timelineThumbnailImage.alt = "", this.timelineThumbnailImage.setAttribute("aria-hidden", "true"), this.timelineThumbnailImage.onload = () => {
782
+ this.thumbnailVttUrl && this.timelineThumbnailPreview.classList.remove("flux-hidden");
783
+ }, this.timelineThumbnailImage.onerror = () => {
784
+ this.hideTimelineThumbnail();
785
+ }, this.timelineThumbnailPreview.appendChild(this.timelineThumbnailImage), this.timeline.appendChild(this.bufferedFill), this.timeline.appendChild(this.progressFill), this.timeline.appendChild(this.timelineThumbnailPreview), e.appendChild(this.timeline);
786
+ let t = document.createElement("div");
787
+ t.className = "flux-player-toolbar";
788
+ let n = document.createElement("div");
789
+ n.className = "flux-player-toolbar-group", this.playBtn = this.createBtn("play", "play", "Play"), this.muteBtn = this.createBtn("mute", "volume", "Mute"), this.volumeSlider = document.createElement("input"), this.volumeSlider.type = "range", this.volumeSlider.min = "0", this.volumeSlider.max = "1", this.volumeSlider.step = "0.05", this.volumeSlider.className = "flux-player-volume-slider", this.volumeSlider.setAttribute("role", "slider"), this.volumeSlider.setAttribute("aria-label", "Volume");
790
+ let r = document.createElement("div");
791
+ r.className = "flux-player-volume-container", r.appendChild(this.muteBtn), r.appendChild(this.volumeSlider), this.timeDisplay = document.createElement("div"), this.timeDisplay.className = "flux-player-time", this.timeDisplay.innerText = "0:00 / 0:00", this.timeDisplay.setAttribute("aria-live", "polite"), this.timeDisplay.setAttribute("aria-atomic", "true"), n.appendChild(this.playBtn), n.appendChild(r), n.appendChild(this.timeDisplay);
792
+ let i = document.createElement("div");
793
+ i.className = "flux-player-toolbar-group", this.liveBadge = document.createElement("div"), this.liveBadge.className = "flux-player-live-badge flux-hidden", this.liveBadge.innerHTML = "<span></span>LIVE", this.liveBadge.setAttribute("aria-live", "polite"), this.liveBadge.setAttribute("aria-label", "Live stream"), this.pipBtn = this.createBtn("pip", "pip", "Picture in Picture"), this.fullscreenBtn = this.createBtn("fullscreen", "fullscreen", "Fullscreen"), this.settingsBtn = this.createBtn("settings", "settings", "Settings"), this.settingsBtn.setAttribute("aria-haspopup", "menu"), this.settingsBtn.setAttribute("aria-expanded", "false"), i.appendChild(this.liveBadge), this.extraButtons = document.createElement("div"), this.extraButtons.className = "flux-player-toolbar-group", i.appendChild(this.extraButtons), i.appendChild(this.pipBtn), i.appendChild(this.settingsBtn), i.appendChild(this.fullscreenBtn), t.appendChild(n), t.appendChild(i), e.appendChild(t), this.settingsMenu = document.createElement("div"), this.settingsMenu.className = "flux-player-settings-menu flux-hidden", this.settingsMenu.setAttribute("role", "menu"), this.settingsMenu.setAttribute("aria-label", "Player settings"), e.appendChild(this.settingsMenu), this.overlay.appendChild(e), this.subtitleDisplay = document.createElement("div"), this.subtitleDisplay.className = "flux-player-subtitles flux-subs-raised", this.wrapper.appendChild(this.subtitleDisplay), this.wrapper.appendChild(this.overlay), this.container.appendChild(this.wrapper), this.setToolbar(this.uiConfig.toolbar ?? {}), _(this.wrapper, "dark");
794
+ }
795
+ setControlsIdle(e) {
796
+ e ? (this.overlay.classList.add("flux-idle"), this.subtitleDisplay.classList.remove("flux-subs-raised")) : (this.overlay.classList.remove("flux-idle"), this.subtitleDisplay.classList.add("flux-subs-raised"));
797
+ }
798
+ setIcons(e) {
799
+ this.iconOverrides = { ...e };
800
+ for (let [e, { name: t }] of this.renderedIcons) this.renderIcon(e, t);
801
+ }
802
+ renderIcon(e, t) {
803
+ let n = this.iconOverrides[t], r = this.renderedIcons.get(e);
804
+ if (r?.name === t && r.url === n) return;
805
+ if (this.renderedIcons.set(e, {
806
+ name: t,
807
+ url: n
808
+ }), !n) {
809
+ e.innerHTML = u[t];
810
+ return;
811
+ }
812
+ let i = document.createElement("img");
813
+ i.alt = "", i.draggable = !1, i.onerror = () => {
814
+ i.parentElement === e && (e.innerHTML = u[t]);
815
+ }, i.src = n, e.replaceChildren(i);
816
+ }
817
+ createBtn(e, t, n) {
818
+ let r = document.createElement("button");
819
+ return r.className = `flux-player-icon-btn flux-btn-${e}`, this.renderIcon(r, t), r.setAttribute("aria-label", n), r;
820
+ }
821
+ formatTime(e) {
822
+ if (isNaN(e)) return "0:00";
823
+ let t = Math.floor(e / 60), n = Math.floor(e % 60);
824
+ return `${t}:${n < 10 ? "0" : ""}${n}`;
825
+ }
826
+ bindEvents() {
827
+ this.cleans.push(this.player.on("state:change", (e) => this.updateState(e)));
828
+ let e = (e) => {
829
+ e && e.stopPropagation(), this.handlePrimaryAction();
830
+ };
831
+ this.listen(this.playBtn, "click", e), this.listen(this.bigPlay, "click", e), this.listen(this.videoEl, "click", e), this.listen(this.replayBtn, "click", () => this.replay()), this.listen(this.muteBtn, "click", () => {
832
+ this.player.setMuted(!this.player.getState().muted);
833
+ }), this.listen(this.volumeSlider, "input", (e) => {
834
+ this.player.setVolume(parseFloat(e.target.value));
835
+ }), this.updatePipAvailability(), this.setupControlRovingTabindex(), this.listen(this.pipBtn, "click", async () => {
836
+ await this.togglePip();
837
+ }), this.listen(this.videoEl, "enterpictureinpicture", () => {
838
+ this.pipBtn.classList.add("flux-active"), this.pipBtn.setAttribute("aria-label", "Exit Picture in Picture");
839
+ }), this.listen(this.videoEl, "leavepictureinpicture", () => {
840
+ this.pipBtn.classList.remove("flux-active"), this.pipBtn.setAttribute("aria-label", "Picture in Picture");
841
+ }), this.listen(this.fullscreenBtn, "click", () => {
842
+ document.fullscreenElement ? document.exitFullscreen().catch(() => {}) : this.wrapper.requestFullscreen().catch(() => {});
843
+ }), this.fullscreenChangeHandler = () => {
844
+ let e = document.fullscreenElement === this.wrapper;
845
+ this.renderIcon(this.fullscreenBtn, e ? "fullscreenExit" : "fullscreen"), this.fullscreenBtn.setAttribute("aria-label", e ? "Exit fullscreen" : "Fullscreen");
846
+ }, this.listen(document, "fullscreenchange", this.fullscreenChangeHandler);
847
+ let t = (e) => {
848
+ let t = this.getTimelineHoverData(e.clientX);
849
+ if (!t) return;
850
+ let { position: n, duration: r, targetTime: i } = t;
851
+ this.progressFill.style.width = `${n * 100}%`, this.timeDisplay.innerText = `${this.formatTime(i)} / ${this.formatTime(r)}`, this.renderTimelineThumbnail(e), (this.uiConfig.seekOnDrag && e.type !== "mouseup" || e.type === "mouseup" || e.type === "click") && this.player.seek(i);
852
+ }, n = (e) => {
853
+ this.isDragging && t(e);
854
+ }, r = (e) => {
855
+ this.isDragging && (this.isDragging = !1, this.wrapper.classList.remove("flux-dragging"), t(e), this.renderTimelineThumbnail(e), document.removeEventListener("mousemove", n), document.removeEventListener("mouseup", r));
856
+ };
857
+ this.listen(this.timeline, "mousedown", (e) => {
858
+ let i = e;
859
+ this.isDragging = !0, this.wrapper.classList.add("flux-dragging"), t(i), this.listen(document, "mousemove", n, !0), this.listen(document, "mouseup", r, !0);
860
+ }), this.listen(this.timeline, "click", (e) => {
861
+ this.isDragging || t(e);
862
+ }), this.listen(this.timeline, "mousemove", (e) => {
863
+ this.renderTimelineThumbnail(e);
864
+ }), this.listen(this.timeline, "mouseenter", (e) => {
865
+ this.renderTimelineThumbnail(e);
866
+ }), this.listen(this.timeline, "mouseleave", () => {
867
+ this.hideTimelineThumbnail();
868
+ }), this.listen(this.timeline, "keydown", (e) => {
869
+ let t = e;
870
+ if (t.key === "ArrowLeft" && (t.preventDefault(), this.player.seek(Math.max(0, this.player.getState().currentTime - 5))), t.key === "ArrowRight") {
871
+ t.preventDefault();
872
+ let e = this.player.getState().duration, n = Number.isFinite(e) ? e : this.player.getState().currentTime + 5;
873
+ this.player.seek(Math.min(n, this.player.getState().currentTime + 5));
874
+ }
875
+ }), this.listen(this.settingsBtn, "click", (e) => {
876
+ e.stopPropagation(), this.toggleMenu();
877
+ }), this.listen(this.wrapper, "click", () => {
878
+ this.menuOpen && this.toggleMenu(!1);
879
+ }), this.listen(this.settingsMenu, "click", (e) => e.stopPropagation()), this.listen(this.settingsMenu, "keydown", (e) => this.handleSettingsKeyDown(e)), this.listen(this.wrapper, "keydown", (e) => this.handleControlBarKeyDown(e));
880
+ let i = () => {
881
+ this.setControlsIdle(!1), clearTimeout(this.idleTimeout), !this.player.getState().paused && !this.menuOpen && (this.idleTimeout = setTimeout(() => {
882
+ this.setControlsIdle(!0);
883
+ }, 3e3));
884
+ };
885
+ this.listen(this.wrapper, "mousemove", i), this.listen(this.wrapper, "touchstart", i);
886
+ for (let e of Array.from(this.videoEl.textTracks)) this.bindSubtitleTrack(e);
887
+ let a = (e) => this.bindSubtitleTrack(e.track);
888
+ this.videoEl.textTracks.addEventListener?.("addtrack", a), this.domCleans.push(() => this.videoEl.textTracks.removeEventListener?.("addtrack", a)), this.listen(this.wrapper, "mouseleave", () => {
889
+ !this.player.getState().paused && !this.menuOpen && this.setControlsIdle(!0);
890
+ });
891
+ }
892
+ setToolbar(e) {
893
+ let t = new Set(e.hidden), n = {
894
+ play: this.playBtn,
895
+ volume: this.volumeSlider.parentElement,
896
+ settings: this.settingsBtn,
897
+ pip: this.pipBtn,
898
+ fullscreen: this.fullscreenBtn
899
+ };
900
+ for (let e of Object.keys(n)) n[e].classList.toggle("flux-hidden", t.has(e));
901
+ t.has("settings") && this.menuOpen && this.toggleMenu(!1), this.extraButtons.replaceChildren(...(e.buttons ?? []).map(({ label: e, onClick: t }) => {
902
+ let n = document.createElement("button");
903
+ return n.type = "button", n.className = "flux-player-icon-btn", n.textContent = e, n.onclick = () => t(this.player), n;
904
+ })), this.extraButtons.style.display = this.extraButtons.childElementCount ? "" : "none", this.setupControlRovingTabindex();
905
+ }
906
+ setupControlRovingTabindex() {
907
+ this.controlElements = [
908
+ this.playBtn,
909
+ this.muteBtn,
910
+ this.volumeSlider,
911
+ this.timeline,
912
+ ...Array.from(this.extraButtons.querySelectorAll("button")),
913
+ this.settingsBtn,
914
+ this.pipBtn,
915
+ this.fullscreenBtn
916
+ ].filter((e) => !e.closest(".flux-hidden") && !e.hasAttribute("disabled")), this.controlElements.forEach((e, t) => {
917
+ e.tabIndex = t === 0 ? 0 : -1;
918
+ });
919
+ }
920
+ moveControlFocus(e) {
921
+ this.controlElements.length !== 0 && (this.controlFocusIndex = (e + this.controlElements.length) % this.controlElements.length, this.controlElements.forEach((e, t) => {
922
+ e.tabIndex = t === this.controlFocusIndex ? 0 : -1;
923
+ }), this.controlElements[this.controlFocusIndex].focus());
924
+ }
925
+ handleControlBarKeyDown(e) {
926
+ if (this.menuOpen) return;
927
+ let t = this.controlElements.findIndex((e) => e === document.activeElement);
928
+ if (t !== -1) {
929
+ if (e.key === "ArrowRight") {
930
+ e.preventDefault(), this.moveControlFocus(t + 1);
931
+ return;
932
+ }
933
+ if (e.key === "ArrowLeft") {
934
+ e.preventDefault(), this.moveControlFocus(t - 1);
935
+ return;
936
+ }
937
+ if (e.key === "Home") {
938
+ e.preventDefault(), this.moveControlFocus(0);
939
+ return;
940
+ }
941
+ e.key === "End" && (e.preventDefault(), this.moveControlFocus(this.controlElements.length - 1));
942
+ }
943
+ }
944
+ updateMenuA11yState() {
945
+ this.menuItems = Array.from(this.settingsMenu.querySelectorAll(".flux-player-menu-item")), this.menuItems.forEach((e, t) => {
946
+ e.setAttribute("role", "menuitemradio"), e.setAttribute("tabindex", t === this.menuFocusIndex ? "0" : "-1"), e.setAttribute("aria-checked", e.classList.contains("flux-active") ? "true" : "false");
947
+ });
948
+ }
949
+ focusMenuItem(e) {
950
+ this.menuItems.length !== 0 && (this.menuFocusIndex = (e + this.menuItems.length) % this.menuItems.length, this.menuItems.forEach((e, t) => {
951
+ e.tabIndex = t === this.menuFocusIndex ? 0 : -1;
952
+ }), this.menuItems[this.menuFocusIndex].focus());
953
+ }
954
+ handleSettingsKeyDown(e) {
955
+ if (!(!this.menuOpen || this.menuItems.length === 0)) {
956
+ if (e.key === "ArrowDown") {
957
+ e.preventDefault(), this.focusMenuItem(this.menuFocusIndex + 1);
958
+ return;
959
+ }
960
+ if (e.key === "ArrowUp") {
961
+ e.preventDefault(), this.focusMenuItem(this.menuFocusIndex - 1);
962
+ return;
963
+ }
964
+ if (e.key === "Home") {
965
+ e.preventDefault(), this.focusMenuItem(0);
966
+ return;
967
+ }
968
+ if (e.key === "End") {
969
+ e.preventDefault(), this.focusMenuItem(this.menuItems.length - 1);
970
+ return;
971
+ }
972
+ if (e.key === "Tab") {
973
+ e.preventDefault();
974
+ let t = e.shiftKey ? -1 : 1;
975
+ this.focusMenuItem(this.menuFocusIndex + t);
976
+ return;
977
+ }
978
+ if (e.key === "Escape") {
979
+ e.preventDefault(), this.toggleMenu(!1), this.settingsBtn.focus();
980
+ return;
981
+ }
982
+ (e.key === "Enter" || e.key === " ") && (e.preventDefault(), this.menuItems[this.menuFocusIndex]?.click());
983
+ }
984
+ }
985
+ updatePipAvailability() {
986
+ let e = document, t = this.videoEl, n = !!(e.pictureInPictureEnabled && this.videoEl.requestPictureInPicture), r = !!t.webkitSupportsPresentationMode?.("picture-in-picture");
987
+ this.pipSupported = n || r, this.pipSupported ? (this.pipBtn.removeAttribute("disabled"), this.pipBtn.removeAttribute("aria-disabled"), this.pipBtn.removeAttribute("title"), this.pipBtn.classList.remove("flux-disabled")) : (this.pipBtn.setAttribute("disabled", "true"), this.pipBtn.setAttribute("aria-disabled", "true"), this.pipBtn.setAttribute("title", "Picture in Picture not supported in this browser"), this.pipBtn.classList.add("flux-disabled"));
988
+ }
989
+ async togglePip() {
990
+ if (!this.pipSupported) return;
991
+ let e = document, t = this.videoEl;
992
+ if (e.pictureInPictureEnabled && this.videoEl.requestPictureInPicture) {
993
+ if (e.pictureInPictureElement === this.videoEl && e.exitPictureInPicture) {
994
+ await e.exitPictureInPicture().catch(() => {});
995
+ return;
996
+ }
997
+ await this.videoEl.requestPictureInPicture().catch(() => {});
998
+ return;
999
+ }
1000
+ if (t.webkitSupportsPresentationMode?.("picture-in-picture") && t.webkitSetPresentationMode) {
1001
+ let e = t.webkitPresentationMode === "picture-in-picture" ? "inline" : "picture-in-picture";
1002
+ try {
1003
+ t.webkitSetPresentationMode(e), this.pipBtn.classList.toggle("flux-active", e === "picture-in-picture");
1004
+ } catch {}
1005
+ }
1006
+ }
1007
+ listen(e, t, n, r = !1) {
1008
+ if (e.addEventListener(t, n), this.domCleans.push(() => {
1009
+ e.removeEventListener(t, n);
1010
+ }), r) {
1011
+ let e = this.domCleans[this.domCleans.length - 1];
1012
+ this.domCleans[this.domCleans.length - 1] = () => {
1013
+ e();
1014
+ };
1015
+ }
1016
+ }
1017
+ getTimelineHoverData(e) {
1018
+ let t = this.timeline.getBoundingClientRect();
1019
+ if (t.width <= 0) return null;
1020
+ let n = (e - t.left) / t.width;
1021
+ n = Math.max(0, Math.min(1, n));
1022
+ let r = this.player.getState().duration || 0;
1023
+ return {
1024
+ position: n,
1025
+ duration: r,
1026
+ targetTime: n * r
1027
+ };
1028
+ }
1029
+ resolveThumbnailVttUrl(e) {
1030
+ let t = typeof this.uiConfig?.thumbnailVtt == "string" ? this.uiConfig.thumbnailVtt.trim() : "";
1031
+ if (t.length > 0) return t;
1032
+ let n = e.source?.thumbnailVtt?.trim() || "";
1033
+ return n.length > 0 ? n : null;
1034
+ }
1035
+ async syncThumbnailTrack(e) {
1036
+ let t = this.resolveThumbnailVttUrl(e);
1037
+ if (t !== this.thumbnailVttUrl && (this.thumbnailVttUrl = t, this.thumbnailCues = [], this.hideTimelineThumbnail(), t)) {
1038
+ this.thumbnailFetchAbort?.abort(), this.thumbnailFetchAbort = new AbortController();
1039
+ try {
1040
+ let e = await fetch(t, { signal: this.thumbnailFetchAbort.signal });
1041
+ if (!e.ok) throw Error(`Failed to fetch thumbnail VTT: ${e.status}`);
1042
+ let n = await e.text();
1043
+ this.thumbnailCues = this.parseThumbnailVtt(n, t);
1044
+ } catch (e) {
1045
+ e.name !== "AbortError" && console.warn("[DefaultUI] Unable to load thumbnail VTT", e), this.thumbnailCues = [];
1046
+ }
1047
+ }
1048
+ }
1049
+ parseThumbnailVtt(e, t) {
1050
+ let n = e.split(/\r?\n/), r = [], i = 0;
1051
+ for (; i < n.length;) {
1052
+ let e = n[i].trim();
1053
+ if (!e || e.toUpperCase() === "WEBVTT" || e.startsWith("NOTE")) {
1054
+ i += 1;
1055
+ continue;
1056
+ }
1057
+ let a = e;
1058
+ if (!a.includes("-->") && i + 1 < n.length && (a = n[i + 1].trim(), i += 1), !a.includes("-->")) {
1059
+ i += 1;
1060
+ continue;
1061
+ }
1062
+ let [o, s] = a.split("-->").map((e) => e.trim()), c = s.split(/\s+/)[0], l = this.parseVttTime(o), u = this.parseVttTime(c);
1063
+ if (!Number.isFinite(l) || !Number.isFinite(u) || u <= l) {
1064
+ i += 1;
1065
+ continue;
1066
+ }
1067
+ i += 1;
1068
+ let d = [];
1069
+ for (; i < n.length && n[i].trim() !== "";) d.push(n[i].trim()), i += 1;
1070
+ let f = d.find((e) => this.isThumbnailPayload(e)) || "", p = this.parseThumbnailCuePayload(f, t);
1071
+ for (p && r.push({
1072
+ start: l,
1073
+ end: u,
1074
+ ...p
1075
+ }); i < n.length && n[i].trim() === "";) i += 1;
1076
+ }
1077
+ return r;
1078
+ }
1079
+ parseVttTime(e) {
1080
+ let t = e.split(":");
1081
+ if (t.length < 2 || t.length > 3) return NaN;
1082
+ let n = Number(t[t.length - 1]), r = Number(t[t.length - 2]), i = t.length === 3 ? Number(t[0]) : 0;
1083
+ return !Number.isFinite(i) || !Number.isFinite(r) || !Number.isFinite(n) ? NaN : i * 3600 + r * 60 + n;
1084
+ }
1085
+ parseThumbnailCuePayload(e, t) {
1086
+ if (!e) return null;
1087
+ let [n, r = ""] = e.split("#", 2);
1088
+ if (!n) return null;
1089
+ let i = n;
1090
+ try {
1091
+ i = new URL(n, t).toString();
1092
+ } catch {
1093
+ i = n;
1094
+ }
1095
+ let a = null, o = null, s = null, c = null, l = r.match(/xywh=(\d+),(\d+),(\d+),(\d+)/i);
1096
+ return l && (a = Number(l[1]), o = Number(l[2]), s = Number(l[3]), c = Number(l[4])), {
1097
+ imageUrl: i,
1098
+ x: a,
1099
+ y: o,
1100
+ w: s,
1101
+ h: c
1102
+ };
1103
+ }
1104
+ isThumbnailPayload(e) {
1105
+ let t = e.trim();
1106
+ return t ? /^(https?:\/\/|\/|\.\/|\.\.\/|[^\s]+\.(jpg|jpeg|png|webp|avif|gif|svg))(#xywh=\d+,\d+,\d+,\d+)?(\?.*)?$/i.test(t) : !1;
1107
+ }
1108
+ findThumbnailCue(e) {
1109
+ if (this.thumbnailCues.length === 0) return null;
1110
+ for (let t of this.thumbnailCues) if (e >= t.start && e < t.end) return t;
1111
+ let t = this.thumbnailCues[this.thumbnailCues.length - 1];
1112
+ return e >= t.start ? t : null;
1113
+ }
1114
+ renderTimelineThumbnail(e) {
1115
+ if (!this.thumbnailVttUrl || this.thumbnailCues.length === 0) {
1116
+ this.hideTimelineThumbnail();
1117
+ return;
1118
+ }
1119
+ let t = this.player.getState();
1120
+ if (t.isLive || !Number.isFinite(t.duration) || t.duration <= 0) {
1121
+ this.hideTimelineThumbnail();
1122
+ return;
1123
+ }
1124
+ let n = this.getTimelineHoverData(e.clientX);
1125
+ if (!n) {
1126
+ this.hideTimelineThumbnail();
1127
+ return;
1128
+ }
1129
+ let r = this.findThumbnailCue(n.targetTime);
1130
+ if (!r) {
1131
+ this.hideTimelineThumbnail();
1132
+ return;
1133
+ }
1134
+ let i = r.x !== null && r.y !== null && r.w !== null && r.h !== null;
1135
+ this.timelineThumbnailImage.style.objectFit = i ? "none" : "cover", i ? (this.timelineThumbnailImage.style.objectPosition = `-${r.x}px -${r.y}px`, this.timelineThumbnailImage.style.width = `${r.w}px`, this.timelineThumbnailImage.style.height = `${r.h}px`) : (this.timelineThumbnailImage.style.objectPosition = "50% 50%", this.timelineThumbnailImage.style.width = "160px", this.timelineThumbnailImage.style.height = "90px");
1136
+ let a = this.timeline.getBoundingClientRect(), o = this.timelineThumbnailPreview.offsetWidth || 160, s = n.position * a.width, c = Math.max(o / 2, Math.min(a.width - o / 2, s));
1137
+ this.timelineThumbnailPreview.style.left = `${c}px`, this.timelineThumbnailImage.src === r.imageUrl ? this.timelineThumbnailImage.complete && this.timelineThumbnailImage.naturalWidth > 0 && this.timelineThumbnailPreview.classList.remove("flux-hidden") : (this.timelineThumbnailPreview.classList.add("flux-hidden"), this.timelineThumbnailImage.src = r.imageUrl);
1138
+ }
1139
+ hideTimelineThumbnail() {
1140
+ this.timelineThumbnailPreview.classList.add("flux-hidden");
1141
+ }
1142
+ bindSubtitleTrack(e) {
1143
+ if (this.subtitleTrackListeners.has(e)) return;
1144
+ let t = () => {
1145
+ e.mode === "showing" && (e.mode = "hidden"), this.renderSubtitleCues();
1146
+ };
1147
+ e.addEventListener("cuechange", t), this.subtitleTrackListeners.set(e, t), this.domCleans.push(() => {
1148
+ e.removeEventListener("cuechange", t), this.subtitleTrackListeners.delete(e);
1149
+ });
1150
+ }
1151
+ renderSubtitleCues() {
1152
+ let e = [];
1153
+ for (let t = 0; t < this.videoEl.textTracks.length; t++) {
1154
+ let n = this.videoEl.textTracks[t];
1155
+ if (!(n.mode === "disabled" || !n.activeCues)) for (let t = 0; t < n.activeCues.length; t++) {
1156
+ let r = (n.activeCues[t].text ?? "").trim().replace(/<[^>]+>/g, "").trim();
1157
+ r && e.push(r);
1158
+ }
1159
+ }
1160
+ if (e.length === 0) {
1161
+ this.subtitleDisplay.innerHTML = "";
1162
+ return;
1163
+ }
1164
+ this.subtitleDisplay.innerHTML = e.map((e) => `<span class="flux-player-subtitle-text">${this.htmlEscape(e)}</span>`).join("<br>");
1165
+ }
1166
+ htmlEscape(e) {
1167
+ return e.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1168
+ }
1169
+ handlePrimaryAction() {
1170
+ let e = this.player.getState();
1171
+ if (e.ended) {
1172
+ this.replay();
1173
+ return;
1174
+ }
1175
+ if (e.paused) {
1176
+ this.player.play().catch((e) => {
1177
+ console.error("[DefaultUI] Play failed:", e);
1178
+ });
1179
+ return;
1180
+ }
1181
+ this.player.pause();
1182
+ }
1183
+ replay() {
1184
+ this.player.seek(0), this.player.play().catch((e) => {
1185
+ console.error("[DefaultUI] Replay failed:", e);
1186
+ });
1187
+ }
1188
+ updateState(e) {
1189
+ this.resetUiForSourceChange(e);
1190
+ let t = e.source?.adBreakTimes || [], n = t.join(",") + "/" + e.duration;
1191
+ if (n !== this.markerSignature) {
1192
+ this.markerSignature = n, this.timeline.querySelectorAll(".flux-ad-marker").forEach((e) => e.remove());
1193
+ for (let n of t) {
1194
+ if (!Number.isFinite(e.duration) || n >= e.duration) continue;
1195
+ let t = document.createElement("span");
1196
+ t.className = "flux-ad-marker", t.title = n === 0 ? "Pre-roll ad" : "Ad at " + this.formatTime(n), t.style.cssText = "position:absolute;top:-2px;height:8px;width:4px;border-radius:1px;background:#ffd45e;z-index:2", t.style.left = 100 * n / e.duration + "%", this.timeline.append(t);
1197
+ }
1198
+ }
1199
+ e.selectedSubtitle === null && !e.availableSubtitles.some((e) => e.selected) && this.subtitleDisplay.replaceChildren(), this.syncThumbnailTrack(e).catch((e) => {
1200
+ console.warn("[DefaultUI] Thumbnail sync failed", e);
1201
+ });
1202
+ let r = e.ended && !e.error ? "replay" : e.paused ? "play" : "pause";
1203
+ this.renderIcon(this.playBtn, r);
1204
+ let i = r === "replay" ? "Replay" : e.paused ? "Play" : "Pause";
1205
+ this.playBtn.ariaLabel !== i && (this.playBtn.ariaLabel = i), e.paused ? this.uiPaused || (this.uiPaused = !0, !e.error && !e.ended && this.bigPlay.classList.remove("flux-hidden"), this.setControlsIdle(!1), clearTimeout(this.idleTimeout)) : this.uiPaused && (this.uiPaused = !1, this.bigPlay.classList.add("flux-hidden"), this.replayBtn.classList.add("flux-hidden"), this.setControlsIdle(!1), clearTimeout(this.idleTimeout), this.menuOpen || (this.idleTimeout = setTimeout(() => {
1206
+ this.setControlsIdle(!0);
1207
+ }, 3e3))), e.buffering ? this.spinner.classList.remove("flux-hidden") : this.spinner.classList.add("flux-hidden"), e.error ? (this.errorPanel.classList.remove("flux-hidden"), this.errorTextEl.innerText = e.error.message, this.spinner.classList.add("flux-hidden"), this.bigPlay.classList.add("flux-hidden"), this.replayBtn.classList.add("flux-hidden")) : this.errorPanel.classList.add("flux-hidden"), e.ended && !e.error ? (this.bigPlay.classList.add("flux-hidden"), this.replayBtn.classList.remove("flux-hidden"), this.setControlsIdle(!1)) : this.replayBtn.classList.add("flux-hidden"), e.isLive ? (this.liveBadge.classList.remove("flux-hidden"), this.timeline.classList.add("flux-disabled"), this.timeDisplay.classList.add("flux-hidden")) : (this.liveBadge.classList.add("flux-hidden"), this.timeline.classList.remove("flux-disabled"), this.timeDisplay.classList.remove("flux-hidden"));
1208
+ let a = e.duration || 0;
1209
+ if (!this.isDragging && (this.timeDisplay.innerText = `${this.formatTime(e.currentTime)} / ${this.formatTime(a)}`, this.timeDisplay.setAttribute("aria-label", e.isLive ? `Live stream, current position ${this.formatTime(e.currentTime)}` : `Current time ${this.formatTime(e.currentTime)} of ${this.formatTime(a)}`), this.timeline.setAttribute("aria-valuemin", "0"), this.timeline.setAttribute("aria-valuenow", String(Math.round(e.currentTime))), this.timeline.setAttribute("aria-valuemax", String(Number.isFinite(a) ? Math.round(a) : 0)), this.timeline.setAttribute("aria-valuetext", `${this.formatTime(e.currentTime)} of ${this.formatTime(a)}`), a > 0)) if (this.progressFill.style.width = `${e.currentTime / a * 100}%`, e.buffered.length > 0) {
1210
+ let t = e.buffered[e.buffered.length - 1];
1211
+ this.bufferedFill.style.width = `${t.end / a * 100}%`;
1212
+ } else this.bufferedFill.style.width = "0%";
1213
+ let o = e.muted ? "Unmute" : "Mute";
1214
+ this.muteBtn.ariaLabel !== o && (this.muteBtn.ariaLabel = o), e.muted || e.volume === 0 ? (this.renderIcon(this.muteBtn, "mute"), this.volumeSlider.value = "0") : (this.renderIcon(this.muteBtn, "volume"), this.volumeSlider.value = String(e.volume));
1215
+ }
1216
+ toggleMenu(e) {
1217
+ this.menuOpen = typeof e == "boolean" ? e : !this.menuOpen, this.menuOpen ? (this.renderMenu(), this.settingsMenu.classList.remove("flux-hidden"), this.settingsBtn.setAttribute("aria-expanded", "true"), this.menuFocusIndex = 0, this.updateMenuA11yState(), this.focusMenuItem(this.menuFocusIndex), clearTimeout(this.idleTimeout)) : (this.settingsMenu.classList.add("flux-hidden"), this.settingsBtn.setAttribute("aria-expanded", "false"), this.wrapper.dispatchEvent(new Event("mousemove")));
1218
+ }
1219
+ renderMenu() {
1220
+ let e = this.player.getState();
1221
+ this.settingsMenu.innerHTML = "";
1222
+ let t = e.selectedSubtitle ?? e.availableSubtitles.find((e) => e.selected)?.id ?? null;
1223
+ this.addMenuSection("Quality", e.availableQualities.map((t) => ({
1224
+ id: String(t.id),
1225
+ label: t.label,
1226
+ active: e.selectedQuality === t.id,
1227
+ onClick: () => this.player.setQuality(t.id)
1228
+ })).concat(e.availableQualities.length > 0 ? [{
1229
+ id: "auto",
1230
+ label: "Auto",
1231
+ active: e.selectedQuality === "auto",
1232
+ onClick: () => this.player.setQuality("auto")
1233
+ }] : [])), this.addMenuSection("Audio", e.availableAudioTracks.map((e) => ({
1234
+ id: e.id,
1235
+ label: e.label,
1236
+ active: e.selected,
1237
+ onClick: () => this.player.setAudioTrack(e.id)
1238
+ }))), this.addMenuSection("Captions", e.availableSubtitles.map((e) => ({
1239
+ id: e.id,
1240
+ label: e.label,
1241
+ active: t === e.id,
1242
+ onClick: () => this.player.setSubtitle(e.id)
1243
+ })).concat(e.availableSubtitles.length > 0 ? [{
1244
+ id: "off",
1245
+ label: "Off",
1246
+ active: t === null,
1247
+ onClick: () => this.player.setSubtitle(null)
1248
+ }] : []));
1249
+ let n = [
1250
+ .5,
1251
+ .75,
1252
+ 1,
1253
+ 1.25,
1254
+ 1.5,
1255
+ 2
1256
+ ].map((t) => ({
1257
+ id: String(t),
1258
+ label: t === 1 ? "Normal (1x)" : `${t}x`,
1259
+ active: e.playbackRate === t,
1260
+ onClick: () => this.player.setPlaybackRate(t)
1261
+ }));
1262
+ this.addMenuSection("Speed", n), this.updateMenuA11yState();
1263
+ }
1264
+ addMenuSection(e, t) {
1265
+ let n = document.createElement("div");
1266
+ n.className = "flux-player-menu-section";
1267
+ let r = document.createElement("div");
1268
+ if (r.className = "flux-player-menu-header", r.innerText = e, n.appendChild(r), t.length === 0) {
1269
+ let e = document.createElement("div");
1270
+ e.className = "flux-player-menu-placeholder", e.innerText = "Not available", n.appendChild(e);
1271
+ } else t.forEach((e) => {
1272
+ let t = document.createElement("div");
1273
+ t.className = `flux-player-menu-item ${e.active ? "flux-active" : ""}`, t.innerText = e.label, t.setAttribute("role", "menuitemradio"), t.setAttribute("aria-checked", e.active ? "true" : "false"), t.tabIndex = -1, t.addEventListener("click", () => {
1274
+ e.onClick(), this.toggleMenu(!1);
1275
+ }), n.appendChild(t);
1276
+ });
1277
+ this.settingsMenu.appendChild(n);
1278
+ }
1279
+ destroy() {
1280
+ this.renderedIcons.clear(), this.thumbnailFetchAbort?.abort(), this.cleans.forEach((e) => e()), this.domCleans.forEach((e) => e()), this.domCleans = [], clearTimeout(this.idleTimeout), this.container.innerHTML = "";
1281
+ }
1282
+ }, y = class {
1283
+ player;
1284
+ adapter;
1285
+ cleans = [];
1286
+ loadStartedAt = null;
1287
+ playbackStartedAt = null;
1288
+ rebufferStartedAt = null;
1289
+ totalRebufferMs = 0;
1290
+ rebufferCount = 0;
1291
+ sessionStartedAt = Date.now();
1292
+ manifestLoadedAt = null;
1293
+ firstFrameAt = null;
1294
+ trace = [];
1295
+ bitrateTimeline = [];
1296
+ constructor(e, t) {
1297
+ this.player = e, this.adapter = t || ((e, t) => console.log(`[Analytics] ${e}`, t)), this.bind();
1298
+ }
1299
+ bind() {
1300
+ this.emit("player.created", "lifecycle", {}), [
1301
+ "source_loading",
1302
+ "source_loaded",
1303
+ "playback_requested",
1304
+ "playback_started",
1305
+ "seek_start",
1306
+ "seek_complete",
1307
+ "error"
1308
+ ].forEach((e) => {
1309
+ this.cleans.push(this.player.on(e, (t) => {
1310
+ e === "source_loading" && (this.loadStartedAt = Date.now(), this.playbackStartedAt = null, this.manifestLoadedAt = null, this.firstFrameAt = null, this.rebufferCount = 0, this.totalRebufferMs = 0), e === "source_loaded" && (this.manifestLoadedAt = Date.now(), this.emit("qoe.startup.manifest_loaded", "qoe", { manifestLoadMs: this.loadStartedAt ? this.manifestLoadedAt - this.loadStartedAt : null })), e === "playback_started" && this.playbackStartedAt === null && (this.playbackStartedAt = Date.now(), this.firstFrameAt = this.playbackStartedAt, this.emit("qoe.startup.first_frame", "qoe", {
1311
+ firstFrameMs: this.loadStartedAt ? this.firstFrameAt - this.loadStartedAt : null,
1312
+ manifestLoadMs: this.loadStartedAt && this.manifestLoadedAt ? this.manifestLoadedAt - this.loadStartedAt : null,
1313
+ postManifestToFirstFrameMs: this.firstFrameAt && this.manifestLoadedAt ? this.firstFrameAt - this.manifestLoadedAt : null
1314
+ })), this.emit(this.normalizeEventName(e), this.categoryForEvent(e), this.withQoe(t));
1315
+ }));
1316
+ }), this.cleans.push(this.player.on("state:paused", (e) => {
1317
+ e && this.emit("playback.pause", "playback", this.withQoe({ currentTime: this.player.getState().currentTime }));
1318
+ })), this.cleans.push(this.player.on("state:buffered", (e) => {
1319
+ this.player.getState().readyState === 2 && this.rebufferStartedAt === null && (this.rebufferStartedAt = Date.now(), this.rebufferCount += 1, this.emit("playback.buffering_start", "qoe", this.withQoe({
1320
+ currentTime: this.player.getState().currentTime,
1321
+ rebufferCount: this.rebufferCount,
1322
+ sinceStartMs: Date.now() - this.sessionStartedAt
1323
+ })));
1324
+ })), this.cleans.push(this.player.on("state:readyState", (e) => {
1325
+ if (e === 4 && this.rebufferStartedAt !== null) {
1326
+ let e = Date.now() - this.rebufferStartedAt;
1327
+ this.totalRebufferMs += e, this.rebufferStartedAt = null, this.emit("playback.buffering_end", "qoe", this.withQoe({
1328
+ currentTime: this.player.getState().currentTime,
1329
+ rebufferMs: e,
1330
+ rebufferCount: this.rebufferCount,
1331
+ totalRebufferMs: this.totalRebufferMs,
1332
+ sinceStartMs: Date.now() - this.sessionStartedAt
1333
+ }));
1334
+ }
1335
+ })), this.cleans.push(this.player.on("state:selectedQuality", (e) => {
1336
+ let t = this.player.getState().availableQualities.find((e) => e.selected);
1337
+ this.bitrateTimeline.push({
1338
+ at: Date.now(),
1339
+ bitrate: t?.bitrate || null,
1340
+ quality: e
1341
+ }), this.emit("track.quality_changed", "track", this.withQoe({ quality: e }));
1342
+ })), this.cleans.push(this.player.on("state:selectedSubtitle", (e) => this.emit("track.subtitle_changed", "track", this.withQoe({ subtitle: e })))), this.cleans.push(this.player.on("state:selectedAudioTrack", (e) => this.emit("track.audio_changed", "track", this.withQoe({ audioTrack: e })))), this.cleans.push(this.player.on("state:volume", (e) => this.emit("playback.volume_changed", "playback", this.withQoe({ volume: e })))), this.cleans.push(this.player.on("state:muted", (e) => this.emit("playback.muted_changed", "playback", this.withQoe({ muted: e })))), this.cleans.push(this.player.on("state:playbackRate", (e) => this.emit("playback.rate_changed", "playback", this.withQoe({ rate: e })))), this.cleans.push(this.player.on("error", (e) => {
1343
+ let t = e?.error || e;
1344
+ this.emit("error.classified", "error", {
1345
+ classification: this.classifyError(t),
1346
+ code: t?.code,
1347
+ message: t?.message
1348
+ });
1349
+ }));
1350
+ }
1351
+ getSessionTrace() {
1352
+ return this.trace.map((e) => ({
1353
+ ...e,
1354
+ payload: JSON.parse(JSON.stringify(e.payload ?? null))
1355
+ }));
1356
+ }
1357
+ normalizeEventName(e) {
1358
+ return {
1359
+ source_loading: "source.loading",
1360
+ source_loaded: "source.loaded",
1361
+ playback_requested: "playback.requested",
1362
+ playback_started: "playback.started",
1363
+ seek_start: "playback.seek_start",
1364
+ seek_complete: "playback.seek_complete",
1365
+ error: "playback.error"
1366
+ }[e] || e;
1367
+ }
1368
+ withQoe(e) {
1369
+ let t = this.player.getState().availableQualities.find((e) => e.selected), n = this.player.getVideoPlaybackQuality?.() || void 0;
1370
+ return {
1371
+ ...e,
1372
+ qoe: {
1373
+ startupTimeMs: this.loadStartedAt && this.playbackStartedAt ? this.playbackStartedAt - this.loadStartedAt : null,
1374
+ manifestLoadMs: this.loadStartedAt && this.manifestLoadedAt ? this.manifestLoadedAt - this.loadStartedAt : null,
1375
+ firstFrameMs: this.loadStartedAt && this.firstFrameAt ? this.firstFrameAt - this.loadStartedAt : null,
1376
+ rebufferCount: this.rebufferCount,
1377
+ totalRebufferMs: this.totalRebufferMs,
1378
+ bitrate: t?.bitrate || null,
1379
+ droppedFrames: n?.droppedVideoFrames ?? null,
1380
+ bitrateTimeline: this.bitrateTimeline.slice(-20)
1381
+ }
1382
+ };
1383
+ }
1384
+ emit(e, t, n) {
1385
+ let r = Date.now(), i = {
1386
+ at: r,
1387
+ sinceStartMs: r - this.sessionStartedAt,
1388
+ event: e,
1389
+ category: t,
1390
+ payload: n
1391
+ };
1392
+ this.trace.push(i), this.trace.length > 500 && this.trace.shift(), this.adapter(e, n);
1393
+ }
1394
+ classifyError(e) {
1395
+ let t = String(e?.code || "").toLowerCase(), n = String(e?.message || "").toLowerCase();
1396
+ return t.includes("network") || n.includes("network") || n.includes("manifest") || n.includes("segment") ? "network" : t.includes("media") || n.includes("decode") || n.includes("demux") ? "decode" : t.includes("drm") || n.includes("drm") || n.includes("key system") || n.includes("license") ? "drm" : "unknown";
1397
+ }
1398
+ categoryForEvent(e) {
1399
+ return e === "error" ? "error" : e.startsWith("seek") || e.startsWith("playback") ? "playback" : e.startsWith("source") ? "lifecycle" : "qoe";
1400
+ }
1401
+ destroy() {
1402
+ this.cleans.forEach((e) => e());
1403
+ }
1404
+ }, b = class {
1405
+ player;
1406
+ mountEl;
1407
+ panel = null;
1408
+ bodyEl = null;
1409
+ visible = !0;
1410
+ events = [];
1411
+ cleans = [];
1412
+ constructor(e, t) {
1413
+ this.player = e, this.mountEl = t || document.body, this.inject(), this.bind();
1414
+ }
1415
+ inject() {
1416
+ this.panel = document.createElement("div"), this.panel.className = "flux-devtools-overlay", this.panel.style.position = this.mountEl === document.body ? "fixed" : "absolute", this.panel.style.top = "10px", this.panel.style.right = "10px", this.panel.style.backgroundColor = "rgba(0,0,0,0.85)", this.panel.style.color = "#0f0", this.panel.style.padding = "10px", this.panel.style.fontFamily = "monospace", this.panel.style.fontSize = "12px", this.panel.style.zIndex = "9999", this.panel.style.width = "320px", this.panel.style.maxHeight = "280px", this.panel.style.overflow = "auto", this.panel.style.borderRadius = "8px", this.panel.style.pointerEvents = "auto", this.bodyEl = document.createElement("pre"), this.bodyEl.style.margin = "0", this.bodyEl.style.whiteSpace = "pre-wrap", this.panel.appendChild(this.bodyEl), this.mountEl.appendChild(this.panel);
1417
+ }
1418
+ bind() {
1419
+ [
1420
+ "source_loading",
1421
+ "source_loaded",
1422
+ "playback_requested",
1423
+ "playback_started",
1424
+ "seek_start",
1425
+ "seek_complete",
1426
+ "error",
1427
+ "state:change"
1428
+ ].forEach((e) => {
1429
+ this.cleans.push(this.player.on(e, (t) => {
1430
+ this.events.unshift({
1431
+ name: e,
1432
+ payload: t,
1433
+ ts: Date.now()
1434
+ }), this.events.length > 25 && (this.events.length = 25), this.render();
1435
+ }));
1436
+ }), this.render();
1437
+ }
1438
+ render() {
1439
+ if (!this.bodyEl || !this.visible) return;
1440
+ let e = this.player.getState(), t = this.events.slice(0, 8).map((e) => `${new Date(e.ts).toLocaleTimeString()} ${e.name}`).join("\n"), n = [
1441
+ `Engine: ${e.engineType || "none"}`,
1442
+ `Status: ${e.status}`,
1443
+ `Time: ${e.currentTime.toFixed(2)} / ${Number.isFinite(e.duration) ? e.duration.toFixed(2) : "live"}`,
1444
+ `Buffered: ${e.buffered.map((e) => `[${e.start.toFixed(1)}-${e.end.toFixed(1)}]`).join(", ") || "none"}`,
1445
+ `Quality: ${e.selectedQuality}`,
1446
+ `Subtitles: ${e.selectedSubtitle || "none"}`,
1447
+ `Audio: ${e.selectedAudioTrack}`,
1448
+ `Bitrate: ${e.availableQualities.find((e) => e.selected)?.bitrate || "n/a"}`,
1449
+ `Error: ${e.error ? `${e.error.code} ${e.error.message}` : "none"}`,
1450
+ "",
1451
+ "Recent Events:",
1452
+ t || "none"
1453
+ ].join("\n");
1454
+ this.bodyEl.innerText = n;
1455
+ }
1456
+ setVisible(e) {
1457
+ this.visible = e, this.panel && (this.panel.style.display = e ? "block" : "none"), e && this.render();
1458
+ }
1459
+ isVisible() {
1460
+ return this.visible;
1461
+ }
1462
+ destroy() {
1463
+ this.cleans.forEach((e) => e()), this.cleans = [], this.panel &&= (this.panel.remove(), null), this.bodyEl = null;
1464
+ }
1465
+ }, x = () => Date.now(), S = class {
1466
+ startedAt = x();
1467
+ waitingStartedAt = null;
1468
+ startupStallStartedAt = null;
1469
+ awaitingFirstFrameAfterPlay = !1;
1470
+ seenTelemetry = /* @__PURE__ */ new Set();
1471
+ startup = this.createStartup(this.startedAt);
1472
+ sessionTrace = [];
1473
+ createStartup(e) {
1474
+ return {
1475
+ playerCreatedAt: e,
1476
+ sourceLoadRequestedAt: null,
1477
+ manifestRequestStartedAt: null,
1478
+ manifestReceivedAt: null,
1479
+ manifestParseStartedAt: null,
1480
+ manifestParseCompletedAt: null,
1481
+ firstSegmentRequestStartedAt: null,
1482
+ firstSegmentReceivedAt: null,
1483
+ firstAppendCompletedAt: null,
1484
+ playCalledAt: null,
1485
+ firstFrameAt: null,
1486
+ startupCompletedAt: null,
1487
+ startupDurationMs: null,
1488
+ sourceLoadToFirstFrameMs: null,
1489
+ playToFirstFrameMs: null,
1490
+ manifestToFirstFrameMs: null,
1491
+ totalRebufferCount: 0,
1492
+ totalRebufferDurationMs: 0,
1493
+ startupStallCount: 0,
1494
+ startupStallMs: 0,
1495
+ retryEvents: 0,
1496
+ errorEvents: 0,
1497
+ bitrateOverTime: []
1498
+ };
1499
+ }
1500
+ resetForNewSource() {
1501
+ this.startedAt = x(), this.waitingStartedAt = null, this.startupStallStartedAt = null, this.awaitingFirstFrameAfterPlay = !1, this.seenTelemetry.clear(), this.startup = this.createStartup(this.startedAt), this.sessionTrace = [];
1502
+ }
1503
+ mark(e, t = x()) {
1504
+ this.startup[e] === null && (this.startup[e] = t);
1505
+ }
1506
+ onSourceLoadRequested() {
1507
+ this.mark("sourceLoadRequestedAt"), this.pushTrace("source_load_requested", "lifecycle", void 0);
1508
+ }
1509
+ onPlayCalled() {
1510
+ this.startup.playCalledAt === null && (this.mark("playCalledAt"), this.awaitingFirstFrameAfterPlay = !0, this.pushTrace("play_called", "playback", void 0));
1511
+ }
1512
+ onFirstFrame() {
1513
+ this.awaitingFirstFrameAfterPlay && this.startup.firstFrameAt === null && (this.mark("firstFrameAt"), this.startup.playCalledAt !== null && this.startup.firstFrameAt !== null && this.startup.startupCompletedAt === null && this.finalizeStartup(this.startup.firstFrameAt));
1514
+ }
1515
+ finalizeStartup(e) {
1516
+ if (this.startup.startupCompletedAt !== null) return;
1517
+ this.startup.startupCompletedAt = e;
1518
+ let t = this.startup.playCalledAt;
1519
+ if (t !== null) {
1520
+ if (e < t) return;
1521
+ this.startup.startupDurationMs = e - t;
1522
+ } else {
1523
+ let t = this.startup.sourceLoadRequestedAt ?? this.startedAt;
1524
+ if (e < t) return;
1525
+ this.startup.startupDurationMs = e - t;
1526
+ }
1527
+ this.awaitingFirstFrameAfterPlay = !1, this.pushTrace("startup_completed", "lifecycle", { startupDurationMs: this.startup.startupDurationMs });
1528
+ }
1529
+ onWaiting() {
1530
+ if (this.waitingStartedAt !== null || this.startupStallStartedAt !== null) return;
1531
+ let e = x();
1532
+ this.startup.firstFrameAt === null ? (this.startupStallStartedAt = e, this.startup.startupStallCount += 1, this.pushTrace("startup_stall_start", "qoe", { startupStallCount: this.startup.startupStallCount })) : (this.waitingStartedAt = e, this.startup.totalRebufferCount += 1, this.pushTrace("rebuffer_start", "qoe", { totalRebufferCount: this.startup.totalRebufferCount }));
1533
+ }
1534
+ onPlaying() {
1535
+ if (this.startupStallStartedAt !== null && (this.startup.startupStallMs += x() - this.startupStallStartedAt, this.startupStallStartedAt = null, this.pushTrace("startup_stall_end", "qoe", { startupStallMs: this.startup.startupStallMs })), this.waitingStartedAt !== null) {
1536
+ let e = x() - this.waitingStartedAt;
1537
+ this.startup.totalRebufferDurationMs += e, this.waitingStartedAt = null, this.pushTrace("rebuffer_end", "qoe", { totalRebufferDurationMs: this.startup.totalRebufferDurationMs });
1538
+ }
1539
+ }
1540
+ onTelemetry(e, t = x(), n) {
1541
+ let r = {
1542
+ manifest_request_started: "manifestRequestStartedAt",
1543
+ manifest_received: "manifestReceivedAt",
1544
+ manifest_parse_started: "manifestParseStartedAt",
1545
+ manifest_parse_completed: "manifestParseCompletedAt",
1546
+ first_segment_request_started: "firstSegmentRequestStartedAt",
1547
+ first_segment_received: "firstSegmentReceivedAt",
1548
+ first_append_completed: "firstAppendCompletedAt"
1549
+ }[e];
1550
+ r && !this.seenTelemetry.has(e) && (this.seenTelemetry.add(e), this.mark(r, t)), typeof n?.bitrate == "number" && Number.isFinite(n.bitrate) && this.startup.bitrateOverTime.push({
1551
+ at: t,
1552
+ bitrate: n.bitrate
1553
+ }), e.toLowerCase().includes("retry") && (this.startup.retryEvents += 1), this.pushTrace(e, "lifecycle", n);
1554
+ }
1555
+ onError(e) {
1556
+ this.startup.errorEvents += 1, this.pushTrace("error", "error", e);
1557
+ }
1558
+ getStartupMetrics() {
1559
+ let e = this.startup, t = (e, t) => e !== null && t !== null ? e - t : null;
1560
+ return {
1561
+ ...e,
1562
+ sourceLoadToFirstFrameMs: t(e.firstFrameAt, e.sourceLoadRequestedAt),
1563
+ playToFirstFrameMs: t(e.firstFrameAt, e.playCalledAt),
1564
+ manifestToFirstFrameMs: t(e.firstFrameAt, e.manifestReceivedAt),
1565
+ startupStallCount: e.startupStallCount,
1566
+ startupStallMs: e.startupStallMs,
1567
+ bitrateOverTime: [...e.bitrateOverTime]
1568
+ };
1569
+ }
1570
+ getSessionTrace() {
1571
+ return [...this.sessionTrace];
1572
+ }
1573
+ printStartupReport() {
1574
+ let e = this.getStartupMetrics(), t = (e) => e === null ? "n/a" : `${Math.round(e)}ms`, n = (t) => t === null ? null : t - e.playerCreatedAt;
1575
+ console.group("[Flux] Startup Report"), console.table({
1576
+ startupDuration: t(e.startupDurationMs),
1577
+ manifestRequestToReceived: t(e.manifestRequestStartedAt && e.manifestReceivedAt ? e.manifestReceivedAt - e.manifestRequestStartedAt : null),
1578
+ parseDuration: t(e.manifestParseStartedAt && e.manifestParseCompletedAt ? e.manifestParseCompletedAt - e.manifestParseStartedAt : null),
1579
+ firstSegmentNetwork: t(e.firstSegmentRequestStartedAt && e.firstSegmentReceivedAt ? e.firstSegmentReceivedAt - e.firstSegmentRequestStartedAt : null),
1580
+ firstAppendToFrame: t(e.firstAppendCompletedAt && e.firstFrameAt ? e.firstFrameAt - e.firstAppendCompletedAt : null),
1581
+ rebufferCount: e.totalRebufferCount,
1582
+ rebufferDuration: t(e.totalRebufferDurationMs),
1583
+ retryEvents: e.retryEvents,
1584
+ errorEvents: e.errorEvents
1585
+ }), console.log("Timeline (ms from player create):", {
1586
+ sourceLoadRequested: n(e.sourceLoadRequestedAt),
1587
+ manifestRequestStarted: n(e.manifestRequestStartedAt),
1588
+ manifestReceived: n(e.manifestReceivedAt),
1589
+ manifestParseStarted: n(e.manifestParseStartedAt),
1590
+ manifestParseCompleted: n(e.manifestParseCompletedAt),
1591
+ firstSegmentRequestStarted: n(e.firstSegmentRequestStartedAt),
1592
+ firstSegmentReceived: n(e.firstSegmentReceivedAt),
1593
+ firstAppendCompleted: n(e.firstAppendCompletedAt),
1594
+ playCalled: n(e.playCalledAt),
1595
+ firstFrame: n(e.firstFrameAt),
1596
+ startupCompleted: n(e.startupCompletedAt)
1597
+ }), console.groupEnd();
1598
+ }
1599
+ pushTrace(e, t, n) {
1600
+ let r = x();
1601
+ this.sessionTrace.push({
1602
+ at: r,
1603
+ sinceStartMs: r - this.startedAt,
1604
+ event: e,
1605
+ category: t,
1606
+ payload: n
1607
+ });
1608
+ }
1609
+ }, C = /* @__PURE__ */ new WeakSet(), w = /* @__PURE__ */ new Map();
1610
+ function T(e, t) {
1611
+ let n = new c();
1612
+ n.setPerformance(t.performance), n.setAbr(t.abr);
1613
+ let r = new S(), i = typeof e == "string" ? document.querySelector(e) : e;
1614
+ if (!i) throw Error("Player target element not found");
1615
+ if (C.has(i)) throw Error("Player target already mounted. Destroy previous instance before creating a new one.");
1616
+ C.add(i), n.registry.register(new l());
1617
+ let a = !1, s = !1, u = null, f = null, p = null, m = null, h;
1618
+ t.ui?.headless ? (h = document.createElement("video"), h.setAttribute("playsinline", ""), h.preload = "auto", h.muted = !!(t.source?.muted ?? !0), i.appendChild(h), n.attachVideo(h)) : u = new v(n, e, t.ui), i && (_(i.querySelector(".flux-player-wrapper") || i, t.theme || "dark"), f = new d(n, i)), t.analytics && (p = new y(n, t.analytics.adapter)), t.devtools && (m = new b(n, i || document.body));
1619
+ let g = async (e) => {
1620
+ let t = e.type && e.type !== "auto" ? e.type : o(e.src, e.mimeType);
1621
+ if ((t === "hls" || t === "auto") && !a) try {
1622
+ let e = new (await (import("./src-DMaUVQqo.js"))).HlsEngine();
1623
+ await e.preload?.(), n.registry.register(e), a = !0;
1624
+ } catch (e) {
1625
+ console.warn("Failed to lazy load HLS engine", e);
1626
+ }
1627
+ if ((t === "dash" || t === "auto") && !s) try {
1628
+ let e = new (await (import("./src-BTcoslE8.js"))).DashEngine();
1629
+ await e.preload?.(), n.registry.register(e), s = !0;
1630
+ } catch (e) {
1631
+ console.warn("Failed to lazy load DASH engine", e);
1632
+ }
1633
+ }, x = (e) => {
1634
+ if (!t.performance?.manifestFastPath) return () => void 0;
1635
+ let n = document.createElement("link");
1636
+ return n.rel = "preload", n.as = "fetch", n.href = e, n.setAttribute("fetchpriority", "high"), n.crossOrigin = "anonymous", document.head.appendChild(n), () => {
1637
+ n.parentNode && n.parentNode.removeChild(n);
1638
+ };
1639
+ }, T = (e) => {
1640
+ if (!t.performance?.manifestFastPath) return () => void 0;
1641
+ let n = new URL(e, window.location.href).origin;
1642
+ if (w.has(n)) return () => void 0;
1643
+ let r = [], i = (e, t) => {
1644
+ let n = document.createElement("link");
1645
+ n.rel = e, n.href = t, e === "preconnect" && (n.crossOrigin = "anonymous"), document.head.appendChild(n), r.push(n);
1646
+ };
1647
+ return i("preconnect", n), i("dns-prefetch", n), w.set(n, r), () => void 0;
1648
+ }, E = !1, D = null, O = () => {
1649
+ let e = navigator;
1650
+ return typeof e.userAgentData?.mobile == "boolean" ? e.userAgentData.mobile : /android|iphone|ipad|ipod|mobile/i.test(navigator.userAgent || "");
1651
+ }, k = (e) => {
1652
+ let t = e.currentTime, n = e.buffered;
1653
+ for (let e = 0; e < n.length; e += 1) {
1654
+ let r = n.start(e), i = n.end(e);
1655
+ if (t >= r - .25 && t <= i + .05) return Math.max(0, i - t);
1656
+ }
1657
+ return 0;
1658
+ }, A = () => {
1659
+ let e = t.performance, r;
1660
+ if (typeof e?.startupBufferSeconds == "number" && Number.isFinite(e.startupBufferSeconds)) r = Math.max(0, e.startupBufferSeconds);
1661
+ else {
1662
+ let t = e?.startupStrategy ?? (e?.startupMode === "fast-first-frame" ? "aggressive" : "balanced"), i = n.getState(), a = O(), o = !!(i.isLive || i.isDvr);
1663
+ r = t === "aggressive" ? o ? a ? .12 : .08 : a ? .18 : .12 : t === "safe" ? o ? a ? .55 : .45 : a ? .9 : .75 : o ? a ? .35 : .28 : a ? .55 : .45;
1664
+ }
1665
+ let i = navigator.connection, a = 1;
1666
+ switch (i?.saveData && (a *= 1.2), (i?.effectiveType || "").toLowerCase()) {
1667
+ case "slow-2g":
1668
+ a *= 1.7;
1669
+ break;
1670
+ case "2g":
1671
+ a *= 1.45;
1672
+ break;
1673
+ case "3g":
1674
+ a *= 1.2;
1675
+ break;
1676
+ case "4g":
1677
+ a *= .9;
1678
+ break;
1679
+ default: break;
1680
+ }
1681
+ typeof i?.downlink == "number" && Number.isFinite(i.downlink) && (i.downlink >= 12 ? a *= .82 : i.downlink >= 6 ? a *= .9 : i.downlink <= 1.5 && (a *= 1.22)), typeof i?.rtt == "number" && Number.isFinite(i.rtt) && i.rtt > 250 && (a *= 1.1);
1682
+ let o = r * a;
1683
+ return Math.max(.12, Math.min(1.5, o));
1684
+ }, j = () => {
1685
+ if ((t.performance?.startupBufferSeconds ?? 0) >= .5) return 4500;
1686
+ let e = t.performance?.startupStrategy ?? (t.performance?.startupMode === "fast-first-frame" ? "aggressive" : "balanced");
1687
+ return e === "safe" ? 3500 : e === "aggressive" ? 1200 : 2200;
1688
+ }, M = async () => {
1689
+ let e = i.querySelector("video");
1690
+ if (!e) return;
1691
+ let t = Math.max(0, A()), a = j(), o = Date.now(), s = HTMLMediaElement.HAVE_FUTURE_DATA, c = "", l = () => {
1692
+ let t = k(e), r = n.getStartupReadiness(), i = !r || r.mediaSourceReadyState === null || r?.mediaSourceReadyState === "open", a = r?.sourceBuffersUpdating !== !0, o = e.buffered.length > 0;
1693
+ return {
1694
+ ahead: t,
1695
+ readyEnough: e.readyState >= s,
1696
+ hasBufferedRange: o,
1697
+ mediaSourceOpen: i,
1698
+ sourceBuffersIdle: a,
1699
+ engineReadiness: r
1700
+ };
1701
+ }, u = (n, r) => {
1702
+ let i = t;
1703
+ return e.readyState >= HTMLMediaElement.HAVE_ENOUGH_DATA && n.ahead >= .25 && (i = Math.min(i, Math.max(.2, t * .65))), r > 900 && n.hasBufferedRange && n.sourceBuffersIdle && n.mediaSourceOpen && (i = Math.min(i, .28)), i;
1704
+ }, d = (e, t) => {
1705
+ let n = [];
1706
+ return e.hasBufferedRange || n.push("no_buffered_range"), e.ahead < t && n.push("insufficient_buffer_ahead"), e.readyEnough || n.push("ready_state_below_have_future_data"), e.mediaSourceOpen || n.push("media_source_not_open"), e.sourceBuffersIdle || n.push("source_buffer_updating"), (e.engineReadiness?.appendQueueDepth ?? 0) > 0 && n.push("append_queue_not_empty"), e.engineReadiness?.appendWaitActive && n.push("append_wait_active"), n;
1707
+ }, f = (n, i, a) => {
1708
+ let o = d(n, a), s = o.join("|");
1709
+ !s || s === c || (c = s, r.onTelemetry("startup_gate_pending", Date.now(), {
1710
+ waitedMs: i,
1711
+ minAhead: a,
1712
+ baseMinAhead: t,
1713
+ ahead: n.ahead,
1714
+ readyState: e.readyState,
1715
+ reasons: o,
1716
+ mediaSourceReadyState: n.engineReadiness?.mediaSourceReadyState ?? null,
1717
+ sourceBuffersUpdating: n.engineReadiness?.sourceBuffersUpdating ?? null,
1718
+ appendQueueDepth: n.engineReadiness?.appendQueueDepth ?? null,
1719
+ appendWaitActive: n.engineReadiness?.appendWaitActive ?? null,
1720
+ appendBackpressureCount: n.engineReadiness?.appendBackpressureCount ?? null
1721
+ }));
1722
+ }, p = l();
1723
+ if (p.hasBufferedRange && p.readyEnough && p.ahead >= u(p, 0) && p.mediaSourceOpen && p.sourceBuffersIdle) {
1724
+ r.onTelemetry("startup_gate_ready", Date.now(), {
1725
+ minAhead: u(p, 0),
1726
+ baseMinAhead: t,
1727
+ ahead: p.ahead,
1728
+ readyState: e.readyState,
1729
+ waitedMs: 0
1730
+ });
1731
+ return;
1732
+ }
1733
+ await new Promise((n) => {
1734
+ let i = !1, s = null, c = null, d = () => {
1735
+ s !== null && window.cancelAnimationFrame(s), c !== null && window.clearTimeout(c);
1736
+ for (let t of [
1737
+ "progress",
1738
+ "loadeddata",
1739
+ "canplay",
1740
+ "canplaythrough"
1741
+ ]) e.removeEventListener(t, h);
1742
+ }, p = (e, t) => {
1743
+ i || (i = !0, d(), r.onTelemetry(e, Date.now(), t), n());
1744
+ }, m = () => {
1745
+ if (i || E) {
1746
+ d(), n();
1747
+ return;
1748
+ }
1749
+ let r = Date.now() - o, c = l(), h = u(c, r), { ahead: g, readyEnough: _, hasBufferedRange: v, mediaSourceOpen: y, sourceBuffersIdle: b } = c;
1750
+ if (v && _ && g >= h && y && b) {
1751
+ p("startup_gate_ready", {
1752
+ minAhead: h,
1753
+ baseMinAhead: t,
1754
+ ahead: g,
1755
+ readyState: e.readyState,
1756
+ waitedMs: r
1757
+ });
1758
+ return;
1759
+ }
1760
+ if (f(c, r, h), r >= a) {
1761
+ p("startup_gate_timeout", {
1762
+ minAhead: h,
1763
+ baseMinAhead: t,
1764
+ ahead: g,
1765
+ readyState: e.readyState,
1766
+ waitedMs: r
1767
+ });
1768
+ return;
1769
+ }
1770
+ s = window.requestAnimationFrame(m);
1771
+ }, h = () => {
1772
+ m();
1773
+ };
1774
+ for (let t of [
1775
+ "progress",
1776
+ "loadeddata",
1777
+ "canplay",
1778
+ "canplaythrough"
1779
+ ]) e.addEventListener(t, h);
1780
+ c = window.setTimeout(m, a), m();
1781
+ });
1782
+ }, N = () => {
1783
+ D?.(), D = null;
1784
+ let e = (e) => {
1785
+ if ("requestVideoFrameCallback" in HTMLVideoElement.prototype) {
1786
+ let t = e, n = t.requestVideoFrameCallback(() => {
1787
+ r.onFirstFrame();
1788
+ });
1789
+ D = () => {
1790
+ t.cancelVideoFrameCallback?.(n);
1791
+ };
1792
+ return;
1793
+ }
1794
+ {
1795
+ let t = null, n = Date.now(), i = () => {
1796
+ if (!e.paused && e.currentTime > 0 && e.readyState >= 2) {
1797
+ r.onFirstFrame();
1798
+ return;
1799
+ }
1800
+ Date.now() - n > 15e3 || (t = window.requestAnimationFrame(i));
1801
+ };
1802
+ t = window.requestAnimationFrame(i);
1803
+ let a = D;
1804
+ D = () => {
1805
+ a?.(), t !== null && window.cancelAnimationFrame(t);
1806
+ };
1807
+ }
1808
+ }, t = i.querySelector("video");
1809
+ if (t) {
1810
+ e(t);
1811
+ return;
1812
+ }
1813
+ let n = new MutationObserver(() => {
1814
+ let t = i.querySelector("video");
1815
+ t && (n.disconnect(), e(t));
1816
+ });
1817
+ n.observe(i, {
1818
+ childList: !0,
1819
+ subtree: !0
1820
+ }), D = () => {
1821
+ n.disconnect();
1822
+ };
1823
+ }, P = 0, F = 0, I = null, L = async (e) => {
1824
+ if (E) throw Error("Player has been destroyed");
1825
+ let t = ++P;
1826
+ D?.(), r.resetForNewSource(), r.onSourceLoadRequested();
1827
+ let i = T(e.src), a = o(e.src, e.mimeType), s = [e.type, a].some((e) => e === "dash" || e === "hls") ? x(e.src) : () => void 0;
1828
+ try {
1829
+ await g(e), !E && t === P && await n.load(e);
1830
+ } finally {
1831
+ i(), s();
1832
+ }
1833
+ }, R = (e) => {
1834
+ ++F;
1835
+ let t = L(e);
1836
+ I = t;
1837
+ let n = () => {
1838
+ I === t && (I = null);
1839
+ };
1840
+ return t.then(n, n), t;
1841
+ };
1842
+ t.source && R(t.source).catch((e) => console.error("Autoload failed", e));
1843
+ let z = {
1844
+ load: R,
1845
+ play: async () => {
1846
+ let e = ++F;
1847
+ if (r.onPlayCalled(), I && await I, E || e !== F) return;
1848
+ let i = t.performance;
1849
+ if (!(i?.startupMode === "fast-first-frame" && i.startupBufferSeconds === void 0 && i.startupStrategy !== "safe") && n.getState().currentTime === 0 && await M(), !(E || e !== F)) return n.play();
1850
+ },
1851
+ pause: () => {
1852
+ ++F, n.pause();
1853
+ },
1854
+ destroy: async () => {
1855
+ E || (E = !0, u && u.destroy(), f && f.destroy(), p && p.destroy(), m && m.destroy(), D?.(), await n.destroy(), h?.remove(), C.delete(i));
1856
+ },
1857
+ seek: (e) => n.seek(e),
1858
+ setVolume: (e) => n.setVolume(e),
1859
+ setMuted: (e) => n.setMuted(e),
1860
+ setPlaybackRate: (e) => n.setPlaybackRate(e),
1861
+ setIcons: (e) => u?.setIcons(e),
1862
+ setToolbar: (e) => u?.setToolbar(e),
1863
+ setTheme: (e) => {
1864
+ i && _(i.querySelector(".flux-player-wrapper") || i, e);
1865
+ },
1866
+ setQuality: (e) => n.setQuality(e),
1867
+ setSubtitle: (e) => n.setSubtitle(e),
1868
+ setAudioTrack: (e) => n.setAudioTrack(e),
1869
+ getState: () => n.getState(),
1870
+ getStats: () => n.getStats(),
1871
+ getStartupMetrics: () => r.getStartupMetrics(),
1872
+ printStartupReport: () => r.printStartupReport(),
1873
+ on: (e, t) => n.on(e, t)
1874
+ };
1875
+ return z.setDevtoolsVisible = (e) => {
1876
+ m?.setVisible(e);
1877
+ }, z.isDevtoolsVisible = () => m?.isVisible() ?? !1, z.getSessionTrace = () => {
1878
+ let e = p?.getSessionTrace() ?? [], t = r.getSessionTrace();
1879
+ return [...e, ...t].sort((e, t) => e.at - t.at);
1880
+ }, n.on("telemetry", (e) => {
1881
+ r.onTelemetry(e?.name || "telemetry", e?.at || Date.now(), e?.data);
1882
+ }), n.on("waiting", () => {
1883
+ r.onWaiting();
1884
+ }), n.on("playback_requested", () => r.onPlayCalled()), n.on("play", () => {
1885
+ N(), r.onPlayCalled();
1886
+ }), n.on("playing", () => {
1887
+ r.onPlaying();
1888
+ }), n.on("error", (e) => {
1889
+ r.onError(e);
1890
+ }), z;
1891
+ }
1892
+ //#endregion
1893
+ //#region packages/player/src/autoInit.ts
1894
+ var E = "[data-flux-player]", D = (e) => {
1895
+ if (e !== null) return e === "true" || e === "1";
1896
+ }, O = (e) => {
1897
+ let t = e.getAttribute("data-src");
1898
+ if (!t) throw Error("Missing data-src for data-flux-player element.");
1899
+ let n = e.getAttribute("data-type") || "auto", r = e.getAttribute("data-poster") || void 0, i = e.getAttribute("data-thumbnail-vtt") || void 0, a = e.getAttribute("data-theme") || "dark", o = e.getAttribute("data-startup-mode") || "fast-first-frame";
1900
+ return {
1901
+ source: {
1902
+ src: t,
1903
+ type: n,
1904
+ poster: r,
1905
+ thumbnailVtt: i,
1906
+ autoplay: D(e.getAttribute("data-autoplay")),
1907
+ muted: D(e.getAttribute("data-muted"))
1908
+ },
1909
+ theme: a,
1910
+ performance: { startupMode: o }
1911
+ };
1912
+ }, k = (e = {}) => {
1913
+ let t = e.selector || E, n = e.root || document, r = Array.from(n.querySelectorAll(t)).filter((e) => e instanceof HTMLElement), i = [];
1914
+ for (let e of r) {
1915
+ if (e.dataset.fluxMounted === "true") continue;
1916
+ let t = T(e, O(e));
1917
+ i.push(t), e.dataset.fluxMounted = "true";
1918
+ }
1919
+ return i;
1920
+ };
1921
+ typeof window < "u" && typeof document < "u" && window.__FLUX_AUTO_INIT__ !== !1 && (document.readyState === "loading" ? document.addEventListener("DOMContentLoaded", () => k(), { once: !0 }) : k());
1922
+ //#endregion
1923
+ //#region packages/player/src/browser.ts
1924
+ var A = {
1925
+ createPlayer: T,
1926
+ autoInitFluxPlayers: k
1927
+ };
1928
+ typeof window < "u" && (window.Flux = A);
1929
+ //#endregion
1930
+ export { A as Flux, k as autoInitFluxPlayers, T as createPlayer };