@supr-design/flux-player 0.0.0-stage → 1.1.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,1902 @@
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
+ cleans = [];
745
+ domCleans = [];
746
+ idleTimeout;
747
+ fullscreenChangeHandler = null;
748
+ pipSupported = !1;
749
+ controlElements = [];
750
+ controlFocusIndex = 0;
751
+ menuItems = [];
752
+ menuFocusIndex = 0;
753
+ thumbnailVttUrl = null;
754
+ thumbnailCues = [];
755
+ thumbnailFetchAbort = null;
756
+ subtitleDisplay;
757
+ subtitleTrackListeners = /* @__PURE__ */ new Map();
758
+ activeSourceToken = null;
759
+ resetUiForSourceChange(e) {
760
+ let t = `${e.source?.src || ""}|${this.resolveThumbnailVttUrl(e) || ""}`;
761
+ if (t !== this.activeSourceToken) {
762
+ this.activeSourceToken = t, this.thumbnailFetchAbort?.abort(), this.thumbnailFetchAbort = null, this.thumbnailVttUrl = null, this.thumbnailCues = [], this.hideTimelineThumbnail(), this.timelineThumbnailImage.removeAttribute("src"), this.subtitleDisplay.innerHTML = "";
763
+ for (let [e, t] of this.subtitleTrackListeners.entries()) e.removeEventListener("cuechange", t);
764
+ this.subtitleTrackListeners.clear();
765
+ for (let e = 0; e < this.videoEl.textTracks.length; e++) this.videoEl.textTracks[e].mode = "disabled", this.bindSubtitleTrack(this.videoEl.textTracks[e]);
766
+ }
767
+ }
768
+ constructor(e, t, n = {}) {
769
+ if (this.player = e, this.uiConfig = n, typeof t == "string") {
770
+ let e = document.querySelector(t);
771
+ if (!e) throw Error(`Target ${t} not found`);
772
+ this.container = e;
773
+ } else this.container = t;
774
+ 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());
775
+ }
776
+ render() {
777
+ 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.innerHTML = u.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.innerHTML = u.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";
778
+ let e = document.createElement("div");
779
+ 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 = () => {
780
+ this.thumbnailVttUrl && this.timelineThumbnailPreview.classList.remove("flux-hidden");
781
+ }, this.timelineThumbnailImage.onerror = () => {
782
+ this.hideTimelineThumbnail();
783
+ }, this.timelineThumbnailPreview.appendChild(this.timelineThumbnailImage), this.timeline.appendChild(this.bufferedFill), this.timeline.appendChild(this.progressFill), this.timeline.appendChild(this.timelineThumbnailPreview), e.appendChild(this.timeline);
784
+ let t = document.createElement("div");
785
+ t.className = "flux-player-toolbar";
786
+ let n = document.createElement("div");
787
+ n.className = "flux-player-toolbar-group", this.playBtn = this.createBtn("play", u.play, "Play"), this.muteBtn = this.createBtn("mute", u.mute, "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");
788
+ let r = document.createElement("div");
789
+ 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);
790
+ let i = document.createElement("div");
791
+ 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", u.pip, "Picture in Picture"), this.fullscreenBtn = this.createBtn("fullscreen", u.fullscreen, "Fullscreen"), this.settingsBtn = this.createBtn("settings", u.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");
792
+ }
793
+ setControlsIdle(e) {
794
+ 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"));
795
+ }
796
+ createBtn(e, t, n) {
797
+ let r = document.createElement("button");
798
+ return r.className = `flux-player-icon-btn flux-btn-${e}`, r.innerHTML = t, r.setAttribute("aria-label", n), r;
799
+ }
800
+ formatTime(e) {
801
+ if (isNaN(e)) return "0:00";
802
+ let t = Math.floor(e / 60), n = Math.floor(e % 60);
803
+ return `${t}:${n < 10 ? "0" : ""}${n}`;
804
+ }
805
+ bindEvents() {
806
+ this.cleans.push(this.player.on("state:change", (e) => this.updateState(e)));
807
+ let e = (e) => {
808
+ e && e.stopPropagation(), this.handlePrimaryAction();
809
+ };
810
+ 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", () => {
811
+ this.player.setMuted(!this.player.getState().muted);
812
+ }), this.listen(this.volumeSlider, "input", (e) => {
813
+ this.player.setVolume(parseFloat(e.target.value));
814
+ }), this.updatePipAvailability(), this.setupControlRovingTabindex(), this.listen(this.pipBtn, "click", async () => {
815
+ await this.togglePip();
816
+ }), this.listen(this.videoEl, "enterpictureinpicture", () => {
817
+ this.pipBtn.classList.add("flux-active"), this.pipBtn.setAttribute("aria-label", "Exit Picture in Picture");
818
+ }), this.listen(this.videoEl, "leavepictureinpicture", () => {
819
+ this.pipBtn.classList.remove("flux-active"), this.pipBtn.setAttribute("aria-label", "Picture in Picture");
820
+ }), this.listen(this.fullscreenBtn, "click", () => {
821
+ document.fullscreenElement ? document.exitFullscreen().catch(() => {}) : this.wrapper.requestFullscreen().catch(() => {});
822
+ }), this.fullscreenChangeHandler = () => {
823
+ document.fullscreenElement ? this.fullscreenBtn.innerHTML = u.fullscreenExit : this.fullscreenBtn.innerHTML = u.fullscreen;
824
+ }, this.listen(document, "fullscreenchange", this.fullscreenChangeHandler);
825
+ let t = (e) => {
826
+ let t = this.getTimelineHoverData(e.clientX);
827
+ if (!t) return;
828
+ let { position: n, duration: r, targetTime: i } = t;
829
+ 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);
830
+ }, n = (e) => {
831
+ this.isDragging && t(e);
832
+ }, r = (e) => {
833
+ this.isDragging && (this.isDragging = !1, this.wrapper.classList.remove("flux-dragging"), t(e), this.renderTimelineThumbnail(e), document.removeEventListener("mousemove", n), document.removeEventListener("mouseup", r));
834
+ };
835
+ this.listen(this.timeline, "mousedown", (e) => {
836
+ let i = e;
837
+ this.isDragging = !0, this.wrapper.classList.add("flux-dragging"), t(i), this.listen(document, "mousemove", n, !0), this.listen(document, "mouseup", r, !0);
838
+ }), this.listen(this.timeline, "click", (e) => {
839
+ this.isDragging || t(e);
840
+ }), this.listen(this.timeline, "mousemove", (e) => {
841
+ this.renderTimelineThumbnail(e);
842
+ }), this.listen(this.timeline, "mouseenter", (e) => {
843
+ this.renderTimelineThumbnail(e);
844
+ }), this.listen(this.timeline, "mouseleave", () => {
845
+ this.hideTimelineThumbnail();
846
+ }), this.listen(this.timeline, "keydown", (e) => {
847
+ let t = e;
848
+ if (t.key === "ArrowLeft" && (t.preventDefault(), this.player.seek(Math.max(0, this.player.getState().currentTime - 5))), t.key === "ArrowRight") {
849
+ t.preventDefault();
850
+ let e = this.player.getState().duration, n = Number.isFinite(e) ? e : this.player.getState().currentTime + 5;
851
+ this.player.seek(Math.min(n, this.player.getState().currentTime + 5));
852
+ }
853
+ }), this.listen(this.settingsBtn, "click", (e) => {
854
+ e.stopPropagation(), this.toggleMenu();
855
+ }), this.listen(this.wrapper, "click", () => {
856
+ this.menuOpen && this.toggleMenu(!1);
857
+ }), 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));
858
+ let i = () => {
859
+ this.setControlsIdle(!1), clearTimeout(this.idleTimeout), !this.player.getState().paused && !this.menuOpen && (this.idleTimeout = setTimeout(() => {
860
+ this.setControlsIdle(!0);
861
+ }, 3e3));
862
+ };
863
+ this.listen(this.wrapper, "mousemove", i), this.listen(this.wrapper, "touchstart", i);
864
+ for (let e of Array.from(this.videoEl.textTracks)) this.bindSubtitleTrack(e);
865
+ let a = (e) => this.bindSubtitleTrack(e.track);
866
+ this.videoEl.textTracks.addEventListener?.("addtrack", a), this.domCleans.push(() => this.videoEl.textTracks.removeEventListener?.("addtrack", a)), this.listen(this.wrapper, "mouseleave", () => {
867
+ !this.player.getState().paused && !this.menuOpen && this.setControlsIdle(!0);
868
+ });
869
+ }
870
+ setToolbar(e) {
871
+ let t = new Set(e.hidden), n = {
872
+ play: this.playBtn,
873
+ volume: this.volumeSlider.parentElement,
874
+ settings: this.settingsBtn,
875
+ pip: this.pipBtn,
876
+ fullscreen: this.fullscreenBtn
877
+ };
878
+ for (let e of Object.keys(n)) n[e].classList.toggle("flux-hidden", t.has(e));
879
+ t.has("settings") && this.menuOpen && this.toggleMenu(!1), this.extraButtons.replaceChildren(...(e.buttons ?? []).map(({ label: e, onClick: t }) => {
880
+ let n = document.createElement("button");
881
+ return n.type = "button", n.className = "flux-player-icon-btn", n.textContent = e, n.onclick = () => t(this.player), n;
882
+ })), this.extraButtons.style.display = this.extraButtons.childElementCount ? "" : "none", this.setupControlRovingTabindex();
883
+ }
884
+ setupControlRovingTabindex() {
885
+ this.controlElements = [
886
+ this.playBtn,
887
+ this.muteBtn,
888
+ this.volumeSlider,
889
+ this.timeline,
890
+ ...Array.from(this.extraButtons.querySelectorAll("button")),
891
+ this.settingsBtn,
892
+ this.pipBtn,
893
+ this.fullscreenBtn
894
+ ].filter((e) => !e.closest(".flux-hidden") && !e.hasAttribute("disabled")), this.controlElements.forEach((e, t) => {
895
+ e.tabIndex = t === 0 ? 0 : -1;
896
+ });
897
+ }
898
+ moveControlFocus(e) {
899
+ this.controlElements.length !== 0 && (this.controlFocusIndex = (e + this.controlElements.length) % this.controlElements.length, this.controlElements.forEach((e, t) => {
900
+ e.tabIndex = t === this.controlFocusIndex ? 0 : -1;
901
+ }), this.controlElements[this.controlFocusIndex].focus());
902
+ }
903
+ handleControlBarKeyDown(e) {
904
+ if (this.menuOpen) return;
905
+ let t = this.controlElements.findIndex((e) => e === document.activeElement);
906
+ if (t !== -1) {
907
+ if (e.key === "ArrowRight") {
908
+ e.preventDefault(), this.moveControlFocus(t + 1);
909
+ return;
910
+ }
911
+ if (e.key === "ArrowLeft") {
912
+ e.preventDefault(), this.moveControlFocus(t - 1);
913
+ return;
914
+ }
915
+ if (e.key === "Home") {
916
+ e.preventDefault(), this.moveControlFocus(0);
917
+ return;
918
+ }
919
+ e.key === "End" && (e.preventDefault(), this.moveControlFocus(this.controlElements.length - 1));
920
+ }
921
+ }
922
+ updateMenuA11yState() {
923
+ this.menuItems = Array.from(this.settingsMenu.querySelectorAll(".flux-player-menu-item")), this.menuItems.forEach((e, t) => {
924
+ e.setAttribute("role", "menuitemradio"), e.setAttribute("tabindex", t === this.menuFocusIndex ? "0" : "-1"), e.setAttribute("aria-checked", e.classList.contains("flux-active") ? "true" : "false");
925
+ });
926
+ }
927
+ focusMenuItem(e) {
928
+ this.menuItems.length !== 0 && (this.menuFocusIndex = (e + this.menuItems.length) % this.menuItems.length, this.menuItems.forEach((e, t) => {
929
+ e.tabIndex = t === this.menuFocusIndex ? 0 : -1;
930
+ }), this.menuItems[this.menuFocusIndex].focus());
931
+ }
932
+ handleSettingsKeyDown(e) {
933
+ if (!(!this.menuOpen || this.menuItems.length === 0)) {
934
+ if (e.key === "ArrowDown") {
935
+ e.preventDefault(), this.focusMenuItem(this.menuFocusIndex + 1);
936
+ return;
937
+ }
938
+ if (e.key === "ArrowUp") {
939
+ e.preventDefault(), this.focusMenuItem(this.menuFocusIndex - 1);
940
+ return;
941
+ }
942
+ if (e.key === "Home") {
943
+ e.preventDefault(), this.focusMenuItem(0);
944
+ return;
945
+ }
946
+ if (e.key === "End") {
947
+ e.preventDefault(), this.focusMenuItem(this.menuItems.length - 1);
948
+ return;
949
+ }
950
+ if (e.key === "Tab") {
951
+ e.preventDefault();
952
+ let t = e.shiftKey ? -1 : 1;
953
+ this.focusMenuItem(this.menuFocusIndex + t);
954
+ return;
955
+ }
956
+ if (e.key === "Escape") {
957
+ e.preventDefault(), this.toggleMenu(!1), this.settingsBtn.focus();
958
+ return;
959
+ }
960
+ (e.key === "Enter" || e.key === " ") && (e.preventDefault(), this.menuItems[this.menuFocusIndex]?.click());
961
+ }
962
+ }
963
+ updatePipAvailability() {
964
+ let e = document, t = this.videoEl, n = !!(e.pictureInPictureEnabled && this.videoEl.requestPictureInPicture), r = !!t.webkitSupportsPresentationMode?.("picture-in-picture");
965
+ 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"));
966
+ }
967
+ async togglePip() {
968
+ if (!this.pipSupported) return;
969
+ let e = document, t = this.videoEl;
970
+ if (e.pictureInPictureEnabled && this.videoEl.requestPictureInPicture) {
971
+ if (e.pictureInPictureElement === this.videoEl && e.exitPictureInPicture) {
972
+ await e.exitPictureInPicture().catch(() => {});
973
+ return;
974
+ }
975
+ await this.videoEl.requestPictureInPicture().catch(() => {});
976
+ return;
977
+ }
978
+ if (t.webkitSupportsPresentationMode?.("picture-in-picture") && t.webkitSetPresentationMode) {
979
+ let e = t.webkitPresentationMode === "picture-in-picture" ? "inline" : "picture-in-picture";
980
+ try {
981
+ t.webkitSetPresentationMode(e), this.pipBtn.classList.toggle("flux-active", e === "picture-in-picture");
982
+ } catch {}
983
+ }
984
+ }
985
+ listen(e, t, n, r = !1) {
986
+ if (e.addEventListener(t, n), this.domCleans.push(() => {
987
+ e.removeEventListener(t, n);
988
+ }), r) {
989
+ let e = this.domCleans[this.domCleans.length - 1];
990
+ this.domCleans[this.domCleans.length - 1] = () => {
991
+ e();
992
+ };
993
+ }
994
+ }
995
+ getTimelineHoverData(e) {
996
+ let t = this.timeline.getBoundingClientRect();
997
+ if (t.width <= 0) return null;
998
+ let n = (e - t.left) / t.width;
999
+ n = Math.max(0, Math.min(1, n));
1000
+ let r = this.player.getState().duration || 0;
1001
+ return {
1002
+ position: n,
1003
+ duration: r,
1004
+ targetTime: n * r
1005
+ };
1006
+ }
1007
+ resolveThumbnailVttUrl(e) {
1008
+ let t = typeof this.uiConfig?.thumbnailVtt == "string" ? this.uiConfig.thumbnailVtt.trim() : "";
1009
+ if (t.length > 0) return t;
1010
+ let n = e.source?.thumbnailVtt?.trim() || "";
1011
+ return n.length > 0 ? n : null;
1012
+ }
1013
+ async syncThumbnailTrack(e) {
1014
+ let t = this.resolveThumbnailVttUrl(e);
1015
+ if (t !== this.thumbnailVttUrl && (this.thumbnailVttUrl = t, this.thumbnailCues = [], this.hideTimelineThumbnail(), t)) {
1016
+ this.thumbnailFetchAbort?.abort(), this.thumbnailFetchAbort = new AbortController();
1017
+ try {
1018
+ let e = await fetch(t, { signal: this.thumbnailFetchAbort.signal });
1019
+ if (!e.ok) throw Error(`Failed to fetch thumbnail VTT: ${e.status}`);
1020
+ let n = await e.text();
1021
+ this.thumbnailCues = this.parseThumbnailVtt(n, t);
1022
+ } catch (e) {
1023
+ e.name !== "AbortError" && console.warn("[DefaultUI] Unable to load thumbnail VTT", e), this.thumbnailCues = [];
1024
+ }
1025
+ }
1026
+ }
1027
+ parseThumbnailVtt(e, t) {
1028
+ let n = e.split(/\r?\n/), r = [], i = 0;
1029
+ for (; i < n.length;) {
1030
+ let e = n[i].trim();
1031
+ if (!e || e.toUpperCase() === "WEBVTT" || e.startsWith("NOTE")) {
1032
+ i += 1;
1033
+ continue;
1034
+ }
1035
+ let a = e;
1036
+ if (!a.includes("-->") && i + 1 < n.length && (a = n[i + 1].trim(), i += 1), !a.includes("-->")) {
1037
+ i += 1;
1038
+ continue;
1039
+ }
1040
+ let [o, s] = a.split("-->").map((e) => e.trim()), c = s.split(/\s+/)[0], l = this.parseVttTime(o), u = this.parseVttTime(c);
1041
+ if (!Number.isFinite(l) || !Number.isFinite(u) || u <= l) {
1042
+ i += 1;
1043
+ continue;
1044
+ }
1045
+ i += 1;
1046
+ let d = [];
1047
+ for (; i < n.length && n[i].trim() !== "";) d.push(n[i].trim()), i += 1;
1048
+ let f = d.find((e) => this.isThumbnailPayload(e)) || "", p = this.parseThumbnailCuePayload(f, t);
1049
+ for (p && r.push({
1050
+ start: l,
1051
+ end: u,
1052
+ ...p
1053
+ }); i < n.length && n[i].trim() === "";) i += 1;
1054
+ }
1055
+ return r;
1056
+ }
1057
+ parseVttTime(e) {
1058
+ let t = e.split(":");
1059
+ if (t.length < 2 || t.length > 3) return NaN;
1060
+ let n = Number(t[t.length - 1]), r = Number(t[t.length - 2]), i = t.length === 3 ? Number(t[0]) : 0;
1061
+ return !Number.isFinite(i) || !Number.isFinite(r) || !Number.isFinite(n) ? NaN : i * 3600 + r * 60 + n;
1062
+ }
1063
+ parseThumbnailCuePayload(e, t) {
1064
+ if (!e) return null;
1065
+ let [n, r = ""] = e.split("#", 2);
1066
+ if (!n) return null;
1067
+ let i = n;
1068
+ try {
1069
+ i = new URL(n, t).toString();
1070
+ } catch {
1071
+ i = n;
1072
+ }
1073
+ let a = null, o = null, s = null, c = null, l = r.match(/xywh=(\d+),(\d+),(\d+),(\d+)/i);
1074
+ return l && (a = Number(l[1]), o = Number(l[2]), s = Number(l[3]), c = Number(l[4])), {
1075
+ imageUrl: i,
1076
+ x: a,
1077
+ y: o,
1078
+ w: s,
1079
+ h: c
1080
+ };
1081
+ }
1082
+ isThumbnailPayload(e) {
1083
+ let t = e.trim();
1084
+ return t ? /^(https?:\/\/|\/|\.\/|\.\.\/|[^\s]+\.(jpg|jpeg|png|webp|avif|gif|svg))(#xywh=\d+,\d+,\d+,\d+)?(\?.*)?$/i.test(t) : !1;
1085
+ }
1086
+ findThumbnailCue(e) {
1087
+ if (this.thumbnailCues.length === 0) return null;
1088
+ for (let t of this.thumbnailCues) if (e >= t.start && e < t.end) return t;
1089
+ let t = this.thumbnailCues[this.thumbnailCues.length - 1];
1090
+ return e >= t.start ? t : null;
1091
+ }
1092
+ renderTimelineThumbnail(e) {
1093
+ if (!this.thumbnailVttUrl || this.thumbnailCues.length === 0) {
1094
+ this.hideTimelineThumbnail();
1095
+ return;
1096
+ }
1097
+ let t = this.player.getState();
1098
+ if (t.isLive || !Number.isFinite(t.duration) || t.duration <= 0) {
1099
+ this.hideTimelineThumbnail();
1100
+ return;
1101
+ }
1102
+ let n = this.getTimelineHoverData(e.clientX);
1103
+ if (!n) {
1104
+ this.hideTimelineThumbnail();
1105
+ return;
1106
+ }
1107
+ let r = this.findThumbnailCue(n.targetTime);
1108
+ if (!r) {
1109
+ this.hideTimelineThumbnail();
1110
+ return;
1111
+ }
1112
+ let i = r.x !== null && r.y !== null && r.w !== null && r.h !== null;
1113
+ 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");
1114
+ 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));
1115
+ 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);
1116
+ }
1117
+ hideTimelineThumbnail() {
1118
+ this.timelineThumbnailPreview.classList.add("flux-hidden");
1119
+ }
1120
+ bindSubtitleTrack(e) {
1121
+ if (this.subtitleTrackListeners.has(e)) return;
1122
+ let t = () => {
1123
+ e.mode === "showing" && (e.mode = "hidden"), this.renderSubtitleCues();
1124
+ };
1125
+ e.addEventListener("cuechange", t), this.subtitleTrackListeners.set(e, t), this.domCleans.push(() => {
1126
+ e.removeEventListener("cuechange", t), this.subtitleTrackListeners.delete(e);
1127
+ });
1128
+ }
1129
+ renderSubtitleCues() {
1130
+ let e = [];
1131
+ for (let t = 0; t < this.videoEl.textTracks.length; t++) {
1132
+ let n = this.videoEl.textTracks[t];
1133
+ if (!(n.mode === "disabled" || !n.activeCues)) for (let t = 0; t < n.activeCues.length; t++) {
1134
+ let r = (n.activeCues[t].text ?? "").trim().replace(/<[^>]+>/g, "").trim();
1135
+ r && e.push(r);
1136
+ }
1137
+ }
1138
+ if (e.length === 0) {
1139
+ this.subtitleDisplay.innerHTML = "";
1140
+ return;
1141
+ }
1142
+ this.subtitleDisplay.innerHTML = e.map((e) => `<span class="flux-player-subtitle-text">${this.htmlEscape(e)}</span>`).join("<br>");
1143
+ }
1144
+ htmlEscape(e) {
1145
+ return e.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1146
+ }
1147
+ handlePrimaryAction() {
1148
+ let e = this.player.getState();
1149
+ if (e.ended) {
1150
+ this.replay();
1151
+ return;
1152
+ }
1153
+ if (e.paused) {
1154
+ this.player.play().catch((e) => {
1155
+ console.error("[DefaultUI] Play failed:", e);
1156
+ });
1157
+ return;
1158
+ }
1159
+ this.player.pause();
1160
+ }
1161
+ replay() {
1162
+ this.player.seek(0), this.player.play().catch((e) => {
1163
+ console.error("[DefaultUI] Replay failed:", e);
1164
+ });
1165
+ }
1166
+ updateState(e) {
1167
+ this.resetUiForSourceChange(e);
1168
+ let t = e.source?.adBreakTimes || [], n = t.join(",") + "/" + e.duration;
1169
+ if (n !== this.markerSignature) {
1170
+ this.markerSignature = n, this.timeline.querySelectorAll(".flux-ad-marker").forEach((e) => e.remove());
1171
+ for (let n of t) {
1172
+ if (!Number.isFinite(e.duration) || n >= e.duration) continue;
1173
+ let t = document.createElement("span");
1174
+ 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);
1175
+ }
1176
+ }
1177
+ e.selectedSubtitle === null && !e.availableSubtitles.some((e) => e.selected) && this.subtitleDisplay.replaceChildren(), this.syncThumbnailTrack(e).catch((e) => {
1178
+ console.warn("[DefaultUI] Thumbnail sync failed", e);
1179
+ }), e.paused ? this.uiPaused || (this.uiPaused = !0, this.playBtn.innerHTML = u.play, !e.error && !e.ended && this.bigPlay.classList.remove("flux-hidden"), this.setControlsIdle(!1), clearTimeout(this.idleTimeout)) : this.uiPaused && (this.uiPaused = !1, this.playBtn.innerHTML = u.pause, this.bigPlay.classList.add("flux-hidden"), this.replayBtn.classList.add("flux-hidden"), this.setControlsIdle(!1), clearTimeout(this.idleTimeout), this.menuOpen || (this.idleTimeout = setTimeout(() => {
1180
+ this.setControlsIdle(!0);
1181
+ }, 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.playBtn.innerHTML = u.replay) : 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"));
1182
+ let r = e.duration || 0;
1183
+ if (!this.isDragging && (this.timeDisplay.innerText = `${this.formatTime(e.currentTime)} / ${this.formatTime(r)}`, this.timeDisplay.setAttribute("aria-label", e.isLive ? `Live stream, current position ${this.formatTime(e.currentTime)}` : `Current time ${this.formatTime(e.currentTime)} of ${this.formatTime(r)}`), this.timeline.setAttribute("aria-valuemin", "0"), this.timeline.setAttribute("aria-valuenow", String(Math.round(e.currentTime))), this.timeline.setAttribute("aria-valuemax", String(Number.isFinite(r) ? Math.round(r) : 0)), this.timeline.setAttribute("aria-valuetext", `${this.formatTime(e.currentTime)} of ${this.formatTime(r)}`), r > 0)) if (this.progressFill.style.width = `${e.currentTime / r * 100}%`, e.buffered.length > 0) {
1184
+ let t = e.buffered[e.buffered.length - 1];
1185
+ this.bufferedFill.style.width = `${t.end / r * 100}%`;
1186
+ } else this.bufferedFill.style.width = "0%";
1187
+ e.muted || e.volume === 0 ? (this.muteBtn.innerHTML = u.mute, this.volumeSlider.value = "0") : (this.muteBtn.innerHTML = u.volume, this.volumeSlider.value = String(e.volume));
1188
+ }
1189
+ toggleMenu(e) {
1190
+ 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")));
1191
+ }
1192
+ renderMenu() {
1193
+ let e = this.player.getState();
1194
+ this.settingsMenu.innerHTML = "";
1195
+ let t = e.selectedSubtitle ?? e.availableSubtitles.find((e) => e.selected)?.id ?? null;
1196
+ this.addMenuSection("Quality", e.availableQualities.map((t) => ({
1197
+ id: String(t.id),
1198
+ label: t.label,
1199
+ active: e.selectedQuality === t.id,
1200
+ onClick: () => this.player.setQuality(t.id)
1201
+ })).concat(e.availableQualities.length > 0 ? [{
1202
+ id: "auto",
1203
+ label: "Auto",
1204
+ active: e.selectedQuality === "auto",
1205
+ onClick: () => this.player.setQuality("auto")
1206
+ }] : [])), this.addMenuSection("Audio", e.availableAudioTracks.map((e) => ({
1207
+ id: e.id,
1208
+ label: e.label,
1209
+ active: e.selected,
1210
+ onClick: () => this.player.setAudioTrack(e.id)
1211
+ }))), this.addMenuSection("Captions", e.availableSubtitles.map((e) => ({
1212
+ id: e.id,
1213
+ label: e.label,
1214
+ active: t === e.id,
1215
+ onClick: () => this.player.setSubtitle(e.id)
1216
+ })).concat(e.availableSubtitles.length > 0 ? [{
1217
+ id: "off",
1218
+ label: "Off",
1219
+ active: t === null,
1220
+ onClick: () => this.player.setSubtitle(null)
1221
+ }] : []));
1222
+ let n = [
1223
+ .5,
1224
+ .75,
1225
+ 1,
1226
+ 1.25,
1227
+ 1.5,
1228
+ 2
1229
+ ].map((t) => ({
1230
+ id: String(t),
1231
+ label: t === 1 ? "Normal (1x)" : `${t}x`,
1232
+ active: e.playbackRate === t,
1233
+ onClick: () => this.player.setPlaybackRate(t)
1234
+ }));
1235
+ this.addMenuSection("Speed", n), this.updateMenuA11yState();
1236
+ }
1237
+ addMenuSection(e, t) {
1238
+ let n = document.createElement("div");
1239
+ n.className = "flux-player-menu-section";
1240
+ let r = document.createElement("div");
1241
+ if (r.className = "flux-player-menu-header", r.innerText = e, n.appendChild(r), t.length === 0) {
1242
+ let e = document.createElement("div");
1243
+ e.className = "flux-player-menu-placeholder", e.innerText = "Not available", n.appendChild(e);
1244
+ } else t.forEach((e) => {
1245
+ let t = document.createElement("div");
1246
+ 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", () => {
1247
+ e.onClick(), this.toggleMenu(!1);
1248
+ }), n.appendChild(t);
1249
+ });
1250
+ this.settingsMenu.appendChild(n);
1251
+ }
1252
+ destroy() {
1253
+ this.thumbnailFetchAbort?.abort(), this.cleans.forEach((e) => e()), this.domCleans.forEach((e) => e()), this.domCleans = [], clearTimeout(this.idleTimeout), this.container.innerHTML = "";
1254
+ }
1255
+ }, y = class {
1256
+ player;
1257
+ adapter;
1258
+ cleans = [];
1259
+ loadStartedAt = null;
1260
+ playbackStartedAt = null;
1261
+ rebufferStartedAt = null;
1262
+ totalRebufferMs = 0;
1263
+ rebufferCount = 0;
1264
+ sessionStartedAt = Date.now();
1265
+ manifestLoadedAt = null;
1266
+ firstFrameAt = null;
1267
+ trace = [];
1268
+ bitrateTimeline = [];
1269
+ constructor(e, t) {
1270
+ this.player = e, this.adapter = t || ((e, t) => console.log(`[Analytics] ${e}`, t)), this.bind();
1271
+ }
1272
+ bind() {
1273
+ this.emit("player.created", "lifecycle", {}), [
1274
+ "source_loading",
1275
+ "source_loaded",
1276
+ "playback_requested",
1277
+ "playback_started",
1278
+ "seek_start",
1279
+ "seek_complete",
1280
+ "error"
1281
+ ].forEach((e) => {
1282
+ this.cleans.push(this.player.on(e, (t) => {
1283
+ 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", {
1284
+ firstFrameMs: this.loadStartedAt ? this.firstFrameAt - this.loadStartedAt : null,
1285
+ manifestLoadMs: this.loadStartedAt && this.manifestLoadedAt ? this.manifestLoadedAt - this.loadStartedAt : null,
1286
+ postManifestToFirstFrameMs: this.firstFrameAt && this.manifestLoadedAt ? this.firstFrameAt - this.manifestLoadedAt : null
1287
+ })), this.emit(this.normalizeEventName(e), this.categoryForEvent(e), this.withQoe(t));
1288
+ }));
1289
+ }), this.cleans.push(this.player.on("state:paused", (e) => {
1290
+ e && this.emit("playback.pause", "playback", this.withQoe({ currentTime: this.player.getState().currentTime }));
1291
+ })), this.cleans.push(this.player.on("state:buffered", (e) => {
1292
+ this.player.getState().readyState === 2 && this.rebufferStartedAt === null && (this.rebufferStartedAt = Date.now(), this.rebufferCount += 1, this.emit("playback.buffering_start", "qoe", this.withQoe({
1293
+ currentTime: this.player.getState().currentTime,
1294
+ rebufferCount: this.rebufferCount,
1295
+ sinceStartMs: Date.now() - this.sessionStartedAt
1296
+ })));
1297
+ })), this.cleans.push(this.player.on("state:readyState", (e) => {
1298
+ if (e === 4 && this.rebufferStartedAt !== null) {
1299
+ let e = Date.now() - this.rebufferStartedAt;
1300
+ this.totalRebufferMs += e, this.rebufferStartedAt = null, this.emit("playback.buffering_end", "qoe", this.withQoe({
1301
+ currentTime: this.player.getState().currentTime,
1302
+ rebufferMs: e,
1303
+ rebufferCount: this.rebufferCount,
1304
+ totalRebufferMs: this.totalRebufferMs,
1305
+ sinceStartMs: Date.now() - this.sessionStartedAt
1306
+ }));
1307
+ }
1308
+ })), this.cleans.push(this.player.on("state:selectedQuality", (e) => {
1309
+ let t = this.player.getState().availableQualities.find((e) => e.selected);
1310
+ this.bitrateTimeline.push({
1311
+ at: Date.now(),
1312
+ bitrate: t?.bitrate || null,
1313
+ quality: e
1314
+ }), this.emit("track.quality_changed", "track", this.withQoe({ quality: e }));
1315
+ })), 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) => {
1316
+ let t = e?.error || e;
1317
+ this.emit("error.classified", "error", {
1318
+ classification: this.classifyError(t),
1319
+ code: t?.code,
1320
+ message: t?.message
1321
+ });
1322
+ }));
1323
+ }
1324
+ getSessionTrace() {
1325
+ return this.trace.map((e) => ({
1326
+ ...e,
1327
+ payload: JSON.parse(JSON.stringify(e.payload ?? null))
1328
+ }));
1329
+ }
1330
+ normalizeEventName(e) {
1331
+ return {
1332
+ source_loading: "source.loading",
1333
+ source_loaded: "source.loaded",
1334
+ playback_requested: "playback.requested",
1335
+ playback_started: "playback.started",
1336
+ seek_start: "playback.seek_start",
1337
+ seek_complete: "playback.seek_complete",
1338
+ error: "playback.error"
1339
+ }[e] || e;
1340
+ }
1341
+ withQoe(e) {
1342
+ let t = this.player.getState().availableQualities.find((e) => e.selected), n = this.player.getVideoPlaybackQuality?.() || void 0;
1343
+ return {
1344
+ ...e,
1345
+ qoe: {
1346
+ startupTimeMs: this.loadStartedAt && this.playbackStartedAt ? this.playbackStartedAt - this.loadStartedAt : null,
1347
+ manifestLoadMs: this.loadStartedAt && this.manifestLoadedAt ? this.manifestLoadedAt - this.loadStartedAt : null,
1348
+ firstFrameMs: this.loadStartedAt && this.firstFrameAt ? this.firstFrameAt - this.loadStartedAt : null,
1349
+ rebufferCount: this.rebufferCount,
1350
+ totalRebufferMs: this.totalRebufferMs,
1351
+ bitrate: t?.bitrate || null,
1352
+ droppedFrames: n?.droppedVideoFrames ?? null,
1353
+ bitrateTimeline: this.bitrateTimeline.slice(-20)
1354
+ }
1355
+ };
1356
+ }
1357
+ emit(e, t, n) {
1358
+ let r = Date.now(), i = {
1359
+ at: r,
1360
+ sinceStartMs: r - this.sessionStartedAt,
1361
+ event: e,
1362
+ category: t,
1363
+ payload: n
1364
+ };
1365
+ this.trace.push(i), this.trace.length > 500 && this.trace.shift(), this.adapter(e, n);
1366
+ }
1367
+ classifyError(e) {
1368
+ let t = String(e?.code || "").toLowerCase(), n = String(e?.message || "").toLowerCase();
1369
+ 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";
1370
+ }
1371
+ categoryForEvent(e) {
1372
+ return e === "error" ? "error" : e.startsWith("seek") || e.startsWith("playback") ? "playback" : e.startsWith("source") ? "lifecycle" : "qoe";
1373
+ }
1374
+ destroy() {
1375
+ this.cleans.forEach((e) => e());
1376
+ }
1377
+ }, b = class {
1378
+ player;
1379
+ mountEl;
1380
+ panel = null;
1381
+ bodyEl = null;
1382
+ visible = !0;
1383
+ events = [];
1384
+ cleans = [];
1385
+ constructor(e, t) {
1386
+ this.player = e, this.mountEl = t || document.body, this.inject(), this.bind();
1387
+ }
1388
+ inject() {
1389
+ 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);
1390
+ }
1391
+ bind() {
1392
+ [
1393
+ "source_loading",
1394
+ "source_loaded",
1395
+ "playback_requested",
1396
+ "playback_started",
1397
+ "seek_start",
1398
+ "seek_complete",
1399
+ "error",
1400
+ "state:change"
1401
+ ].forEach((e) => {
1402
+ this.cleans.push(this.player.on(e, (t) => {
1403
+ this.events.unshift({
1404
+ name: e,
1405
+ payload: t,
1406
+ ts: Date.now()
1407
+ }), this.events.length > 25 && (this.events.length = 25), this.render();
1408
+ }));
1409
+ }), this.render();
1410
+ }
1411
+ render() {
1412
+ if (!this.bodyEl || !this.visible) return;
1413
+ let e = this.player.getState(), t = this.events.slice(0, 8).map((e) => `${new Date(e.ts).toLocaleTimeString()} ${e.name}`).join("\n"), n = [
1414
+ `Engine: ${e.engineType || "none"}`,
1415
+ `Status: ${e.status}`,
1416
+ `Time: ${e.currentTime.toFixed(2)} / ${Number.isFinite(e.duration) ? e.duration.toFixed(2) : "live"}`,
1417
+ `Buffered: ${e.buffered.map((e) => `[${e.start.toFixed(1)}-${e.end.toFixed(1)}]`).join(", ") || "none"}`,
1418
+ `Quality: ${e.selectedQuality}`,
1419
+ `Subtitles: ${e.selectedSubtitle || "none"}`,
1420
+ `Audio: ${e.selectedAudioTrack}`,
1421
+ `Bitrate: ${e.availableQualities.find((e) => e.selected)?.bitrate || "n/a"}`,
1422
+ `Error: ${e.error ? `${e.error.code} ${e.error.message}` : "none"}`,
1423
+ "",
1424
+ "Recent Events:",
1425
+ t || "none"
1426
+ ].join("\n");
1427
+ this.bodyEl.innerText = n;
1428
+ }
1429
+ setVisible(e) {
1430
+ this.visible = e, this.panel && (this.panel.style.display = e ? "block" : "none"), e && this.render();
1431
+ }
1432
+ isVisible() {
1433
+ return this.visible;
1434
+ }
1435
+ destroy() {
1436
+ this.cleans.forEach((e) => e()), this.cleans = [], this.panel &&= (this.panel.remove(), null), this.bodyEl = null;
1437
+ }
1438
+ }, x = () => Date.now(), S = class {
1439
+ startedAt = x();
1440
+ waitingStartedAt = null;
1441
+ startupStallStartedAt = null;
1442
+ awaitingFirstFrameAfterPlay = !1;
1443
+ seenTelemetry = /* @__PURE__ */ new Set();
1444
+ startup = this.createStartup(this.startedAt);
1445
+ sessionTrace = [];
1446
+ createStartup(e) {
1447
+ return {
1448
+ playerCreatedAt: e,
1449
+ sourceLoadRequestedAt: null,
1450
+ manifestRequestStartedAt: null,
1451
+ manifestReceivedAt: null,
1452
+ manifestParseStartedAt: null,
1453
+ manifestParseCompletedAt: null,
1454
+ firstSegmentRequestStartedAt: null,
1455
+ firstSegmentReceivedAt: null,
1456
+ firstAppendCompletedAt: null,
1457
+ playCalledAt: null,
1458
+ firstFrameAt: null,
1459
+ startupCompletedAt: null,
1460
+ startupDurationMs: null,
1461
+ sourceLoadToFirstFrameMs: null,
1462
+ playToFirstFrameMs: null,
1463
+ manifestToFirstFrameMs: null,
1464
+ totalRebufferCount: 0,
1465
+ totalRebufferDurationMs: 0,
1466
+ startupStallCount: 0,
1467
+ startupStallMs: 0,
1468
+ retryEvents: 0,
1469
+ errorEvents: 0,
1470
+ bitrateOverTime: []
1471
+ };
1472
+ }
1473
+ resetForNewSource() {
1474
+ this.startedAt = x(), this.waitingStartedAt = null, this.startupStallStartedAt = null, this.awaitingFirstFrameAfterPlay = !1, this.seenTelemetry.clear(), this.startup = this.createStartup(this.startedAt), this.sessionTrace = [];
1475
+ }
1476
+ mark(e, t = x()) {
1477
+ this.startup[e] === null && (this.startup[e] = t);
1478
+ }
1479
+ onSourceLoadRequested() {
1480
+ this.mark("sourceLoadRequestedAt"), this.pushTrace("source_load_requested", "lifecycle", void 0);
1481
+ }
1482
+ onPlayCalled() {
1483
+ this.startup.playCalledAt === null && (this.mark("playCalledAt"), this.awaitingFirstFrameAfterPlay = !0, this.pushTrace("play_called", "playback", void 0));
1484
+ }
1485
+ onFirstFrame() {
1486
+ 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));
1487
+ }
1488
+ finalizeStartup(e) {
1489
+ if (this.startup.startupCompletedAt !== null) return;
1490
+ this.startup.startupCompletedAt = e;
1491
+ let t = this.startup.playCalledAt;
1492
+ if (t !== null) {
1493
+ if (e < t) return;
1494
+ this.startup.startupDurationMs = e - t;
1495
+ } else {
1496
+ let t = this.startup.sourceLoadRequestedAt ?? this.startedAt;
1497
+ if (e < t) return;
1498
+ this.startup.startupDurationMs = e - t;
1499
+ }
1500
+ this.awaitingFirstFrameAfterPlay = !1, this.pushTrace("startup_completed", "lifecycle", { startupDurationMs: this.startup.startupDurationMs });
1501
+ }
1502
+ onWaiting() {
1503
+ if (this.waitingStartedAt !== null || this.startupStallStartedAt !== null) return;
1504
+ let e = x();
1505
+ 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 }));
1506
+ }
1507
+ onPlaying() {
1508
+ 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) {
1509
+ let e = x() - this.waitingStartedAt;
1510
+ this.startup.totalRebufferDurationMs += e, this.waitingStartedAt = null, this.pushTrace("rebuffer_end", "qoe", { totalRebufferDurationMs: this.startup.totalRebufferDurationMs });
1511
+ }
1512
+ }
1513
+ onTelemetry(e, t = x(), n) {
1514
+ let r = {
1515
+ manifest_request_started: "manifestRequestStartedAt",
1516
+ manifest_received: "manifestReceivedAt",
1517
+ manifest_parse_started: "manifestParseStartedAt",
1518
+ manifest_parse_completed: "manifestParseCompletedAt",
1519
+ first_segment_request_started: "firstSegmentRequestStartedAt",
1520
+ first_segment_received: "firstSegmentReceivedAt",
1521
+ first_append_completed: "firstAppendCompletedAt"
1522
+ }[e];
1523
+ 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({
1524
+ at: t,
1525
+ bitrate: n.bitrate
1526
+ }), e.toLowerCase().includes("retry") && (this.startup.retryEvents += 1), this.pushTrace(e, "lifecycle", n);
1527
+ }
1528
+ onError(e) {
1529
+ this.startup.errorEvents += 1, this.pushTrace("error", "error", e);
1530
+ }
1531
+ getStartupMetrics() {
1532
+ let e = this.startup, t = (e, t) => e !== null && t !== null ? e - t : null;
1533
+ return {
1534
+ ...e,
1535
+ sourceLoadToFirstFrameMs: t(e.firstFrameAt, e.sourceLoadRequestedAt),
1536
+ playToFirstFrameMs: t(e.firstFrameAt, e.playCalledAt),
1537
+ manifestToFirstFrameMs: t(e.firstFrameAt, e.manifestReceivedAt),
1538
+ startupStallCount: e.startupStallCount,
1539
+ startupStallMs: e.startupStallMs,
1540
+ bitrateOverTime: [...e.bitrateOverTime]
1541
+ };
1542
+ }
1543
+ getSessionTrace() {
1544
+ return [...this.sessionTrace];
1545
+ }
1546
+ printStartupReport() {
1547
+ let e = this.getStartupMetrics(), t = (e) => e === null ? "n/a" : `${Math.round(e)}ms`, n = (t) => t === null ? null : t - e.playerCreatedAt;
1548
+ console.group("[Flux] Startup Report"), console.table({
1549
+ startupDuration: t(e.startupDurationMs),
1550
+ manifestRequestToReceived: t(e.manifestRequestStartedAt && e.manifestReceivedAt ? e.manifestReceivedAt - e.manifestRequestStartedAt : null),
1551
+ parseDuration: t(e.manifestParseStartedAt && e.manifestParseCompletedAt ? e.manifestParseCompletedAt - e.manifestParseStartedAt : null),
1552
+ firstSegmentNetwork: t(e.firstSegmentRequestStartedAt && e.firstSegmentReceivedAt ? e.firstSegmentReceivedAt - e.firstSegmentRequestStartedAt : null),
1553
+ firstAppendToFrame: t(e.firstAppendCompletedAt && e.firstFrameAt ? e.firstFrameAt - e.firstAppendCompletedAt : null),
1554
+ rebufferCount: e.totalRebufferCount,
1555
+ rebufferDuration: t(e.totalRebufferDurationMs),
1556
+ retryEvents: e.retryEvents,
1557
+ errorEvents: e.errorEvents
1558
+ }), console.log("Timeline (ms from player create):", {
1559
+ sourceLoadRequested: n(e.sourceLoadRequestedAt),
1560
+ manifestRequestStarted: n(e.manifestRequestStartedAt),
1561
+ manifestReceived: n(e.manifestReceivedAt),
1562
+ manifestParseStarted: n(e.manifestParseStartedAt),
1563
+ manifestParseCompleted: n(e.manifestParseCompletedAt),
1564
+ firstSegmentRequestStarted: n(e.firstSegmentRequestStartedAt),
1565
+ firstSegmentReceived: n(e.firstSegmentReceivedAt),
1566
+ firstAppendCompleted: n(e.firstAppendCompletedAt),
1567
+ playCalled: n(e.playCalledAt),
1568
+ firstFrame: n(e.firstFrameAt),
1569
+ startupCompleted: n(e.startupCompletedAt)
1570
+ }), console.groupEnd();
1571
+ }
1572
+ pushTrace(e, t, n) {
1573
+ let r = x();
1574
+ this.sessionTrace.push({
1575
+ at: r,
1576
+ sinceStartMs: r - this.startedAt,
1577
+ event: e,
1578
+ category: t,
1579
+ payload: n
1580
+ });
1581
+ }
1582
+ }, C = /* @__PURE__ */ new WeakSet(), w = /* @__PURE__ */ new Map();
1583
+ function T(e, t) {
1584
+ let n = new c();
1585
+ n.setPerformance(t.performance), n.setAbr(t.abr);
1586
+ let r = new S(), i = typeof e == "string" ? document.querySelector(e) : e;
1587
+ if (!i) throw Error("Player target element not found");
1588
+ if (C.has(i)) throw Error("Player target already mounted. Destroy previous instance before creating a new one.");
1589
+ C.add(i), n.registry.register(new l());
1590
+ let a = !1, s = !1, u = null, f = null, p = null, m = null, h;
1591
+ 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));
1592
+ let g = async (e) => {
1593
+ let t = e.type && e.type !== "auto" ? e.type : o(e.src, e.mimeType);
1594
+ if ((t === "hls" || t === "auto") && !a) try {
1595
+ let e = new (await (import("./src-DMaUVQqo.js"))).HlsEngine();
1596
+ await e.preload?.(), n.registry.register(e), a = !0;
1597
+ } catch (e) {
1598
+ console.warn("Failed to lazy load HLS engine", e);
1599
+ }
1600
+ if ((t === "dash" || t === "auto") && !s) try {
1601
+ let e = new (await (import("./src-BTcoslE8.js"))).DashEngine();
1602
+ await e.preload?.(), n.registry.register(e), s = !0;
1603
+ } catch (e) {
1604
+ console.warn("Failed to lazy load DASH engine", e);
1605
+ }
1606
+ }, x = (e) => {
1607
+ if (!t.performance?.manifestFastPath) return () => void 0;
1608
+ let n = document.createElement("link");
1609
+ return n.rel = "preload", n.as = "fetch", n.href = e, n.setAttribute("fetchpriority", "high"), n.crossOrigin = "anonymous", document.head.appendChild(n), () => {
1610
+ n.parentNode && n.parentNode.removeChild(n);
1611
+ };
1612
+ }, T = (e) => {
1613
+ if (!t.performance?.manifestFastPath) return () => void 0;
1614
+ let n = new URL(e, window.location.href).origin;
1615
+ if (w.has(n)) return () => void 0;
1616
+ let r = [], i = (e, t) => {
1617
+ let n = document.createElement("link");
1618
+ n.rel = e, n.href = t, e === "preconnect" && (n.crossOrigin = "anonymous"), document.head.appendChild(n), r.push(n);
1619
+ };
1620
+ return i("preconnect", n), i("dns-prefetch", n), w.set(n, r), () => void 0;
1621
+ }, E = !1, D = null, O = () => {
1622
+ let e = navigator;
1623
+ return typeof e.userAgentData?.mobile == "boolean" ? e.userAgentData.mobile : /android|iphone|ipad|ipod|mobile/i.test(navigator.userAgent || "");
1624
+ }, k = (e) => {
1625
+ let t = e.currentTime, n = e.buffered;
1626
+ for (let e = 0; e < n.length; e += 1) {
1627
+ let r = n.start(e), i = n.end(e);
1628
+ if (t >= r - .25 && t <= i + .05) return Math.max(0, i - t);
1629
+ }
1630
+ return 0;
1631
+ }, A = () => {
1632
+ let e = t.performance, r;
1633
+ if (typeof e?.startupBufferSeconds == "number" && Number.isFinite(e.startupBufferSeconds)) r = Math.max(0, e.startupBufferSeconds);
1634
+ else {
1635
+ let t = e?.startupStrategy ?? (e?.startupMode === "fast-first-frame" ? "aggressive" : "balanced"), i = n.getState(), a = O(), o = !!(i.isLive || i.isDvr);
1636
+ 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;
1637
+ }
1638
+ let i = navigator.connection, a = 1;
1639
+ switch (i?.saveData && (a *= 1.2), (i?.effectiveType || "").toLowerCase()) {
1640
+ case "slow-2g":
1641
+ a *= 1.7;
1642
+ break;
1643
+ case "2g":
1644
+ a *= 1.45;
1645
+ break;
1646
+ case "3g":
1647
+ a *= 1.2;
1648
+ break;
1649
+ case "4g":
1650
+ a *= .9;
1651
+ break;
1652
+ default: break;
1653
+ }
1654
+ 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);
1655
+ let o = r * a;
1656
+ return Math.max(.12, Math.min(1.5, o));
1657
+ }, j = () => {
1658
+ if ((t.performance?.startupBufferSeconds ?? 0) >= .5) return 4500;
1659
+ let e = t.performance?.startupStrategy ?? (t.performance?.startupMode === "fast-first-frame" ? "aggressive" : "balanced");
1660
+ return e === "safe" ? 3500 : e === "aggressive" ? 1200 : 2200;
1661
+ }, M = async () => {
1662
+ let e = i.querySelector("video");
1663
+ if (!e) return;
1664
+ let t = Math.max(0, A()), a = j(), o = Date.now(), s = HTMLMediaElement.HAVE_FUTURE_DATA, c = "", l = () => {
1665
+ let t = k(e), r = n.getStartupReadiness(), i = !r || r.mediaSourceReadyState === null || r?.mediaSourceReadyState === "open", a = r?.sourceBuffersUpdating !== !0, o = e.buffered.length > 0;
1666
+ return {
1667
+ ahead: t,
1668
+ readyEnough: e.readyState >= s,
1669
+ hasBufferedRange: o,
1670
+ mediaSourceOpen: i,
1671
+ sourceBuffersIdle: a,
1672
+ engineReadiness: r
1673
+ };
1674
+ }, u = (n, r) => {
1675
+ let i = t;
1676
+ 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;
1677
+ }, d = (e, t) => {
1678
+ let n = [];
1679
+ 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;
1680
+ }, f = (n, i, a) => {
1681
+ let o = d(n, a), s = o.join("|");
1682
+ !s || s === c || (c = s, r.onTelemetry("startup_gate_pending", Date.now(), {
1683
+ waitedMs: i,
1684
+ minAhead: a,
1685
+ baseMinAhead: t,
1686
+ ahead: n.ahead,
1687
+ readyState: e.readyState,
1688
+ reasons: o,
1689
+ mediaSourceReadyState: n.engineReadiness?.mediaSourceReadyState ?? null,
1690
+ sourceBuffersUpdating: n.engineReadiness?.sourceBuffersUpdating ?? null,
1691
+ appendQueueDepth: n.engineReadiness?.appendQueueDepth ?? null,
1692
+ appendWaitActive: n.engineReadiness?.appendWaitActive ?? null,
1693
+ appendBackpressureCount: n.engineReadiness?.appendBackpressureCount ?? null
1694
+ }));
1695
+ }, p = l();
1696
+ if (p.hasBufferedRange && p.readyEnough && p.ahead >= u(p, 0) && p.mediaSourceOpen && p.sourceBuffersIdle) {
1697
+ r.onTelemetry("startup_gate_ready", Date.now(), {
1698
+ minAhead: u(p, 0),
1699
+ baseMinAhead: t,
1700
+ ahead: p.ahead,
1701
+ readyState: e.readyState,
1702
+ waitedMs: 0
1703
+ });
1704
+ return;
1705
+ }
1706
+ await new Promise((n) => {
1707
+ let i = !1, s = null, c = null, d = () => {
1708
+ s !== null && window.cancelAnimationFrame(s), c !== null && window.clearTimeout(c);
1709
+ for (let t of [
1710
+ "progress",
1711
+ "loadeddata",
1712
+ "canplay",
1713
+ "canplaythrough"
1714
+ ]) e.removeEventListener(t, h);
1715
+ }, p = (e, t) => {
1716
+ i || (i = !0, d(), r.onTelemetry(e, Date.now(), t), n());
1717
+ }, m = () => {
1718
+ if (i || E) {
1719
+ d(), n();
1720
+ return;
1721
+ }
1722
+ let r = Date.now() - o, c = l(), h = u(c, r), { ahead: g, readyEnough: _, hasBufferedRange: v, mediaSourceOpen: y, sourceBuffersIdle: b } = c;
1723
+ if (v && _ && g >= h && y && b) {
1724
+ p("startup_gate_ready", {
1725
+ minAhead: h,
1726
+ baseMinAhead: t,
1727
+ ahead: g,
1728
+ readyState: e.readyState,
1729
+ waitedMs: r
1730
+ });
1731
+ return;
1732
+ }
1733
+ if (f(c, r, h), r >= a) {
1734
+ p("startup_gate_timeout", {
1735
+ minAhead: h,
1736
+ baseMinAhead: t,
1737
+ ahead: g,
1738
+ readyState: e.readyState,
1739
+ waitedMs: r
1740
+ });
1741
+ return;
1742
+ }
1743
+ s = window.requestAnimationFrame(m);
1744
+ }, h = () => {
1745
+ m();
1746
+ };
1747
+ for (let t of [
1748
+ "progress",
1749
+ "loadeddata",
1750
+ "canplay",
1751
+ "canplaythrough"
1752
+ ]) e.addEventListener(t, h);
1753
+ c = window.setTimeout(m, a), m();
1754
+ });
1755
+ }, N = () => {
1756
+ D?.(), D = null;
1757
+ let e = (e) => {
1758
+ if ("requestVideoFrameCallback" in HTMLVideoElement.prototype) {
1759
+ let t = e, n = t.requestVideoFrameCallback(() => {
1760
+ r.onFirstFrame();
1761
+ });
1762
+ D = () => {
1763
+ t.cancelVideoFrameCallback?.(n);
1764
+ };
1765
+ return;
1766
+ }
1767
+ {
1768
+ let t = null, n = Date.now(), i = () => {
1769
+ if (!e.paused && e.currentTime > 0 && e.readyState >= 2) {
1770
+ r.onFirstFrame();
1771
+ return;
1772
+ }
1773
+ Date.now() - n > 15e3 || (t = window.requestAnimationFrame(i));
1774
+ };
1775
+ t = window.requestAnimationFrame(i);
1776
+ let a = D;
1777
+ D = () => {
1778
+ a?.(), t !== null && window.cancelAnimationFrame(t);
1779
+ };
1780
+ }
1781
+ }, t = i.querySelector("video");
1782
+ if (t) {
1783
+ e(t);
1784
+ return;
1785
+ }
1786
+ let n = new MutationObserver(() => {
1787
+ let t = i.querySelector("video");
1788
+ t && (n.disconnect(), e(t));
1789
+ });
1790
+ n.observe(i, {
1791
+ childList: !0,
1792
+ subtree: !0
1793
+ }), D = () => {
1794
+ n.disconnect();
1795
+ };
1796
+ }, P = 0, F = 0, I = null, L = async (e) => {
1797
+ if (E) throw Error("Player has been destroyed");
1798
+ let t = ++P;
1799
+ D?.(), r.resetForNewSource(), r.onSourceLoadRequested();
1800
+ 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;
1801
+ try {
1802
+ await g(e), !E && t === P && await n.load(e);
1803
+ } finally {
1804
+ i(), s();
1805
+ }
1806
+ }, R = (e) => {
1807
+ ++F;
1808
+ let t = L(e);
1809
+ I = t;
1810
+ let n = () => {
1811
+ I === t && (I = null);
1812
+ };
1813
+ return t.then(n, n), t;
1814
+ };
1815
+ t.source && R(t.source).catch((e) => console.error("Autoload failed", e));
1816
+ let z = {
1817
+ load: R,
1818
+ play: async () => {
1819
+ let e = ++F;
1820
+ if (r.onPlayCalled(), I && await I, E || e !== F) return;
1821
+ let i = t.performance;
1822
+ 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();
1823
+ },
1824
+ pause: () => {
1825
+ ++F, n.pause();
1826
+ },
1827
+ destroy: async () => {
1828
+ E || (E = !0, u && u.destroy(), f && f.destroy(), p && p.destroy(), m && m.destroy(), D?.(), await n.destroy(), h?.remove(), C.delete(i));
1829
+ },
1830
+ seek: (e) => n.seek(e),
1831
+ setVolume: (e) => n.setVolume(e),
1832
+ setMuted: (e) => n.setMuted(e),
1833
+ setPlaybackRate: (e) => n.setPlaybackRate(e),
1834
+ setToolbar: (e) => u?.setToolbar(e),
1835
+ setTheme: (e) => {
1836
+ i && _(i.querySelector(".flux-player-wrapper") || i, e);
1837
+ },
1838
+ setQuality: (e) => n.setQuality(e),
1839
+ setSubtitle: (e) => n.setSubtitle(e),
1840
+ setAudioTrack: (e) => n.setAudioTrack(e),
1841
+ getState: () => n.getState(),
1842
+ getStats: () => n.getStats(),
1843
+ getStartupMetrics: () => r.getStartupMetrics(),
1844
+ printStartupReport: () => r.printStartupReport(),
1845
+ on: (e, t) => n.on(e, t)
1846
+ };
1847
+ return z.setDevtoolsVisible = (e) => {
1848
+ m?.setVisible(e);
1849
+ }, z.isDevtoolsVisible = () => m?.isVisible() ?? !1, z.getSessionTrace = () => {
1850
+ let e = p?.getSessionTrace() ?? [], t = r.getSessionTrace();
1851
+ return [...e, ...t].sort((e, t) => e.at - t.at);
1852
+ }, n.on("telemetry", (e) => {
1853
+ r.onTelemetry(e?.name || "telemetry", e?.at || Date.now(), e?.data);
1854
+ }), n.on("waiting", () => {
1855
+ r.onWaiting();
1856
+ }), n.on("playback_requested", () => r.onPlayCalled()), n.on("play", () => {
1857
+ N(), r.onPlayCalled();
1858
+ }), n.on("playing", () => {
1859
+ r.onPlaying();
1860
+ }), n.on("error", (e) => {
1861
+ r.onError(e);
1862
+ }), z;
1863
+ }
1864
+ //#endregion
1865
+ //#region packages/player/src/autoInit.ts
1866
+ var E = "[data-flux-player]", D = (e) => {
1867
+ if (e !== null) return e === "true" || e === "1";
1868
+ }, O = (e) => {
1869
+ let t = e.getAttribute("data-src");
1870
+ if (!t) throw Error("Missing data-src for data-flux-player element.");
1871
+ 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";
1872
+ return {
1873
+ source: {
1874
+ src: t,
1875
+ type: n,
1876
+ poster: r,
1877
+ thumbnailVtt: i,
1878
+ autoplay: D(e.getAttribute("data-autoplay")),
1879
+ muted: D(e.getAttribute("data-muted"))
1880
+ },
1881
+ theme: a,
1882
+ performance: { startupMode: o }
1883
+ };
1884
+ }, k = (e = {}) => {
1885
+ let t = e.selector || E, n = e.root || document, r = Array.from(n.querySelectorAll(t)).filter((e) => e instanceof HTMLElement), i = [];
1886
+ for (let e of r) {
1887
+ if (e.dataset.fluxMounted === "true") continue;
1888
+ let t = T(e, O(e));
1889
+ i.push(t), e.dataset.fluxMounted = "true";
1890
+ }
1891
+ return i;
1892
+ };
1893
+ typeof window < "u" && typeof document < "u" && window.__FLUX_AUTO_INIT__ !== !1 && (document.readyState === "loading" ? document.addEventListener("DOMContentLoaded", () => k(), { once: !0 }) : k());
1894
+ //#endregion
1895
+ //#region packages/player/src/browser.ts
1896
+ var A = {
1897
+ createPlayer: T,
1898
+ autoInitFluxPlayers: k
1899
+ };
1900
+ typeof window < "u" && (window.Flux = A);
1901
+ //#endregion
1902
+ export { A as Flux, k as autoInitFluxPlayers, T as createPlayer };