@scarlett-player/hls 1.1.1 → 1.4.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.
package/dist/index.js CHANGED
@@ -1,15 +1,20 @@
1
1
  import {
2
- formatLevel,
3
- getInitialBandwidthEstimate,
4
- mapLevels,
5
- setupHlsEventHandlers,
6
- setupVideoEventHandlers
7
- } from "./chunk-L73PRXS4.js";
8
-
9
- // src/index.ts
10
- import { ErrorCode } from "@scarlett-player/core";
2
+ __export,
3
+ createHLSPluginWith
4
+ } from "./chunk-IFUZZQQE.js";
11
5
 
12
6
  // src/hls-loader.ts
7
+ var hls_loader_exports = {};
8
+ __export(hls_loader_exports, {
9
+ createHlsInstance: () => createHlsInstance,
10
+ getHlsConstructor: () => getHlsConstructor,
11
+ isHLSSupported: () => isHLSSupported,
12
+ isHlsJsSupported: () => isHlsJsSupported,
13
+ loadHlsJs: () => loadHlsJs,
14
+ resetLoader: () => resetLoader,
15
+ shouldPreferNativeHLS: () => shouldPreferNativeHLS,
16
+ supportsNativeHLS: () => supportsNativeHLS
17
+ });
13
18
  var hlsConstructor = null;
14
19
  var loadingPromise = null;
