@livo-tv/blocks 1.26.0 → 1.28.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.cjs CHANGED
@@ -3391,877 +3391,928 @@ function SeekBar({
3391
3391
  );
3392
3392
  }
3393
3393
 
3394
- // src/components/video/hls-config.ts
3395
- function shouldRetryLiveEdge404(retryConfig, retryCount, _isTimeout, loaderResponse, defaultRetry) {
3396
- if (loaderResponse?.code === 404) {
3397
- return retryConfig != null && retryCount < retryConfig.maxNumRetry;
3394
+ // src/components/video/captions.ts
3395
+ var CAPTION_LOCALES = ["en", "es", "pt"];
3396
+ var LIVE_CUE_EXTRA_LAG_MS = 2e3;
3397
+ var LIVE_STACK_MAX_CUES = 150;
3398
+ var CAPTION_CHARS_PER_SECOND = 17;
3399
+ var CAPTION_MIN_DWELL_MS = 1200;
3400
+ var CAPTION_MAX_DWELL_MS = 6e3;
3401
+ var CAPTION_RUSH_DWELL_MS = 2500;
3402
+ var CAPTION_MAX_CHARS_PER_LINE = 42;
3403
+ var CAPTION_COMPACT_CHARS_PER_LINE = 32;
3404
+ var CAPTION_MAX_LINES = 2;
3405
+ var CAPTION_BACKLOG_DROP = 8;
3406
+ var CAPTION_GAP_FILL_MS = 1e3;
3407
+ var LIVE_LAG_SPIKE_MS = 2500;
3408
+ var CAPTION_BREAK_PUNCT = /[.,;:?!]$/;
3409
+ var CAPTION_MIN_PUNCT_LINE = 8;
3410
+ var EMPTY_LIVE_CAPTION_PLAYOUT = {
3411
+ screen: null,
3412
+ hideAt: 0,
3413
+ cursor: 0,
3414
+ queue: []
3415
+ };
3416
+ function stabilizeLiveLagMs(previous, next) {
3417
+ if (previous == null || !Number.isFinite(previous)) return next;
3418
+ if (next <= previous) return next;
3419
+ if (next - previous < LIVE_LAG_SPIKE_MS) return previous;
3420
+ return next;
3421
+ }
3422
+ function isCaptionLocale(value) {
3423
+ return CAPTION_LOCALES.includes(value);
3424
+ }
3425
+ function isLivePlaylistSrc(src) {
3426
+ return /\/live\//i.test(src);
3427
+ }
3428
+ function captionsVttUrlFromPlayback(src, locale) {
3429
+ const trimmed = src.trim();
3430
+ if (!trimmed) return null;
3431
+ const replaced = trimmed.replace(
3432
+ /index\.m3u8(?:\?.*)?$/i,
3433
+ `subs/${locale}.vtt`
3434
+ );
3435
+ if (replaced === trimmed) return null;
3436
+ return replaced;
3437
+ }
3438
+ function liveCaptionsUrl(base, locale) {
3439
+ return `${base.replace(/\/$/, "")}/${locale}`;
3440
+ }
3441
+ function parseCaptionVtt(text) {
3442
+ const cues = [];
3443
+ const blocks = text.replace(/^\uFEFF?WEBVTT[^\n]*\n/i, "").split(/\n\s*\n/);
3444
+ for (const block of blocks) {
3445
+ const lines = block.split("\n").map((line) => line.trim()).filter(Boolean);
3446
+ const timing = lines.find((line) => line.includes("-->"));
3447
+ if (!timing) continue;
3448
+ const [startRaw, endRaw] = timing.split("-->").map((part) => part.trim());
3449
+ if (!startRaw || !endRaw) continue;
3450
+ const textLines = lines.filter(
3451
+ (line) => line !== timing && !/^\d+$/.test(line)
3452
+ );
3453
+ const payload = textLines.join("\n").trim();
3454
+ if (!payload) continue;
3455
+ cues.push({
3456
+ start: parseVttTimestamp(startRaw.split(" ")[0] ?? startRaw),
3457
+ end: parseVttTimestamp(endRaw.split(" ")[0] ?? endRaw),
3458
+ text: payload
3459
+ });
3398
3460
  }
3399
- return defaultRetry;
3461
+ return cues;
3400
3462
  }
3401
- var liveEdgeErrorRetry = {
3402
- maxNumRetry: 8,
3403
- retryDelayMs: 250,
3404
- maxRetryDelayMs: 4e3,
3405
- backoff: "exponential",
3406
- shouldRetry: shouldRetryLiveEdge404
3407
- };
3408
- function createLiveHlsConfig() {
3409
- return {
3410
- enableWorker: true,
3411
- // No custom request headers: Cache-Control/Pragma are not
3412
- // CORS-safelisted and would force an OPTIONS preflight before every
3413
- // manifest poll and segment fetch. Freshness is controlled by the
3414
- // origin's response Cache-Control headers instead.
3415
- liveSyncDurationCount: 4,
3416
- liveMaxLatencyDurationCount: 12,
3417
- fragLoadPolicy: {
3418
- default: {
3419
- maxTimeToFirstByteMs: 1e4,
3420
- maxLoadTimeMs: 12e4,
3421
- timeoutRetry: {
3422
- maxNumRetry: 4,
3423
- retryDelayMs: 0,
3424
- maxRetryDelayMs: 0
3425
- },
3426
- errorRetry: liveEdgeErrorRetry
3427
- }
3428
- },
3429
- playlistLoadPolicy: {
3430
- default: {
3431
- maxTimeToFirstByteMs: 1e4,
3432
- maxLoadTimeMs: 3e4,
3433
- timeoutRetry: {
3434
- maxNumRetry: 2,
3435
- retryDelayMs: 0,
3436
- maxRetryDelayMs: 0
3437
- },
3438
- errorRetry: {
3439
- ...liveEdgeErrorRetry,
3440
- maxNumRetry: 6
3463
+ function captionScreenRow(text, speaker) {
3464
+ return speaker == null ? { text } : { text, speaker };
3465
+ }
3466
+ function chunkLongWord(word, maxCharsPerLine) {
3467
+ if (word.length <= maxCharsPerLine) return [word];
3468
+ const parts = [];
3469
+ for (let index = 0; index < word.length; index += maxCharsPerLine) {
3470
+ parts.push(word.slice(index, index + maxCharsPerLine));
3471
+ }
3472
+ return parts;
3473
+ }
3474
+ function wrapCaptionLines(text, maxCharsPerLine) {
3475
+ const tokens = text.split(" ").filter(Boolean).flatMap((word) => chunkLongWord(word, maxCharsPerLine));
3476
+ const lines = [];
3477
+ let index = 0;
3478
+ while (index < tokens.length) {
3479
+ let end = index;
3480
+ let length = 0;
3481
+ while (end < tokens.length) {
3482
+ const added = tokens[end].length + (end > index ? 1 : 0);
3483
+ if (length + added > maxCharsPerLine && end > index) break;
3484
+ length += added;
3485
+ end += 1;
3486
+ }
3487
+ let breakAt = end;
3488
+ if (end < tokens.length) {
3489
+ for (let cursor = end - 1; cursor > index; cursor -= 1) {
3490
+ if (!CAPTION_BREAK_PUNCT.test(tokens[cursor])) continue;
3491
+ const firstLen = tokens.slice(index, cursor + 1).join(" ").length;
3492
+ if (firstLen >= Math.min(CAPTION_MIN_PUNCT_LINE, maxCharsPerLine)) {
3493
+ breakAt = cursor + 1;
3441
3494
  }
3495
+ break;
3442
3496
  }
3443
3497
  }
3444
- };
3498
+ lines.push(tokens.slice(index, breakAt).join(" "));
3499
+ index = breakAt;
3500
+ }
3501
+ return lines;
3445
3502
  }
3446
- function createVodHlsConfig() {
3447
- return {
3448
- enableWorker: true,
3449
- startPosition: 0
3450
- };
3503
+ function balanceCaptionLines(lines, maxCharsPerLine) {
3504
+ const next = [...lines];
3505
+ for (let index = 0; index + 1 < next.length; index += CAPTION_MAX_LINES) {
3506
+ const left = next[index].split(" ");
3507
+ const right = next[index + 1].split(" ");
3508
+ if (right.length !== 1 || left.length < 3) continue;
3509
+ const moved = left[left.length - 1];
3510
+ const newRight = `${moved} ${right[0]}`;
3511
+ if (newRight.length > maxCharsPerLine) continue;
3512
+ next[index] = left.slice(0, -1).join(" ");
3513
+ next[index + 1] = newRight;
3514
+ }
3515
+ return next;
3451
3516
  }
3452
-
3453
- // src/components/video/hls-errors.ts
3454
- var MEDIA_ERROR_NAMES = {
3455
- 1: "MEDIA_ERR_ABORTED",
3456
- 2: "MEDIA_ERR_NETWORK",
3457
- 3: "MEDIA_ERR_DECODE",
3458
- 4: "MEDIA_ERR_SRC_NOT_SUPPORTED"
3459
- };
3460
- var MEDIA_ERR_NETWORK = 2;
3461
- var MEDIA_ERR_DECODE = 3;
3462
- var MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
3463
- function errorMessageFromUnknown(error) {
3464
- if (error instanceof Error) return error.message;
3465
- if (typeof error === "string") return error;
3466
- return void 0;
3517
+ function splitCaptionScreens(text, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
3518
+ const trimmed = text.trim().replace(/\s+/g, " ");
3519
+ if (!trimmed) return [];
3520
+ const lines = balanceCaptionLines(
3521
+ wrapCaptionLines(trimmed, maxCharsPerLine),
3522
+ maxCharsPerLine
3523
+ );
3524
+ const screens = [];
3525
+ for (let index = 0; index < lines.length; index += CAPTION_MAX_LINES) {
3526
+ screens.push(lines.slice(index, index + CAPTION_MAX_LINES).join("\n"));
3527
+ }
3528
+ return screens;
3467
3529
  }
3468
- function isNotFound(httpStatus, details) {
3469
- return httpStatus === 404 || details === "manifestLoadError" || details === "levelLoadError" || details === "fragLoadError";
3530
+ function captionDwellMs(text, backlog = 0) {
3531
+ const chars = text.replace(/\s+/g, " ").trim().length;
3532
+ const raw = chars / CAPTION_CHARS_PER_SECOND * 1e3;
3533
+ const max = backlog > 0 ? CAPTION_RUSH_DWELL_MS : CAPTION_MAX_DWELL_MS;
3534
+ return Math.min(max, Math.max(CAPTION_MIN_DWELL_MS, raw));
3470
3535
  }
3471
- function kindForHls(input) {
3472
- const httpStatus = input.response?.code;
3473
- if (input.type === "networkError" && isNotFound(httpStatus, input.details)) {
3474
- return input.context.mode === "vod" || !input.context.manifestParsed ? "unavailable" : "network";
3536
+ function advanceLiveCaptionPlayout(state, cues, now, lagMs, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
3537
+ let screen = state.screen;
3538
+ let hideAt = state.hideAt;
3539
+ let cursor = state.cursor;
3540
+ let queue = state.queue.slice();
3541
+ if (lagMs != null && Number.isFinite(lagMs) && lagMs >= 0) {
3542
+ const threshold = lagMs + LIVE_CUE_EXTRA_LAG_MS;
3543
+ const incoming = cues.filter(
3544
+ (cue) => Boolean(cue.text.trim()) && Number.isFinite(cue.receivedAt) && cue.receivedAt > cursor && now - cue.receivedAt >= threshold
3545
+ ).sort((left, right) => left.receivedAt - right.receivedAt);
3546
+ for (const cue of incoming) {
3547
+ for (const text of splitCaptionScreens(cue.text, maxCharsPerLine)) {
3548
+ queue.push(captionScreenRow(text, cue.speaker));
3549
+ }
3550
+ cursor = cue.receivedAt;
3551
+ }
3552
+ if (queue.length > CAPTION_BACKLOG_DROP) {
3553
+ queue = queue.slice(queue.length - CAPTION_BACKLOG_DROP);
3554
+ }
3475
3555
  }
3476
- if (input.type === "mediaError" || input.details === "bufferAppendError" || input.details === "bufferSeekOverHole") {
3477
- return "media";
3556
+ if (now >= hideAt) {
3557
+ const next = queue.shift();
3558
+ if (next) {
3559
+ screen = next;
3560
+ hideAt = now + captionDwellMs(next.text, queue.length);
3561
+ } else {
3562
+ screen = null;
3563
+ }
3478
3564
  }
3479
- return "generic";
3565
+ return { screen, hideAt, cursor, queue };
3480
3566
  }
3481
- function kindForNative(input) {
3482
- const code = input.mediaError?.code;
3483
- if (code === MEDIA_ERR_DECODE) return "media";
3484
- if (code === MEDIA_ERR_SRC_NOT_SUPPORTED) return "unsupported";
3485
- if (code === MEDIA_ERR_NETWORK) return "unavailable";
3486
- return "generic";
3567
+ function cueEndWithGapFill(cues, index) {
3568
+ const cue = cues[index];
3569
+ if (!cue) return 0;
3570
+ const next = cues[index + 1];
3571
+ if (!next || !Number.isFinite(next.start)) return cue.end;
3572
+ const gapMs = (next.start - cue.end) * 1e3;
3573
+ if (gapMs > 0 && gapMs < CAPTION_GAP_FILL_MS) return next.start;
3574
+ return cue.end;
3487
3575
  }
3488
- function describeAvResync(input) {
3489
- const lag = Number.isFinite(input.lagSeconds) ? input.lagSeconds : 0;
3490
- return {
3491
- summary: `av-resync lag=${lag.toFixed(3)}s (non-fatal)`,
3492
- kind: "resync",
3493
- detail: {
3494
- source: input.context.source,
3495
- kind: "resync",
3496
- fatal: false,
3497
- reason: `presented frame lag ${lag.toFixed(3)}s`,
3498
- context: input.context
3576
+ function captionScreenAtTime(cues, time, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
3577
+ if (!Number.isFinite(time)) return null;
3578
+ const ordered = cues.filter(
3579
+ (cue) => Boolean(cue.text.trim()) && Number.isFinite(cue.start) && Number.isFinite(cue.end)
3580
+ ).sort((left, right) => left.start - right.start);
3581
+ for (let index = 0; index < ordered.length; index += 1) {
3582
+ const cue = ordered[index];
3583
+ const end = cueEndWithGapFill(ordered, index);
3584
+ if (time < cue.start || time >= end) continue;
3585
+ const screens = splitCaptionScreens(cue.text, maxCharsPerLine);
3586
+ if (screens.length === 0) return null;
3587
+ const weights = screens.map(
3588
+ (text) => Math.max(1, text.replace(/\s+/g, "").length)
3589
+ );
3590
+ const total = weights.reduce((sum, weight) => sum + weight, 0);
3591
+ const duration = Math.max(end - cue.start, 0);
3592
+ let cursor = cue.start;
3593
+ for (let screenIndex = 0; screenIndex < screens.length; screenIndex += 1) {
3594
+ const isLast = screenIndex === screens.length - 1;
3595
+ const slice = isLast ? end - cursor : duration * (weights[screenIndex] / total);
3596
+ const sliceEnd = cursor + slice;
3597
+ if (time >= cursor && time < sliceEnd) {
3598
+ return captionScreenRow(screens[screenIndex]);
3599
+ }
3600
+ cursor = sliceEnd;
3499
3601
  }
3500
- };
3602
+ return captionScreenRow(screens[screens.length - 1]);
3603
+ }
3604
+ return null;
3501
3605
  }
3502
- function describePlaybackError(input) {
3503
- if (input.source === "unsupported") {
3504
- return {
3505
- summary: "playback unsupported (hls.js unavailable, native HLS unsupported)",
3506
- kind: "unsupported",
3507
- detail: {
3508
- source: "unsupported",
3509
- kind: "unsupported",
3510
- context: input.context
3606
+ var LIVE_OVERLAP_MIN_WORDS = 4;
3607
+ function normalizeLiveCaptionText(text) {
3608
+ return text.trim().replace(/\s+/g, " ").toLowerCase();
3609
+ }
3610
+ function lastSubseqIndex(haystack, needle) {
3611
+ if (needle.length === 0 || needle.length > haystack.length) return -1;
3612
+ let found = -1;
3613
+ for (let index = 0; index <= haystack.length - needle.length; index += 1) {
3614
+ let match = true;
3615
+ for (let offset = 0; offset < needle.length; offset += 1) {
3616
+ if (haystack[index + offset] !== needle[offset]) {
3617
+ match = false;
3618
+ break;
3511
3619
  }
3512
- };
3513
- }
3514
- if (input.source === "native") {
3515
- const code = input.mediaError?.code;
3516
- const kind2 = kindForNative(input);
3517
- const detail2 = {
3518
- source: "native",
3519
- kind: kind2,
3520
- mediaErrorCode: code,
3521
- mediaErrorName: code !== void 0 ? MEDIA_ERROR_NAMES[code] : void 0,
3522
- errorMessage: input.mediaError?.message,
3523
- context: input.context
3524
- };
3525
- const name = detail2.mediaErrorName ?? "MEDIA_ERR_UNKNOWN";
3526
- return {
3527
- summary: `native ${name}${input.mediaError?.message ? `: ${input.mediaError.message}` : ""}`,
3528
- kind: kind2,
3529
- detail: detail2
3530
- };
3620
+ }
3621
+ if (match) found = index;
3531
3622
  }
3532
- const httpStatus = input.response?.code;
3533
- const kind = kindForHls(input);
3534
- const detail = {
3535
- source: "hls",
3536
- kind,
3537
- type: input.type,
3538
- details: input.details,
3539
- fatal: input.fatal,
3540
- httpStatus,
3541
- url: input.url,
3542
- reason: input.reason,
3543
- errorMessage: errorMessageFromUnknown(input.error),
3544
- context: input.context
3545
- };
3546
- const statusSuffix = httpStatus !== void 0 ? ` ${httpStatus}` : "";
3547
- const summary = [
3548
- "hls",
3549
- input.type ?? "unknown",
3550
- input.details ?? "unknown",
3551
- input.fatal ? "(fatal)" : "(non-fatal)",
3552
- statusSuffix.trim()
3553
- ].filter(Boolean).join(" ");
3554
- return { summary, kind, detail };
3623
+ return found;
3555
3624
  }
3556
-
3557
- // src/components/video/useHlsPlayback.ts
3558
- var RETRY_INTERVAL_MS = 3e3;
3559
- var MAX_MEDIA_ERROR_RETRIES = 5;
3560
- var DRIFT_THRESHOLD_S = 0.4;
3561
- var DRIFT_CONSECUTIVE_SAMPLES = 3;
3562
- var RESYNC_COOLDOWN_MS = 1e4;
3563
- var LIVE_EDGE_RESYNC_THRESHOLD_S = 8;
3564
- function useHlsPlayback({
3565
- src,
3566
- mode,
3567
- active,
3568
- autoPlay = false,
3569
- muted = false,
3570
- onError,
3571
- onPlayingChange,
3572
- onRebuffer,
3573
- onQualityChange
3574
- }) {
3575
- const videoRef = React9__namespace.useRef(null);
3576
- const hlsRef = React9__namespace.useRef(null);
3577
- const [state, setState] = React9__namespace.useState("idle");
3578
- const [qualities, setQualities] = React9__namespace.useState([]);
3579
- const [activeLevel, setActiveLevel] = React9__namespace.useState(-1);
3580
- const [autoplayState, setAutoplayState] = React9__namespace.useState("none");
3581
- const [error, setError] = React9__namespace.useState(null);
3582
- const [reloadKey, setReloadKey] = React9__namespace.useState(0);
3583
- const onErrorRef = React9__namespace.useRef(onError);
3584
- const onPlayingChangeRef = React9__namespace.useRef(onPlayingChange);
3585
- const onRebufferRef = React9__namespace.useRef(onRebuffer);
3586
- const onQualityChangeRef = React9__namespace.useRef(onQualityChange);
3587
- React9__namespace.useEffect(() => {
3588
- onErrorRef.current = onError;
3589
- onPlayingChangeRef.current = onPlayingChange;
3590
- onRebufferRef.current = onRebuffer;
3591
- onQualityChangeRef.current = onQualityChange;
3592
- }, [onError, onPlayingChange, onRebuffer, onQualityChange]);
3593
- const retry = React9__namespace.useCallback(() => {
3594
- setError(null);
3595
- setState("loading");
3596
- setAutoplayState("none");
3597
- setReloadKey((k) => k + 1);
3598
- }, []);
3599
- React9__namespace.useEffect(() => {
3600
- const media = videoRef.current;
3601
- if (!media || !src || !active) {
3602
- setState("idle");
3603
- return;
3604
- }
3605
- let cancelled = false;
3606
- let retryTimer = null;
3607
- let manifestParsed = false;
3608
- let mediaErrorRetries = 0;
3609
- let playbackSource = "hls";
3610
- const teardown = [];
3611
- applyMute(media);
3612
- setState("loading");
3613
- setError(null);
3614
- setAutoplayState("none");
3615
- setQualities([]);
3616
- setActiveLevel(-1);
3617
- function baseContext() {
3618
- return {
3619
- mode,
3620
- src,
3621
- manifestParsed,
3622
- retryCount: mediaErrorRetries,
3623
- source: playbackSource
3624
- };
3625
- }
3626
- function clearRetryTimer() {
3627
- if (retryTimer !== null) {
3628
- clearTimeout(retryTimer);
3629
- retryTimer = null;
3625
+ function remainderAfterOverlap(previous, next) {
3626
+ const prevWords = normalizeLiveCaptionText(previous).split(" ").filter(Boolean);
3627
+ const nextWords = next.trim().replace(/\s+/g, " ").split(" ").filter(Boolean);
3628
+ const nextNorm = nextWords.map((word) => word.toLowerCase());
3629
+ const maxN = Math.min(prevWords.length, nextNorm.length);
3630
+ for (let size = maxN; size >= LIVE_OVERLAP_MIN_WORDS; size -= 1) {
3631
+ for (let start = prevWords.length - size; start >= 0; start -= 1) {
3632
+ const gram = prevWords.slice(start, start + size);
3633
+ const index = lastSubseqIndex(nextNorm, gram);
3634
+ if (index !== -1) {
3635
+ return nextWords.slice(index + size).join(" ");
3630
3636
  }
3631
3637
  }
3632
- function destroyHls() {
3633
- hlsRef.current?.destroy();
3634
- hlsRef.current = null;
3635
- }
3636
- function reportFatal(input) {
3637
- const described = describePlaybackError(input);
3638
- onErrorRef.current?.(described);
3639
- setError(described);
3640
- setState("error");
3641
- }
3642
- function applyMute(el) {
3643
- el.muted = muted;
3638
+ }
3639
+ return null;
3640
+ }
3641
+ function liveCaptionRow(text, receivedAt, speaker) {
3642
+ return speaker == null ? { text, receivedAt } : { text, receivedAt, speaker };
3643
+ }
3644
+ function coalesceLiveCaptionCues(cues) {
3645
+ const out = [];
3646
+ for (const cue of cues) {
3647
+ const text = cue.text.trim();
3648
+ if (!text) continue;
3649
+ const last = out[out.length - 1];
3650
+ if (!last) {
3651
+ out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
3652
+ continue;
3644
3653
  }
3645
- function preserveMute(el, fn) {
3646
- const wasMuted = el.muted;
3647
- fn();
3648
- el.muted = wasMuted;
3654
+ if (last.speaker !== cue.speaker && (last.speaker != null || cue.speaker != null)) {
3655
+ out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
3656
+ continue;
3649
3657
  }
3650
- function attemptAutoplay(el) {
3651
- applyMute(el);
3652
- void el.play().then(
3653
- () => {
3654
- applyMute(el);
3655
- setAutoplayState("playing");
3656
- },
3657
- () => {
3658
- el.muted = true;
3659
- void el.play().then(
3660
- () => setAutoplayState(muted ? "playing" : "muted"),
3661
- () => {
3662
- if (el.paused) {
3663
- setAutoplayState("blocked");
3664
- return;
3665
- }
3666
- setAutoplayState(el.muted && !muted ? "muted" : "playing");
3667
- }
3668
- );
3669
- }
3658
+ const lastNorm = normalizeLiveCaptionText(last.text);
3659
+ const nextNorm = normalizeLiveCaptionText(text);
3660
+ if (lastNorm === nextNorm) continue;
3661
+ if (nextNorm.startsWith(lastNorm) || lastNorm.startsWith(nextNorm)) {
3662
+ out[out.length - 1] = liveCaptionRow(
3663
+ nextNorm.length >= lastNorm.length ? text : last.text,
3664
+ cue.receivedAt,
3665
+ cue.speaker ?? last.speaker
3670
3666
  );
3667
+ continue;
3671
3668
  }
3672
- function scheduleRetry(retryFn) {
3673
- clearRetryTimer();
3674
- if (cancelled) return;
3675
- setState("waiting");
3676
- retryTimer = setTimeout(() => {
3677
- retryTimer = null;
3678
- if (!cancelled) retryFn();
3679
- }, RETRY_INTERVAL_MS);
3680
- }
3681
- function startDriftWatchdog(el) {
3682
- if (typeof el.requestVideoFrameCallback !== "function") return;
3683
- let consecutiveLagSamples = 0;
3684
- let lastResyncAt = 0;
3685
- let handle = null;
3686
- const tick = (_now, metadata) => {
3687
- if (cancelled) return;
3688
- handle = el.requestVideoFrameCallback(tick);
3689
- if (el.paused || el.ended) {
3690
- consecutiveLagSamples = 0;
3691
- return;
3692
- }
3693
- const lag = el.currentTime - metadata.mediaTime;
3694
- if (!(lag > DRIFT_THRESHOLD_S)) {
3695
- consecutiveLagSamples = 0;
3696
- return;
3697
- }
3698
- consecutiveLagSamples += 1;
3699
- if (consecutiveLagSamples < DRIFT_CONSECUTIVE_SAMPLES) return;
3700
- const nowMs = performance.now();
3701
- if (nowMs - lastResyncAt < RESYNC_COOLDOWN_MS) return;
3702
- lastResyncAt = nowMs;
3703
- consecutiveLagSamples = 0;
3704
- if (mode === "live" && el.seekable.length > 0) {
3705
- const edge = el.seekable.end(el.seekable.length - 1);
3706
- if (edge - el.currentTime > LIVE_EDGE_RESYNC_THRESHOLD_S) {
3707
- el.currentTime = edge;
3708
- } else {
3709
- el.currentTime = el.currentTime + 1e-3;
3710
- }
3711
- } else {
3712
- el.currentTime = el.currentTime + 1e-3;
3713
- }
3714
- onErrorRef.current?.(
3715
- describeAvResync({
3716
- lagSeconds: lag,
3717
- context: baseContext()
3718
- })
3719
- );
3720
- };
3721
- handle = el.requestVideoFrameCallback(tick);
3722
- teardown.push(() => {
3723
- if (handle != null && typeof el.cancelVideoFrameCallback === "function") {
3724
- el.cancelVideoFrameCallback(handle);
3725
- }
3726
- });
3727
- }
3728
- let hasPlayed = false;
3729
- let waitingSince = null;
3730
- function onPlaying() {
3731
- manifestParsed = true;
3732
- mediaErrorRetries = 0;
3733
- clearRetryTimer();
3734
- setState("ready");
3735
- setAutoplayState(
3736
- (prev) => prev === "blocked" || prev === "none" ? "playing" : prev
3737
- );
3738
- if (waitingSince != null) {
3739
- const seconds = (performance.now() - waitingSince) / 1e3;
3740
- waitingSince = null;
3741
- if (seconds > 0) onRebufferRef.current?.(seconds);
3742
- }
3743
- hasPlayed = true;
3744
- onPlayingChangeRef.current?.(true);
3745
- }
3746
- function onPaused() {
3747
- onPlayingChangeRef.current?.(false);
3748
- }
3749
- function onWaiting() {
3750
- if (!hasPlayed || waitingSince != null) return;
3751
- waitingSince = performance.now();
3669
+ const remainder = remainderAfterOverlap(last.text, text);
3670
+ if (remainder !== null) {
3671
+ if (!remainder) continue;
3672
+ out.push(liveCaptionRow(remainder, cue.receivedAt, cue.speaker));
3673
+ continue;
3752
3674
  }
3753
- media.addEventListener("playing", onPlaying);
3754
- media.addEventListener("pause", onPaused);
3755
- media.addEventListener("ended", onPaused);
3756
- media.addEventListener("waiting", onWaiting);
3757
- teardown.push(() => {
3758
- media.removeEventListener("playing", onPlaying);
3759
- media.removeEventListener("pause", onPaused);
3760
- media.removeEventListener("ended", onPaused);
3761
- media.removeEventListener("waiting", onWaiting);
3675
+ out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
3676
+ }
3677
+ return out;
3678
+ }
3679
+ function mergeLiveCaptionCues(existing, incoming, cap = LIVE_STACK_MAX_CUES) {
3680
+ const map = /* @__PURE__ */ new Map();
3681
+ for (const cue of existing) {
3682
+ if (Number.isFinite(cue.receivedAt)) map.set(cue.receivedAt, cue);
3683
+ }
3684
+ for (const cue of incoming) {
3685
+ if (Number.isFinite(cue.receivedAt)) map.set(cue.receivedAt, cue);
3686
+ }
3687
+ return [...map.values()].sort((left, right) => left.receivedAt - right.receivedAt).slice(-Math.max(1, cap));
3688
+ }
3689
+ async function loadCaptionVtt(url) {
3690
+ try {
3691
+ const response = await fetch(url, { cache: "no-store" });
3692
+ if (!response.ok) return [];
3693
+ return parseCaptionVtt(await response.text());
3694
+ } catch {
3695
+ return [];
3696
+ }
3697
+ }
3698
+ async function loadLiveCaptions(url) {
3699
+ try {
3700
+ const response = await fetch(url, {
3701
+ cache: "no-store",
3702
+ headers: { Accept: "application/json" }
3762
3703
  });
3763
- startDriftWatchdog(media);
3764
- function initNative() {
3765
- playbackSource = "native";
3766
- manifestParsed = false;
3767
- media.removeAttribute("src");
3768
- media.load();
3769
- media.src = src;
3770
- applyMute(media);
3771
- const onReady = () => {
3772
- manifestParsed = true;
3773
- clearRetryTimer();
3774
- setState("ready");
3775
- if (mode === "live" || autoPlay) attemptAutoplay(media);
3776
- };
3777
- const onErr = () => {
3778
- if (manifestParsed) {
3779
- reportFatal({
3780
- source: "native",
3781
- mediaError: media.error,
3782
- context: baseContext()
3783
- });
3784
- return;
3785
- }
3786
- onErrorRef.current?.(
3787
- describePlaybackError({
3788
- source: "native",
3789
- mediaError: media.error,
3790
- context: baseContext()
3791
- })
3792
- );
3793
- scheduleRetry(() => {
3794
- media.src = src;
3795
- media.load();
3796
- });
3797
- };
3798
- media.addEventListener("loadedmetadata", onReady);
3799
- media.addEventListener("error", onErr);
3800
- teardown.push(() => {
3801
- media.removeEventListener("loadedmetadata", onReady);
3802
- media.removeEventListener("error", onErr);
3803
- });
3804
- }
3805
- function initHlsJs(Hls) {
3806
- playbackSource = "hls";
3807
- destroyHls();
3808
- manifestParsed = false;
3809
- const config = mode === "live" ? createLiveHlsConfig() : createVodHlsConfig();
3810
- const hls = new Hls(config);
3811
- hlsRef.current = hls;
3812
- hls.loadSource(src);
3813
- hls.attachMedia(media);
3814
- applyMute(media);
3815
- hls.on(Hls.Events.MANIFEST_PARSED, (_e, data) => {
3816
- manifestParsed = true;
3817
- clearRetryTimer();
3818
- setQualities(
3819
- data.levels.map((l, index) => ({ index, height: l.height }))
3820
- );
3821
- setState("ready");
3822
- if (mode === "live" || autoPlay) attemptAutoplay(media);
3823
- });
3824
- hls.on(Hls.Events.LEVEL_SWITCHED, (_e, data) => {
3825
- if (hls.autoLevelEnabled) setActiveLevel(-1);
3826
- else setActiveLevel(data.level);
3827
- const height = hls.levels?.[data.level]?.height;
3828
- onQualityChangeRef.current?.(
3829
- typeof height === "number" && height > 0 ? `${height}p` : "auto"
3830
- );
3831
- });
3832
- hls.on(Hls.Events.ERROR, (_e, data) => {
3833
- onErrorRef.current?.(
3834
- describePlaybackError({
3835
- source: "hls",
3836
- type: data.type,
3837
- details: data.details,
3838
- fatal: data.fatal,
3839
- url: data.url,
3840
- response: data.response,
3841
- reason: data.reason,
3842
- error: data.error,
3843
- context: baseContext()
3844
- })
3845
- );
3846
- if (!data.fatal) return;
3847
- if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
3848
- if (!manifestParsed) {
3849
- scheduleRetry(() => initHlsJs(Hls));
3850
- return;
3851
- }
3852
- hls.startLoad();
3853
- return;
3854
- }
3855
- mediaErrorRetries += 1;
3856
- if (mediaErrorRetries === 1) {
3857
- preserveMute(media, () => hls.recoverMediaError());
3858
- return;
3859
- }
3860
- if (mediaErrorRetries === 2) {
3861
- preserveMute(media, () => {
3862
- hls.swapAudioCodec();
3863
- hls.recoverMediaError();
3864
- });
3865
- return;
3866
- }
3867
- if (mediaErrorRetries < MAX_MEDIA_ERROR_RETRIES) {
3868
- scheduleRetry(() => initHlsJs(Hls));
3869
- return;
3870
- }
3871
- reportFatal({
3872
- source: "hls",
3873
- type: data.type,
3874
- details: data.details,
3875
- fatal: true,
3876
- url: data.url,
3877
- response: data.response,
3878
- reason: data.reason,
3879
- error: data.error,
3880
- context: baseContext()
3881
- });
3882
- });
3704
+ if (!response.ok) return { ok: false, cues: [] };
3705
+ const body = await response.json();
3706
+ if (!body || typeof body !== "object" || !("cues" in body)) {
3707
+ return { ok: false, cues: [] };
3883
3708
  }
3884
- async function setup() {
3885
- let Hls = null;
3886
- try {
3887
- Hls = (await import('hls.js')).default;
3888
- } catch {
3889
- Hls = null;
3709
+ const rows = body.cues;
3710
+ if (!Array.isArray(rows)) return { ok: false, cues: [] };
3711
+ const cues = [];
3712
+ for (const row of rows) {
3713
+ if (!row || typeof row !== "object") continue;
3714
+ const record = row;
3715
+ if (typeof record.text !== "string" || !record.text.trim()) continue;
3716
+ if (typeof record.receivedAt !== "number" || !Number.isFinite(record.receivedAt)) {
3717
+ continue;
3890
3718
  }
3891
- if (cancelled) return;
3892
- if (Hls && Hls.isSupported()) {
3893
- initHlsJs(Hls);
3894
- } else if (media.canPlayType("application/vnd.apple.mpegurl")) {
3895
- initNative();
3896
- } else {
3897
- playbackSource = "unsupported";
3898
- reportFatal({
3899
- source: "unsupported",
3900
- context: baseContext()
3901
- });
3719
+ const parsed = {
3720
+ text: record.text.trim(),
3721
+ receivedAt: record.receivedAt
3722
+ };
3723
+ if (typeof record.speaker === "number" && Number.isFinite(record.speaker)) {
3724
+ parsed.speaker = record.speaker;
3902
3725
  }
3726
+ cues.push(parsed);
3903
3727
  }
3904
- void setup();
3905
- return () => {
3906
- cancelled = true;
3907
- clearRetryTimer();
3908
- for (const fn of teardown) fn();
3909
- destroyHls();
3910
- };
3911
- }, [src, mode, active, autoPlay, muted, reloadKey]);
3912
- const setLevel = React9__namespace.useCallback((index) => {
3913
- const hls = hlsRef.current;
3914
- if (!hls) return;
3915
- hls.nextLevel = index;
3916
- setActiveLevel(index);
3917
- }, []);
3728
+ return { ok: true, cues };
3729
+ } catch {
3730
+ return { ok: false, cues: [] };
3731
+ }
3732
+ }
3733
+
3734
+ // src/components/video/hls-config.ts
3735
+ function shouldRetryLiveEdge404(retryConfig, retryCount, _isTimeout, loaderResponse, defaultRetry) {
3736
+ if (loaderResponse?.code === 404) {
3737
+ return retryConfig != null && retryCount < retryConfig.maxNumRetry;
3738
+ }
3739
+ return defaultRetry;
3740
+ }
3741
+ var liveEdgeErrorRetry = {
3742
+ maxNumRetry: 8,
3743
+ retryDelayMs: 250,
3744
+ maxRetryDelayMs: 4e3,
3745
+ backoff: "exponential",
3746
+ shouldRetry: shouldRetryLiveEdge404
3747
+ };
3748
+ function createLiveHlsConfig() {
3918
3749
  return {
3919
- videoRef,
3920
- state,
3921
- qualities,
3922
- activeLevel,
3923
- setLevel,
3924
- autoplayState,
3925
- error,
3926
- retry
3750
+ enableWorker: true,
3751
+ // No custom request headers: Cache-Control/Pragma are not
3752
+ // CORS-safelisted and would force an OPTIONS preflight before every
3753
+ // manifest poll and segment fetch. Freshness is controlled by the
3754
+ // origin's response Cache-Control headers instead.
3755
+ liveSyncDurationCount: 4,
3756
+ liveMaxLatencyDurationCount: 12,
3757
+ fragLoadPolicy: {
3758
+ default: {
3759
+ maxTimeToFirstByteMs: 1e4,
3760
+ maxLoadTimeMs: 12e4,
3761
+ timeoutRetry: {
3762
+ maxNumRetry: 4,
3763
+ retryDelayMs: 0,
3764
+ maxRetryDelayMs: 0
3765
+ },
3766
+ errorRetry: liveEdgeErrorRetry
3767
+ }
3768
+ },
3769
+ playlistLoadPolicy: {
3770
+ default: {
3771
+ maxTimeToFirstByteMs: 1e4,
3772
+ maxLoadTimeMs: 3e4,
3773
+ timeoutRetry: {
3774
+ maxNumRetry: 2,
3775
+ retryDelayMs: 0,
3776
+ maxRetryDelayMs: 0
3777
+ },
3778
+ errorRetry: {
3779
+ ...liveEdgeErrorRetry,
3780
+ maxNumRetry: 6
3781
+ }
3782
+ }
3783
+ }
3784
+ };
3785
+ }
3786
+ function createVodHlsConfig() {
3787
+ return {
3788
+ enableWorker: true,
3789
+ startPosition: 0
3927
3790
  };
3928
3791
  }
3929
3792
 
3930
- // src/components/video/captions.ts
3931
- var CAPTION_LOCALES = ["en", "es", "pt"];
3932
- var LIVE_CUE_EXTRA_LAG_MS = 2e3;
3933
- var LIVE_STACK_MAX_CUES = 150;
3934
- var CAPTION_CHARS_PER_SECOND = 17;
3935
- var CAPTION_MIN_DWELL_MS = 1200;
3936
- var CAPTION_MAX_DWELL_MS = 6e3;
3937
- var CAPTION_RUSH_DWELL_MS = 2500;
3938
- var CAPTION_MAX_CHARS_PER_LINE = 42;
3939
- var CAPTION_COMPACT_CHARS_PER_LINE = 32;
3940
- var CAPTION_MAX_LINES = 2;
3941
- var CAPTION_BACKLOG_DROP = 8;
3942
- var CAPTION_GAP_FILL_MS = 1e3;
3943
- var LIVE_LAG_SPIKE_MS = 2500;
3944
- var CAPTION_BREAK_PUNCT = /[.,;:?!]$/;
3945
- var CAPTION_MIN_PUNCT_LINE = 8;
3946
- var EMPTY_LIVE_CAPTION_PLAYOUT = {
3947
- screen: null,
3948
- hideAt: 0,
3949
- cursor: 0,
3950
- queue: []
3793
+ // src/components/video/hls-errors.ts
3794
+ var MEDIA_ERROR_NAMES = {
3795
+ 1: "MEDIA_ERR_ABORTED",
3796
+ 2: "MEDIA_ERR_NETWORK",
3797
+ 3: "MEDIA_ERR_DECODE",
3798
+ 4: "MEDIA_ERR_SRC_NOT_SUPPORTED"
3951
3799
  };
3952
- function stabilizeLiveLagMs(previous, next) {
3953
- if (previous == null || !Number.isFinite(previous)) return next;
3954
- if (next <= previous) return next;
3955
- if (next - previous < LIVE_LAG_SPIKE_MS) return previous;
3956
- return next;
3957
- }
3958
- function isCaptionLocale(value) {
3959
- return CAPTION_LOCALES.includes(value);
3960
- }
3961
- function captionsVttUrlFromPlayback(src, locale) {
3962
- const trimmed = src.trim();
3963
- if (!trimmed) return null;
3964
- const replaced = trimmed.replace(
3965
- /index\.m3u8(?:\?.*)?$/i,
3966
- `subs/${locale}.vtt`
3967
- );
3968
- if (replaced === trimmed) return null;
3969
- return replaced;
3800
+ var MEDIA_ERR_NETWORK = 2;
3801
+ var MEDIA_ERR_DECODE = 3;
3802
+ var MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
3803
+ function errorMessageFromUnknown(error) {
3804
+ if (error instanceof Error) return error.message;
3805
+ if (typeof error === "string") return error;
3806
+ return void 0;
3970
3807
  }
3971
- function liveCaptionsUrl(base, locale) {
3972
- return `${base.replace(/\/$/, "")}/${locale}`;
3808
+ function isNotFound(httpStatus, details) {
3809
+ return httpStatus === 404 || details === "manifestLoadError" || details === "levelLoadError" || details === "fragLoadError";
3973
3810
  }
3974
- function parseCaptionVtt(text) {
3975
- const cues = [];
3976
- const blocks = text.replace(/^\uFEFF?WEBVTT[^\n]*\n/i, "").split(/\n\s*\n/);
3977
- for (const block of blocks) {
3978
- const lines = block.split("\n").map((line) => line.trim()).filter(Boolean);
3979
- const timing = lines.find((line) => line.includes("-->"));
3980
- if (!timing) continue;
3981
- const [startRaw, endRaw] = timing.split("-->").map((part) => part.trim());
3982
- if (!startRaw || !endRaw) continue;
3983
- const textLines = lines.filter(
3984
- (line) => line !== timing && !/^\d+$/.test(line)
3985
- );
3986
- const payload = textLines.join("\n").trim();
3987
- if (!payload) continue;
3988
- cues.push({
3989
- start: parseVttTimestamp(startRaw.split(" ")[0] ?? startRaw),
3990
- end: parseVttTimestamp(endRaw.split(" ")[0] ?? endRaw),
3991
- text: payload
3992
- });
3811
+ function kindForHls(input) {
3812
+ const httpStatus = input.response?.code;
3813
+ if (input.type === "networkError" && isNotFound(httpStatus, input.details)) {
3814
+ return input.context.mode === "vod" || !input.context.manifestParsed ? "unavailable" : "network";
3993
3815
  }
3994
- return cues;
3816
+ if (input.type === "mediaError" || input.details === "bufferAppendError" || input.details === "bufferSeekOverHole") {
3817
+ return "media";
3818
+ }
3819
+ return "generic";
3995
3820
  }
3996
- function captionScreenRow(text, speaker) {
3997
- return speaker == null ? { text } : { text, speaker };
3821
+ function kindForNative(input) {
3822
+ const code = input.mediaError?.code;
3823
+ if (code === MEDIA_ERR_DECODE) return "media";
3824
+ if (code === MEDIA_ERR_SRC_NOT_SUPPORTED) return "unsupported";
3825
+ if (code === MEDIA_ERR_NETWORK) return "unavailable";
3826
+ return "generic";
3998
3827
  }
3999
- function chunkLongWord(word, maxCharsPerLine) {
4000
- if (word.length <= maxCharsPerLine) return [word];
4001
- const parts = [];
4002
- for (let index = 0; index < word.length; index += maxCharsPerLine) {
4003
- parts.push(word.slice(index, index + maxCharsPerLine));
3828
+ function describeAvResync(input) {
3829
+ const lag = Number.isFinite(input.lagSeconds) ? input.lagSeconds : 0;
3830
+ return {
3831
+ summary: `av-resync lag=${lag.toFixed(3)}s (non-fatal)`,
3832
+ kind: "resync",
3833
+ detail: {
3834
+ source: input.context.source,
3835
+ kind: "resync",
3836
+ fatal: false,
3837
+ reason: `presented frame lag ${lag.toFixed(3)}s`,
3838
+ context: input.context
3839
+ }
3840
+ };
3841
+ }
3842
+ function describePlaybackError(input) {
3843
+ if (input.source === "unsupported") {
3844
+ return {
3845
+ summary: "playback unsupported (hls.js unavailable, native HLS unsupported)",
3846
+ kind: "unsupported",
3847
+ detail: {
3848
+ source: "unsupported",
3849
+ kind: "unsupported",
3850
+ context: input.context
3851
+ }
3852
+ };
4004
3853
  }
4005
- return parts;
3854
+ if (input.source === "native") {
3855
+ const code = input.mediaError?.code;
3856
+ const kind2 = kindForNative(input);
3857
+ const detail2 = {
3858
+ source: "native",
3859
+ kind: kind2,
3860
+ mediaErrorCode: code,
3861
+ mediaErrorName: code !== void 0 ? MEDIA_ERROR_NAMES[code] : void 0,
3862
+ errorMessage: input.mediaError?.message,
3863
+ context: input.context
3864
+ };
3865
+ const name = detail2.mediaErrorName ?? "MEDIA_ERR_UNKNOWN";
3866
+ return {
3867
+ summary: `native ${name}${input.mediaError?.message ? `: ${input.mediaError.message}` : ""}`,
3868
+ kind: kind2,
3869
+ detail: detail2
3870
+ };
3871
+ }
3872
+ const httpStatus = input.response?.code;
3873
+ const kind = kindForHls(input);
3874
+ const detail = {
3875
+ source: "hls",
3876
+ kind,
3877
+ type: input.type,
3878
+ details: input.details,
3879
+ fatal: input.fatal,
3880
+ httpStatus,
3881
+ url: input.url,
3882
+ reason: input.reason,
3883
+ errorMessage: errorMessageFromUnknown(input.error),
3884
+ context: input.context
3885
+ };
3886
+ const statusSuffix = httpStatus !== void 0 ? ` ${httpStatus}` : "";
3887
+ const summary = [
3888
+ "hls",
3889
+ input.type ?? "unknown",
3890
+ input.details ?? "unknown",
3891
+ input.fatal ? "(fatal)" : "(non-fatal)",
3892
+ statusSuffix.trim()
3893
+ ].filter(Boolean).join(" ");
3894
+ return { summary, kind, detail };
4006
3895
  }
4007
- function wrapCaptionLines(text, maxCharsPerLine) {
4008
- const tokens = text.split(" ").filter(Boolean).flatMap((word) => chunkLongWord(word, maxCharsPerLine));
4009
- const lines = [];
4010
- let index = 0;
4011
- while (index < tokens.length) {
4012
- let end = index;
4013
- let length = 0;
4014
- while (end < tokens.length) {
4015
- const added = tokens[end].length + (end > index ? 1 : 0);
4016
- if (length + added > maxCharsPerLine && end > index) break;
4017
- length += added;
4018
- end += 1;
3896
+
3897
+ // src/components/video/useHlsPlayback.ts
3898
+ function effectivePlaybackMode(src, mode, sealed) {
3899
+ if (isLivePlaylistSrc(src)) return sealed ? "vod" : "live";
3900
+ return mode;
3901
+ }
3902
+ var RETRY_INTERVAL_MS = 3e3;
3903
+ var MAX_MEDIA_ERROR_RETRIES = 5;
3904
+ var DRIFT_THRESHOLD_S = 0.4;
3905
+ var DRIFT_CONSECUTIVE_SAMPLES = 3;
3906
+ var RESYNC_COOLDOWN_MS = 1e4;
3907
+ var LIVE_EDGE_RESYNC_THRESHOLD_S = 8;
3908
+ function useHlsPlayback({
3909
+ src,
3910
+ mode,
3911
+ active,
3912
+ autoPlay = false,
3913
+ muted = false,
3914
+ onError,
3915
+ onPlayingChange,
3916
+ onRebuffer,
3917
+ onQualityChange
3918
+ }) {
3919
+ const videoRef = React9__namespace.useRef(null);
3920
+ const hlsRef = React9__namespace.useRef(null);
3921
+ const [state, setState] = React9__namespace.useState("idle");
3922
+ const [qualities, setQualities] = React9__namespace.useState([]);
3923
+ const [activeLevel, setActiveLevel] = React9__namespace.useState(-1);
3924
+ const [autoplayState, setAutoplayState] = React9__namespace.useState("none");
3925
+ const [error, setError] = React9__namespace.useState(null);
3926
+ const [reloadKey, setReloadKey] = React9__namespace.useState(0);
3927
+ const [sealed, setSealed] = React9__namespace.useState(false);
3928
+ const modeRef = React9__namespace.useRef(mode);
3929
+ const lastSrcRef = React9__namespace.useRef(src);
3930
+ const sealedRef = React9__namespace.useRef(false);
3931
+ const sawLiveRef = React9__namespace.useRef(false);
3932
+ const sealedDuringSessionRef = React9__namespace.useRef(false);
3933
+ React9__namespace.useEffect(() => {
3934
+ modeRef.current = mode;
3935
+ }, [mode]);
3936
+ const onErrorRef = React9__namespace.useRef(onError);
3937
+ const onPlayingChangeRef = React9__namespace.useRef(onPlayingChange);
3938
+ const onRebufferRef = React9__namespace.useRef(onRebuffer);
3939
+ const onQualityChangeRef = React9__namespace.useRef(onQualityChange);
3940
+ React9__namespace.useEffect(() => {
3941
+ onErrorRef.current = onError;
3942
+ onPlayingChangeRef.current = onPlayingChange;
3943
+ onRebufferRef.current = onRebuffer;
3944
+ onQualityChangeRef.current = onQualityChange;
3945
+ }, [onError, onPlayingChange, onRebuffer, onQualityChange]);
3946
+ const retry = React9__namespace.useCallback(() => {
3947
+ setError(null);
3948
+ setState("loading");
3949
+ setAutoplayState("none");
3950
+ setReloadKey((k) => k + 1);
3951
+ }, []);
3952
+ React9__namespace.useEffect(() => {
3953
+ const media = videoRef.current;
3954
+ if (!media || !src || !active) {
3955
+ setState("idle");
3956
+ return;
4019
3957
  }
4020
- let breakAt = end;
4021
- if (end < tokens.length) {
4022
- for (let cursor = end - 1; cursor > index; cursor -= 1) {
4023
- if (!CAPTION_BREAK_PUNCT.test(tokens[cursor])) continue;
4024
- const firstLen = tokens.slice(index, cursor + 1).join(" ").length;
4025
- if (firstLen >= Math.min(CAPTION_MIN_PUNCT_LINE, maxCharsPerLine)) {
4026
- breakAt = cursor + 1;
4027
- }
4028
- break;
3958
+ let cancelled = false;
3959
+ let retryTimer = null;
3960
+ let manifestParsed = false;
3961
+ let mediaErrorRetries = 0;
3962
+ let playbackSource = "hls";
3963
+ const teardown = [];
3964
+ const liveSrc = isLivePlaylistSrc(src);
3965
+ if (lastSrcRef.current !== src) {
3966
+ lastSrcRef.current = src;
3967
+ sealedRef.current = false;
3968
+ sawLiveRef.current = false;
3969
+ sealedDuringSessionRef.current = false;
3970
+ setSealed(false);
3971
+ }
3972
+ applyMute(media);
3973
+ setState("loading");
3974
+ setError(null);
3975
+ setAutoplayState("none");
3976
+ setQualities([]);
3977
+ setActiveLevel(-1);
3978
+ function baseContext() {
3979
+ return {
3980
+ mode: modeRef.current,
3981
+ src,
3982
+ manifestParsed,
3983
+ retryCount: mediaErrorRetries,
3984
+ source: playbackSource
3985
+ };
3986
+ }
3987
+ function shouldAutoplay() {
3988
+ if (sealedDuringSessionRef.current) return false;
3989
+ return modeRef.current === "live" || autoPlay;
3990
+ }
3991
+ function hlsConfig() {
3992
+ if (liveSrc) {
3993
+ return sealedRef.current ? createVodHlsConfig() : createLiveHlsConfig();
4029
3994
  }
3995
+ return modeRef.current === "live" ? createLiveHlsConfig() : createVodHlsConfig();
4030
3996
  }
4031
- lines.push(tokens.slice(index, breakAt).join(" "));
4032
- index = breakAt;
4033
- }
4034
- return lines;
4035
- }
4036
- function balanceCaptionLines(lines, maxCharsPerLine) {
4037
- const next = [...lines];
4038
- for (let index = 0; index + 1 < next.length; index += CAPTION_MAX_LINES) {
4039
- const left = next[index].split(" ");
4040
- const right = next[index + 1].split(" ");
4041
- if (right.length !== 1 || left.length < 3) continue;
4042
- const moved = left[left.length - 1];
4043
- const newRight = `${moved} ${right[0]}`;
4044
- if (newRight.length > maxCharsPerLine) continue;
4045
- next[index] = left.slice(0, -1).join(" ");
4046
- next[index + 1] = newRight;
4047
- }
4048
- return next;
4049
- }
4050
- function splitCaptionScreens(text, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
4051
- const trimmed = text.trim().replace(/\s+/g, " ");
4052
- if (!trimmed) return [];
4053
- const lines = balanceCaptionLines(
4054
- wrapCaptionLines(trimmed, maxCharsPerLine),
4055
- maxCharsPerLine
4056
- );
4057
- const screens = [];
4058
- for (let index = 0; index < lines.length; index += CAPTION_MAX_LINES) {
4059
- screens.push(lines.slice(index, index + CAPTION_MAX_LINES).join("\n"));
4060
- }
4061
- return screens;
4062
- }
4063
- function captionDwellMs(text, backlog = 0) {
4064
- const chars = text.replace(/\s+/g, " ").trim().length;
4065
- const raw = chars / CAPTION_CHARS_PER_SECOND * 1e3;
4066
- const max = backlog > 0 ? CAPTION_RUSH_DWELL_MS : CAPTION_MAX_DWELL_MS;
4067
- return Math.min(max, Math.max(CAPTION_MIN_DWELL_MS, raw));
4068
- }
4069
- function advanceLiveCaptionPlayout(state, cues, now, lagMs, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
4070
- let screen = state.screen;
4071
- let hideAt = state.hideAt;
4072
- let cursor = state.cursor;
4073
- let queue = state.queue.slice();
4074
- if (lagMs != null && Number.isFinite(lagMs) && lagMs >= 0) {
4075
- const threshold = lagMs + LIVE_CUE_EXTRA_LAG_MS;
4076
- const incoming = cues.filter(
4077
- (cue) => Boolean(cue.text.trim()) && Number.isFinite(cue.receivedAt) && cue.receivedAt > cursor && now - cue.receivedAt >= threshold
4078
- ).sort((left, right) => left.receivedAt - right.receivedAt);
4079
- for (const cue of incoming) {
4080
- for (const text of splitCaptionScreens(cue.text, maxCharsPerLine)) {
4081
- queue.push(captionScreenRow(text, cue.speaker));
3997
+ function clearRetryTimer() {
3998
+ if (retryTimer !== null) {
3999
+ clearTimeout(retryTimer);
4000
+ retryTimer = null;
4082
4001
  }
4083
- cursor = cue.receivedAt;
4084
4002
  }
4085
- if (queue.length > CAPTION_BACKLOG_DROP) {
4086
- queue = queue.slice(queue.length - CAPTION_BACKLOG_DROP);
4003
+ function destroyHls() {
4004
+ hlsRef.current?.destroy();
4005
+ hlsRef.current = null;
4087
4006
  }
4088
- }
4089
- if (now >= hideAt) {
4090
- const next = queue.shift();
4091
- if (next) {
4092
- screen = next;
4093
- hideAt = now + captionDwellMs(next.text, queue.length);
4094
- } else {
4095
- screen = null;
4007
+ function reportFatal(input) {
4008
+ const described = describePlaybackError(input);
4009
+ onErrorRef.current?.(described);
4010
+ setError(described);
4011
+ setState("error");
4096
4012
  }
4097
- }
4098
- return { screen, hideAt, cursor, queue };
4099
- }
4100
- function cueEndWithGapFill(cues, index) {
4101
- const cue = cues[index];
4102
- if (!cue) return 0;
4103
- const next = cues[index + 1];
4104
- if (!next || !Number.isFinite(next.start)) return cue.end;
4105
- const gapMs = (next.start - cue.end) * 1e3;
4106
- if (gapMs > 0 && gapMs < CAPTION_GAP_FILL_MS) return next.start;
4107
- return cue.end;
4108
- }
4109
- function captionScreenAtTime(cues, time, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
4110
- if (!Number.isFinite(time)) return null;
4111
- const ordered = cues.filter(
4112
- (cue) => Boolean(cue.text.trim()) && Number.isFinite(cue.start) && Number.isFinite(cue.end)
4113
- ).sort((left, right) => left.start - right.start);
4114
- for (let index = 0; index < ordered.length; index += 1) {
4115
- const cue = ordered[index];
4116
- const end = cueEndWithGapFill(ordered, index);
4117
- if (time < cue.start || time >= end) continue;
4118
- const screens = splitCaptionScreens(cue.text, maxCharsPerLine);
4119
- if (screens.length === 0) return null;
4120
- const weights = screens.map(
4121
- (text) => Math.max(1, text.replace(/\s+/g, "").length)
4122
- );
4123
- const total = weights.reduce((sum, weight) => sum + weight, 0);
4124
- const duration = Math.max(end - cue.start, 0);
4125
- let cursor = cue.start;
4126
- for (let screenIndex = 0; screenIndex < screens.length; screenIndex += 1) {
4127
- const isLast = screenIndex === screens.length - 1;
4128
- const slice = isLast ? end - cursor : duration * (weights[screenIndex] / total);
4129
- const sliceEnd = cursor + slice;
4130
- if (time >= cursor && time < sliceEnd) {
4131
- return captionScreenRow(screens[screenIndex]);
4132
- }
4133
- cursor = sliceEnd;
4013
+ function applyMute(el) {
4014
+ el.muted = muted;
4134
4015
  }
4135
- return captionScreenRow(screens[screens.length - 1]);
4136
- }
4137
- return null;
4138
- }
4139
- var LIVE_OVERLAP_MIN_WORDS = 4;
4140
- function normalizeLiveCaptionText(text) {
4141
- return text.trim().replace(/\s+/g, " ").toLowerCase();
4142
- }
4143
- function lastSubseqIndex(haystack, needle) {
4144
- if (needle.length === 0 || needle.length > haystack.length) return -1;
4145
- let found = -1;
4146
- for (let index = 0; index <= haystack.length - needle.length; index += 1) {
4147
- let match = true;
4148
- for (let offset = 0; offset < needle.length; offset += 1) {
4149
- if (haystack[index + offset] !== needle[offset]) {
4150
- match = false;
4151
- break;
4152
- }
4016
+ function preserveMute(el, fn) {
4017
+ const wasMuted = el.muted;
4018
+ fn();
4019
+ el.muted = wasMuted;
4153
4020
  }
4154
- if (match) found = index;
4155
- }
4156
- return found;
4157
- }
4158
- function remainderAfterOverlap(previous, next) {
4159
- const prevWords = normalizeLiveCaptionText(previous).split(" ").filter(Boolean);
4160
- const nextWords = next.trim().replace(/\s+/g, " ").split(" ").filter(Boolean);
4161
- const nextNorm = nextWords.map((word) => word.toLowerCase());
4162
- const maxN = Math.min(prevWords.length, nextNorm.length);
4163
- for (let size = maxN; size >= LIVE_OVERLAP_MIN_WORDS; size -= 1) {
4164
- for (let start = prevWords.length - size; start >= 0; start -= 1) {
4165
- const gram = prevWords.slice(start, start + size);
4166
- const index = lastSubseqIndex(nextNorm, gram);
4167
- if (index !== -1) {
4168
- return nextWords.slice(index + size).join(" ");
4169
- }
4021
+ function attemptAutoplay(el) {
4022
+ applyMute(el);
4023
+ void el.play().then(
4024
+ () => {
4025
+ applyMute(el);
4026
+ setAutoplayState("playing");
4027
+ },
4028
+ () => {
4029
+ el.muted = true;
4030
+ void el.play().then(
4031
+ () => setAutoplayState(muted ? "playing" : "muted"),
4032
+ () => {
4033
+ if (el.paused) {
4034
+ setAutoplayState("blocked");
4035
+ return;
4036
+ }
4037
+ setAutoplayState(el.muted && !muted ? "muted" : "playing");
4038
+ }
4039
+ );
4040
+ }
4041
+ );
4170
4042
  }
4171
- }
4172
- return null;
4173
- }
4174
- function liveCaptionRow(text, receivedAt, speaker) {
4175
- return speaker == null ? { text, receivedAt } : { text, receivedAt, speaker };
4176
- }
4177
- function coalesceLiveCaptionCues(cues) {
4178
- const out = [];
4179
- for (const cue of cues) {
4180
- const text = cue.text.trim();
4181
- if (!text) continue;
4182
- const last = out[out.length - 1];
4183
- if (!last) {
4184
- out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
4185
- continue;
4043
+ function scheduleRetry(retryFn) {
4044
+ clearRetryTimer();
4045
+ if (cancelled) return;
4046
+ setState("waiting");
4047
+ retryTimer = setTimeout(() => {
4048
+ retryTimer = null;
4049
+ if (!cancelled) retryFn();
4050
+ }, RETRY_INTERVAL_MS);
4186
4051
  }
4187
- if (last.speaker !== cue.speaker && (last.speaker != null || cue.speaker != null)) {
4188
- out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
4189
- continue;
4052
+ function startDriftWatchdog(el) {
4053
+ if (typeof el.requestVideoFrameCallback !== "function") return;
4054
+ let consecutiveLagSamples = 0;
4055
+ let lastResyncAt = 0;
4056
+ let handle = null;
4057
+ const tick = (_now, metadata) => {
4058
+ if (cancelled) return;
4059
+ handle = el.requestVideoFrameCallback(tick);
4060
+ if (el.paused || el.ended) {
4061
+ consecutiveLagSamples = 0;
4062
+ return;
4063
+ }
4064
+ const lag = el.currentTime - metadata.mediaTime;
4065
+ if (!(lag > DRIFT_THRESHOLD_S)) {
4066
+ consecutiveLagSamples = 0;
4067
+ return;
4068
+ }
4069
+ consecutiveLagSamples += 1;
4070
+ if (consecutiveLagSamples < DRIFT_CONSECUTIVE_SAMPLES) return;
4071
+ const nowMs = performance.now();
4072
+ if (nowMs - lastResyncAt < RESYNC_COOLDOWN_MS) return;
4073
+ lastResyncAt = nowMs;
4074
+ consecutiveLagSamples = 0;
4075
+ if (modeRef.current === "live" && el.seekable.length > 0) {
4076
+ const edge = el.seekable.end(el.seekable.length - 1);
4077
+ if (edge - el.currentTime > LIVE_EDGE_RESYNC_THRESHOLD_S) {
4078
+ el.currentTime = edge;
4079
+ } else {
4080
+ el.currentTime = el.currentTime + 1e-3;
4081
+ }
4082
+ } else {
4083
+ el.currentTime = el.currentTime + 1e-3;
4084
+ }
4085
+ onErrorRef.current?.(
4086
+ describeAvResync({
4087
+ lagSeconds: lag,
4088
+ context: baseContext()
4089
+ })
4090
+ );
4091
+ };
4092
+ handle = el.requestVideoFrameCallback(tick);
4093
+ teardown.push(() => {
4094
+ if (handle != null && typeof el.cancelVideoFrameCallback === "function") {
4095
+ el.cancelVideoFrameCallback(handle);
4096
+ }
4097
+ });
4190
4098
  }
4191
- const lastNorm = normalizeLiveCaptionText(last.text);
4192
- const nextNorm = normalizeLiveCaptionText(text);
4193
- if (lastNorm === nextNorm) continue;
4194
- if (nextNorm.startsWith(lastNorm) || lastNorm.startsWith(nextNorm)) {
4195
- out[out.length - 1] = liveCaptionRow(
4196
- nextNorm.length >= lastNorm.length ? text : last.text,
4197
- cue.receivedAt,
4198
- cue.speaker ?? last.speaker
4099
+ let hasPlayed = false;
4100
+ let waitingSince = null;
4101
+ function onPlaying() {
4102
+ manifestParsed = true;
4103
+ mediaErrorRetries = 0;
4104
+ clearRetryTimer();
4105
+ setState("ready");
4106
+ setAutoplayState(
4107
+ (prev) => prev === "blocked" || prev === "none" ? "playing" : prev
4199
4108
  );
4200
- continue;
4109
+ if (waitingSince != null) {
4110
+ const seconds = (performance.now() - waitingSince) / 1e3;
4111
+ waitingSince = null;
4112
+ if (seconds > 0) onRebufferRef.current?.(seconds);
4113
+ }
4114
+ hasPlayed = true;
4115
+ onPlayingChangeRef.current?.(true);
4201
4116
  }
4202
- const remainder = remainderAfterOverlap(last.text, text);
4203
- if (remainder !== null) {
4204
- if (!remainder) continue;
4205
- out.push(liveCaptionRow(remainder, cue.receivedAt, cue.speaker));
4206
- continue;
4117
+ function onPaused() {
4118
+ onPlayingChangeRef.current?.(false);
4207
4119
  }
4208
- out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
4209
- }
4210
- return out;
4211
- }
4212
- function mergeLiveCaptionCues(existing, incoming, cap = LIVE_STACK_MAX_CUES) {
4213
- const map = /* @__PURE__ */ new Map();
4214
- for (const cue of existing) {
4215
- if (Number.isFinite(cue.receivedAt)) map.set(cue.receivedAt, cue);
4216
- }
4217
- for (const cue of incoming) {
4218
- if (Number.isFinite(cue.receivedAt)) map.set(cue.receivedAt, cue);
4219
- }
4220
- return [...map.values()].sort((left, right) => left.receivedAt - right.receivedAt).slice(-Math.max(1, cap));
4221
- }
4222
- async function loadCaptionVtt(url) {
4223
- try {
4224
- const response = await fetch(url, { cache: "no-store" });
4225
- if (!response.ok) return [];
4226
- return parseCaptionVtt(await response.text());
4227
- } catch {
4228
- return [];
4229
- }
4230
- }
4231
- async function loadLiveCaptions(url) {
4232
- try {
4233
- const response = await fetch(url, {
4234
- cache: "no-store",
4235
- headers: { Accept: "application/json" }
4120
+ function onWaiting() {
4121
+ if (!hasPlayed || waitingSince != null) return;
4122
+ waitingSince = performance.now();
4123
+ }
4124
+ media.addEventListener("playing", onPlaying);
4125
+ media.addEventListener("pause", onPaused);
4126
+ media.addEventListener("ended", onPaused);
4127
+ media.addEventListener("waiting", onWaiting);
4128
+ teardown.push(() => {
4129
+ media.removeEventListener("playing", onPlaying);
4130
+ media.removeEventListener("pause", onPaused);
4131
+ media.removeEventListener("ended", onPaused);
4132
+ media.removeEventListener("waiting", onWaiting);
4236
4133
  });
4237
- if (!response.ok) return { ok: false, cues: [] };
4238
- const body = await response.json();
4239
- if (!body || typeof body !== "object" || !("cues" in body)) {
4240
- return { ok: false, cues: [] };
4134
+ startDriftWatchdog(media);
4135
+ function initNative() {
4136
+ playbackSource = "native";
4137
+ manifestParsed = false;
4138
+ media.removeAttribute("src");
4139
+ media.load();
4140
+ media.src = src;
4141
+ applyMute(media);
4142
+ const onReady = () => {
4143
+ manifestParsed = true;
4144
+ clearRetryTimer();
4145
+ setState("ready");
4146
+ if (shouldAutoplay()) attemptAutoplay(media);
4147
+ };
4148
+ const onErr = () => {
4149
+ if (manifestParsed) {
4150
+ reportFatal({
4151
+ source: "native",
4152
+ mediaError: media.error,
4153
+ context: baseContext()
4154
+ });
4155
+ return;
4156
+ }
4157
+ onErrorRef.current?.(
4158
+ describePlaybackError({
4159
+ source: "native",
4160
+ mediaError: media.error,
4161
+ context: baseContext()
4162
+ })
4163
+ );
4164
+ scheduleRetry(() => {
4165
+ media.src = src;
4166
+ media.load();
4167
+ });
4168
+ };
4169
+ media.addEventListener("loadedmetadata", onReady);
4170
+ media.addEventListener("error", onErr);
4171
+ teardown.push(() => {
4172
+ media.removeEventListener("loadedmetadata", onReady);
4173
+ media.removeEventListener("error", onErr);
4174
+ });
4241
4175
  }
4242
- const rows = body.cues;
4243
- if (!Array.isArray(rows)) return { ok: false, cues: [] };
4244
- const cues = [];
4245
- for (const row of rows) {
4246
- if (!row || typeof row !== "object") continue;
4247
- const record = row;
4248
- if (typeof record.text !== "string" || !record.text.trim()) continue;
4249
- if (typeof record.receivedAt !== "number" || !Number.isFinite(record.receivedAt)) {
4250
- continue;
4176
+ function initHlsJs(Hls) {
4177
+ playbackSource = "hls";
4178
+ destroyHls();
4179
+ manifestParsed = false;
4180
+ const config = hlsConfig();
4181
+ const hls = new Hls(config);
4182
+ hlsRef.current = hls;
4183
+ hls.loadSource(src);
4184
+ hls.attachMedia(media);
4185
+ applyMute(media);
4186
+ hls.on(Hls.Events.LEVEL_LOADED, (_e, data) => {
4187
+ if (!liveSrc || cancelled) return;
4188
+ const details = data.details;
4189
+ if (!details) return;
4190
+ if (details.live) {
4191
+ sawLiveRef.current = true;
4192
+ return;
4193
+ }
4194
+ if (sealedRef.current) return;
4195
+ sealedRef.current = true;
4196
+ setSealed(true);
4197
+ if (sawLiveRef.current) {
4198
+ sealedDuringSessionRef.current = true;
4199
+ }
4200
+ setReloadKey((k) => k + 1);
4201
+ });
4202
+ hls.on(Hls.Events.MANIFEST_PARSED, (_e, data) => {
4203
+ manifestParsed = true;
4204
+ clearRetryTimer();
4205
+ setQualities(
4206
+ data.levels.map((l, index) => ({ index, height: l.height }))
4207
+ );
4208
+ setState("ready");
4209
+ if (shouldAutoplay()) attemptAutoplay(media);
4210
+ });
4211
+ hls.on(Hls.Events.LEVEL_SWITCHED, (_e, data) => {
4212
+ if (hls.autoLevelEnabled) setActiveLevel(-1);
4213
+ else setActiveLevel(data.level);
4214
+ const height = hls.levels?.[data.level]?.height;
4215
+ onQualityChangeRef.current?.(
4216
+ typeof height === "number" && height > 0 ? `${height}p` : "auto"
4217
+ );
4218
+ });
4219
+ hls.on(Hls.Events.ERROR, (_e, data) => {
4220
+ onErrorRef.current?.(
4221
+ describePlaybackError({
4222
+ source: "hls",
4223
+ type: data.type,
4224
+ details: data.details,
4225
+ fatal: data.fatal,
4226
+ url: data.url,
4227
+ response: data.response,
4228
+ reason: data.reason,
4229
+ error: data.error,
4230
+ context: baseContext()
4231
+ })
4232
+ );
4233
+ if (!data.fatal) return;
4234
+ if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
4235
+ if (!manifestParsed) {
4236
+ scheduleRetry(() => initHlsJs(Hls));
4237
+ return;
4238
+ }
4239
+ hls.startLoad();
4240
+ return;
4241
+ }
4242
+ mediaErrorRetries += 1;
4243
+ if (mediaErrorRetries === 1) {
4244
+ preserveMute(media, () => hls.recoverMediaError());
4245
+ return;
4246
+ }
4247
+ if (mediaErrorRetries === 2) {
4248
+ preserveMute(media, () => {
4249
+ hls.swapAudioCodec();
4250
+ hls.recoverMediaError();
4251
+ });
4252
+ return;
4253
+ }
4254
+ if (mediaErrorRetries < MAX_MEDIA_ERROR_RETRIES) {
4255
+ scheduleRetry(() => initHlsJs(Hls));
4256
+ return;
4257
+ }
4258
+ reportFatal({
4259
+ source: "hls",
4260
+ type: data.type,
4261
+ details: data.details,
4262
+ fatal: true,
4263
+ url: data.url,
4264
+ response: data.response,
4265
+ reason: data.reason,
4266
+ error: data.error,
4267
+ context: baseContext()
4268
+ });
4269
+ });
4270
+ }
4271
+ async function setup() {
4272
+ let Hls = null;
4273
+ try {
4274
+ Hls = (await import('hls.js')).default;
4275
+ } catch {
4276
+ Hls = null;
4251
4277
  }
4252
- const parsed = {
4253
- text: record.text.trim(),
4254
- receivedAt: record.receivedAt
4255
- };
4256
- if (typeof record.speaker === "number" && Number.isFinite(record.speaker)) {
4257
- parsed.speaker = record.speaker;
4278
+ if (cancelled) return;
4279
+ if (Hls && Hls.isSupported()) {
4280
+ initHlsJs(Hls);
4281
+ } else if (media.canPlayType("application/vnd.apple.mpegurl")) {
4282
+ initNative();
4283
+ } else {
4284
+ playbackSource = "unsupported";
4285
+ reportFatal({
4286
+ source: "unsupported",
4287
+ context: baseContext()
4288
+ });
4258
4289
  }
4259
- cues.push(parsed);
4260
4290
  }
4261
- return { ok: true, cues };
4262
- } catch {
4263
- return { ok: false, cues: [] };
4264
- }
4291
+ void setup();
4292
+ return () => {
4293
+ cancelled = true;
4294
+ clearRetryTimer();
4295
+ for (const fn of teardown) fn();
4296
+ destroyHls();
4297
+ };
4298
+ }, [src, active, autoPlay, muted, reloadKey]);
4299
+ const setLevel = React9__namespace.useCallback((index) => {
4300
+ const hls = hlsRef.current;
4301
+ if (!hls) return;
4302
+ hls.nextLevel = index;
4303
+ setActiveLevel(index);
4304
+ }, []);
4305
+ return {
4306
+ videoRef,
4307
+ state,
4308
+ qualities,
4309
+ activeLevel,
4310
+ setLevel,
4311
+ autoplayState,
4312
+ error,
4313
+ retry,
4314
+ effectiveMode: effectivePlaybackMode(src, mode, sealed)
4315
+ };
4265
4316
  }
4266
4317
 
4267
4318
  // src/components/video/fullscreen.ts
@@ -4511,7 +4562,8 @@ function VideoPlayer({
4511
4562
  setLevel,
4512
4563
  autoplayState,
4513
4564
  error,
4514
- retry
4565
+ retry,
4566
+ effectiveMode
4515
4567
  } = useHlsPlayback({
4516
4568
  src,
4517
4569
  mode,
@@ -4596,11 +4648,15 @@ function VideoPlayer({
4596
4648
  lastProgressAtRef.current = now;
4597
4649
  progress(
4598
4650
  video.currentTime,
4599
- finitePlaybackDuration(video.duration, video.seekable, mode)
4651
+ finitePlaybackDuration(
4652
+ video.duration,
4653
+ video.seekable,
4654
+ effectiveMode
4655
+ )
4600
4656
  );
4601
4657
  }
4602
4658
  }
4603
- if (mode === "live" && video.seekable.length > 0) {
4659
+ if (effectiveMode === "live" && video.seekable.length > 0) {
4604
4660
  const edge = video.seekable.end(video.seekable.length - 1);
4605
4661
  const lagSeconds = edge - video.currentTime;
4606
4662
  setBehindLive(lagSeconds > LIVE_EDGE_THRESHOLD_S);
@@ -4609,7 +4665,9 @@ function VideoPlayer({
4609
4665
  }
4610
4666
  }
4611
4667
  };
4612
- const onDuration = () => setDuration(finitePlaybackDuration(video.duration, video.seekable, mode));
4668
+ const onDuration = () => setDuration(
4669
+ finitePlaybackDuration(video.duration, video.seekable, effectiveMode)
4670
+ );
4613
4671
  const onVolume = () => {
4614
4672
  setIsMuted(video.muted);
4615
4673
  setVolume(video.volume);
@@ -4633,7 +4691,7 @@ function VideoPlayer({
4633
4691
  video.removeEventListener("ratechange", onRate);
4634
4692
  video.removeEventListener("playing", onPlaying);
4635
4693
  };
4636
- }, [videoRef, active, mode, liveCaptionsBaseUrl]);
4694
+ }, [videoRef, active, effectiveMode, liveCaptionsBaseUrl]);
4637
4695
  React9__namespace.useLayoutEffect(() => {
4638
4696
  const video = videoRef.current;
4639
4697
  if (video) video.muted = isMuted;
@@ -4940,6 +4998,18 @@ function VideoPlayer({
4940
4998
  setLevel(index);
4941
4999
  setOpenMenu(null);
4942
5000
  }
5001
+ function chooseCaption(locale) {
5002
+ setCaptionLocale(locale);
5003
+ setOpenMenu(null);
5004
+ }
5005
+ function toggleControls() {
5006
+ setOpenMenu(null);
5007
+ setControlsVisible((current) => {
5008
+ const next = !current;
5009
+ if (next) scheduleHide();
5010
+ return next;
5011
+ });
5012
+ }
4943
5013
  function handleKeyDown(e) {
4944
5014
  if (!active) return;
4945
5015
  switch (e.key) {
@@ -4961,13 +5031,13 @@ function VideoPlayer({
4961
5031
  }
4962
5032
  break;
4963
5033
  case "ArrowLeft":
4964
- if (mode === "vod") {
5034
+ if (effectiveMode === "vod") {
4965
5035
  e.preventDefault();
4966
5036
  seekBy(-SEEK_STEP_S);
4967
5037
  }
4968
5038
  break;
4969
5039
  case "ArrowRight":
4970
- if (mode === "vod") {
5040
+ if (effectiveMode === "vod") {
4971
5041
  e.preventDefault();
4972
5042
  seekBy(SEEK_STEP_S);
4973
5043
  }
@@ -5005,7 +5075,7 @@ function VideoPlayer({
5005
5075
  }
5006
5076
  const VolumeIcon = isMuted || volume === 0 ? lucideReact.VolumeX : volume < 0.5 ? lucideReact.Volume1 : lucideReact.Volume2;
5007
5077
  const showSpinner = active && (state === "loading" || state === "waiting");
5008
- const showControls = active && state === "ready" && (controlsVisible || !isPlaying);
5078
+ const showControls = active && state === "ready" && controlsVisible;
5009
5079
  const showPoster = !active && !!poster;
5010
5080
  const currentLevelLabel = activeLevel < 0 ? t.auto : `${qualities.find((q) => q.index === activeLevel)?.height ?? ""}p`;
5011
5081
  const showQuality = showQualitySelector && qualities.length > 1;
@@ -5014,7 +5084,7 @@ function VideoPlayer({
5014
5084
  {
5015
5085
  ref: containerRef,
5016
5086
  "data-slot": "video-player",
5017
- "data-mode": mode,
5087
+ "data-mode": effectiveMode,
5018
5088
  "data-fit": fit,
5019
5089
  "data-css-fullscreen": cssFullscreen ? "" : void 0,
5020
5090
  className: cn(
@@ -5040,7 +5110,7 @@ function VideoPlayer({
5040
5110
  playsInline: true,
5041
5111
  muted: isMuted,
5042
5112
  className: "livo-video-player-media h-full w-full bg-black object-contain",
5043
- onClick: active ? togglePlay : void 0,
5113
+ onClick: active ? toggleControls : void 0,
5044
5114
  poster,
5045
5115
  children: !liveCaptionsBaseUrl ? CAPTION_LOCALES.map((locale) => {
5046
5116
  const url = captionsVttUrlFromPlayback(src, locale);
@@ -5115,7 +5185,7 @@ function VideoPlayer({
5115
5185
  ]
5116
5186
  }
5117
5187
  ),
5118
- mode === "live" && active && state === "ready" && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "absolute top-3 left-3 flex items-center gap-2", children: [
5188
+ effectiveMode === "live" && active && state === "ready" && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "absolute top-3 left-3 flex items-center gap-2", children: [
5119
5189
  /* @__PURE__ */ jsxRuntime.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: [
5120
5190
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "size-1.5 animate-pulse rounded-full bg-white" }),
5121
5191
  t.live
@@ -5132,7 +5202,7 @@ function VideoPlayer({
5132
5202
  ),
5133
5203
  "data-slot": "video-controls",
5134
5204
  children: [
5135
- mode === "vod" && /* @__PURE__ */ jsxRuntime.jsx(
5205
+ effectiveMode === "vod" && /* @__PURE__ */ jsxRuntime.jsx(
5136
5206
  SeekBar,
5137
5207
  {
5138
5208
  src,
@@ -5173,11 +5243,11 @@ function VideoPlayer({
5173
5243
  }
5174
5244
  ) })
5175
5245
  ] }),
5176
- mode === "vod" && /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "ml-1 shrink-0 text-xs tabular-nums", children: [
5246
+ effectiveMode === "vod" && /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "ml-1 shrink-0 text-xs tabular-nums", children: [
5177
5247
  formatTime(currentTime),
5178
5248
  !compactChrome && ` / ${formatTime(duration)}`
5179
5249
  ] }),
5180
- mode === "live" && behindLive && /* @__PURE__ */ jsxRuntime.jsxs(
5250
+ effectiveMode === "live" && behindLive && /* @__PURE__ */ jsxRuntime.jsxs(
5181
5251
  "button",
5182
5252
  {
5183
5253
  type: "button",
@@ -5190,7 +5260,7 @@ function VideoPlayer({
5190
5260
  }
5191
5261
  ),
5192
5262
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "ml-auto flex shrink-0 items-center gap-1", children: [
5193
- !compactChrome && mode === "vod" && typeof stats?.views === "number" && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "mr-1 text-xs", children: t.formatViews ? t.formatViews(stats.views) : `${stats.views} views` }),
5263
+ !compactChrome && effectiveMode === "vod" && typeof stats?.views === "number" && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "mr-1 text-xs", children: t.formatViews ? t.formatViews(stats.views) : `${stats.views} views` }),
5194
5264
  /* @__PURE__ */ jsxRuntime.jsxs(
5195
5265
  MenuControl,
5196
5266
  {
@@ -5203,7 +5273,7 @@ function VideoPlayer({
5203
5273
  MenuItem,
5204
5274
  {
5205
5275
  selected: captionLocale === "off",
5206
- onSelect: () => setCaptionLocale("off"),
5276
+ onSelect: () => chooseCaption("off"),
5207
5277
  children: t.captionsOff
5208
5278
  }
5209
5279
  ),
@@ -5211,7 +5281,7 @@ function VideoPlayer({
5211
5281
  MenuItem,
5212
5282
  {
5213
5283
  selected: captionLocale === locale,
5214
- onSelect: () => setCaptionLocale(locale),
5284
+ onSelect: () => chooseCaption(locale),
5215
5285
  children: captionLocaleLabel(locale, t)
5216
5286
  },
5217
5287
  locale
@@ -5219,7 +5289,7 @@ function VideoPlayer({
5219
5289
  ]
5220
5290
  }
5221
5291
  ),
5222
- !compactChrome && mode === "vod" && /* @__PURE__ */ jsxRuntime.jsx(
5292
+ !compactChrome && effectiveMode === "vod" && /* @__PURE__ */ jsxRuntime.jsx(
5223
5293
  MenuControl,
5224
5294
  {
5225
5295
  label: t.speed,
@@ -5349,7 +5419,7 @@ function VideoPlayer({
5349
5419
  q.index
5350
5420
  ))
5351
5421
  ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
5352
- mode === "vod" && /* @__PURE__ */ jsxRuntime.jsx(
5422
+ effectiveMode === "vod" && /* @__PURE__ */ jsxRuntime.jsx(
5353
5423
  MenuNavRow,
5354
5424
  {
5355
5425
  icon: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Gauge, { className: "size-4" }),
@@ -5367,7 +5437,7 @@ function VideoPlayer({
5367
5437
  onSelect: () => setMorePane("quality")
5368
5438
  }
5369
5439
  ),
5370
- (mode === "vod" || showQuality) && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "my-1 h-px bg-primary/15" }),
5440
+ (effectiveMode === "vod" || showQuality) && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "my-1 h-px bg-primary/15" }),
5371
5441
  /* @__PURE__ */ jsxRuntime.jsx(
5372
5442
  MenuAction,
5373
5443
  {