@livo-tv/blocks 1.26.0 → 1.27.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
@@ -3365,877 +3365,928 @@ function SeekBar({
3365
3365
  );
3366
3366
  }
3367
3367
 
3368
- // src/components/video/hls-config.ts
3369
- function shouldRetryLiveEdge404(retryConfig, retryCount, _isTimeout, loaderResponse, defaultRetry) {
3370
- if (loaderResponse?.code === 404) {
3371
- return retryConfig != null && retryCount < retryConfig.maxNumRetry;
3368
+ // src/components/video/captions.ts
3369
+ var CAPTION_LOCALES = ["en", "es", "pt"];
3370
+ var LIVE_CUE_EXTRA_LAG_MS = 2e3;
3371
+ var LIVE_STACK_MAX_CUES = 150;
3372
+ var CAPTION_CHARS_PER_SECOND = 17;
3373
+ var CAPTION_MIN_DWELL_MS = 1200;
3374
+ var CAPTION_MAX_DWELL_MS = 6e3;
3375
+ var CAPTION_RUSH_DWELL_MS = 2500;
3376
+ var CAPTION_MAX_CHARS_PER_LINE = 42;
3377
+ var CAPTION_COMPACT_CHARS_PER_LINE = 32;
3378
+ var CAPTION_MAX_LINES = 2;
3379
+ var CAPTION_BACKLOG_DROP = 8;
3380
+ var CAPTION_GAP_FILL_MS = 1e3;
3381
+ var LIVE_LAG_SPIKE_MS = 2500;
3382
+ var CAPTION_BREAK_PUNCT = /[.,;:?!]$/;
3383
+ var CAPTION_MIN_PUNCT_LINE = 8;
3384
+ var EMPTY_LIVE_CAPTION_PLAYOUT = {
3385
+ screen: null,
3386
+ hideAt: 0,
3387
+ cursor: 0,
3388
+ queue: []
3389
+ };
3390
+ function stabilizeLiveLagMs(previous, next) {
3391
+ if (previous == null || !Number.isFinite(previous)) return next;
3392
+ if (next <= previous) return next;
3393
+ if (next - previous < LIVE_LAG_SPIKE_MS) return previous;
3394
+ return next;
3395
+ }
3396
+ function isCaptionLocale(value) {
3397
+ return CAPTION_LOCALES.includes(value);
3398
+ }
3399
+ function isLivePlaylistSrc(src) {
3400
+ return /\/live\//i.test(src);
3401
+ }
3402
+ function captionsVttUrlFromPlayback(src, locale) {
3403
+ const trimmed = src.trim();
3404
+ if (!trimmed) return null;
3405
+ const replaced = trimmed.replace(
3406
+ /index\.m3u8(?:\?.*)?$/i,
3407
+ `subs/${locale}.vtt`
3408
+ );
3409
+ if (replaced === trimmed) return null;
3410
+ return replaced;
3411
+ }
3412
+ function liveCaptionsUrl(base, locale) {
3413
+ return `${base.replace(/\/$/, "")}/${locale}`;
3414
+ }
3415
+ function parseCaptionVtt(text) {
3416
+ const cues = [];
3417
+ const blocks = text.replace(/^\uFEFF?WEBVTT[^\n]*\n/i, "").split(/\n\s*\n/);
3418
+ for (const block of blocks) {
3419
+ const lines = block.split("\n").map((line) => line.trim()).filter(Boolean);
3420
+ const timing = lines.find((line) => line.includes("-->"));
3421
+ if (!timing) continue;
3422
+ const [startRaw, endRaw] = timing.split("-->").map((part) => part.trim());
3423
+ if (!startRaw || !endRaw) continue;
3424
+ const textLines = lines.filter(
3425
+ (line) => line !== timing && !/^\d+$/.test(line)
3426
+ );
3427
+ const payload = textLines.join("\n").trim();
3428
+ if (!payload) continue;
3429
+ cues.push({
3430
+ start: parseVttTimestamp(startRaw.split(" ")[0] ?? startRaw),
3431
+ end: parseVttTimestamp(endRaw.split(" ")[0] ?? endRaw),
3432
+ text: payload
3433
+ });
3372
3434
  }
3373
- return defaultRetry;
3435
+ return cues;
3374
3436
  }
3375
- var liveEdgeErrorRetry = {
3376
- maxNumRetry: 8,
3377
- retryDelayMs: 250,
3378
- maxRetryDelayMs: 4e3,
3379
- backoff: "exponential",
3380
- shouldRetry: shouldRetryLiveEdge404
3381
- };
3382
- function createLiveHlsConfig() {
3383
- return {
3384
- enableWorker: true,
3385
- // No custom request headers: Cache-Control/Pragma are not
3386
- // CORS-safelisted and would force an OPTIONS preflight before every
3387
- // manifest poll and segment fetch. Freshness is controlled by the
3388
- // origin's response Cache-Control headers instead.
3389
- liveSyncDurationCount: 4,
3390
- liveMaxLatencyDurationCount: 12,
3391
- fragLoadPolicy: {
3392
- default: {
3393
- maxTimeToFirstByteMs: 1e4,
3394
- maxLoadTimeMs: 12e4,
3395
- timeoutRetry: {
3396
- maxNumRetry: 4,
3397
- retryDelayMs: 0,
3398
- maxRetryDelayMs: 0
3399
- },
3400
- errorRetry: liveEdgeErrorRetry
3401
- }
3402
- },
3403
- playlistLoadPolicy: {
3404
- default: {
3405
- maxTimeToFirstByteMs: 1e4,
3406
- maxLoadTimeMs: 3e4,
3407
- timeoutRetry: {
3408
- maxNumRetry: 2,
3409
- retryDelayMs: 0,
3410
- maxRetryDelayMs: 0
3411
- },
3412
- errorRetry: {
3413
- ...liveEdgeErrorRetry,
3414
- maxNumRetry: 6
3437
+ function captionScreenRow(text, speaker) {
3438
+ return speaker == null ? { text } : { text, speaker };
3439
+ }
3440
+ function chunkLongWord(word, maxCharsPerLine) {
3441
+ if (word.length <= maxCharsPerLine) return [word];
3442
+ const parts = [];
3443
+ for (let index = 0; index < word.length; index += maxCharsPerLine) {
3444
+ parts.push(word.slice(index, index + maxCharsPerLine));
3445
+ }
3446
+ return parts;
3447
+ }
3448
+ function wrapCaptionLines(text, maxCharsPerLine) {
3449
+ const tokens = text.split(" ").filter(Boolean).flatMap((word) => chunkLongWord(word, maxCharsPerLine));
3450
+ const lines = [];
3451
+ let index = 0;
3452
+ while (index < tokens.length) {
3453
+ let end = index;
3454
+ let length = 0;
3455
+ while (end < tokens.length) {
3456
+ const added = tokens[end].length + (end > index ? 1 : 0);
3457
+ if (length + added > maxCharsPerLine && end > index) break;
3458
+ length += added;
3459
+ end += 1;
3460
+ }
3461
+ let breakAt = end;
3462
+ if (end < tokens.length) {
3463
+ for (let cursor = end - 1; cursor > index; cursor -= 1) {
3464
+ if (!CAPTION_BREAK_PUNCT.test(tokens[cursor])) continue;
3465
+ const firstLen = tokens.slice(index, cursor + 1).join(" ").length;
3466
+ if (firstLen >= Math.min(CAPTION_MIN_PUNCT_LINE, maxCharsPerLine)) {
3467
+ breakAt = cursor + 1;
3415
3468
  }
3469
+ break;
3416
3470
  }
3417
3471
  }
3418
- };
3472
+ lines.push(tokens.slice(index, breakAt).join(" "));
3473
+ index = breakAt;
3474
+ }
3475
+ return lines;
3419
3476
  }
3420
- function createVodHlsConfig() {
3421
- return {
3422
- enableWorker: true,
3423
- startPosition: 0
3424
- };
3477
+ function balanceCaptionLines(lines, maxCharsPerLine) {
3478
+ const next = [...lines];
3479
+ for (let index = 0; index + 1 < next.length; index += CAPTION_MAX_LINES) {
3480
+ const left = next[index].split(" ");
3481
+ const right = next[index + 1].split(" ");
3482
+ if (right.length !== 1 || left.length < 3) continue;
3483
+ const moved = left[left.length - 1];
3484
+ const newRight = `${moved} ${right[0]}`;
3485
+ if (newRight.length > maxCharsPerLine) continue;
3486
+ next[index] = left.slice(0, -1).join(" ");
3487
+ next[index + 1] = newRight;
3488
+ }
3489
+ return next;
3425
3490
  }
3426
-
3427
- // src/components/video/hls-errors.ts
3428
- var MEDIA_ERROR_NAMES = {
3429
- 1: "MEDIA_ERR_ABORTED",
3430
- 2: "MEDIA_ERR_NETWORK",
3431
- 3: "MEDIA_ERR_DECODE",
3432
- 4: "MEDIA_ERR_SRC_NOT_SUPPORTED"
3433
- };
3434
- var MEDIA_ERR_NETWORK = 2;
3435
- var MEDIA_ERR_DECODE = 3;
3436
- var MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
3437
- function errorMessageFromUnknown(error) {
3438
- if (error instanceof Error) return error.message;
3439
- if (typeof error === "string") return error;
3440
- return void 0;
3491
+ function splitCaptionScreens(text, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
3492
+ const trimmed = text.trim().replace(/\s+/g, " ");
3493
+ if (!trimmed) return [];
3494
+ const lines = balanceCaptionLines(
3495
+ wrapCaptionLines(trimmed, maxCharsPerLine),
3496
+ maxCharsPerLine
3497
+ );
3498
+ const screens = [];
3499
+ for (let index = 0; index < lines.length; index += CAPTION_MAX_LINES) {
3500
+ screens.push(lines.slice(index, index + CAPTION_MAX_LINES).join("\n"));
3501
+ }
3502
+ return screens;
3441
3503
  }
3442
- function isNotFound(httpStatus, details) {
3443
- return httpStatus === 404 || details === "manifestLoadError" || details === "levelLoadError" || details === "fragLoadError";
3504
+ function captionDwellMs(text, backlog = 0) {
3505
+ const chars = text.replace(/\s+/g, " ").trim().length;
3506
+ const raw = chars / CAPTION_CHARS_PER_SECOND * 1e3;
3507
+ const max = backlog > 0 ? CAPTION_RUSH_DWELL_MS : CAPTION_MAX_DWELL_MS;
3508
+ return Math.min(max, Math.max(CAPTION_MIN_DWELL_MS, raw));
3444
3509
  }
3445
- function kindForHls(input) {
3446
- const httpStatus = input.response?.code;
3447
- if (input.type === "networkError" && isNotFound(httpStatus, input.details)) {
3448
- return input.context.mode === "vod" || !input.context.manifestParsed ? "unavailable" : "network";
3510
+ function advanceLiveCaptionPlayout(state, cues, now, lagMs, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
3511
+ let screen = state.screen;
3512
+ let hideAt = state.hideAt;
3513
+ let cursor = state.cursor;
3514
+ let queue = state.queue.slice();
3515
+ if (lagMs != null && Number.isFinite(lagMs) && lagMs >= 0) {
3516
+ const threshold = lagMs + LIVE_CUE_EXTRA_LAG_MS;
3517
+ const incoming = cues.filter(
3518
+ (cue) => Boolean(cue.text.trim()) && Number.isFinite(cue.receivedAt) && cue.receivedAt > cursor && now - cue.receivedAt >= threshold
3519
+ ).sort((left, right) => left.receivedAt - right.receivedAt);
3520
+ for (const cue of incoming) {
3521
+ for (const text of splitCaptionScreens(cue.text, maxCharsPerLine)) {
3522
+ queue.push(captionScreenRow(text, cue.speaker));
3523
+ }
3524
+ cursor = cue.receivedAt;
3525
+ }
3526
+ if (queue.length > CAPTION_BACKLOG_DROP) {
3527
+ queue = queue.slice(queue.length - CAPTION_BACKLOG_DROP);
3528
+ }
3449
3529
  }
3450
- if (input.type === "mediaError" || input.details === "bufferAppendError" || input.details === "bufferSeekOverHole") {
3451
- return "media";
3530
+ if (now >= hideAt) {
3531
+ const next = queue.shift();
3532
+ if (next) {
3533
+ screen = next;
3534
+ hideAt = now + captionDwellMs(next.text, queue.length);
3535
+ } else {
3536
+ screen = null;
3537
+ }
3452
3538
  }
3453
- return "generic";
3539
+ return { screen, hideAt, cursor, queue };
3454
3540
  }
3455
- function kindForNative(input) {
3456
- const code = input.mediaError?.code;
3457
- if (code === MEDIA_ERR_DECODE) return "media";
3458
- if (code === MEDIA_ERR_SRC_NOT_SUPPORTED) return "unsupported";
3459
- if (code === MEDIA_ERR_NETWORK) return "unavailable";
3460
- return "generic";
3541
+ function cueEndWithGapFill(cues, index) {
3542
+ const cue = cues[index];
3543
+ if (!cue) return 0;
3544
+ const next = cues[index + 1];
3545
+ if (!next || !Number.isFinite(next.start)) return cue.end;
3546
+ const gapMs = (next.start - cue.end) * 1e3;
3547
+ if (gapMs > 0 && gapMs < CAPTION_GAP_FILL_MS) return next.start;
3548
+ return cue.end;
3461
3549
  }
3462
- function describeAvResync(input) {
3463
- const lag = Number.isFinite(input.lagSeconds) ? input.lagSeconds : 0;
3464
- return {
3465
- summary: `av-resync lag=${lag.toFixed(3)}s (non-fatal)`,
3466
- kind: "resync",
3467
- detail: {
3468
- source: input.context.source,
3469
- kind: "resync",
3470
- fatal: false,
3471
- reason: `presented frame lag ${lag.toFixed(3)}s`,
3472
- context: input.context
3550
+ function captionScreenAtTime(cues, time, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
3551
+ if (!Number.isFinite(time)) return null;
3552
+ const ordered = cues.filter(
3553
+ (cue) => Boolean(cue.text.trim()) && Number.isFinite(cue.start) && Number.isFinite(cue.end)
3554
+ ).sort((left, right) => left.start - right.start);
3555
+ for (let index = 0; index < ordered.length; index += 1) {
3556
+ const cue = ordered[index];
3557
+ const end = cueEndWithGapFill(ordered, index);
3558
+ if (time < cue.start || time >= end) continue;
3559
+ const screens = splitCaptionScreens(cue.text, maxCharsPerLine);
3560
+ if (screens.length === 0) return null;
3561
+ const weights = screens.map(
3562
+ (text) => Math.max(1, text.replace(/\s+/g, "").length)
3563
+ );
3564
+ const total = weights.reduce((sum, weight) => sum + weight, 0);
3565
+ const duration = Math.max(end - cue.start, 0);
3566
+ let cursor = cue.start;
3567
+ for (let screenIndex = 0; screenIndex < screens.length; screenIndex += 1) {
3568
+ const isLast = screenIndex === screens.length - 1;
3569
+ const slice = isLast ? end - cursor : duration * (weights[screenIndex] / total);
3570
+ const sliceEnd = cursor + slice;
3571
+ if (time >= cursor && time < sliceEnd) {
3572
+ return captionScreenRow(screens[screenIndex]);
3573
+ }
3574
+ cursor = sliceEnd;
3473
3575
  }
3474
- };
3576
+ return captionScreenRow(screens[screens.length - 1]);
3577
+ }
3578
+ return null;
3475
3579
  }
3476
- function describePlaybackError(input) {
3477
- if (input.source === "unsupported") {
3478
- return {
3479
- summary: "playback unsupported (hls.js unavailable, native HLS unsupported)",
3480
- kind: "unsupported",
3481
- detail: {
3482
- source: "unsupported",
3483
- kind: "unsupported",
3484
- context: input.context
3580
+ var LIVE_OVERLAP_MIN_WORDS = 4;
3581
+ function normalizeLiveCaptionText(text) {
3582
+ return text.trim().replace(/\s+/g, " ").toLowerCase();
3583
+ }
3584
+ function lastSubseqIndex(haystack, needle) {
3585
+ if (needle.length === 0 || needle.length > haystack.length) return -1;
3586
+ let found = -1;
3587
+ for (let index = 0; index <= haystack.length - needle.length; index += 1) {
3588
+ let match = true;
3589
+ for (let offset = 0; offset < needle.length; offset += 1) {
3590
+ if (haystack[index + offset] !== needle[offset]) {
3591
+ match = false;
3592
+ break;
3485
3593
  }
3486
- };
3487
- }
3488
- if (input.source === "native") {
3489
- const code = input.mediaError?.code;
3490
- const kind2 = kindForNative(input);
3491
- const detail2 = {
3492
- source: "native",
3493
- kind: kind2,
3494
- mediaErrorCode: code,
3495
- mediaErrorName: code !== void 0 ? MEDIA_ERROR_NAMES[code] : void 0,
3496
- errorMessage: input.mediaError?.message,
3497
- context: input.context
3498
- };
3499
- const name = detail2.mediaErrorName ?? "MEDIA_ERR_UNKNOWN";
3500
- return {
3501
- summary: `native ${name}${input.mediaError?.message ? `: ${input.mediaError.message}` : ""}`,
3502
- kind: kind2,
3503
- detail: detail2
3504
- };
3594
+ }
3595
+ if (match) found = index;
3505
3596
  }
3506
- const httpStatus = input.response?.code;
3507
- const kind = kindForHls(input);
3508
- const detail = {
3509
- source: "hls",
3510
- kind,
3511
- type: input.type,
3512
- details: input.details,
3513
- fatal: input.fatal,
3514
- httpStatus,
3515
- url: input.url,
3516
- reason: input.reason,
3517
- errorMessage: errorMessageFromUnknown(input.error),
3518
- context: input.context
3519
- };
3520
- const statusSuffix = httpStatus !== void 0 ? ` ${httpStatus}` : "";
3521
- const summary = [
3522
- "hls",
3523
- input.type ?? "unknown",
3524
- input.details ?? "unknown",
3525
- input.fatal ? "(fatal)" : "(non-fatal)",
3526
- statusSuffix.trim()
3527
- ].filter(Boolean).join(" ");
3528
- return { summary, kind, detail };
3597
+ return found;
3529
3598
  }
3530
-
3531
- // src/components/video/useHlsPlayback.ts
3532
- var RETRY_INTERVAL_MS = 3e3;
3533
- var MAX_MEDIA_ERROR_RETRIES = 5;
3534
- var DRIFT_THRESHOLD_S = 0.4;
3535
- var DRIFT_CONSECUTIVE_SAMPLES = 3;
3536
- var RESYNC_COOLDOWN_MS = 1e4;
3537
- var LIVE_EDGE_RESYNC_THRESHOLD_S = 8;
3538
- function useHlsPlayback({
3539
- src,
3540
- mode,
3541
- active,
3542
- autoPlay = false,
3543
- muted = false,
3544
- onError,
3545
- onPlayingChange,
3546
- onRebuffer,
3547
- onQualityChange
3548
- }) {
3549
- const videoRef = React9.useRef(null);
3550
- const hlsRef = React9.useRef(null);
3551
- const [state, setState] = React9.useState("idle");
3552
- const [qualities, setQualities] = React9.useState([]);
3553
- const [activeLevel, setActiveLevel] = React9.useState(-1);
3554
- const [autoplayState, setAutoplayState] = React9.useState("none");
3555
- const [error, setError] = React9.useState(null);
3556
- const [reloadKey, setReloadKey] = React9.useState(0);
3557
- const onErrorRef = React9.useRef(onError);
3558
- const onPlayingChangeRef = React9.useRef(onPlayingChange);
3559
- const onRebufferRef = React9.useRef(onRebuffer);
3560
- const onQualityChangeRef = React9.useRef(onQualityChange);
3561
- React9.useEffect(() => {
3562
- onErrorRef.current = onError;
3563
- onPlayingChangeRef.current = onPlayingChange;
3564
- onRebufferRef.current = onRebuffer;
3565
- onQualityChangeRef.current = onQualityChange;
3566
- }, [onError, onPlayingChange, onRebuffer, onQualityChange]);
3567
- const retry = React9.useCallback(() => {
3568
- setError(null);
3569
- setState("loading");
3570
- setAutoplayState("none");
3571
- setReloadKey((k) => k + 1);
3572
- }, []);
3573
- React9.useEffect(() => {
3574
- const media = videoRef.current;
3575
- if (!media || !src || !active) {
3576
- setState("idle");
3577
- return;
3578
- }
3579
- let cancelled = false;
3580
- let retryTimer = null;
3581
- let manifestParsed = false;
3582
- let mediaErrorRetries = 0;
3583
- let playbackSource = "hls";
3584
- const teardown = [];
3585
- applyMute(media);
3586
- setState("loading");
3587
- setError(null);
3588
- setAutoplayState("none");
3589
- setQualities([]);
3590
- setActiveLevel(-1);
3591
- function baseContext() {
3592
- return {
3593
- mode,
3594
- src,
3595
- manifestParsed,
3596
- retryCount: mediaErrorRetries,
3597
- source: playbackSource
3598
- };
3599
- }
3600
- function clearRetryTimer() {
3601
- if (retryTimer !== null) {
3602
- clearTimeout(retryTimer);
3603
- retryTimer = null;
3599
+ function remainderAfterOverlap(previous, next) {
3600
+ const prevWords = normalizeLiveCaptionText(previous).split(" ").filter(Boolean);
3601
+ const nextWords = next.trim().replace(/\s+/g, " ").split(" ").filter(Boolean);
3602
+ const nextNorm = nextWords.map((word) => word.toLowerCase());
3603
+ const maxN = Math.min(prevWords.length, nextNorm.length);
3604
+ for (let size = maxN; size >= LIVE_OVERLAP_MIN_WORDS; size -= 1) {
3605
+ for (let start = prevWords.length - size; start >= 0; start -= 1) {
3606
+ const gram = prevWords.slice(start, start + size);
3607
+ const index = lastSubseqIndex(nextNorm, gram);
3608
+ if (index !== -1) {
3609
+ return nextWords.slice(index + size).join(" ");
3604
3610
  }
3605
3611
  }
3606
- function destroyHls() {
3607
- hlsRef.current?.destroy();
3608
- hlsRef.current = null;
3609
- }
3610
- function reportFatal(input) {
3611
- const described = describePlaybackError(input);
3612
- onErrorRef.current?.(described);
3613
- setError(described);
3614
- setState("error");
3615
- }
3616
- function applyMute(el) {
3617
- el.muted = muted;
3612
+ }
3613
+ return null;
3614
+ }
3615
+ function liveCaptionRow(text, receivedAt, speaker) {
3616
+ return speaker == null ? { text, receivedAt } : { text, receivedAt, speaker };
3617
+ }
3618
+ function coalesceLiveCaptionCues(cues) {
3619
+ const out = [];
3620
+ for (const cue of cues) {
3621
+ const text = cue.text.trim();
3622
+ if (!text) continue;
3623
+ const last = out[out.length - 1];
3624
+ if (!last) {
3625
+ out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
3626
+ continue;
3618
3627
  }
3619
- function preserveMute(el, fn) {
3620
- const wasMuted = el.muted;
3621
- fn();
3622
- el.muted = wasMuted;
3628
+ if (last.speaker !== cue.speaker && (last.speaker != null || cue.speaker != null)) {
3629
+ out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
3630
+ continue;
3623
3631
  }
3624
- function attemptAutoplay(el) {
3625
- applyMute(el);
3626
- void el.play().then(
3627
- () => {
3628
- applyMute(el);
3629
- setAutoplayState("playing");
3630
- },
3631
- () => {
3632
- el.muted = true;
3633
- void el.play().then(
3634
- () => setAutoplayState(muted ? "playing" : "muted"),
3635
- () => {
3636
- if (el.paused) {
3637
- setAutoplayState("blocked");
3638
- return;
3639
- }
3640
- setAutoplayState(el.muted && !muted ? "muted" : "playing");
3641
- }
3642
- );
3643
- }
3632
+ const lastNorm = normalizeLiveCaptionText(last.text);
3633
+ const nextNorm = normalizeLiveCaptionText(text);
3634
+ if (lastNorm === nextNorm) continue;
3635
+ if (nextNorm.startsWith(lastNorm) || lastNorm.startsWith(nextNorm)) {
3636
+ out[out.length - 1] = liveCaptionRow(
3637
+ nextNorm.length >= lastNorm.length ? text : last.text,
3638
+ cue.receivedAt,
3639
+ cue.speaker ?? last.speaker
3644
3640
  );
3641
+ continue;
3645
3642
  }
3646
- function scheduleRetry(retryFn) {
3647
- clearRetryTimer();
3648
- if (cancelled) return;
3649
- setState("waiting");
3650
- retryTimer = setTimeout(() => {
3651
- retryTimer = null;
3652
- if (!cancelled) retryFn();
3653
- }, RETRY_INTERVAL_MS);
3654
- }
3655
- function startDriftWatchdog(el) {
3656
- if (typeof el.requestVideoFrameCallback !== "function") return;
3657
- let consecutiveLagSamples = 0;
3658
- let lastResyncAt = 0;
3659
- let handle = null;
3660
- const tick = (_now, metadata) => {
3661
- if (cancelled) return;
3662
- handle = el.requestVideoFrameCallback(tick);
3663
- if (el.paused || el.ended) {
3664
- consecutiveLagSamples = 0;
3665
- return;
3666
- }
3667
- const lag = el.currentTime - metadata.mediaTime;
3668
- if (!(lag > DRIFT_THRESHOLD_S)) {
3669
- consecutiveLagSamples = 0;
3670
- return;
3671
- }
3672
- consecutiveLagSamples += 1;
3673
- if (consecutiveLagSamples < DRIFT_CONSECUTIVE_SAMPLES) return;
3674
- const nowMs = performance.now();
3675
- if (nowMs - lastResyncAt < RESYNC_COOLDOWN_MS) return;
3676
- lastResyncAt = nowMs;
3677
- consecutiveLagSamples = 0;
3678
- if (mode === "live" && el.seekable.length > 0) {
3679
- const edge = el.seekable.end(el.seekable.length - 1);
3680
- if (edge - el.currentTime > LIVE_EDGE_RESYNC_THRESHOLD_S) {
3681
- el.currentTime = edge;
3682
- } else {
3683
- el.currentTime = el.currentTime + 1e-3;
3684
- }
3685
- } else {
3686
- el.currentTime = el.currentTime + 1e-3;
3687
- }
3688
- onErrorRef.current?.(
3689
- describeAvResync({
3690
- lagSeconds: lag,
3691
- context: baseContext()
3692
- })
3693
- );
3694
- };
3695
- handle = el.requestVideoFrameCallback(tick);
3696
- teardown.push(() => {
3697
- if (handle != null && typeof el.cancelVideoFrameCallback === "function") {
3698
- el.cancelVideoFrameCallback(handle);
3699
- }
3700
- });
3701
- }
3702
- let hasPlayed = false;
3703
- let waitingSince = null;
3704
- function onPlaying() {
3705
- manifestParsed = true;
3706
- mediaErrorRetries = 0;
3707
- clearRetryTimer();
3708
- setState("ready");
3709
- setAutoplayState(
3710
- (prev) => prev === "blocked" || prev === "none" ? "playing" : prev
3711
- );
3712
- if (waitingSince != null) {
3713
- const seconds = (performance.now() - waitingSince) / 1e3;
3714
- waitingSince = null;
3715
- if (seconds > 0) onRebufferRef.current?.(seconds);
3716
- }
3717
- hasPlayed = true;
3718
- onPlayingChangeRef.current?.(true);
3719
- }
3720
- function onPaused() {
3721
- onPlayingChangeRef.current?.(false);
3722
- }
3723
- function onWaiting() {
3724
- if (!hasPlayed || waitingSince != null) return;
3725
- waitingSince = performance.now();
3643
+ const remainder = remainderAfterOverlap(last.text, text);
3644
+ if (remainder !== null) {
3645
+ if (!remainder) continue;
3646
+ out.push(liveCaptionRow(remainder, cue.receivedAt, cue.speaker));
3647
+ continue;
3726
3648
  }
3727
- media.addEventListener("playing", onPlaying);
3728
- media.addEventListener("pause", onPaused);
3729
- media.addEventListener("ended", onPaused);
3730
- media.addEventListener("waiting", onWaiting);
3731
- teardown.push(() => {
3732
- media.removeEventListener("playing", onPlaying);
3733
- media.removeEventListener("pause", onPaused);
3734
- media.removeEventListener("ended", onPaused);
3735
- media.removeEventListener("waiting", onWaiting);
3649
+ out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
3650
+ }
3651
+ return out;
3652
+ }
3653
+ function mergeLiveCaptionCues(existing, incoming, cap = LIVE_STACK_MAX_CUES) {
3654
+ const map = /* @__PURE__ */ new Map();
3655
+ for (const cue of existing) {
3656
+ if (Number.isFinite(cue.receivedAt)) map.set(cue.receivedAt, cue);
3657
+ }
3658
+ for (const cue of incoming) {
3659
+ if (Number.isFinite(cue.receivedAt)) map.set(cue.receivedAt, cue);
3660
+ }
3661
+ return [...map.values()].sort((left, right) => left.receivedAt - right.receivedAt).slice(-Math.max(1, cap));
3662
+ }
3663
+ async function loadCaptionVtt(url) {
3664
+ try {
3665
+ const response = await fetch(url, { cache: "no-store" });
3666
+ if (!response.ok) return [];
3667
+ return parseCaptionVtt(await response.text());
3668
+ } catch {
3669
+ return [];
3670
+ }
3671
+ }
3672
+ async function loadLiveCaptions(url) {
3673
+ try {
3674
+ const response = await fetch(url, {
3675
+ cache: "no-store",
3676
+ headers: { Accept: "application/json" }
3736
3677
  });
3737
- startDriftWatchdog(media);
3738
- function initNative() {
3739
- playbackSource = "native";
3740
- manifestParsed = false;
3741
- media.removeAttribute("src");
3742
- media.load();
3743
- media.src = src;
3744
- applyMute(media);
3745
- const onReady = () => {
3746
- manifestParsed = true;
3747
- clearRetryTimer();
3748
- setState("ready");
3749
- if (mode === "live" || autoPlay) attemptAutoplay(media);
3750
- };
3751
- const onErr = () => {
3752
- if (manifestParsed) {
3753
- reportFatal({
3754
- source: "native",
3755
- mediaError: media.error,
3756
- context: baseContext()
3757
- });
3758
- return;
3759
- }
3760
- onErrorRef.current?.(
3761
- describePlaybackError({
3762
- source: "native",
3763
- mediaError: media.error,
3764
- context: baseContext()
3765
- })
3766
- );
3767
- scheduleRetry(() => {
3768
- media.src = src;
3769
- media.load();
3770
- });
3771
- };
3772
- media.addEventListener("loadedmetadata", onReady);
3773
- media.addEventListener("error", onErr);
3774
- teardown.push(() => {
3775
- media.removeEventListener("loadedmetadata", onReady);
3776
- media.removeEventListener("error", onErr);
3777
- });
3678
+ if (!response.ok) return { ok: false, cues: [] };
3679
+ const body = await response.json();
3680
+ if (!body || typeof body !== "object" || !("cues" in body)) {
3681
+ return { ok: false, cues: [] };
3778
3682
  }
3779
- function initHlsJs(Hls) {
3780
- playbackSource = "hls";
3781
- destroyHls();
3782
- manifestParsed = false;
3783
- const config = mode === "live" ? createLiveHlsConfig() : createVodHlsConfig();
3784
- const hls = new Hls(config);
3785
- hlsRef.current = hls;
3786
- hls.loadSource(src);
3787
- hls.attachMedia(media);
3788
- applyMute(media);
3789
- hls.on(Hls.Events.MANIFEST_PARSED, (_e, data) => {
3790
- manifestParsed = true;
3791
- clearRetryTimer();
3792
- setQualities(
3793
- data.levels.map((l, index) => ({ index, height: l.height }))
3794
- );
3795
- setState("ready");
3796
- if (mode === "live" || autoPlay) attemptAutoplay(media);
3797
- });
3798
- hls.on(Hls.Events.LEVEL_SWITCHED, (_e, data) => {
3799
- if (hls.autoLevelEnabled) setActiveLevel(-1);
3800
- else setActiveLevel(data.level);
3801
- const height = hls.levels?.[data.level]?.height;
3802
- onQualityChangeRef.current?.(
3803
- typeof height === "number" && height > 0 ? `${height}p` : "auto"
3804
- );
3805
- });
3806
- hls.on(Hls.Events.ERROR, (_e, data) => {
3807
- onErrorRef.current?.(
3808
- describePlaybackError({
3809
- source: "hls",
3810
- type: data.type,
3811
- details: data.details,
3812
- fatal: data.fatal,
3813
- url: data.url,
3814
- response: data.response,
3815
- reason: data.reason,
3816
- error: data.error,
3817
- context: baseContext()
3818
- })
3819
- );
3820
- if (!data.fatal) return;
3821
- if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
3822
- if (!manifestParsed) {
3823
- scheduleRetry(() => initHlsJs(Hls));
3824
- return;
3825
- }
3826
- hls.startLoad();
3827
- return;
3828
- }
3829
- mediaErrorRetries += 1;
3830
- if (mediaErrorRetries === 1) {
3831
- preserveMute(media, () => hls.recoverMediaError());
3832
- return;
3833
- }
3834
- if (mediaErrorRetries === 2) {
3835
- preserveMute(media, () => {
3836
- hls.swapAudioCodec();
3837
- hls.recoverMediaError();
3838
- });
3839
- return;
3840
- }
3841
- if (mediaErrorRetries < MAX_MEDIA_ERROR_RETRIES) {
3842
- scheduleRetry(() => initHlsJs(Hls));
3843
- return;
3844
- }
3845
- reportFatal({
3846
- source: "hls",
3847
- type: data.type,
3848
- details: data.details,
3849
- fatal: true,
3850
- url: data.url,
3851
- response: data.response,
3852
- reason: data.reason,
3853
- error: data.error,
3854
- context: baseContext()
3855
- });
3856
- });
3683
+ const rows = body.cues;
3684
+ if (!Array.isArray(rows)) return { ok: false, cues: [] };
3685
+ const cues = [];
3686
+ for (const row of rows) {
3687
+ if (!row || typeof row !== "object") continue;
3688
+ const record = row;
3689
+ if (typeof record.text !== "string" || !record.text.trim()) continue;
3690
+ if (typeof record.receivedAt !== "number" || !Number.isFinite(record.receivedAt)) {
3691
+ continue;
3692
+ }
3693
+ const parsed = {
3694
+ text: record.text.trim(),
3695
+ receivedAt: record.receivedAt
3696
+ };
3697
+ if (typeof record.speaker === "number" && Number.isFinite(record.speaker)) {
3698
+ parsed.speaker = record.speaker;
3699
+ }
3700
+ cues.push(parsed);
3857
3701
  }
3858
- async function setup() {
3859
- let Hls = null;
3860
- try {
3861
- Hls = (await import('hls.js')).default;
3862
- } catch {
3863
- Hls = null;
3702
+ return { ok: true, cues };
3703
+ } catch {
3704
+ return { ok: false, cues: [] };
3705
+ }
3706
+ }
3707
+
3708
+ // src/components/video/hls-config.ts
3709
+ function shouldRetryLiveEdge404(retryConfig, retryCount, _isTimeout, loaderResponse, defaultRetry) {
3710
+ if (loaderResponse?.code === 404) {
3711
+ return retryConfig != null && retryCount < retryConfig.maxNumRetry;
3712
+ }
3713
+ return defaultRetry;
3714
+ }
3715
+ var liveEdgeErrorRetry = {
3716
+ maxNumRetry: 8,
3717
+ retryDelayMs: 250,
3718
+ maxRetryDelayMs: 4e3,
3719
+ backoff: "exponential",
3720
+ shouldRetry: shouldRetryLiveEdge404
3721
+ };
3722
+ function createLiveHlsConfig() {
3723
+ return {
3724
+ enableWorker: true,
3725
+ // No custom request headers: Cache-Control/Pragma are not
3726
+ // CORS-safelisted and would force an OPTIONS preflight before every
3727
+ // manifest poll and segment fetch. Freshness is controlled by the
3728
+ // origin's response Cache-Control headers instead.
3729
+ liveSyncDurationCount: 4,
3730
+ liveMaxLatencyDurationCount: 12,
3731
+ fragLoadPolicy: {
3732
+ default: {
3733
+ maxTimeToFirstByteMs: 1e4,
3734
+ maxLoadTimeMs: 12e4,
3735
+ timeoutRetry: {
3736
+ maxNumRetry: 4,
3737
+ retryDelayMs: 0,
3738
+ maxRetryDelayMs: 0
3739
+ },
3740
+ errorRetry: liveEdgeErrorRetry
3864
3741
  }
3865
- if (cancelled) return;
3866
- if (Hls && Hls.isSupported()) {
3867
- initHlsJs(Hls);
3868
- } else if (media.canPlayType("application/vnd.apple.mpegurl")) {
3869
- initNative();
3870
- } else {
3871
- playbackSource = "unsupported";
3872
- reportFatal({
3873
- source: "unsupported",
3874
- context: baseContext()
3875
- });
3742
+ },
3743
+ playlistLoadPolicy: {
3744
+ default: {
3745
+ maxTimeToFirstByteMs: 1e4,
3746
+ maxLoadTimeMs: 3e4,
3747
+ timeoutRetry: {
3748
+ maxNumRetry: 2,
3749
+ retryDelayMs: 0,
3750
+ maxRetryDelayMs: 0
3751
+ },
3752
+ errorRetry: {
3753
+ ...liveEdgeErrorRetry,
3754
+ maxNumRetry: 6
3755
+ }
3876
3756
  }
3877
3757
  }
3878
- void setup();
3879
- return () => {
3880
- cancelled = true;
3881
- clearRetryTimer();
3882
- for (const fn of teardown) fn();
3883
- destroyHls();
3884
- };
3885
- }, [src, mode, active, autoPlay, muted, reloadKey]);
3886
- const setLevel = React9.useCallback((index) => {
3887
- const hls = hlsRef.current;
3888
- if (!hls) return;
3889
- hls.nextLevel = index;
3890
- setActiveLevel(index);
3891
- }, []);
3758
+ };
3759
+ }
3760
+ function createVodHlsConfig() {
3892
3761
  return {
3893
- videoRef,
3894
- state,
3895
- qualities,
3896
- activeLevel,
3897
- setLevel,
3898
- autoplayState,
3899
- error,
3900
- retry
3762
+ enableWorker: true,
3763
+ startPosition: 0
3901
3764
  };
3902
3765
  }
3903
3766
 
3904
- // src/components/video/captions.ts
3905
- var CAPTION_LOCALES = ["en", "es", "pt"];
3906
- var LIVE_CUE_EXTRA_LAG_MS = 2e3;
3907
- var LIVE_STACK_MAX_CUES = 150;
3908
- var CAPTION_CHARS_PER_SECOND = 17;
3909
- var CAPTION_MIN_DWELL_MS = 1200;
3910
- var CAPTION_MAX_DWELL_MS = 6e3;
3911
- var CAPTION_RUSH_DWELL_MS = 2500;
3912
- var CAPTION_MAX_CHARS_PER_LINE = 42;
3913
- var CAPTION_COMPACT_CHARS_PER_LINE = 32;
3914
- var CAPTION_MAX_LINES = 2;
3915
- var CAPTION_BACKLOG_DROP = 8;
3916
- var CAPTION_GAP_FILL_MS = 1e3;
3917
- var LIVE_LAG_SPIKE_MS = 2500;
3918
- var CAPTION_BREAK_PUNCT = /[.,;:?!]$/;
3919
- var CAPTION_MIN_PUNCT_LINE = 8;
3920
- var EMPTY_LIVE_CAPTION_PLAYOUT = {
3921
- screen: null,
3922
- hideAt: 0,
3923
- cursor: 0,
3924
- queue: []
3767
+ // src/components/video/hls-errors.ts
3768
+ var MEDIA_ERROR_NAMES = {
3769
+ 1: "MEDIA_ERR_ABORTED",
3770
+ 2: "MEDIA_ERR_NETWORK",
3771
+ 3: "MEDIA_ERR_DECODE",
3772
+ 4: "MEDIA_ERR_SRC_NOT_SUPPORTED"
3925
3773
  };
3926
- function stabilizeLiveLagMs(previous, next) {
3927
- if (previous == null || !Number.isFinite(previous)) return next;
3928
- if (next <= previous) return next;
3929
- if (next - previous < LIVE_LAG_SPIKE_MS) return previous;
3930
- return next;
3931
- }
3932
- function isCaptionLocale(value) {
3933
- return CAPTION_LOCALES.includes(value);
3934
- }
3935
- function captionsVttUrlFromPlayback(src, locale) {
3936
- const trimmed = src.trim();
3937
- if (!trimmed) return null;
3938
- const replaced = trimmed.replace(
3939
- /index\.m3u8(?:\?.*)?$/i,
3940
- `subs/${locale}.vtt`
3941
- );
3942
- if (replaced === trimmed) return null;
3943
- return replaced;
3774
+ var MEDIA_ERR_NETWORK = 2;
3775
+ var MEDIA_ERR_DECODE = 3;
3776
+ var MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
3777
+ function errorMessageFromUnknown(error) {
3778
+ if (error instanceof Error) return error.message;
3779
+ if (typeof error === "string") return error;
3780
+ return void 0;
3944
3781
  }
3945
- function liveCaptionsUrl(base, locale) {
3946
- return `${base.replace(/\/$/, "")}/${locale}`;
3782
+ function isNotFound(httpStatus, details) {
3783
+ return httpStatus === 404 || details === "manifestLoadError" || details === "levelLoadError" || details === "fragLoadError";
3947
3784
  }
3948
- function parseCaptionVtt(text) {
3949
- const cues = [];
3950
- const blocks = text.replace(/^\uFEFF?WEBVTT[^\n]*\n/i, "").split(/\n\s*\n/);
3951
- for (const block of blocks) {
3952
- const lines = block.split("\n").map((line) => line.trim()).filter(Boolean);
3953
- const timing = lines.find((line) => line.includes("-->"));
3954
- if (!timing) continue;
3955
- const [startRaw, endRaw] = timing.split("-->").map((part) => part.trim());
3956
- if (!startRaw || !endRaw) continue;
3957
- const textLines = lines.filter(
3958
- (line) => line !== timing && !/^\d+$/.test(line)
3959
- );
3960
- const payload = textLines.join("\n").trim();
3961
- if (!payload) continue;
3962
- cues.push({
3963
- start: parseVttTimestamp(startRaw.split(" ")[0] ?? startRaw),
3964
- end: parseVttTimestamp(endRaw.split(" ")[0] ?? endRaw),
3965
- text: payload
3966
- });
3785
+ function kindForHls(input) {
3786
+ const httpStatus = input.response?.code;
3787
+ if (input.type === "networkError" && isNotFound(httpStatus, input.details)) {
3788
+ return input.context.mode === "vod" || !input.context.manifestParsed ? "unavailable" : "network";
3967
3789
  }
3968
- return cues;
3969
- }
3970
- function captionScreenRow(text, speaker) {
3971
- return speaker == null ? { text } : { text, speaker };
3972
- }
3973
- function chunkLongWord(word, maxCharsPerLine) {
3974
- if (word.length <= maxCharsPerLine) return [word];
3975
- const parts = [];
3976
- for (let index = 0; index < word.length; index += maxCharsPerLine) {
3977
- parts.push(word.slice(index, index + maxCharsPerLine));
3790
+ if (input.type === "mediaError" || input.details === "bufferAppendError" || input.details === "bufferSeekOverHole") {
3791
+ return "media";
3978
3792
  }
3979
- return parts;
3793
+ return "generic";
3980
3794
  }
3981
- function wrapCaptionLines(text, maxCharsPerLine) {
3982
- const tokens = text.split(" ").filter(Boolean).flatMap((word) => chunkLongWord(word, maxCharsPerLine));
3983
- const lines = [];
3984
- let index = 0;
3985
- while (index < tokens.length) {
3986
- let end = index;
3987
- let length = 0;
3988
- while (end < tokens.length) {
3989
- const added = tokens[end].length + (end > index ? 1 : 0);
3990
- if (length + added > maxCharsPerLine && end > index) break;
3991
- length += added;
3992
- end += 1;
3993
- }
3994
- let breakAt = end;
3995
- if (end < tokens.length) {
3996
- for (let cursor = end - 1; cursor > index; cursor -= 1) {
3997
- if (!CAPTION_BREAK_PUNCT.test(tokens[cursor])) continue;
3998
- const firstLen = tokens.slice(index, cursor + 1).join(" ").length;
3999
- if (firstLen >= Math.min(CAPTION_MIN_PUNCT_LINE, maxCharsPerLine)) {
4000
- breakAt = cursor + 1;
4001
- }
4002
- break;
4003
- }
3795
+ function kindForNative(input) {
3796
+ const code = input.mediaError?.code;
3797
+ if (code === MEDIA_ERR_DECODE) return "media";
3798
+ if (code === MEDIA_ERR_SRC_NOT_SUPPORTED) return "unsupported";
3799
+ if (code === MEDIA_ERR_NETWORK) return "unavailable";
3800
+ return "generic";
3801
+ }
3802
+ function describeAvResync(input) {
3803
+ const lag = Number.isFinite(input.lagSeconds) ? input.lagSeconds : 0;
3804
+ return {
3805
+ summary: `av-resync lag=${lag.toFixed(3)}s (non-fatal)`,
3806
+ kind: "resync",
3807
+ detail: {
3808
+ source: input.context.source,
3809
+ kind: "resync",
3810
+ fatal: false,
3811
+ reason: `presented frame lag ${lag.toFixed(3)}s`,
3812
+ context: input.context
4004
3813
  }
4005
- lines.push(tokens.slice(index, breakAt).join(" "));
4006
- index = breakAt;
4007
- }
4008
- return lines;
3814
+ };
4009
3815
  }
4010
- function balanceCaptionLines(lines, maxCharsPerLine) {
4011
- const next = [...lines];
4012
- for (let index = 0; index + 1 < next.length; index += CAPTION_MAX_LINES) {
4013
- const left = next[index].split(" ");
4014
- const right = next[index + 1].split(" ");
4015
- if (right.length !== 1 || left.length < 3) continue;
4016
- const moved = left[left.length - 1];
4017
- const newRight = `${moved} ${right[0]}`;
4018
- if (newRight.length > maxCharsPerLine) continue;
4019
- next[index] = left.slice(0, -1).join(" ");
4020
- next[index + 1] = newRight;
3816
+ function describePlaybackError(input) {
3817
+ if (input.source === "unsupported") {
3818
+ return {
3819
+ summary: "playback unsupported (hls.js unavailable, native HLS unsupported)",
3820
+ kind: "unsupported",
3821
+ detail: {
3822
+ source: "unsupported",
3823
+ kind: "unsupported",
3824
+ context: input.context
3825
+ }
3826
+ };
4021
3827
  }
4022
- return next;
4023
- }
4024
- function splitCaptionScreens(text, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
4025
- const trimmed = text.trim().replace(/\s+/g, " ");
4026
- if (!trimmed) return [];
4027
- const lines = balanceCaptionLines(
4028
- wrapCaptionLines(trimmed, maxCharsPerLine),
4029
- maxCharsPerLine
4030
- );
4031
- const screens = [];
4032
- for (let index = 0; index < lines.length; index += CAPTION_MAX_LINES) {
4033
- screens.push(lines.slice(index, index + CAPTION_MAX_LINES).join("\n"));
3828
+ if (input.source === "native") {
3829
+ const code = input.mediaError?.code;
3830
+ const kind2 = kindForNative(input);
3831
+ const detail2 = {
3832
+ source: "native",
3833
+ kind: kind2,
3834
+ mediaErrorCode: code,
3835
+ mediaErrorName: code !== void 0 ? MEDIA_ERROR_NAMES[code] : void 0,
3836
+ errorMessage: input.mediaError?.message,
3837
+ context: input.context
3838
+ };
3839
+ const name = detail2.mediaErrorName ?? "MEDIA_ERR_UNKNOWN";
3840
+ return {
3841
+ summary: `native ${name}${input.mediaError?.message ? `: ${input.mediaError.message}` : ""}`,
3842
+ kind: kind2,
3843
+ detail: detail2
3844
+ };
4034
3845
  }
4035
- return screens;
3846
+ const httpStatus = input.response?.code;
3847
+ const kind = kindForHls(input);
3848
+ const detail = {
3849
+ source: "hls",
3850
+ kind,
3851
+ type: input.type,
3852
+ details: input.details,
3853
+ fatal: input.fatal,
3854
+ httpStatus,
3855
+ url: input.url,
3856
+ reason: input.reason,
3857
+ errorMessage: errorMessageFromUnknown(input.error),
3858
+ context: input.context
3859
+ };
3860
+ const statusSuffix = httpStatus !== void 0 ? ` ${httpStatus}` : "";
3861
+ const summary = [
3862
+ "hls",
3863
+ input.type ?? "unknown",
3864
+ input.details ?? "unknown",
3865
+ input.fatal ? "(fatal)" : "(non-fatal)",
3866
+ statusSuffix.trim()
3867
+ ].filter(Boolean).join(" ");
3868
+ return { summary, kind, detail };
4036
3869
  }
4037
- function captionDwellMs(text, backlog = 0) {
4038
- const chars = text.replace(/\s+/g, " ").trim().length;
4039
- const raw = chars / CAPTION_CHARS_PER_SECOND * 1e3;
4040
- const max = backlog > 0 ? CAPTION_RUSH_DWELL_MS : CAPTION_MAX_DWELL_MS;
4041
- return Math.min(max, Math.max(CAPTION_MIN_DWELL_MS, raw));
3870
+
3871
+ // src/components/video/useHlsPlayback.ts
3872
+ function effectivePlaybackMode(src, mode, sealed) {
3873
+ if (isLivePlaylistSrc(src)) return sealed ? "vod" : "live";
3874
+ return mode;
4042
3875
  }
4043
- function advanceLiveCaptionPlayout(state, cues, now, lagMs, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
4044
- let screen = state.screen;
4045
- let hideAt = state.hideAt;
4046
- let cursor = state.cursor;
4047
- let queue = state.queue.slice();
4048
- if (lagMs != null && Number.isFinite(lagMs) && lagMs >= 0) {
4049
- const threshold = lagMs + LIVE_CUE_EXTRA_LAG_MS;
4050
- const incoming = cues.filter(
4051
- (cue) => Boolean(cue.text.trim()) && Number.isFinite(cue.receivedAt) && cue.receivedAt > cursor && now - cue.receivedAt >= threshold
4052
- ).sort((left, right) => left.receivedAt - right.receivedAt);
4053
- for (const cue of incoming) {
4054
- for (const text of splitCaptionScreens(cue.text, maxCharsPerLine)) {
4055
- queue.push(captionScreenRow(text, cue.speaker));
4056
- }
4057
- cursor = cue.receivedAt;
3876
+ var RETRY_INTERVAL_MS = 3e3;
3877
+ var MAX_MEDIA_ERROR_RETRIES = 5;
3878
+ var DRIFT_THRESHOLD_S = 0.4;
3879
+ var DRIFT_CONSECUTIVE_SAMPLES = 3;
3880
+ var RESYNC_COOLDOWN_MS = 1e4;
3881
+ var LIVE_EDGE_RESYNC_THRESHOLD_S = 8;
3882
+ function useHlsPlayback({
3883
+ src,
3884
+ mode,
3885
+ active,
3886
+ autoPlay = false,
3887
+ muted = false,
3888
+ onError,
3889
+ onPlayingChange,
3890
+ onRebuffer,
3891
+ onQualityChange
3892
+ }) {
3893
+ const videoRef = React9.useRef(null);
3894
+ const hlsRef = React9.useRef(null);
3895
+ const [state, setState] = React9.useState("idle");
3896
+ const [qualities, setQualities] = React9.useState([]);
3897
+ const [activeLevel, setActiveLevel] = React9.useState(-1);
3898
+ const [autoplayState, setAutoplayState] = React9.useState("none");
3899
+ const [error, setError] = React9.useState(null);
3900
+ const [reloadKey, setReloadKey] = React9.useState(0);
3901
+ const [sealed, setSealed] = React9.useState(false);
3902
+ const modeRef = React9.useRef(mode);
3903
+ const lastSrcRef = React9.useRef(src);
3904
+ const sealedRef = React9.useRef(false);
3905
+ const sawLiveRef = React9.useRef(false);
3906
+ const sealedDuringSessionRef = React9.useRef(false);
3907
+ React9.useEffect(() => {
3908
+ modeRef.current = mode;
3909
+ }, [mode]);
3910
+ const onErrorRef = React9.useRef(onError);
3911
+ const onPlayingChangeRef = React9.useRef(onPlayingChange);
3912
+ const onRebufferRef = React9.useRef(onRebuffer);
3913
+ const onQualityChangeRef = React9.useRef(onQualityChange);
3914
+ React9.useEffect(() => {
3915
+ onErrorRef.current = onError;
3916
+ onPlayingChangeRef.current = onPlayingChange;
3917
+ onRebufferRef.current = onRebuffer;
3918
+ onQualityChangeRef.current = onQualityChange;
3919
+ }, [onError, onPlayingChange, onRebuffer, onQualityChange]);
3920
+ const retry = React9.useCallback(() => {
3921
+ setError(null);
3922
+ setState("loading");
3923
+ setAutoplayState("none");
3924
+ setReloadKey((k) => k + 1);
3925
+ }, []);
3926
+ React9.useEffect(() => {
3927
+ const media = videoRef.current;
3928
+ if (!media || !src || !active) {
3929
+ setState("idle");
3930
+ return;
4058
3931
  }
4059
- if (queue.length > CAPTION_BACKLOG_DROP) {
4060
- queue = queue.slice(queue.length - CAPTION_BACKLOG_DROP);
3932
+ let cancelled = false;
3933
+ let retryTimer = null;
3934
+ let manifestParsed = false;
3935
+ let mediaErrorRetries = 0;
3936
+ let playbackSource = "hls";
3937
+ const teardown = [];
3938
+ const liveSrc = isLivePlaylistSrc(src);
3939
+ if (lastSrcRef.current !== src) {
3940
+ lastSrcRef.current = src;
3941
+ sealedRef.current = false;
3942
+ sawLiveRef.current = false;
3943
+ sealedDuringSessionRef.current = false;
3944
+ setSealed(false);
4061
3945
  }
4062
- }
4063
- if (now >= hideAt) {
4064
- const next = queue.shift();
4065
- if (next) {
4066
- screen = next;
4067
- hideAt = now + captionDwellMs(next.text, queue.length);
4068
- } else {
4069
- screen = null;
3946
+ applyMute(media);
3947
+ setState("loading");
3948
+ setError(null);
3949
+ setAutoplayState("none");
3950
+ setQualities([]);
3951
+ setActiveLevel(-1);
3952
+ function baseContext() {
3953
+ return {
3954
+ mode: modeRef.current,
3955
+ src,
3956
+ manifestParsed,
3957
+ retryCount: mediaErrorRetries,
3958
+ source: playbackSource
3959
+ };
4070
3960
  }
4071
- }
4072
- return { screen, hideAt, cursor, queue };
4073
- }
4074
- function cueEndWithGapFill(cues, index) {
4075
- const cue = cues[index];
4076
- if (!cue) return 0;
4077
- const next = cues[index + 1];
4078
- if (!next || !Number.isFinite(next.start)) return cue.end;
4079
- const gapMs = (next.start - cue.end) * 1e3;
4080
- if (gapMs > 0 && gapMs < CAPTION_GAP_FILL_MS) return next.start;
4081
- return cue.end;
4082
- }
4083
- function captionScreenAtTime(cues, time, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
4084
- if (!Number.isFinite(time)) return null;
4085
- const ordered = cues.filter(
4086
- (cue) => Boolean(cue.text.trim()) && Number.isFinite(cue.start) && Number.isFinite(cue.end)
4087
- ).sort((left, right) => left.start - right.start);
4088
- for (let index = 0; index < ordered.length; index += 1) {
4089
- const cue = ordered[index];
4090
- const end = cueEndWithGapFill(ordered, index);
4091
- if (time < cue.start || time >= end) continue;
4092
- const screens = splitCaptionScreens(cue.text, maxCharsPerLine);
4093
- if (screens.length === 0) return null;
4094
- const weights = screens.map(
4095
- (text) => Math.max(1, text.replace(/\s+/g, "").length)
4096
- );
4097
- const total = weights.reduce((sum, weight) => sum + weight, 0);
4098
- const duration = Math.max(end - cue.start, 0);
4099
- let cursor = cue.start;
4100
- for (let screenIndex = 0; screenIndex < screens.length; screenIndex += 1) {
4101
- const isLast = screenIndex === screens.length - 1;
4102
- const slice = isLast ? end - cursor : duration * (weights[screenIndex] / total);
4103
- const sliceEnd = cursor + slice;
4104
- if (time >= cursor && time < sliceEnd) {
4105
- return captionScreenRow(screens[screenIndex]);
4106
- }
4107
- cursor = sliceEnd;
3961
+ function shouldAutoplay() {
3962
+ if (sealedDuringSessionRef.current) return false;
3963
+ return modeRef.current === "live" || autoPlay;
4108
3964
  }
4109
- return captionScreenRow(screens[screens.length - 1]);
4110
- }
4111
- return null;
4112
- }
4113
- var LIVE_OVERLAP_MIN_WORDS = 4;
4114
- function normalizeLiveCaptionText(text) {
4115
- return text.trim().replace(/\s+/g, " ").toLowerCase();
4116
- }
4117
- function lastSubseqIndex(haystack, needle) {
4118
- if (needle.length === 0 || needle.length > haystack.length) return -1;
4119
- let found = -1;
4120
- for (let index = 0; index <= haystack.length - needle.length; index += 1) {
4121
- let match = true;
4122
- for (let offset = 0; offset < needle.length; offset += 1) {
4123
- if (haystack[index + offset] !== needle[offset]) {
4124
- match = false;
4125
- break;
3965
+ function hlsConfig() {
3966
+ if (liveSrc) {
3967
+ return sealedRef.current ? createVodHlsConfig() : createLiveHlsConfig();
4126
3968
  }
3969
+ return modeRef.current === "live" ? createLiveHlsConfig() : createVodHlsConfig();
4127
3970
  }
4128
- if (match) found = index;
4129
- }
4130
- return found;
4131
- }
4132
- function remainderAfterOverlap(previous, next) {
4133
- const prevWords = normalizeLiveCaptionText(previous).split(" ").filter(Boolean);
4134
- const nextWords = next.trim().replace(/\s+/g, " ").split(" ").filter(Boolean);
4135
- const nextNorm = nextWords.map((word) => word.toLowerCase());
4136
- const maxN = Math.min(prevWords.length, nextNorm.length);
4137
- for (let size = maxN; size >= LIVE_OVERLAP_MIN_WORDS; size -= 1) {
4138
- for (let start = prevWords.length - size; start >= 0; start -= 1) {
4139
- const gram = prevWords.slice(start, start + size);
4140
- const index = lastSubseqIndex(nextNorm, gram);
4141
- if (index !== -1) {
4142
- return nextWords.slice(index + size).join(" ");
3971
+ function clearRetryTimer() {
3972
+ if (retryTimer !== null) {
3973
+ clearTimeout(retryTimer);
3974
+ retryTimer = null;
4143
3975
  }
4144
3976
  }
4145
- }
4146
- return null;
4147
- }
4148
- function liveCaptionRow(text, receivedAt, speaker) {
4149
- return speaker == null ? { text, receivedAt } : { text, receivedAt, speaker };
4150
- }
4151
- function coalesceLiveCaptionCues(cues) {
4152
- const out = [];
4153
- for (const cue of cues) {
4154
- const text = cue.text.trim();
4155
- if (!text) continue;
4156
- const last = out[out.length - 1];
4157
- if (!last) {
4158
- out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
4159
- continue;
3977
+ function destroyHls() {
3978
+ hlsRef.current?.destroy();
3979
+ hlsRef.current = null;
4160
3980
  }
4161
- if (last.speaker !== cue.speaker && (last.speaker != null || cue.speaker != null)) {
4162
- out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
4163
- continue;
3981
+ function reportFatal(input) {
3982
+ const described = describePlaybackError(input);
3983
+ onErrorRef.current?.(described);
3984
+ setError(described);
3985
+ setState("error");
4164
3986
  }
4165
- const lastNorm = normalizeLiveCaptionText(last.text);
4166
- const nextNorm = normalizeLiveCaptionText(text);
4167
- if (lastNorm === nextNorm) continue;
4168
- if (nextNorm.startsWith(lastNorm) || lastNorm.startsWith(nextNorm)) {
4169
- out[out.length - 1] = liveCaptionRow(
4170
- nextNorm.length >= lastNorm.length ? text : last.text,
4171
- cue.receivedAt,
4172
- cue.speaker ?? last.speaker
3987
+ function applyMute(el) {
3988
+ el.muted = muted;
3989
+ }
3990
+ function preserveMute(el, fn) {
3991
+ const wasMuted = el.muted;
3992
+ fn();
3993
+ el.muted = wasMuted;
3994
+ }
3995
+ function attemptAutoplay(el) {
3996
+ applyMute(el);
3997
+ void el.play().then(
3998
+ () => {
3999
+ applyMute(el);
4000
+ setAutoplayState("playing");
4001
+ },
4002
+ () => {
4003
+ el.muted = true;
4004
+ void el.play().then(
4005
+ () => setAutoplayState(muted ? "playing" : "muted"),
4006
+ () => {
4007
+ if (el.paused) {
4008
+ setAutoplayState("blocked");
4009
+ return;
4010
+ }
4011
+ setAutoplayState(el.muted && !muted ? "muted" : "playing");
4012
+ }
4013
+ );
4014
+ }
4015
+ );
4016
+ }
4017
+ function scheduleRetry(retryFn) {
4018
+ clearRetryTimer();
4019
+ if (cancelled) return;
4020
+ setState("waiting");
4021
+ retryTimer = setTimeout(() => {
4022
+ retryTimer = null;
4023
+ if (!cancelled) retryFn();
4024
+ }, RETRY_INTERVAL_MS);
4025
+ }
4026
+ function startDriftWatchdog(el) {
4027
+ if (typeof el.requestVideoFrameCallback !== "function") return;
4028
+ let consecutiveLagSamples = 0;
4029
+ let lastResyncAt = 0;
4030
+ let handle = null;
4031
+ const tick = (_now, metadata) => {
4032
+ if (cancelled) return;
4033
+ handle = el.requestVideoFrameCallback(tick);
4034
+ if (el.paused || el.ended) {
4035
+ consecutiveLagSamples = 0;
4036
+ return;
4037
+ }
4038
+ const lag = el.currentTime - metadata.mediaTime;
4039
+ if (!(lag > DRIFT_THRESHOLD_S)) {
4040
+ consecutiveLagSamples = 0;
4041
+ return;
4042
+ }
4043
+ consecutiveLagSamples += 1;
4044
+ if (consecutiveLagSamples < DRIFT_CONSECUTIVE_SAMPLES) return;
4045
+ const nowMs = performance.now();
4046
+ if (nowMs - lastResyncAt < RESYNC_COOLDOWN_MS) return;
4047
+ lastResyncAt = nowMs;
4048
+ consecutiveLagSamples = 0;
4049
+ if (modeRef.current === "live" && el.seekable.length > 0) {
4050
+ const edge = el.seekable.end(el.seekable.length - 1);
4051
+ if (edge - el.currentTime > LIVE_EDGE_RESYNC_THRESHOLD_S) {
4052
+ el.currentTime = edge;
4053
+ } else {
4054
+ el.currentTime = el.currentTime + 1e-3;
4055
+ }
4056
+ } else {
4057
+ el.currentTime = el.currentTime + 1e-3;
4058
+ }
4059
+ onErrorRef.current?.(
4060
+ describeAvResync({
4061
+ lagSeconds: lag,
4062
+ context: baseContext()
4063
+ })
4064
+ );
4065
+ };
4066
+ handle = el.requestVideoFrameCallback(tick);
4067
+ teardown.push(() => {
4068
+ if (handle != null && typeof el.cancelVideoFrameCallback === "function") {
4069
+ el.cancelVideoFrameCallback(handle);
4070
+ }
4071
+ });
4072
+ }
4073
+ let hasPlayed = false;
4074
+ let waitingSince = null;
4075
+ function onPlaying() {
4076
+ manifestParsed = true;
4077
+ mediaErrorRetries = 0;
4078
+ clearRetryTimer();
4079
+ setState("ready");
4080
+ setAutoplayState(
4081
+ (prev) => prev === "blocked" || prev === "none" ? "playing" : prev
4173
4082
  );
4174
- continue;
4083
+ if (waitingSince != null) {
4084
+ const seconds = (performance.now() - waitingSince) / 1e3;
4085
+ waitingSince = null;
4086
+ if (seconds > 0) onRebufferRef.current?.(seconds);
4087
+ }
4088
+ hasPlayed = true;
4089
+ onPlayingChangeRef.current?.(true);
4175
4090
  }
4176
- const remainder = remainderAfterOverlap(last.text, text);
4177
- if (remainder !== null) {
4178
- if (!remainder) continue;
4179
- out.push(liveCaptionRow(remainder, cue.receivedAt, cue.speaker));
4180
- continue;
4091
+ function onPaused() {
4092
+ onPlayingChangeRef.current?.(false);
4181
4093
  }
4182
- out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
4183
- }
4184
- return out;
4185
- }
4186
- function mergeLiveCaptionCues(existing, incoming, cap = LIVE_STACK_MAX_CUES) {
4187
- const map = /* @__PURE__ */ new Map();
4188
- for (const cue of existing) {
4189
- if (Number.isFinite(cue.receivedAt)) map.set(cue.receivedAt, cue);
4190
- }
4191
- for (const cue of incoming) {
4192
- if (Number.isFinite(cue.receivedAt)) map.set(cue.receivedAt, cue);
4193
- }
4194
- return [...map.values()].sort((left, right) => left.receivedAt - right.receivedAt).slice(-Math.max(1, cap));
4195
- }
4196
- async function loadCaptionVtt(url) {
4197
- try {
4198
- const response = await fetch(url, { cache: "no-store" });
4199
- if (!response.ok) return [];
4200
- return parseCaptionVtt(await response.text());
4201
- } catch {
4202
- return [];
4203
- }
4204
- }
4205
- async function loadLiveCaptions(url) {
4206
- try {
4207
- const response = await fetch(url, {
4208
- cache: "no-store",
4209
- headers: { Accept: "application/json" }
4094
+ function onWaiting() {
4095
+ if (!hasPlayed || waitingSince != null) return;
4096
+ waitingSince = performance.now();
4097
+ }
4098
+ media.addEventListener("playing", onPlaying);
4099
+ media.addEventListener("pause", onPaused);
4100
+ media.addEventListener("ended", onPaused);
4101
+ media.addEventListener("waiting", onWaiting);
4102
+ teardown.push(() => {
4103
+ media.removeEventListener("playing", onPlaying);
4104
+ media.removeEventListener("pause", onPaused);
4105
+ media.removeEventListener("ended", onPaused);
4106
+ media.removeEventListener("waiting", onWaiting);
4210
4107
  });
4211
- if (!response.ok) return { ok: false, cues: [] };
4212
- const body = await response.json();
4213
- if (!body || typeof body !== "object" || !("cues" in body)) {
4214
- return { ok: false, cues: [] };
4108
+ startDriftWatchdog(media);
4109
+ function initNative() {
4110
+ playbackSource = "native";
4111
+ manifestParsed = false;
4112
+ media.removeAttribute("src");
4113
+ media.load();
4114
+ media.src = src;
4115
+ applyMute(media);
4116
+ const onReady = () => {
4117
+ manifestParsed = true;
4118
+ clearRetryTimer();
4119
+ setState("ready");
4120
+ if (shouldAutoplay()) attemptAutoplay(media);
4121
+ };
4122
+ const onErr = () => {
4123
+ if (manifestParsed) {
4124
+ reportFatal({
4125
+ source: "native",
4126
+ mediaError: media.error,
4127
+ context: baseContext()
4128
+ });
4129
+ return;
4130
+ }
4131
+ onErrorRef.current?.(
4132
+ describePlaybackError({
4133
+ source: "native",
4134
+ mediaError: media.error,
4135
+ context: baseContext()
4136
+ })
4137
+ );
4138
+ scheduleRetry(() => {
4139
+ media.src = src;
4140
+ media.load();
4141
+ });
4142
+ };
4143
+ media.addEventListener("loadedmetadata", onReady);
4144
+ media.addEventListener("error", onErr);
4145
+ teardown.push(() => {
4146
+ media.removeEventListener("loadedmetadata", onReady);
4147
+ media.removeEventListener("error", onErr);
4148
+ });
4215
4149
  }
4216
- const rows = body.cues;
4217
- if (!Array.isArray(rows)) return { ok: false, cues: [] };
4218
- const cues = [];
4219
- for (const row of rows) {
4220
- if (!row || typeof row !== "object") continue;
4221
- const record = row;
4222
- if (typeof record.text !== "string" || !record.text.trim()) continue;
4223
- if (typeof record.receivedAt !== "number" || !Number.isFinite(record.receivedAt)) {
4224
- continue;
4150
+ function initHlsJs(Hls) {
4151
+ playbackSource = "hls";
4152
+ destroyHls();
4153
+ manifestParsed = false;
4154
+ const config = hlsConfig();
4155
+ const hls = new Hls(config);
4156
+ hlsRef.current = hls;
4157
+ hls.loadSource(src);
4158
+ hls.attachMedia(media);
4159
+ applyMute(media);
4160
+ hls.on(Hls.Events.LEVEL_LOADED, (_e, data) => {
4161
+ if (!liveSrc || cancelled) return;
4162
+ const details = data.details;
4163
+ if (!details) return;
4164
+ if (details.live) {
4165
+ sawLiveRef.current = true;
4166
+ return;
4167
+ }
4168
+ if (sealedRef.current) return;
4169
+ sealedRef.current = true;
4170
+ setSealed(true);
4171
+ if (sawLiveRef.current) {
4172
+ sealedDuringSessionRef.current = true;
4173
+ }
4174
+ setReloadKey((k) => k + 1);
4175
+ });
4176
+ hls.on(Hls.Events.MANIFEST_PARSED, (_e, data) => {
4177
+ manifestParsed = true;
4178
+ clearRetryTimer();
4179
+ setQualities(
4180
+ data.levels.map((l, index) => ({ index, height: l.height }))
4181
+ );
4182
+ setState("ready");
4183
+ if (shouldAutoplay()) attemptAutoplay(media);
4184
+ });
4185
+ hls.on(Hls.Events.LEVEL_SWITCHED, (_e, data) => {
4186
+ if (hls.autoLevelEnabled) setActiveLevel(-1);
4187
+ else setActiveLevel(data.level);
4188
+ const height = hls.levels?.[data.level]?.height;
4189
+ onQualityChangeRef.current?.(
4190
+ typeof height === "number" && height > 0 ? `${height}p` : "auto"
4191
+ );
4192
+ });
4193
+ hls.on(Hls.Events.ERROR, (_e, data) => {
4194
+ onErrorRef.current?.(
4195
+ describePlaybackError({
4196
+ source: "hls",
4197
+ type: data.type,
4198
+ details: data.details,
4199
+ fatal: data.fatal,
4200
+ url: data.url,
4201
+ response: data.response,
4202
+ reason: data.reason,
4203
+ error: data.error,
4204
+ context: baseContext()
4205
+ })
4206
+ );
4207
+ if (!data.fatal) return;
4208
+ if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
4209
+ if (!manifestParsed) {
4210
+ scheduleRetry(() => initHlsJs(Hls));
4211
+ return;
4212
+ }
4213
+ hls.startLoad();
4214
+ return;
4215
+ }
4216
+ mediaErrorRetries += 1;
4217
+ if (mediaErrorRetries === 1) {
4218
+ preserveMute(media, () => hls.recoverMediaError());
4219
+ return;
4220
+ }
4221
+ if (mediaErrorRetries === 2) {
4222
+ preserveMute(media, () => {
4223
+ hls.swapAudioCodec();
4224
+ hls.recoverMediaError();
4225
+ });
4226
+ return;
4227
+ }
4228
+ if (mediaErrorRetries < MAX_MEDIA_ERROR_RETRIES) {
4229
+ scheduleRetry(() => initHlsJs(Hls));
4230
+ return;
4231
+ }
4232
+ reportFatal({
4233
+ source: "hls",
4234
+ type: data.type,
4235
+ details: data.details,
4236
+ fatal: true,
4237
+ url: data.url,
4238
+ response: data.response,
4239
+ reason: data.reason,
4240
+ error: data.error,
4241
+ context: baseContext()
4242
+ });
4243
+ });
4244
+ }
4245
+ async function setup() {
4246
+ let Hls = null;
4247
+ try {
4248
+ Hls = (await import('hls.js')).default;
4249
+ } catch {
4250
+ Hls = null;
4225
4251
  }
4226
- const parsed = {
4227
- text: record.text.trim(),
4228
- receivedAt: record.receivedAt
4229
- };
4230
- if (typeof record.speaker === "number" && Number.isFinite(record.speaker)) {
4231
- parsed.speaker = record.speaker;
4252
+ if (cancelled) return;
4253
+ if (Hls && Hls.isSupported()) {
4254
+ initHlsJs(Hls);
4255
+ } else if (media.canPlayType("application/vnd.apple.mpegurl")) {
4256
+ initNative();
4257
+ } else {
4258
+ playbackSource = "unsupported";
4259
+ reportFatal({
4260
+ source: "unsupported",
4261
+ context: baseContext()
4262
+ });
4232
4263
  }
4233
- cues.push(parsed);
4234
4264
  }
4235
- return { ok: true, cues };
4236
- } catch {
4237
- return { ok: false, cues: [] };
4238
- }
4265
+ void setup();
4266
+ return () => {
4267
+ cancelled = true;
4268
+ clearRetryTimer();
4269
+ for (const fn of teardown) fn();
4270
+ destroyHls();
4271
+ };
4272
+ }, [src, active, autoPlay, muted, reloadKey]);
4273
+ const setLevel = React9.useCallback((index) => {
4274
+ const hls = hlsRef.current;
4275
+ if (!hls) return;
4276
+ hls.nextLevel = index;
4277
+ setActiveLevel(index);
4278
+ }, []);
4279
+ return {
4280
+ videoRef,
4281
+ state,
4282
+ qualities,
4283
+ activeLevel,
4284
+ setLevel,
4285
+ autoplayState,
4286
+ error,
4287
+ retry,
4288
+ effectiveMode: effectivePlaybackMode(src, mode, sealed)
4289
+ };
4239
4290
  }
4240
4291
 
4241
4292
  // src/components/video/fullscreen.ts
@@ -4485,7 +4536,8 @@ function VideoPlayer({
4485
4536
  setLevel,
4486
4537
  autoplayState,
4487
4538
  error,
4488
- retry
4539
+ retry,
4540
+ effectiveMode
4489
4541
  } = useHlsPlayback({
4490
4542
  src,
4491
4543
  mode,
@@ -4570,11 +4622,15 @@ function VideoPlayer({
4570
4622
  lastProgressAtRef.current = now;
4571
4623
  progress(
4572
4624
  video.currentTime,
4573
- finitePlaybackDuration(video.duration, video.seekable, mode)
4625
+ finitePlaybackDuration(
4626
+ video.duration,
4627
+ video.seekable,
4628
+ effectiveMode
4629
+ )
4574
4630
  );
4575
4631
  }
4576
4632
  }
4577
- if (mode === "live" && video.seekable.length > 0) {
4633
+ if (effectiveMode === "live" && video.seekable.length > 0) {
4578
4634
  const edge = video.seekable.end(video.seekable.length - 1);
4579
4635
  const lagSeconds = edge - video.currentTime;
4580
4636
  setBehindLive(lagSeconds > LIVE_EDGE_THRESHOLD_S);
@@ -4583,7 +4639,9 @@ function VideoPlayer({
4583
4639
  }
4584
4640
  }
4585
4641
  };
4586
- const onDuration = () => setDuration(finitePlaybackDuration(video.duration, video.seekable, mode));
4642
+ const onDuration = () => setDuration(
4643
+ finitePlaybackDuration(video.duration, video.seekable, effectiveMode)
4644
+ );
4587
4645
  const onVolume = () => {
4588
4646
  setIsMuted(video.muted);
4589
4647
  setVolume(video.volume);
@@ -4607,7 +4665,7 @@ function VideoPlayer({
4607
4665
  video.removeEventListener("ratechange", onRate);
4608
4666
  video.removeEventListener("playing", onPlaying);
4609
4667
  };
4610
- }, [videoRef, active, mode, liveCaptionsBaseUrl]);
4668
+ }, [videoRef, active, effectiveMode, liveCaptionsBaseUrl]);
4611
4669
  React9.useLayoutEffect(() => {
4612
4670
  const video = videoRef.current;
4613
4671
  if (video) video.muted = isMuted;
@@ -4935,13 +4993,13 @@ function VideoPlayer({
4935
4993
  }
4936
4994
  break;
4937
4995
  case "ArrowLeft":
4938
- if (mode === "vod") {
4996
+ if (effectiveMode === "vod") {
4939
4997
  e.preventDefault();
4940
4998
  seekBy(-SEEK_STEP_S);
4941
4999
  }
4942
5000
  break;
4943
5001
  case "ArrowRight":
4944
- if (mode === "vod") {
5002
+ if (effectiveMode === "vod") {
4945
5003
  e.preventDefault();
4946
5004
  seekBy(SEEK_STEP_S);
4947
5005
  }
@@ -4988,7 +5046,7 @@ function VideoPlayer({
4988
5046
  {
4989
5047
  ref: containerRef,
4990
5048
  "data-slot": "video-player",
4991
- "data-mode": mode,
5049
+ "data-mode": effectiveMode,
4992
5050
  "data-fit": fit,
4993
5051
  "data-css-fullscreen": cssFullscreen ? "" : void 0,
4994
5052
  className: cn(
@@ -5089,7 +5147,7 @@ function VideoPlayer({
5089
5147
  ]
5090
5148
  }
5091
5149
  ),
5092
- mode === "live" && active && state === "ready" && /* @__PURE__ */ jsxs("div", { className: "absolute top-3 left-3 flex items-center gap-2", children: [
5150
+ effectiveMode === "live" && active && state === "ready" && /* @__PURE__ */ jsxs("div", { className: "absolute top-3 left-3 flex items-center gap-2", children: [
5093
5151
  /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1.5 rounded bg-red-600 px-2 py-0.5 text-xs font-semibold tracking-wide", children: [
5094
5152
  /* @__PURE__ */ jsx("span", { className: "size-1.5 animate-pulse rounded-full bg-white" }),
5095
5153
  t.live
@@ -5106,7 +5164,7 @@ function VideoPlayer({
5106
5164
  ),
5107
5165
  "data-slot": "video-controls",
5108
5166
  children: [
5109
- mode === "vod" && /* @__PURE__ */ jsx(
5167
+ effectiveMode === "vod" && /* @__PURE__ */ jsx(
5110
5168
  SeekBar,
5111
5169
  {
5112
5170
  src,
@@ -5147,11 +5205,11 @@ function VideoPlayer({
5147
5205
  }
5148
5206
  ) })
5149
5207
  ] }),
5150
- mode === "vod" && /* @__PURE__ */ jsxs("span", { className: "ml-1 shrink-0 text-xs tabular-nums", children: [
5208
+ effectiveMode === "vod" && /* @__PURE__ */ jsxs("span", { className: "ml-1 shrink-0 text-xs tabular-nums", children: [
5151
5209
  formatTime(currentTime),
5152
5210
  !compactChrome && ` / ${formatTime(duration)}`
5153
5211
  ] }),
5154
- mode === "live" && behindLive && /* @__PURE__ */ jsxs(
5212
+ effectiveMode === "live" && behindLive && /* @__PURE__ */ jsxs(
5155
5213
  "button",
5156
5214
  {
5157
5215
  type: "button",
@@ -5164,7 +5222,7 @@ function VideoPlayer({
5164
5222
  }
5165
5223
  ),
5166
5224
  /* @__PURE__ */ jsxs("div", { className: "ml-auto flex shrink-0 items-center gap-1", children: [
5167
- !compactChrome && mode === "vod" && typeof stats?.views === "number" && /* @__PURE__ */ jsx("span", { className: "mr-1 text-xs", children: t.formatViews ? t.formatViews(stats.views) : `${stats.views} views` }),
5225
+ !compactChrome && effectiveMode === "vod" && typeof stats?.views === "number" && /* @__PURE__ */ jsx("span", { className: "mr-1 text-xs", children: t.formatViews ? t.formatViews(stats.views) : `${stats.views} views` }),
5168
5226
  /* @__PURE__ */ jsxs(
5169
5227
  MenuControl,
5170
5228
  {
@@ -5193,7 +5251,7 @@ function VideoPlayer({
5193
5251
  ]
5194
5252
  }
5195
5253
  ),
5196
- !compactChrome && mode === "vod" && /* @__PURE__ */ jsx(
5254
+ !compactChrome && effectiveMode === "vod" && /* @__PURE__ */ jsx(
5197
5255
  MenuControl,
5198
5256
  {
5199
5257
  label: t.speed,
@@ -5323,7 +5381,7 @@ function VideoPlayer({
5323
5381
  q.index
5324
5382
  ))
5325
5383
  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
5326
- mode === "vod" && /* @__PURE__ */ jsx(
5384
+ effectiveMode === "vod" && /* @__PURE__ */ jsx(
5327
5385
  MenuNavRow,
5328
5386
  {
5329
5387
  icon: /* @__PURE__ */ jsx(Gauge, { className: "size-4" }),
@@ -5341,7 +5399,7 @@ function VideoPlayer({
5341
5399
  onSelect: () => setMorePane("quality")
5342
5400
  }
5343
5401
  ),
5344
- (mode === "vod" || showQuality) && /* @__PURE__ */ jsx("div", { className: "my-1 h-px bg-primary/15" }),
5402
+ (effectiveMode === "vod" || showQuality) && /* @__PURE__ */ jsx("div", { className: "my-1 h-px bg-primary/15" }),
5345
5403
  /* @__PURE__ */ jsx(
5346
5404
  MenuAction,
5347
5405
  {