15
20
  function supportsNativeHLS() {
@@ -17,6 +22,13 @@ function supportsNativeHLS() {
17
22
  const video = document.createElement("video");
18
23
  return video.canPlayType("application/vnd.apple.mpegurl") !== "";
19
24
  }
25
+ function shouldPreferNativeHLS() {
26
+ if (!supportsNativeHLS()) return false;
27
+ if (typeof navigator === "undefined") return false;
28
+ const ua = navigator.userAgent;
29
+ const isSafari = /Safari/.test(ua) && !/Chrome/.test(ua) && !/CriOS/.test(ua);
30
+ return isSafari;
31
+ }
20
32
  function isHlsJsSupported() {
21
33
  if (hlsConstructor) {
22
34
  return hlsConstructor.isSupported();
@@ -60,692 +72,23 @@ function createHlsInstance(config) {
60
72
  function getHlsConstructor() {
61
73
  return hlsConstructor;
62
74
  }
75
+ function resetLoader() {
76
+ hlsConstructor = null;
77
+ loadingPromise = null;
78
+ }
63
79
 
64
80
  // src/index.ts
65
- var DEFAULT_CONFIG = {
66
- debug: false,
67
- autoStartLoad: true,
68
- startPosition: -1,
69
- lowLatencyMode: false,
70
- maxBufferLength: 30,
71
- maxMaxBufferLength: 600,
72
- backBufferLength: 30,
73
- enableWorker: true,
74
- capLevelToPlayerSize: true,
75
- // Error recovery settings
76
- maxNetworkRetries: 3,
77
- maxMediaRetries: 2,
78
- retryDelayMs: 1e3,
79
- retryBackoffFactor: 2,
80
- // Load watchdog: never leave the viewer on an endless spinner
81
- loadTimeoutMs: 3e4,
82
- // Self-healing: reconnect automatically after fatal errors mid-playback
83
- autoReconnect: true,
84
- reconnectBaseDelayMs: 2e3,
85
- reconnectMaxDelayMs: 3e4,
86
- reconnectWindowMs: 3e5
87
- };
88
- var MANIFEST_PHASE_ERRORS = [
89
- "manifestLoadError",
90
- "manifestLoadTimeOut",
91
- "manifestParsingError"
92
- ];
93
81
  function createHLSPlugin(config) {
94
- const mergedConfig = { ...DEFAULT_CONFIG, ...config };
95
- let api = null;
96
- let hls = null;
97
- let video = null;
98
- let isNative = false;
99
- let currentSrc = null;
100
- let cleanupHlsEvents = null;
101
- let cleanupVideoEvents = null;
102
- let isAutoQuality = true;
103
- let networkRetryCount = 0;
104
- let mediaRetryCount = 0;
105
- let retryTimeout = null;
106
- let errorCount = 0;
107
- let errorWindowStart = 0;
108
- const MAX_ERRORS_IN_WINDOW = 10;
109
- const ERROR_WINDOW_MS = 5e3;
110
- let hasPlayedContent = false;
111
- let reconnectTimer = null;
112
- let reconnectAttempts = 0;
113
- let reconnectWindowStart = 0;
114
- let reconnectResumePosition = 0;
115
- let onlineListener = null;
116
- const getOrCreateVideo = () => {
117
- if (video) return video;
118
- const existing = api?.container.querySelector("video");
119
- if (existing) {
120
- video = existing;
121
- return video;
122
- }
123
- video = document.createElement("video");
124
- video.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;display:block;object-fit:contain;background:#000";
125
- video.preload = "metadata";
126
- video.controls = false;
127
- video.playsInline = true;
128
- const poster = api?.getState("poster");
129
- if (poster) {
130
- video.poster = poster;
131
- }
132
- api?.container.appendChild(video);
133
- return video;
134
- };
135
- const cleanup = () => {
136
- cleanupHlsEvents?.();
137
- cleanupHlsEvents = null;
138
- cleanupVideoEvents?.();
139
- cleanupVideoEvents = null;
140
- if (retryTimeout) {
141
- clearTimeout(retryTimeout);
142
- retryTimeout = null;
143
- }
144
- if (hls) {
145
- hls.destroy();
146
- hls = null;
147
- }
148
- currentSrc = null;
149
- isNative = false;
150
- isAutoQuality = true;
151
- networkRetryCount = 0;
152
- mediaRetryCount = 0;
153
- errorCount = 0;
154
- errorWindowStart = 0;
155
- };
156
- const buildHlsConfig = () => ({
157
- debug: mergedConfig.debug,
158
- autoStartLoad: mergedConfig.autoStartLoad,
159
- startPosition: mergedConfig.startPosition,
160
- startLevel: -1,
161
- // Auto quality selection (ABR)
162
- abrEwmaDefaultEstimate: getInitialBandwidthEstimate(mergedConfig.initialBandwidthEstimate),
163
- lowLatencyMode: mergedConfig.lowLatencyMode,
164
- maxBufferLength: mergedConfig.maxBufferLength,
165
- maxMaxBufferLength: mergedConfig.maxMaxBufferLength,
166
- backBufferLength: mergedConfig.backBufferLength,
167
- enableWorker: mergedConfig.enableWorker,
168
- capLevelToPlayerSize: mergedConfig.capLevelToPlayerSize,
169
- // Minimize hls.js internal retries - we handle retries ourselves
170
- fragLoadingMaxRetry: 1,
171
- manifestLoadingMaxRetry: 1,
172
- levelLoadingMaxRetry: 1,
173
- fragLoadingRetryDelay: 500,
174
- manifestLoadingRetryDelay: 500,
175
- levelLoadingRetryDelay: 500
176
- });
177
- const getRetryDelay = (retryCount) => {
178
- const baseDelay = mergedConfig.retryDelayMs ?? 1e3;
179
- const backoffFactor = mergedConfig.retryBackoffFactor ?? 2;
180
- const delay = baseDelay * Math.pow(backoffFactor, retryCount);
181
- const jitter = delay * (0.7 + Math.random() * 0.3);
182
- return jitter;
183
- };
184
- const mapFatalErrorCode = (error) => {
185
- switch (error.type) {
186
- case "network":
187
- return ErrorCode.MEDIA_NETWORK_ERROR;
188
- case "media":
189
- case "mux":
190
- return ErrorCode.MEDIA_DECODE_ERROR;
191
- default:
192
- return ErrorCode.PLAYBACK_FAILED;
193
- }
194
- };
195
- const emitFatalError = (error, retriesExhausted) => {
196
- const message = retriesExhausted ? `HLS error: ${error.details} (max retries exceeded)` : `HLS error: ${error.details}`;
197
- api?.logger.error(message, { type: error.type, details: error.details });
198
- api?.setState("playbackState", "error");
199
- api?.setState("buffering", false);
200
- api?.emit("error", {
201
- code: mapFatalErrorCode(error),
202
- message,
203
- fatal: true,
204
- timestamp: Date.now()
205
- });
206
- maybeScheduleReconnect(error);
207
- };
208
- const handleHlsError = (error) => {
209
- const Hls = getHlsConstructor();
210
- if (!Hls || !hls) return false;
211
- const now = Date.now();
212
- if (now - errorWindowStart > ERROR_WINDOW_MS) {
213
- errorCount = 1;
214
- errorWindowStart = now;
215
- } else {
216
- errorCount++;
217
- }
218
- if (errorCount >= MAX_ERRORS_IN_WINDOW) {
219
- api?.logger.error(`Too many errors (${errorCount} in ${ERROR_WINDOW_MS}ms), giving up`);
220
- emitFatalError(error, true);
221
- cleanupHlsEvents?.();
222
- cleanupHlsEvents = null;
223
- hls.destroy();
224
- hls = null;
225
- return true;
226
- }
227
- if (error.fatal) {
228
- api?.logger.error("Fatal HLS error", { type: error.type, details: error.details });
229
- switch (error.type) {
230
- case "network": {
231
- const maxRetries = mergedConfig.maxNetworkRetries ?? 3;
232
- if (networkRetryCount >= maxRetries) {
233
- api?.logger.error(`Network error recovery failed after ${networkRetryCount} attempts`);
234
- emitFatalError(error, true);
235
- return true;
236
- }
237
- networkRetryCount++;
238
- const delay = getRetryDelay(networkRetryCount - 1);
239
- api?.logger.info(`Attempting network error recovery (attempt ${networkRetryCount}/${maxRetries}) in ${delay}ms`);
240
- api?.emit("error:network", { error: new Error(error.details) });
241
- if (retryTimeout) {
242
- clearTimeout(retryTimeout);
243
- }
244
- const isManifestPhase = MANIFEST_PHASE_ERRORS.includes(error.details);
245
- retryTimeout = setTimeout(() => {
246
- if (!hls) return;
247
- if (isManifestPhase && currentSrc) {
248
- hls.loadSource(currentSrc);
249
- } else {
250
- hls.startLoad();
251
- }
252
- }, delay);
253
- break;
254
- }
255
- case "media": {
256
- const maxRetries = mergedConfig.maxMediaRetries ?? 2;
257
- if (mediaRetryCount >= maxRetries) {
258
- api?.logger.error(`Media error recovery failed after ${mediaRetryCount} attempts`);
259
- emitFatalError(error, true);
260
- return true;
261
- }
262
- mediaRetryCount++;
263
- const delay = getRetryDelay(mediaRetryCount - 1);
264
- api?.logger.info(`Attempting media error recovery (attempt ${mediaRetryCount}/${maxRetries}) in ${delay}ms`);
265
- api?.emit("error:media", { error: new Error(error.details) });
266
- if (retryTimeout) {
267
- clearTimeout(retryTimeout);
268
- }
269
- retryTimeout = setTimeout(() => {
270
- if (hls) {
271
- hls.recoverMediaError();
272
- }
273
- }, delay);
274
- break;
275
- }
276
- default:
277
- emitFatalError(error, false);
278
- return true;
279
- }
280
- }
281
- return false;
282
- };
283
- const loadNative = async (src) => {
284
- const videoEl = getOrCreateVideo();
285
- isNative = true;
286
- if (api) {
287
- cleanupVideoEvents = setupVideoEventHandlers(videoEl, api);
288
- }
289
- return new Promise((resolve, reject) => {
290
- let watchdog = null;
291
- const settle = () => {
292
- videoEl.removeEventListener("loadedmetadata", onLoaded);
293
- videoEl.removeEventListener("error", onError);
294
- if (watchdog !== null) {
295
- clearTimeout(watchdog);
296
- watchdog = null;
297
- }
298
- };
299
- const onLoaded = () => {
300
- settle();
301
- hasPlayedContent = true;
302
- const onFatalVideoError = () => {
303
- const media_error = videoEl.error;
304
- const hls_error = {
305
- type: media_error?.code === MediaError.MEDIA_ERR_NETWORK ? "network" : "media",
306
- details: media_error?.message || "Native HLS playback error",
307
- fatal: true
308
- };
309
- emitFatalError(hls_error, false);
310
- };
311
- videoEl.addEventListener("error", onFatalVideoError);
312
- const removeFatalListener = () => videoEl.removeEventListener("error", onFatalVideoError);
313
- const previous_cleanup = cleanupVideoEvents;
314
- cleanupVideoEvents = () => {
315
- removeFatalListener();
316
- previous_cleanup?.();
317
- };
318
- api?.setState("source", { src, type: "application/x-mpegURL" });
319
- api?.emit("media:loaded", { src, type: "application/x-mpegURL" });
320
- resolve();
321
- };
322
- const onError = () => {
323
- settle();
324
- const error = videoEl.error;
325
- reject(new Error(error?.message || "Failed to load HLS source"));
326
- };
327
- const timeout_ms = mergedConfig.loadTimeoutMs ?? 3e4;
328
- if (timeout_ms > 0) {
329
- watchdog = setTimeout(() => {
330
- settle();
331
- reject(new Error("Video took too long to load (network timeout)"));
332
- }, timeout_ms);
333
- }
334
- videoEl.addEventListener("loadedmetadata", onLoaded);
335
- videoEl.addEventListener("error", onError);
336
- videoEl.src = src;
337
- videoEl.load();
338
- });
339
- };
340
- const loadWithHlsJs = async (src) => {
341
- await loadHlsJs();
342
- const videoEl = getOrCreateVideo();
343
- isNative = false;
344
- hls = createHlsInstance(buildHlsConfig());
345
- if (api) {
346
- cleanupVideoEvents = setupVideoEventHandlers(videoEl, api);
347
- }
348
- return new Promise((resolve, reject) => {
349
- if (!hls || !api) {
350
- reject(new Error("HLS not initialized"));
351
- return;
352
- }
353
- let resolved = false;
354
- let watchdog = null;
355
- const clearWatchdog = () => {
356
- if (watchdog !== null) {
357
- clearTimeout(watchdog);
358
- watchdog = null;
359
- }
360
- };
361
- cleanupHlsEvents = setupHlsEventHandlers(hls, api, {
362
- onManifestParsed: () => {
363
- if (!resolved) {
364
- resolved = true;
365
- clearWatchdog();
366
- hasPlayedContent = true;
367
- api?.setState("source", { src, type: "application/x-mpegURL" });
368
- api?.emit("media:loaded", { src, type: "application/x-mpegURL" });
369
- resolve();
370
- }
371
- },
372
- onLevelSwitched: () => {
373
- },
374
- onError: (error) => {
375
- const terminal = handleHlsError(error);
376
- if (terminal && !resolved) {
377
- resolved = true;
378
- clearWatchdog();
379
- reject(new Error(error.details));
380
- }
381
- },
382
- onFragLoaded: () => {
383
- if (networkRetryCount > 0 || mediaRetryCount > 0) {
384
- api?.logger.debug("Playback recovered, resetting retry budgets");
385
- networkRetryCount = 0;
386
- mediaRetryCount = 0;
387
- }
388
- },
389
- getIsAutoQuality: () => isAutoQuality
390
- });
391
- const timeout_ms = mergedConfig.loadTimeoutMs ?? 3e4;
392
- if (timeout_ms > 0) {
393
- watchdog = setTimeout(() => {
394
- if (resolved) return;
395
- resolved = true;
396
- api?.logger.error(`HLS load timed out after ${timeout_ms}ms`, { src });
397
- if (retryTimeout) {
398
- clearTimeout(retryTimeout);
399
- retryTimeout = null;
400
- }
401
- cleanupHlsEvents?.();
402
- cleanupHlsEvents = null;
403
- hls?.destroy();
404
- hls = null;
405
- reject(new Error("Video took too long to load (network timeout)"));
406
- }, timeout_ms);
407
- }
408
- hls.attachMedia(videoEl);
409
- hls.loadSource(src);
410
- });
411
- };
412
- const cancelReconnect = () => {
413
- if (reconnectTimer) {
414
- clearTimeout(reconnectTimer);
415
- reconnectTimer = null;
416
- }
417
- reconnectAttempts = 0;
418
- reconnectWindowStart = 0;
419
- reconnectResumePosition = 0;
420
- };
421
- const scheduleReconnectAttempt = () => {
422
- if (reconnectTimer) return;
423
- const window_ms = mergedConfig.reconnectWindowMs ?? 3e5;
424
- if (Date.now() - reconnectWindowStart > window_ms) {
425
- api?.logger.warn(`Auto-reconnect window exhausted after ${reconnectAttempts} attempts`);
426
- return;
427
- }
428
- const base_delay = mergedConfig.reconnectBaseDelayMs ?? 2e3;
429
- const max_delay = mergedConfig.reconnectMaxDelayMs ?? 3e4;
430
- const backoff = Math.min(base_delay * Math.pow(2, reconnectAttempts), max_delay);
431
- const delay = Math.round(backoff * (0.7 + Math.random() * 0.3));
432
- api?.logger.info(`Scheduling auto-reconnect attempt ${reconnectAttempts + 1} in ${delay}ms`);
433
- api?.emit("error:reconnecting", { attempt: reconnectAttempts + 1, delayMs: delay });
434
- reconnectTimer = setTimeout(() => {
435
- reconnectTimer = null;
436
- void attemptReconnect();
437
- }, delay);
438
- };
439
- const maybeScheduleReconnect = (error) => {
440
- if (mergedConfig.autoReconnect === false) return;
441
- if (!hasPlayedContent || !currentSrc) return;
442
- if (error.type !== "network" && error.type !== "media") return;
443
- if (reconnectWindowStart === 0) {
444
- reconnectWindowStart = Date.now();
445
- reconnectResumePosition = video?.currentTime ?? 0;
446
- }
447
- scheduleReconnectAttempt();
448
- };
449
- const attemptReconnect = async () => {
450
- if (!api || !currentSrc) return;
451
- reconnectAttempts++;
452
- const saved_src = currentSrc;
453
- const was_live = api.getState("live");
454
- const was_native = isNative;
455
- const resume_position = reconnectResumePosition;
456
- api.logger.info(`Auto-reconnect attempt ${reconnectAttempts}`, { src: saved_src });
457
- try {
458
- cleanupHlsEvents?.();
459
- cleanupHlsEvents = null;
460
- cleanupVideoEvents?.();
461
- cleanupVideoEvents = null;
462
- if (retryTimeout) {
463
- clearTimeout(retryTimeout);
464
- retryTimeout = null;
465
- }
466
- hls?.destroy();
467
- hls = null;
468
- networkRetryCount = 0;
469
- mediaRetryCount = 0;
470
- errorCount = 0;
471
- errorWindowStart = 0;
472
- currentSrc = saved_src;
473
- api.setState("playbackState", "loading");
474
- if (was_native && supportsNativeHLS()) {
475
- await loadNative(saved_src);
476
- } else {
477
- await loadWithHlsJs(saved_src);
478
- }
479
- if (!was_live && video && resume_position > 0) {
480
- video.currentTime = resume_position;
481
- }
482
- api.setState("playbackState", "ready");
483
- api.setState("buffering", false);
484
- api.emit("error:recovered", void 0);
485
- api.logger.info("Auto-reconnect succeeded");
486
- cancelReconnect();
487
- try {
488
- await video?.play();
489
- } catch {
490
- }
491
- } catch {
492
- api?.logger.warn(`Auto-reconnect attempt ${reconnectAttempts} failed`);
493
- scheduleReconnectAttempt();
494
- }
495
- };
496
- const plugin = {
497
- id: "hls-provider",
498
- name: "HLS Provider",
499
- version: "1.0.0",
500
- type: "provider",
501
- description: "HLS playback provider using hls.js",
502
- canPlay(src) {
503
- if (!isHLSSupported()) return false;
504
- const url = src.toLowerCase();
505
- const urlWithoutQuery = url.split("?")[0].split("#")[0];
506
- if (urlWithoutQuery.endsWith(".m3u8")) return true;
507
- if (url.includes("application/x-mpegurl")) return true;
508
- if (url.includes("application/vnd.apple.mpegurl")) return true;
509
- return false;
82
+ return createHLSPluginWith(
83
+ hls_loader_exports,
84
+ {
85
+ name: "HLS Provider",
86
+ description: "HLS playback provider using hls.js",
87
+ logSuffix: "",
88
+ engineLabel: "hls.js"
510
89
  },
511
- async init(pluginApi) {
512
- api = pluginApi;
513
- api.logger.info("HLS plugin initialized");
514
- const unsubPlay = api.on("playback:play", async () => {
515
- if (!video) return;
516
- try {
517
- await video.play();
518
- } catch (e) {
519
- api?.logger.error("Play failed", e);
520
- }
521
- });
522
- const unsubPause = api.on("playback:pause", () => {
523
- video?.pause();
524
- });
525
- const unsubSeek = api.on("playback:seeking", ({ time }) => {
526
- if (!video) return;
527
- const clampedTime = Math.max(0, Math.min(time, video.duration || 0));
528
- video.currentTime = clampedTime;
529
- });
530
- const unsubVolume = api.on("volume:change", ({ volume }) => {
531
- if (video) video.volume = volume;
532
- });
533
- const unsubMute = api.on("volume:mute", ({ muted }) => {
534
- if (video) video.muted = muted;
535
- });
536
- const unsubRate = api.on("playback:ratechange", ({ rate }) => {
537
- if (video) video.playbackRate = rate;
538
- });
539
- const unsubQuality = api.on("quality:select", ({ quality, auto }) => {
540
- if (!hls || isNative) {
541
- api?.logger.warn("Quality selection not available");
542
- return;
543
- }
544
- if (auto || quality === "auto") {
545
- isAutoQuality = true;
546
- hls.currentLevel = -1;
547
- api?.logger.debug("Quality: auto selection enabled");
548
- api?.setState("currentQuality", {
549
- id: "auto",
550
- label: "Auto",
551
- width: 0,
552
- height: 0,
553
- bitrate: 0,
554
- active: true
555
- });
556
- } else {
557
- isAutoQuality = false;
558
- const levelIndex = parseInt(quality.replace("level-", ""), 10);
559
- if (!isNaN(levelIndex) && levelIndex >= 0 && levelIndex < hls.levels.length) {
560
- hls.nextLevel = levelIndex;
561
- api?.logger.debug(`Quality: queued switch to level ${levelIndex}`);
562
- const targetLevel = hls.levels[levelIndex];
563
- if (targetLevel) {
564
- const label = formatLevel(targetLevel);
565
- api?.setState("currentQuality", {
566
- id: `level-${levelIndex}`,
567
- label: `${label}...`,
568
- // Ellipsis indicates switching in progress
569
- width: targetLevel.width,
570
- height: targetLevel.height,
571
- bitrate: targetLevel.bitrate,
572
- active: false
573
- // Not yet active
574
- });
575
- }
576
- }
577
- }
578
- });
579
- if (typeof window !== "undefined") {
580
- onlineListener = () => {
581
- if (reconnectTimer) {
582
- api?.logger.info("Browser back online, reconnecting immediately");
583
- clearTimeout(reconnectTimer);
584
- reconnectTimer = null;
585
- void attemptReconnect();
586
- }
587
- };
588
- window.addEventListener("online", onlineListener);
589
- }
590
- api.onDestroy(() => {
591
- unsubPlay();
592
- unsubPause();
593
- unsubSeek();
594
- unsubVolume();
595
- unsubMute();
596
- unsubRate();
597
- unsubQuality();
598
- });
599
- },
600
- async destroy() {
601
- api?.logger.info("HLS plugin destroying");
602
- cancelReconnect();
603
- if (onlineListener && typeof window !== "undefined") {
604
- window.removeEventListener("online", onlineListener);
605
- onlineListener = null;
606
- }
607
- cleanup();
608
- if (video?.parentNode) {
609
- video.parentNode.removeChild(video);
610
- }
611
- video = null;
612
- api = null;
613
- },
614
- async loadSource(src) {
615
- if (!api) throw new Error("Plugin not initialized");
616
- api.logger.info("Loading HLS source", { src });
617
- cancelReconnect();
618
- hasPlayedContent = false;
619
- cleanup();
620
- currentSrc = src;
621
- api.setState("playbackState", "loading");
622
- api.setState("buffering", true);
623
- if (api.getState("airplayActive") && supportsNativeHLS()) {
624
- api.logger.info("Using native HLS (AirPlay active)");
625
- await loadNative(src);
626
- } else if (isHlsJsSupported()) {
627
- api.logger.info("Using hls.js for HLS playback");
628
- await loadWithHlsJs(src);
629
- } else if (supportsNativeHLS()) {
630
- api.logger.info("Using native HLS playback (hls.js not supported)");
631
- await loadNative(src);
632
- } else {
633
- throw new Error("HLS playback not supported in this browser");
634
- }
635
- if (video) {
636
- const muted = api.getState("muted");
637
- const volume = api.getState("volume");
638
- if (muted !== void 0) video.muted = muted;
639
- if (volume !== void 0) video.volume = volume;
640
- }
641
- api.setState("playbackState", "ready");
642
- api.setState("buffering", false);
643
- },
644
- getCurrentLevel() {
645
- if (isNative || !hls) return -1;
646
- return hls.currentLevel;
647
- },
648
- setLevel(index) {
649
- if (isNative || !hls) {
650
- api?.logger.warn("Quality selection not available in native HLS mode");
651
- return;
652
- }
653
- hls.currentLevel = index;
654
- },
655
- getLevels() {
656
- if (isNative || !hls) return [];
657
- return mapLevels(hls.levels, hls.currentLevel);
658
- },
659
- getHlsInstance() {
660
- return hls;
661
- },
662
- isNativeHLS() {
663
- return isNative;
664
- },
665
- getLiveInfo() {
666
- if (isNative || !hls) return null;
667
- const live = api?.getState("live") || false;
668
- if (!live) return null;
669
- return {
670
- isLive: true,
671
- latency: hls.latency || 0,
672
- targetLatency: hls.targetLatency || 3,
673
- drift: hls.drift || 0
674
- };
675
- },
676
- /**
677
- * Switch from hls.js to native HLS playback.
678
- * Used for AirPlay compatibility in Safari.
679
- * Preserves current playback position.
680
- */
681
- async switchToNative() {
682
- if (isNative) {
683
- api?.logger.debug("Already using native HLS");
684
- return;
685
- }
686
- if (!supportsNativeHLS()) {
687
- api?.logger.warn("Native HLS not supported in this browser");
688
- return;
689
- }
690
- if (!currentSrc) {
691
- api?.logger.warn("No source loaded");
692
- return;
693
- }
694
- api?.logger.info("Switching to native HLS for AirPlay");
695
- const wasPlaying = api?.getState("playing") || false;
696
- const currentTime = video?.currentTime || 0;
697
- const savedSrc = currentSrc;
698
- cleanup();
699
- await loadNative(savedSrc);
700
- if (video && currentTime > 0) {
701
- video.currentTime = currentTime;
702
- }
703
- if (wasPlaying && video) {
704
- try {
705
- await video.play();
706
- } catch (e) {
707
- api?.logger.debug("Could not auto-resume after switch");
708
- }
709
- }
710
- api?.logger.info("Switched to native HLS");
711
- },
712
- /**
713
- * Switch from native HLS back to hls.js.
714
- * Restores quality control after AirPlay session ends.
715
- */
716
- async switchToHlsJs() {
717
- if (!isNative) {
718
- api?.logger.debug("Already using hls.js");
719
- return;
720
- }
721
- if (!isHlsJsSupported()) {
722
- api?.logger.warn("hls.js not supported in this browser");
723
- return;
724
- }
725
- if (!currentSrc) {
726
- api?.logger.warn("No source loaded");
727
- return;
728
- }
729
- api?.logger.info("Switching back to hls.js");
730
- const wasPlaying = api?.getState("playing") || false;
731
- const currentTime = video?.currentTime || 0;
732
- const savedSrc = currentSrc;
733
- cleanup();
734
- await loadWithHlsJs(savedSrc);
735
- if (video && currentTime > 0) {
736
- video.currentTime = currentTime;
737
- }
738
- if (wasPlaying && video) {
739
- try {
740
- await video.play();
741
- } catch (e) {
742
- api?.logger.debug("Could not auto-resume after switch");
743
- }
744
- }
745
- api?.logger.info("Switched to hls.js");
746
- }
747
- };
748
- return plugin;
90
+ config
91
+ );
749
92
  }
750
93
  var index_default = createHLSPlugin;
751
94
  export {