@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,439 @@
1
+ //#region packages/engine-hls/dist/src/HlsEngine.js
2
+ var e = null, t = class {
3
+ id = "hls";
4
+ isNative = !1;
5
+ video = null;
6
+ hls = null;
7
+ HlsCtor = null;
8
+ loadVersion = 0;
9
+ cancelPendingLoad;
10
+ lastSource = null;
11
+ networkRetryCount = 0;
12
+ mediaRetryCount = 0;
13
+ maxNetworkRetries = 3;
14
+ maxMediaRetries = 2;
15
+ startupAutoLevelReleaseTimer = null;
16
+ startupAutoLevelCapAppliedAt = null;
17
+ startupAutoLevelCap = -1;
18
+ appendQueueDepth = 0;
19
+ appendWaitStartedAt = null;
20
+ appendBackpressureCount = 0;
21
+ runtimeConfig = {
22
+ performance: {
23
+ startupMode: "balanced",
24
+ startupBufferSeconds: 1.2,
25
+ manifestFastPath: !1
26
+ },
27
+ abr: {
28
+ startupProfile: "balanced",
29
+ upgradeAggression: "medium",
30
+ rebufferSafetyBias: "medium"
31
+ }
32
+ };
33
+ lastRebufferDowngradeAt = 0;
34
+ listeners = /* @__PURE__ */ new Map();
35
+ domListeners = [];
36
+ setRuntimeConfig(e) {
37
+ this.runtimeConfig = {
38
+ performance: {
39
+ startupMode: e.performance?.startupMode ?? this.runtimeConfig.performance.startupMode,
40
+ startupBufferSeconds: e.performance?.startupBufferSeconds ?? this.runtimeConfig.performance.startupBufferSeconds,
41
+ manifestFastPath: e.performance?.manifestFastPath ?? this.runtimeConfig.performance.manifestFastPath
42
+ },
43
+ abr: {
44
+ startupProfile: e.abr?.startupProfile ?? this.runtimeConfig.abr.startupProfile,
45
+ upgradeAggression: e.abr?.upgradeAggression ?? this.runtimeConfig.abr.upgradeAggression,
46
+ rebufferSafetyBias: e.abr?.rebufferSafetyBias ?? this.runtimeConfig.abr.rebufferSafetyBias
47
+ }
48
+ };
49
+ }
50
+ canPlayType(e) {
51
+ return e === "hls" && typeof window < "u" && "MediaSource" in window;
52
+ }
53
+ canPlaySource(e) {
54
+ return e.toLowerCase().includes(".m3u8") && typeof window < "u" && "MediaSource" in window;
55
+ }
56
+ async preload() {
57
+ await this.ensureCtor();
58
+ }
59
+ async ensureCtor() {
60
+ return this.HlsCtor ||= (await import("./hls-Db1HP87O.js")).default, this.HlsCtor;
61
+ }
62
+ attach(e) {
63
+ this.video = e, this.bindDomEvents(), this.hls && this.hls.attachMedia(e);
64
+ }
65
+ getStartupReadiness() {
66
+ let e = this.getMediaSource(), t = this.getSourceBuffers(), n = t.length > 0 ? t.some((e) => !!e.updating) : null;
67
+ return {
68
+ mediaSourceReadyState: e?.readyState ?? null,
69
+ sourceBuffersUpdating: n,
70
+ bufferAheadSeconds: this.getBufferedAheadSeconds(),
71
+ videoReadyState: this.video?.readyState ?? null,
72
+ appendQueueDepth: this.appendQueueDepth,
73
+ appendWaitActive: this.appendWaitStartedAt !== null,
74
+ appendBackpressureCount: this.appendBackpressureCount,
75
+ appendQueueBlocked: this.appendWaitStartedAt !== null,
76
+ appendCollisions: this.appendBackpressureCount
77
+ };
78
+ }
79
+ bindDomEvents() {
80
+ if (!this.video) return;
81
+ this.unbindDomEvents();
82
+ let e = (e, t, n = () => void 0) => {
83
+ let r = (r) => {
84
+ let i = n(r);
85
+ e === "waiting" && this.rebufferAwareDowngrade(), this.emit(t, i);
86
+ };
87
+ this.video.addEventListener(e, r), this.domListeners.push({
88
+ event: e,
89
+ handler: r
90
+ });
91
+ };
92
+ 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", () => ({
93
+ volume: this.video.volume,
94
+ muted: this.video.muted
95
+ })), e("ratechange", "ratechange", () => ({ playbackRate: this.video.playbackRate })), e("progress", "progress", () => {
96
+ let e = [], t = this.video.buffered;
97
+ for (let n = 0; n < t.length; n++) e.push({
98
+ start: t.start(n),
99
+ end: t.end(n)
100
+ });
101
+ return { buffered: e };
102
+ });
103
+ }
104
+ unbindDomEvents() {
105
+ this.video && (this.domListeners.forEach(({ event: e, handler: t }) => {
106
+ this.video.removeEventListener(e, t);
107
+ }), this.domListeners = []);
108
+ }
109
+ async load(t) {
110
+ if (!this.video) throw Error("Video element not attached");
111
+ this.video.poster = t.poster || "";
112
+ let n = ++this.loadVersion;
113
+ this.lastSource = t, this.networkRetryCount = 0, this.mediaRetryCount = 0;
114
+ let r = await this.ensureCtor();
115
+ if (n === this.loadVersion) {
116
+ if (!r?.isSupported?.()) throw Error("HLS is not supported in this runtime");
117
+ return this.hls && this.hls.destroy(), new Promise((n, i) => {
118
+ this.cancelPendingLoad = () => i(new DOMException("Load superseded", "AbortError")), this.clearStartupUpswitchDelay(), this.resetAppendQueueState();
119
+ let a = !1, o = !1, s = !1, c = this.runtimeConfig.abr.startupProfile, l = this.runtimeConfig.abr.upgradeAggression, u = this.runtimeConfig.abr.rebufferSafetyBias, d = this.runtimeConfig.performance.startupMode, f = this.runtimeConfig.performance.manifestFastPath || d === "fast-first-frame", p = u === "high" ? {
120
+ abrBandWidthFactor: .7,
121
+ abrBandWidthUpFactor: .5
122
+ } : u === "low" ? {
123
+ abrBandWidthFactor: .92,
124
+ abrBandWidthUpFactor: .88
125
+ } : {
126
+ abrBandWidthFactor: .82,
127
+ abrBandWidthUpFactor: .7
128
+ }, m = l === "high" ? {
129
+ abrEwmaFastLive: 2,
130
+ abrEwmaSlowLive: 6,
131
+ abrEwmaFastVoD: 2,
132
+ abrEwmaSlowVoD: 8
133
+ } : l === "low" ? {
134
+ abrEwmaFastLive: 5,
135
+ abrEwmaSlowLive: 12,
136
+ abrEwmaFastVoD: 5,
137
+ abrEwmaSlowVoD: 14
138
+ } : {
139
+ abrEwmaFastLive: 3,
140
+ abrEwmaSlowLive: 9,
141
+ abrEwmaFastVoD: 3,
142
+ abrEwmaSlowVoD: 10
143
+ }, h = c === "fast" || d === "fast-first-frame" ? 0 : c === "quality" ? -1 : 1;
144
+ this.startupAutoLevelCap = h >= 0 ? h : 0, this.hls = new r({
145
+ enableWorker: !0,
146
+ lowLatencyMode: d === "fast-first-frame",
147
+ startLevel: h,
148
+ maxBufferLength: f ? 8 : 16,
149
+ maxMaxBufferLength: f ? 12 : 30,
150
+ renderTextTracksNatively: !0,
151
+ startFragPrefetch: f,
152
+ progressive: !1,
153
+ appendErrorMaxRetry: f ? 8 : 3,
154
+ ...e === null ? {} : { abrEwmaDefaultEstimate: e },
155
+ ...p,
156
+ ...m
157
+ }), this.emit("telemetry", {
158
+ name: "manifest_request_started",
159
+ at: Date.now()
160
+ }), this.emit("telemetry", {
161
+ name: "manifest_parse_started",
162
+ at: Date.now()
163
+ }), this.hls.loadSource(t.src), this.hls.attachMedia(this.video), (d === "fast-first-frame" || c === "fast") && (this.hls.autoLevelCapping = this.startupAutoLevelCap), this.hls.on(r.Events.MANIFEST_LOADED, () => {
164
+ this.emit("telemetry", {
165
+ name: "manifest_received",
166
+ at: Date.now()
167
+ });
168
+ }), this.hls.on(r.Events.BUFFER_CREATED, (e, t) => {
169
+ this.emit("telemetry", {
170
+ name: "append_queue_created",
171
+ at: Date.now(),
172
+ data: {
173
+ tracks: Object.keys(t?.tracks || {}),
174
+ sourceBuffers: this.getSourceBuffers().length
175
+ }
176
+ });
177
+ }), this.hls.on(r.Events.BUFFER_APPENDING, (e, t) => {
178
+ let n = this.getSourceBuffers().some((e) => e.updating);
179
+ (n || this.appendQueueDepth > 0) && (this.appendBackpressureCount += 1, this.appendWaitStartedAt === null && (this.appendWaitStartedAt = Date.now()), this.emit("telemetry", {
180
+ name: "append_queue_backpressure",
181
+ at: Date.now(),
182
+ data: {
183
+ queueDepth: this.appendQueueDepth,
184
+ updating: n,
185
+ backpressureCount: this.appendBackpressureCount,
186
+ parent: t?.parent,
187
+ type: t?.type
188
+ }
189
+ })), this.appendQueueDepth += 1, this.emit("telemetry", {
190
+ name: "append_queue_enqueue",
191
+ at: Date.now(),
192
+ data: {
193
+ queueDepth: this.appendQueueDepth,
194
+ updating: n,
195
+ parent: t?.parent,
196
+ type: t?.type
197
+ }
198
+ });
199
+ }), this.hls.on(r.Events.BUFFER_APPENDED, (e, t) => {
200
+ this.appendQueueDepth = Math.max(0, this.appendQueueDepth - 1);
201
+ let n = {
202
+ queueDepth: this.appendQueueDepth,
203
+ parent: t?.parent,
204
+ type: t?.type,
205
+ pending: t?.pending
206
+ };
207
+ this.appendQueueDepth === 0 && this.appendWaitStartedAt !== null ? (n.waitedMs = Date.now() - this.appendWaitStartedAt, n.backpressureCount = this.appendBackpressureCount, this.appendWaitStartedAt = null, this.emit("telemetry", {
208
+ name: "append_queue_wait_cleared",
209
+ at: Date.now(),
210
+ data: n
211
+ })) : this.emit("telemetry", {
212
+ name: "append_queue_appended",
213
+ at: Date.now(),
214
+ data: n
215
+ }), this.maybeReleaseStartupQualityCap("append_backpressure_cleared");
216
+ }), this.hls.on(r.Events.MANIFEST_PARSED, () => {
217
+ this.emit("telemetry", {
218
+ name: "manifest_parse_completed",
219
+ at: Date.now()
220
+ });
221
+ let t = this.hls?.bandwidthEstimate;
222
+ typeof t == "number" && t > 0 && (e = t), f ? queueMicrotask(() => this.syncTracks()) : this.syncTracks(), this.cancelPendingLoad = void 0, n();
223
+ }), this.hls.on(r.Events.FRAG_LOADING, () => {
224
+ a || (a = !0, this.emit("telemetry", {
225
+ name: "first_segment_request_started",
226
+ at: Date.now()
227
+ }));
228
+ }), this.hls.on(r.Events.FRAG_LOADED, () => {
229
+ o || (o = !0, this.emit("telemetry", {
230
+ name: "first_segment_received",
231
+ at: Date.now()
232
+ }), this.maybeReleaseStartupQualityCap("strong_throughput_frag_loaded"));
233
+ }), this.hls.on(r.Events.FRAG_BUFFERED, () => {
234
+ s || (s = !0, u === "high" && this.hls && (this.hls.config.maxBufferLength = 30, this.hls.config.maxMaxBufferLength = 60), this.emit("telemetry", {
235
+ name: "first_append_completed",
236
+ at: Date.now()
237
+ }), this.maybeReleaseStartupQualityCap("first_append_buffered"));
238
+ }), this.hls.on(r.Events.LEVEL_SWITCHED, (e, t) => {
239
+ this.emit("qualitychange", { level: this.hls?.autoLevelEnabled ? "auto" : t.level }), this.syncTracks();
240
+ }), this.hls.on(r.Events.SUBTITLE_TRACK_SWITCH, () => this.syncTracks()), this.hls.on(r.Events.AUDIO_TRACK_SWITCHED, () => this.syncTracks()), this.hls.on(r.Events.ERROR, (e, t) => {
241
+ if (String(t?.details || "") === "bufferAppendError" && this.emit("telemetry", {
242
+ name: "append_queue_error",
243
+ at: Date.now(),
244
+ data: {
245
+ queueDepth: this.appendQueueDepth,
246
+ updating: this.getSourceBuffers().some((e) => e.updating),
247
+ backpressureCount: this.appendBackpressureCount,
248
+ sourceBufferName: t?.sourceBufferName,
249
+ errorName: t?.error?.name || t?.err?.name || null
250
+ }
251
+ }), t.fatal) {
252
+ let e = String(t.details || "").toLowerCase(), n = /^(manifest|level|frag|audioTrack|subtitleTrack)load(error|timeout)$/i.test(e);
253
+ if (t.type === r.ErrorTypes.NETWORK_ERROR && n && ![401, 403].includes(t.response?.code) && this.networkRetryCount < this.maxNetworkRetries) {
254
+ this.networkRetryCount += 1, e.includes("manifest") && this.lastSource ? this.hls.loadSource(this.lastSource.src) : this.hls.startLoad(this.video?.currentTime ?? -1), this.emit("error", { error: {
255
+ code: `HLS_${String(t.type)}_RETRY`,
256
+ message: `Retrying network request (${this.networkRetryCount}/${this.maxNetworkRetries})`,
257
+ engine: this.id,
258
+ recoverable: !0,
259
+ originalError: t
260
+ } });
261
+ return;
262
+ }
263
+ if (t.type === r.ErrorTypes.MEDIA_ERROR && this.mediaRetryCount < this.maxMediaRetries) {
264
+ this.mediaRetryCount += 1;
265
+ let e = typeof this.hls.currentLevel == "number" ? this.hls.currentLevel : -1;
266
+ e > 0 && (this.hls.nextLevel = e - 1), this.hls.recoverMediaError(), this.emit("error", { error: {
267
+ code: `HLS_${String(t.type)}_RETRY`,
268
+ message: `Attempting media recovery (${this.mediaRetryCount}/${this.maxMediaRetries})`,
269
+ engine: this.id,
270
+ recoverable: !0,
271
+ originalError: t
272
+ } });
273
+ return;
274
+ }
275
+ this.hls.destroy(), i(/* @__PURE__ */ Error(`HLS Error: ${t.details}`)), this.emit("error", { error: {
276
+ code: `HLS_${String(t.type)}`,
277
+ message: t.details,
278
+ engine: this.id,
279
+ recoverable: !1,
280
+ originalError: t
281
+ } });
282
+ } else this.emit("error", { error: {
283
+ code: `HLS_${String(t.type)}`,
284
+ message: t.details,
285
+ engine: this.id,
286
+ recoverable: !0,
287
+ originalError: t
288
+ } });
289
+ });
290
+ });
291
+ }
292
+ }
293
+ syncTracks() {
294
+ if (!this.hls) return;
295
+ let e = this.hls.levels.map((e, t) => ({
296
+ id: t,
297
+ label: e.name || `${e.height}p`,
298
+ bitrate: e.bitrate,
299
+ width: e.width,
300
+ height: e.height,
301
+ selected: this.hls.currentLevel === t
302
+ })), t = this.hls.subtitleTracks.map((e, t) => ({
303
+ id: String(t),
304
+ label: e.name || e.lang || `Track ${t}`,
305
+ language: e.lang,
306
+ selected: this.hls.subtitleTrack === t
307
+ })), n = this.hls.audioTracks.map((e, t) => ({
308
+ id: String(t),
309
+ label: e.name || e.lang || `Audio ${t}`,
310
+ language: e.lang,
311
+ selected: this.hls.audioTrack === t
312
+ }));
313
+ this.emit("trackschange", {
314
+ qualities: e,
315
+ subtitles: t,
316
+ audioTracks: n
317
+ });
318
+ }
319
+ rebufferAwareDowngrade() {
320
+ if (!this.hls) return;
321
+ let e = Date.now();
322
+ if (e - this.lastRebufferDowngradeAt < 2e3 || !this.video || this.video.currentTime < .5) return;
323
+ let t = this.runtimeConfig.abr.rebufferSafetyBias, n = typeof this.hls.currentLevel == "number" ? this.hls.currentLevel : -1;
324
+ if (!(n > 0)) return;
325
+ let r = Math.max(0, n - (t === "high" ? 2 : 1));
326
+ this.hls.nextLevel = r, this.lastRebufferDowngradeAt = e, this.emit("telemetry", {
327
+ name: "abr_rebuffer_downgrade",
328
+ at: e,
329
+ data: {
330
+ from: n,
331
+ to: r,
332
+ bias: t
333
+ }
334
+ });
335
+ }
336
+ async play() {
337
+ this.armStartupUpswitchDelay(), await this.video?.play();
338
+ }
339
+ pause() {
340
+ this.video?.pause();
341
+ }
342
+ async destroy() {
343
+ ++this.loadVersion, this.cancelPendingLoad?.(), this.cancelPendingLoad = void 0, this.unbindDomEvents(), this.clearStartupUpswitchDelay(), this.resetAppendQueueState(), this.hls &&= (this.hls.destroy(), null), this.video && (this.video.src = "", this.video.removeAttribute("src")), this.video = null, this.listeners.clear();
344
+ }
345
+ seek(e) {
346
+ this.video && (this.video.currentTime = e);
347
+ }
348
+ setVolume(e) {
349
+ this.video && (this.video.volume = e);
350
+ }
351
+ setMuted(e) {
352
+ this.video && (this.video.muted = e);
353
+ }
354
+ setPlaybackRate(e) {
355
+ this.video && (this.video.playbackRate = e);
356
+ }
357
+ setQuality(e) {
358
+ this.hls && (e === "auto" ? this.hls.currentLevel = -1 : this.hls.currentLevel = Number(e), this.emit("qualitychange", { level: e }));
359
+ }
360
+ setSubtitle(e) {
361
+ this.hls && (e === null ? (this.hls.subtitleTrack = -1, this.hls.subtitleDisplay = !1) : (this.hls.subtitleTrack = Number(e), this.hls.subtitleDisplay = !1));
362
+ }
363
+ setAudioTrack(e) {
364
+ this.hls && (this.hls.audioTrack = Number(e));
365
+ }
366
+ on(e, t) {
367
+ let n = e;
368
+ return this.listeners.has(n) || this.listeners.set(n, []), this.listeners.get(n).push(t), () => this.off(e, t);
369
+ }
370
+ off(e, t) {
371
+ let n = e, r = this.listeners.get(n);
372
+ if (!r) return;
373
+ let i = r.indexOf(t);
374
+ i > -1 && r.splice(i, 1);
375
+ }
376
+ emit(e, t) {
377
+ let n = e, r = this.listeners.get(n);
378
+ if (r) for (let e of [...r]) e(t);
379
+ }
380
+ getBufferedAheadSeconds() {
381
+ if (!this.video) return null;
382
+ let e = this.video.currentTime, t = this.video.buffered;
383
+ for (let n = 0; n < t.length; n += 1) {
384
+ let r = t.start(n), i = t.end(n);
385
+ if (e >= r - .25 && e <= i + .05) return Math.max(0, i - e);
386
+ }
387
+ return 0;
388
+ }
389
+ getMediaSource() {
390
+ let e = this.hls?.mediaSource;
391
+ if (e?.sourceBuffers) return e;
392
+ let t = this.hls?.bufferController?.mediaSource;
393
+ return t?.sourceBuffers ? t : null;
394
+ }
395
+ getSourceBuffers() {
396
+ let e = this.getMediaSource();
397
+ if (e?.sourceBuffers) return Array.from(e.sourceBuffers);
398
+ let t = this.hls?.bufferController?.sourceBuffer;
399
+ return t && typeof t == "object" ? Object.values(t).filter(Boolean) : [];
400
+ }
401
+ clearStartupUpswitchDelay() {
402
+ this.startupAutoLevelReleaseTimer !== null && (window.clearTimeout(this.startupAutoLevelReleaseTimer), this.startupAutoLevelReleaseTimer = null), this.startupAutoLevelCapAppliedAt = null;
403
+ }
404
+ resetAppendQueueState() {
405
+ this.appendQueueDepth = 0, this.appendWaitStartedAt = null, this.appendBackpressureCount = 0;
406
+ }
407
+ releaseStartupQualityCap(e) {
408
+ if (!this.hls || this.hls.autoLevelCapping === -1) return;
409
+ let t = Date.now(), n = this.startupAutoLevelCapAppliedAt === null ? null : t - this.startupAutoLevelCapAppliedAt;
410
+ this.clearStartupUpswitchDelay(), this.hls.autoLevelCapping = -1, this.emit("telemetry", {
411
+ name: "startup_quality_cap_released",
412
+ at: t,
413
+ data: {
414
+ reason: e,
415
+ heldMs: n
416
+ }
417
+ });
418
+ }
419
+ maybeReleaseStartupQualityCap(e) {
420
+ if (!this.hls || this.hls.autoLevelCapping === -1 || (this.startupAutoLevelCapAppliedAt === null ? 0 : Date.now() - this.startupAutoLevelCapAppliedAt) < 1200) return;
421
+ let t = this.hls.bandwidthEstimate;
422
+ if (typeof t != "number" || !Number.isFinite(t) || t <= 0) return;
423
+ let n = typeof this.hls.currentLevel == "number" && this.hls.currentLevel >= 0 ? this.hls.currentLevel : this.startupAutoLevelCap, r = this.hls.levels?.[n]?.bitrate, i = this.getBufferedAheadSeconds() ?? 0;
424
+ (typeof r == "number" && t >= r * 2.5 || t >= 6e6) && i >= 1.2 && this.releaseStartupQualityCap(e);
425
+ }
426
+ armStartupUpswitchDelay() {
427
+ if (!this.hls) return;
428
+ let e = this.runtimeConfig.abr.startupProfile;
429
+ this.runtimeConfig.performance.startupMode !== "fast-first-frame" && e !== "fast" || (this.clearStartupUpswitchDelay(), this.hls.autoLevelCapping = this.startupAutoLevelCap, this.startupAutoLevelCapAppliedAt = Date.now(), this.emit("telemetry", {
430
+ name: "startup_quality_cap_applied",
431
+ at: this.startupAutoLevelCapAppliedAt,
432
+ data: { levelCap: this.startupAutoLevelCap }
433
+ }), this.startupAutoLevelReleaseTimer = window.setTimeout(() => {
434
+ this.releaseStartupQualityCap("timeout");
435
+ }, 8e3));
436
+ }
437
+ };
438
+ //#endregion
439
+ export { t as HlsEngine };