@livo-tv/blocks 1.25.1 → 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.cjs CHANGED
@@ -3391,853 +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
- }) {
3573
- const videoRef = React9__namespace.useRef(null);
3574
- const hlsRef = React9__namespace.useRef(null);
3575
- const [state, setState] = React9__namespace.useState("idle");
3576
- const [qualities, setQualities] = React9__namespace.useState([]);
3577
- const [activeLevel, setActiveLevel] = React9__namespace.useState(-1);
3578
- const [autoplayState, setAutoplayState] = React9__namespace.useState("none");
3579
- const [error, setError] = React9__namespace.useState(null);
3580
- const [reloadKey, setReloadKey] = React9__namespace.useState(0);
3581
- const onErrorRef = React9__namespace.useRef(onError);
3582
- const onPlayingChangeRef = React9__namespace.useRef(onPlayingChange);
3583
- React9__namespace.useEffect(() => {
3584
- onErrorRef.current = onError;
3585
- onPlayingChangeRef.current = onPlayingChange;
3586
- }, [onError, onPlayingChange]);
3587
- const retry = React9__namespace.useCallback(() => {
3588
- setError(null);
3589
- setState("loading");
3590
- setAutoplayState("none");
3591
- setReloadKey((k) => k + 1);
3592
- }, []);
3593
- React9__namespace.useEffect(() => {
3594
- const media = videoRef.current;
3595
- if (!media || !src || !active) {
3596
- setState("idle");
3597
- return;
3598
- }
3599
- let cancelled = false;
3600
- let retryTimer = null;
3601
- let manifestParsed = false;
3602
- let mediaErrorRetries = 0;
3603
- let playbackSource = "hls";
3604
- const teardown = [];
3605
- applyMute(media);
3606
- setState("loading");
3607
- setError(null);
3608
- setAutoplayState("none");
3609
- setQualities([]);
3610
- setActiveLevel(-1);
3611
- function baseContext() {
3612
- return {
3613
- mode,
3614
- src,
3615
- manifestParsed,
3616
- retryCount: mediaErrorRetries,
3617
- source: playbackSource
3618
- };
3619
- }
3620
- function clearRetryTimer() {
3621
- if (retryTimer !== null) {
3622
- clearTimeout(retryTimer);
3623
- 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(" ");
3624
3636
  }
3625
3637
  }
3626
- function destroyHls() {
3627
- hlsRef.current?.destroy();
3628
- hlsRef.current = null;
3629
- }
3630
- function reportFatal(input) {
3631
- const described = describePlaybackError(input);
3632
- onErrorRef.current?.(described);
3633
- setError(described);
3634
- setState("error");
3635
- }
3636
- function applyMute(el) {
3637
- 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;
3638
3653
  }
3639
- function preserveMute(el, fn) {
3640
- const wasMuted = el.muted;
3641
- fn();
3642
- 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;
3643
3657
  }
3644
- function attemptAutoplay(el) {
3645
- applyMute(el);
3646
- void el.play().then(
3647
- () => {
3648
- applyMute(el);
3649
- setAutoplayState("playing");
3650
- },
3651
- () => {
3652
- el.muted = true;
3653
- void el.play().then(
3654
- () => setAutoplayState(muted ? "playing" : "muted"),
3655
- () => {
3656
- if (el.paused) {
3657
- setAutoplayState("blocked");
3658
- return;
3659
- }
3660
- setAutoplayState(el.muted && !muted ? "muted" : "playing");
3661
- }
3662
- );
3663
- }
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
3664
3666
  );
3667
+ continue;
3665
3668
  }
3666
- function scheduleRetry(retryFn) {
3667
- clearRetryTimer();
3668
- if (cancelled) return;
3669
- setState("waiting");
3670
- retryTimer = setTimeout(() => {
3671
- retryTimer = null;
3672
- if (!cancelled) retryFn();
3673
- }, RETRY_INTERVAL_MS);
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;
3674
3674
  }
3675
- function startDriftWatchdog(el) {
3676
- if (typeof el.requestVideoFrameCallback !== "function") return;
3677
- let consecutiveLagSamples = 0;
3678
- let lastResyncAt = 0;
3679
- let handle = null;
3680
- const tick = (_now, metadata) => {
3681
- if (cancelled) return;
3682
- handle = el.requestVideoFrameCallback(tick);
3683
- if (el.paused || el.ended) {
3684
- consecutiveLagSamples = 0;
3685
- return;
3686
- }
3687
- const lag = el.currentTime - metadata.mediaTime;
3688
- if (!(lag > DRIFT_THRESHOLD_S)) {
3689
- consecutiveLagSamples = 0;
3690
- return;
3691
- }
3692
- consecutiveLagSamples += 1;
3693
- if (consecutiveLagSamples < DRIFT_CONSECUTIVE_SAMPLES) return;
3694
- const nowMs = performance.now();
3695
- if (nowMs - lastResyncAt < RESYNC_COOLDOWN_MS) return;
3696
- lastResyncAt = nowMs;
3697
- consecutiveLagSamples = 0;
3698
- if (mode === "live" && el.seekable.length > 0) {
3699
- const edge = el.seekable.end(el.seekable.length - 1);
3700
- if (edge - el.currentTime > LIVE_EDGE_RESYNC_THRESHOLD_S) {
3701
- el.currentTime = edge;
3702
- } else {
3703
- el.currentTime = el.currentTime + 1e-3;
3704
- }
3705
- } else {
3706
- el.currentTime = el.currentTime + 1e-3;
3707
- }
3708
- onErrorRef.current?.(
3709
- describeAvResync({
3710
- lagSeconds: lag,
3711
- context: baseContext()
3712
- })
3713
- );
3714
- };
3715
- handle = el.requestVideoFrameCallback(tick);
3716
- teardown.push(() => {
3717
- if (handle != null && typeof el.cancelVideoFrameCallback === "function") {
3718
- el.cancelVideoFrameCallback(handle);
3719
- }
3720
- });
3721
- }
3722
- function onPlaying() {
3723
- manifestParsed = true;
3724
- mediaErrorRetries = 0;
3725
- clearRetryTimer();
3726
- setState("ready");
3727
- setAutoplayState(
3728
- (prev) => prev === "blocked" || prev === "none" ? "playing" : prev
3729
- );
3730
- onPlayingChangeRef.current?.(true);
3731
- }
3732
- function onPaused() {
3733
- onPlayingChangeRef.current?.(false);
3734
- }
3735
- media.addEventListener("playing", onPlaying);
3736
- media.addEventListener("pause", onPaused);
3737
- media.addEventListener("ended", onPaused);
3738
- teardown.push(() => {
3739
- media.removeEventListener("playing", onPlaying);
3740
- media.removeEventListener("pause", onPaused);
3741
- media.removeEventListener("ended", onPaused);
3742
- });
3743
- startDriftWatchdog(media);
3744
- function initNative() {
3745
- playbackSource = "native";
3746
- manifestParsed = false;
3747
- media.removeAttribute("src");
3748
- media.load();
3749
- media.src = src;
3750
- applyMute(media);
3751
- const onReady = () => {
3752
- manifestParsed = true;
3753
- clearRetryTimer();
3754
- setState("ready");
3755
- if (mode === "live" || autoPlay) attemptAutoplay(media);
3756
- };
3757
- const onErr = () => {
3758
- if (manifestParsed) {
3759
- reportFatal({
3760
- source: "native",
3761
- mediaError: media.error,
3762
- context: baseContext()
3763
- });
3764
- return;
3765
- }
3766
- onErrorRef.current?.(
3767
- describePlaybackError({
3768
- source: "native",
3769
- mediaError: media.error,
3770
- context: baseContext()
3771
- })
3772
- );
3773
- scheduleRetry(() => {
3774
- media.src = src;
3775
- media.load();
3776
- });
3777
- };
3778
- media.addEventListener("loadedmetadata", onReady);
3779
- media.addEventListener("error", onErr);
3780
- teardown.push(() => {
3781
- media.removeEventListener("loadedmetadata", onReady);
3782
- media.removeEventListener("error", onErr);
3783
- });
3784
- }
3785
- function initHlsJs(Hls) {
3786
- playbackSource = "hls";
3787
- destroyHls();
3788
- manifestParsed = false;
3789
- const config = mode === "live" ? createLiveHlsConfig() : createVodHlsConfig();
3790
- const hls = new Hls(config);
3791
- hlsRef.current = hls;
3792
- hls.loadSource(src);
3793
- hls.attachMedia(media);
3794
- applyMute(media);
3795
- hls.on(Hls.Events.MANIFEST_PARSED, (_e, data) => {
3796
- manifestParsed = true;
3797
- clearRetryTimer();
3798
- setQualities(
3799
- data.levels.map((l, index) => ({ index, height: l.height }))
3800
- );
3801
- setState("ready");
3802
- if (mode === "live" || autoPlay) attemptAutoplay(media);
3803
- });
3804
- hls.on(Hls.Events.LEVEL_SWITCHED, (_e, data) => {
3805
- if (hls.autoLevelEnabled) setActiveLevel(-1);
3806
- else setActiveLevel(data.level);
3807
- });
3808
- hls.on(Hls.Events.ERROR, (_e, data) => {
3809
- onErrorRef.current?.(
3810
- describePlaybackError({
3811
- source: "hls",
3812
- type: data.type,
3813
- details: data.details,
3814
- fatal: data.fatal,
3815
- url: data.url,
3816
- response: data.response,
3817
- reason: data.reason,
3818
- error: data.error,
3819
- context: baseContext()
3820
- })
3821
- );
3822
- if (!data.fatal) return;
3823
- if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
3824
- if (!manifestParsed) {
3825
- scheduleRetry(() => initHlsJs(Hls));
3826
- return;
3827
- }
3828
- hls.startLoad();
3829
- return;
3830
- }
3831
- mediaErrorRetries += 1;
3832
- if (mediaErrorRetries === 1) {
3833
- preserveMute(media, () => hls.recoverMediaError());
3834
- return;
3835
- }
3836
- if (mediaErrorRetries === 2) {
3837
- preserveMute(media, () => {
3838
- hls.swapAudioCodec();
3839
- hls.recoverMediaError();
3840
- });
3841
- return;
3842
- }
3843
- if (mediaErrorRetries < MAX_MEDIA_ERROR_RETRIES) {
3844
- scheduleRetry(() => initHlsJs(Hls));
3845
- return;
3846
- }
3847
- reportFatal({
3848
- source: "hls",
3849
- type: data.type,
3850
- details: data.details,
3851
- fatal: true,
3852
- url: data.url,
3853
- response: data.response,
3854
- reason: data.reason,
3855
- error: data.error,
3856
- context: baseContext()
3857
- });
3858
- });
3859
- }
3860
- async function setup() {
3861
- let Hls = null;
3862
- try {
3863
- Hls = (await import('hls.js')).default;
3864
- } catch {
3865
- Hls = null;
3866
- }
3867
- if (cancelled) return;
3868
- if (Hls && Hls.isSupported()) {
3869
- initHlsJs(Hls);
3870
- } else if (media.canPlayType("application/vnd.apple.mpegurl")) {
3871
- initNative();
3872
- } else {
3873
- playbackSource = "unsupported";
3874
- reportFatal({
3875
- source: "unsupported",
3876
- context: baseContext()
3877
- });
3878
- }
3879
- }
3880
- void setup();
3881
- return () => {
3882
- cancelled = true;
3883
- clearRetryTimer();
3884
- for (const fn of teardown) fn();
3885
- destroyHls();
3886
- };
3887
- }, [src, mode, active, autoPlay, muted, reloadKey]);
3888
- const setLevel = React9__namespace.useCallback((index) => {
3889
- const hls = hlsRef.current;
3890
- if (!hls) return;
3891
- hls.nextLevel = index;
3892
- setActiveLevel(index);
3893
- }, []);
3894
- return {
3895
- videoRef,
3896
- state,
3897
- qualities,
3898
- activeLevel,
3899
- setLevel,
3900
- autoplayState,
3901
- error,
3902
- retry
3903
- };
3904
- }
3905
-
3906
- // src/components/video/captions.ts
3907
- var CAPTION_LOCALES = ["en", "es", "pt"];
3908
- var LIVE_CUE_EXTRA_LAG_MS = 2e3;
3909
- var LIVE_STACK_MAX_CUES = 150;
3910
- var CAPTION_CHARS_PER_SECOND = 17;
3911
- var CAPTION_MIN_DWELL_MS = 1200;
3912
- var CAPTION_MAX_DWELL_MS = 6e3;
3913
- var CAPTION_RUSH_DWELL_MS = 2500;
3914
- var CAPTION_MAX_CHARS_PER_LINE = 42;
3915
- var CAPTION_COMPACT_CHARS_PER_LINE = 32;
3916
- var CAPTION_MAX_LINES = 2;
3917
- var CAPTION_BACKLOG_DROP = 8;
3918
- var CAPTION_GAP_FILL_MS = 1e3;
3919
- var LIVE_LAG_SPIKE_MS = 2500;
3920
- var CAPTION_BREAK_PUNCT = /[.,;:?!]$/;
3921
- var CAPTION_MIN_PUNCT_LINE = 8;
3922
- var EMPTY_LIVE_CAPTION_PLAYOUT = {
3923
- screen: null,
3924
- hideAt: 0,
3925
- cursor: 0,
3926
- queue: []
3927
- };
3928
- function stabilizeLiveLagMs(previous, next) {
3929
- if (previous == null || !Number.isFinite(previous)) return next;
3930
- if (next <= previous) return next;
3931
- if (next - previous < LIVE_LAG_SPIKE_MS) return previous;
3932
- return next;
3933
- }
3934
- function isCaptionLocale(value) {
3935
- return CAPTION_LOCALES.includes(value);
3936
- }
3937
- function captionsVttUrlFromPlayback(src, locale) {
3938
- const trimmed = src.trim();
3939
- if (!trimmed) return null;
3940
- const replaced = trimmed.replace(
3941
- /index\.m3u8(?:\?.*)?$/i,
3942
- `subs/${locale}.vtt`
3943
- );
3944
- if (replaced === trimmed) return null;
3945
- return replaced;
3946
- }
3947
- function liveCaptionsUrl(base, locale) {
3948
- return `${base.replace(/\/$/, "")}/${locale}`;
3949
- }
3950
- function parseCaptionVtt(text) {
3951
- const cues = [];
3952
- const blocks = text.replace(/^\uFEFF?WEBVTT[^\n]*\n/i, "").split(/\n\s*\n/);
3953
- for (const block of blocks) {
3954
- const lines = block.split("\n").map((line) => line.trim()).filter(Boolean);
3955
- const timing = lines.find((line) => line.includes("-->"));
3956
- if (!timing) continue;
3957
- const [startRaw, endRaw] = timing.split("-->").map((part) => part.trim());
3958
- if (!startRaw || !endRaw) continue;
3959
- const textLines = lines.filter(
3960
- (line) => line !== timing && !/^\d+$/.test(line)
3961
- );
3962
- const payload = textLines.join("\n").trim();
3963
- if (!payload) continue;
3964
- cues.push({
3965
- start: parseVttTimestamp(startRaw.split(" ")[0] ?? startRaw),
3966
- end: parseVttTimestamp(endRaw.split(" ")[0] ?? endRaw),
3967
- text: payload
3968
- });
3675
+ out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
3969
3676
  }
3970
- return cues;
3677
+ return out;
3971
3678
  }
3972
- function captionScreenRow(text, speaker) {
3973
- return speaker == null ? { text } : { text, speaker };
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));
3974
3688
  }
3975
- function chunkLongWord(word, maxCharsPerLine) {
3976
- if (word.length <= maxCharsPerLine) return [word];
3977
- const parts = [];
3978
- for (let index = 0; index < word.length; index += maxCharsPerLine) {
3979
- parts.push(word.slice(index, index + maxCharsPerLine));
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 [];
3980
3696
  }
3981
- return parts;
3982
3697
  }
3983
- function wrapCaptionLines(text, maxCharsPerLine) {
3984
- const tokens = text.split(" ").filter(Boolean).flatMap((word) => chunkLongWord(word, maxCharsPerLine));
3985
- const lines = [];
3986
- let index = 0;
3987
- while (index < tokens.length) {
3988
- let end = index;
3989
- let length = 0;
3990
- while (end < tokens.length) {
3991
- const added = tokens[end].length + (end > index ? 1 : 0);
3992
- if (length + added > maxCharsPerLine && end > index) break;
3993
- length += added;
3994
- end += 1;
3698
+ async function loadLiveCaptions(url) {
3699
+ try {
3700
+ const response = await fetch(url, {
3701
+ cache: "no-store",
3702
+ headers: { Accept: "application/json" }
3703
+ });
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: [] };
3995
3708
  }
3996
- let breakAt = end;
3997
- if (end < tokens.length) {
3998
- for (let cursor = end - 1; cursor > index; cursor -= 1) {
3999
- if (!CAPTION_BREAK_PUNCT.test(tokens[cursor])) continue;
4000
- const firstLen = tokens.slice(index, cursor + 1).join(" ").length;
4001
- if (firstLen >= Math.min(CAPTION_MIN_PUNCT_LINE, maxCharsPerLine)) {
4002
- breakAt = cursor + 1;
4003
- }
4004
- break;
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;
3718
+ }
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;
4005
3725
  }
3726
+ cues.push(parsed);
4006
3727
  }
4007
- lines.push(tokens.slice(index, breakAt).join(" "));
4008
- index = breakAt;
4009
- }
4010
- return lines;
4011
- }
4012
- function balanceCaptionLines(lines, maxCharsPerLine) {
4013
- const next = [...lines];
4014
- for (let index = 0; index + 1 < next.length; index += CAPTION_MAX_LINES) {
4015
- const left = next[index].split(" ");
4016
- const right = next[index + 1].split(" ");
4017
- if (right.length !== 1 || left.length < 3) continue;
4018
- const moved = left[left.length - 1];
4019
- const newRight = `${moved} ${right[0]}`;
4020
- if (newRight.length > maxCharsPerLine) continue;
4021
- next[index] = left.slice(0, -1).join(" ");
4022
- next[index + 1] = newRight;
3728
+ return { ok: true, cues };
3729
+ } catch {
3730
+ return { ok: false, cues: [] };
4023
3731
  }
4024
- return next;
4025
3732
  }
4026
- function splitCaptionScreens(text, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
4027
- const trimmed = text.trim().replace(/\s+/g, " ");
4028
- if (!trimmed) return [];
4029
- const lines = balanceCaptionLines(
4030
- wrapCaptionLines(trimmed, maxCharsPerLine),
4031
- maxCharsPerLine
4032
- );
4033
- const screens = [];
4034
- for (let index = 0; index < lines.length; index += CAPTION_MAX_LINES) {
4035
- screens.push(lines.slice(index, index + CAPTION_MAX_LINES).join("\n"));
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;
4036
3738
  }
4037
- return screens;
4038
- }
4039
- function captionDwellMs(text, backlog = 0) {
4040
- const chars = text.replace(/\s+/g, " ").trim().length;
4041
- const raw = chars / CAPTION_CHARS_PER_SECOND * 1e3;
4042
- const max = backlog > 0 ? CAPTION_RUSH_DWELL_MS : CAPTION_MAX_DWELL_MS;
4043
- return Math.min(max, Math.max(CAPTION_MIN_DWELL_MS, raw));
3739
+ return defaultRetry;
4044
3740
  }
4045
- function advanceLiveCaptionPlayout(state, cues, now, lagMs, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
4046
- let screen = state.screen;
4047
- let hideAt = state.hideAt;
4048
- let cursor = state.cursor;
4049
- let queue = state.queue.slice();
4050
- if (lagMs != null && Number.isFinite(lagMs) && lagMs >= 0) {
4051
- const threshold = lagMs + LIVE_CUE_EXTRA_LAG_MS;
4052
- const incoming = cues.filter(
4053
- (cue) => Boolean(cue.text.trim()) && Number.isFinite(cue.receivedAt) && cue.receivedAt > cursor && now - cue.receivedAt >= threshold
4054
- ).sort((left, right) => left.receivedAt - right.receivedAt);
4055
- for (const cue of incoming) {
4056
- for (const text of splitCaptionScreens(cue.text, maxCharsPerLine)) {
4057
- queue.push(captionScreenRow(text, cue.speaker));
3741
+ var liveEdgeErrorRetry = {
3742
+ maxNumRetry: 8,
3743
+ retryDelayMs: 250,
3744
+ maxRetryDelayMs: 4e3,
3745
+ backoff: "exponential",
3746
+ shouldRetry: shouldRetryLiveEdge404
3747
+ };
3748
+ function createLiveHlsConfig() {
3749
+ return {
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
+ }
4058
3782
  }
4059
- cursor = cue.receivedAt;
4060
- }
4061
- if (queue.length > CAPTION_BACKLOG_DROP) {
4062
- queue = queue.slice(queue.length - CAPTION_BACKLOG_DROP);
4063
3783
  }
3784
+ };
3785
+ }
3786
+ function createVodHlsConfig() {
3787
+ return {
3788
+ enableWorker: true,
3789
+ startPosition: 0
3790
+ };
3791
+ }
3792
+
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"
3799
+ };
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;
3807
+ }
3808
+ function isNotFound(httpStatus, details) {
3809
+ return httpStatus === 404 || details === "manifestLoadError" || details === "levelLoadError" || details === "fragLoadError";
3810
+ }
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";
4064
3815
  }
4065
- if (now >= hideAt) {
4066
- const next = queue.shift();
4067
- if (next) {
4068
- screen = next;
4069
- hideAt = now + captionDwellMs(next.text, queue.length);
4070
- } else {
4071
- screen = null;
4072
- }
3816
+ if (input.type === "mediaError" || input.details === "bufferAppendError" || input.details === "bufferSeekOverHole") {
3817
+ return "media";
4073
3818
  }
4074
- return { screen, hideAt, cursor, queue };
3819
+ return "generic";
4075
3820
  }
4076
- function cueEndWithGapFill(cues, index) {
4077
- const cue = cues[index];
4078
- if (!cue) return 0;
4079
- const next = cues[index + 1];
4080
- if (!next || !Number.isFinite(next.start)) return cue.end;
4081
- const gapMs = (next.start - cue.end) * 1e3;
4082
- if (gapMs > 0 && gapMs < CAPTION_GAP_FILL_MS) return next.start;
4083
- return cue.end;
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";
4084
3827
  }
4085
- function captionScreenAtTime(cues, time, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
4086
- if (!Number.isFinite(time)) return null;
4087
- const ordered = cues.filter(
4088
- (cue) => Boolean(cue.text.trim()) && Number.isFinite(cue.start) && Number.isFinite(cue.end)
4089
- ).sort((left, right) => left.start - right.start);
4090
- for (let index = 0; index < ordered.length; index += 1) {
4091
- const cue = ordered[index];
4092
- const end = cueEndWithGapFill(ordered, index);
4093
- if (time < cue.start || time >= end) continue;
4094
- const screens = splitCaptionScreens(cue.text, maxCharsPerLine);
4095
- if (screens.length === 0) return null;
4096
- const weights = screens.map(
4097
- (text) => Math.max(1, text.replace(/\s+/g, "").length)
4098
- );
4099
- const total = weights.reduce((sum, weight) => sum + weight, 0);
4100
- const duration = Math.max(end - cue.start, 0);
4101
- let cursor = cue.start;
4102
- for (let screenIndex = 0; screenIndex < screens.length; screenIndex += 1) {
4103
- const isLast = screenIndex === screens.length - 1;
4104
- const slice = isLast ? end - cursor : duration * (weights[screenIndex] / total);
4105
- const sliceEnd = cursor + slice;
4106
- if (time >= cursor && time < sliceEnd) {
4107
- return captionScreenRow(screens[screenIndex]);
4108
- }
4109
- cursor = sliceEnd;
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
4110
3839
  }
4111
- return captionScreenRow(screens[screens.length - 1]);
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
+ };
4112
3853
  }
4113
- return null;
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 };
4114
3895
  }
4115
- var LIVE_OVERLAP_MIN_WORDS = 4;
4116
- function normalizeLiveCaptionText(text) {
4117
- return text.trim().replace(/\s+/g, " ").toLowerCase();
3896
+
3897
+ // src/components/video/useHlsPlayback.ts
3898
+ function effectivePlaybackMode(src, mode, sealed) {
3899
+ if (isLivePlaylistSrc(src)) return sealed ? "vod" : "live";
3900
+ return mode;
4118
3901
  }
4119
- function lastSubseqIndex(haystack, needle) {
4120
- if (needle.length === 0 || needle.length > haystack.length) return -1;
4121
- let found = -1;
4122
- for (let index = 0; index <= haystack.length - needle.length; index += 1) {
4123
- let match = true;
4124
- for (let offset = 0; offset < needle.length; offset += 1) {
4125
- if (haystack[index + offset] !== needle[offset]) {
4126
- match = false;
4127
- break;
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;
3957
+ }
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();
4128
3994
  }
3995
+ return modeRef.current === "live" ? createLiveHlsConfig() : createVodHlsConfig();
4129
3996
  }
4130
- if (match) found = index;
4131
- }
4132
- return found;
4133
- }
4134
- function remainderAfterOverlap(previous, next) {
4135
- const prevWords = normalizeLiveCaptionText(previous).split(" ").filter(Boolean);
4136
- const nextWords = next.trim().replace(/\s+/g, " ").split(" ").filter(Boolean);
4137
- const nextNorm = nextWords.map((word) => word.toLowerCase());
4138
- const maxN = Math.min(prevWords.length, nextNorm.length);
4139
- for (let size = maxN; size >= LIVE_OVERLAP_MIN_WORDS; size -= 1) {
4140
- for (let start = prevWords.length - size; start >= 0; start -= 1) {
4141
- const gram = prevWords.slice(start, start + size);
4142
- const index = lastSubseqIndex(nextNorm, gram);
4143
- if (index !== -1) {
4144
- return nextWords.slice(index + size).join(" ");
3997
+ function clearRetryTimer() {
3998
+ if (retryTimer !== null) {
3999
+ clearTimeout(retryTimer);
4000
+ retryTimer = null;
4145
4001
  }
4146
4002
  }
4147
- }
4148
- return null;
4149
- }
4150
- function liveCaptionRow(text, receivedAt, speaker) {
4151
- return speaker == null ? { text, receivedAt } : { text, receivedAt, speaker };
4152
- }
4153
- function coalesceLiveCaptionCues(cues) {
4154
- const out = [];
4155
- for (const cue of cues) {
4156
- const text = cue.text.trim();
4157
- if (!text) continue;
4158
- const last = out[out.length - 1];
4159
- if (!last) {
4160
- out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
4161
- continue;
4003
+ function destroyHls() {
4004
+ hlsRef.current?.destroy();
4005
+ hlsRef.current = null;
4006
+ }
4007
+ function reportFatal(input) {
4008
+ const described = describePlaybackError(input);
4009
+ onErrorRef.current?.(described);
4010
+ setError(described);
4011
+ setState("error");
4012
+ }
4013
+ function applyMute(el) {
4014
+ el.muted = muted;
4015
+ }
4016
+ function preserveMute(el, fn) {
4017
+ const wasMuted = el.muted;
4018
+ fn();
4019
+ el.muted = wasMuted;
4020
+ }
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
+ );
4042
+ }
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);
4162
4051
  }
4163
- if (last.speaker !== cue.speaker && (last.speaker != null || cue.speaker != null)) {
4164
- out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
4165
- 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
+ });
4166
4098
  }
4167
- const lastNorm = normalizeLiveCaptionText(last.text);
4168
- const nextNorm = normalizeLiveCaptionText(text);
4169
- if (lastNorm === nextNorm) continue;
4170
- if (nextNorm.startsWith(lastNorm) || lastNorm.startsWith(nextNorm)) {
4171
- out[out.length - 1] = liveCaptionRow(
4172
- nextNorm.length >= lastNorm.length ? text : last.text,
4173
- cue.receivedAt,
4174
- 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
4175
4108
  );
4176
- 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);
4177
4116
  }
4178
- const remainder = remainderAfterOverlap(last.text, text);
4179
- if (remainder !== null) {
4180
- if (!remainder) continue;
4181
- out.push(liveCaptionRow(remainder, cue.receivedAt, cue.speaker));
4182
- continue;
4117
+ function onPaused() {
4118
+ onPlayingChangeRef.current?.(false);
4183
4119
  }
4184
- out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
4185
- }
4186
- return out;
4187
- }
4188
- function mergeLiveCaptionCues(existing, incoming, cap = LIVE_STACK_MAX_CUES) {
4189
- const map = /* @__PURE__ */ new Map();
4190
- for (const cue of existing) {
4191
- if (Number.isFinite(cue.receivedAt)) map.set(cue.receivedAt, cue);
4192
- }
4193
- for (const cue of incoming) {
4194
- if (Number.isFinite(cue.receivedAt)) map.set(cue.receivedAt, cue);
4195
- }
4196
- return [...map.values()].sort((left, right) => left.receivedAt - right.receivedAt).slice(-Math.max(1, cap));
4197
- }
4198
- async function loadCaptionVtt(url) {
4199
- try {
4200
- const response = await fetch(url, { cache: "no-store" });
4201
- if (!response.ok) return [];
4202
- return parseCaptionVtt(await response.text());
4203
- } catch {
4204
- return [];
4205
- }
4206
- }
4207
- async function loadLiveCaptions(url) {
4208
- try {
4209
- const response = await fetch(url, {
4210
- cache: "no-store",
4211
- 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);
4212
4133
  });
4213
- if (!response.ok) return { ok: false, cues: [] };
4214
- const body = await response.json();
4215
- if (!body || typeof body !== "object" || !("cues" in body)) {
4216
- 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
+ });
4175
+ }
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
+ });
4217
4270
  }
4218
- const rows = body.cues;
4219
- if (!Array.isArray(rows)) return { ok: false, cues: [] };
4220
- const cues = [];
4221
- for (const row of rows) {
4222
- if (!row || typeof row !== "object") continue;
4223
- const record = row;
4224
- if (typeof record.text !== "string" || !record.text.trim()) continue;
4225
- if (typeof record.receivedAt !== "number" || !Number.isFinite(record.receivedAt)) {
4226
- continue;
4271
+ async function setup() {
4272
+ let Hls = null;
4273
+ try {
4274
+ Hls = (await import('hls.js')).default;
4275
+ } catch {
4276
+ Hls = null;
4227
4277
  }
4228
- const parsed = {
4229
- text: record.text.trim(),
4230
- receivedAt: record.receivedAt
4231
- };
4232
- if (typeof record.speaker === "number" && Number.isFinite(record.speaker)) {
4233
- 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
+ });
4234
4289
  }
4235
- cues.push(parsed);
4236
4290
  }
4237
- return { ok: true, cues };
4238
- } catch {
4239
- return { ok: false, cues: [] };
4240
- }
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
+ };
4241
4316
  }
4242
4317
 
4243
4318
  // src/components/video/fullscreen.ts
@@ -4398,6 +4473,7 @@ var PLAYBACK_RATES = [0.75, 1, 1.25, 1.5, 2];
4398
4473
  var CONTROLS_HIDE_MS = 3e3;
4399
4474
  var LIVE_EDGE_THRESHOLD_S = 8;
4400
4475
  var SEEK_STEP_S = 5;
4476
+ var PROGRESS_THROTTLE_MS = 5e3;
4401
4477
  var LIVE_CAPTION_PLAYOUT_MS = 250;
4402
4478
  var COMPACT_CHROME_PX = 640;
4403
4479
  var VIDEO_MEDIA_STYLE = `
@@ -4446,6 +4522,9 @@ function VideoPlayer({
4446
4522
  onPlayingChange,
4447
4523
  onFirstPlay,
4448
4524
  onError,
4525
+ onPlaybackProgress,
4526
+ onRebuffer,
4527
+ onQualityChange,
4449
4528
  fit = "aspect-video",
4450
4529
  className,
4451
4530
  defaultCaptionLocale,
@@ -4454,6 +4533,9 @@ function VideoPlayer({
4454
4533
  const t = { ...DEFAULT_LABELS3, ...labels };
4455
4534
  const containerRef = React9__namespace.useRef(null);
4456
4535
  const firstPlayFiredRef = React9__namespace.useRef(false);
4536
+ const lastProgressAtRef = React9__namespace.useRef(-PROGRESS_THROTTLE_MS);
4537
+ const onPlaybackProgressRef = React9__namespace.useRef(onPlaybackProgress);
4538
+ onPlaybackProgressRef.current = onPlaybackProgress;
4457
4539
  const applyingTrackModesRef = React9__namespace.useRef(false);
4458
4540
  const captionLocaleRef = React9__namespace.useRef("off");
4459
4541
  const cssFullscreenRef = React9__namespace.useRef(false);
@@ -4480,7 +4562,8 @@ function VideoPlayer({
4480
4562
  setLevel,
4481
4563
  autoplayState,
4482
4564
  error,
4483
- retry
4565
+ retry,
4566
+ effectiveMode
4484
4567
  } = useHlsPlayback({
4485
4568
  src,
4486
4569
  mode,
@@ -4488,7 +4571,9 @@ function VideoPlayer({
4488
4571
  autoPlay: autoplayActive,
4489
4572
  muted,
4490
4573
  onError,
4491
- onPlayingChange: handlePlayingChange
4574
+ onPlayingChange: handlePlayingChange,
4575
+ onRebuffer,
4576
+ onQualityChange
4492
4577
  });
4493
4578
  const [isPlaying, setIsPlaying] = React9__namespace.useState(false);
4494
4579
  const [isMuted, setIsMuted] = React9__namespace.useState(muted);
@@ -4556,7 +4641,22 @@ function VideoPlayer({
4556
4641
  if (video.buffered.length > 0) {
4557
4642
  setBuffered(video.buffered.end(video.buffered.length - 1));
4558
4643
  }
4559
- if (mode === "live" && video.seekable.length > 0) {
4644
+ const progress = onPlaybackProgressRef.current;
4645
+ if (progress) {
4646
+ const now = performance.now();
4647
+ if (now - lastProgressAtRef.current >= PROGRESS_THROTTLE_MS) {
4648
+ lastProgressAtRef.current = now;
4649
+ progress(
4650
+ video.currentTime,
4651
+ finitePlaybackDuration(
4652
+ video.duration,
4653
+ video.seekable,
4654
+ effectiveMode
4655
+ )
4656
+ );
4657
+ }
4658
+ }
4659
+ if (effectiveMode === "live" && video.seekable.length > 0) {
4560
4660
  const edge = video.seekable.end(video.seekable.length - 1);
4561
4661
  const lagSeconds = edge - video.currentTime;
4562
4662
  setBehindLive(lagSeconds > LIVE_EDGE_THRESHOLD_S);
@@ -4565,7 +4665,9 @@ function VideoPlayer({
4565
4665
  }
4566
4666
  }
4567
4667
  };
4568
- const onDuration = () => setDuration(finitePlaybackDuration(video.duration, video.seekable, mode));
4668
+ const onDuration = () => setDuration(
4669
+ finitePlaybackDuration(video.duration, video.seekable, effectiveMode)
4670
+ );
4569
4671
  const onVolume = () => {
4570
4672
  setIsMuted(video.muted);
4571
4673
  setVolume(video.volume);
@@ -4589,7 +4691,7 @@ function VideoPlayer({
4589
4691
  video.removeEventListener("ratechange", onRate);
4590
4692
  video.removeEventListener("playing", onPlaying);
4591
4693
  };
4592
- }, [videoRef, active, mode, liveCaptionsBaseUrl]);
4694
+ }, [videoRef, active, effectiveMode, liveCaptionsBaseUrl]);
4593
4695
  React9__namespace.useLayoutEffect(() => {
4594
4696
  const video = videoRef.current;
4595
4697
  if (video) video.muted = isMuted;
@@ -4917,13 +5019,13 @@ function VideoPlayer({
4917
5019
  }
4918
5020
  break;
4919
5021
  case "ArrowLeft":
4920
- if (mode === "vod") {
5022
+ if (effectiveMode === "vod") {
4921
5023
  e.preventDefault();
4922
5024
  seekBy(-SEEK_STEP_S);
4923
5025
  }
4924
5026
  break;
4925
5027
  case "ArrowRight":
4926
- if (mode === "vod") {
5028
+ if (effectiveMode === "vod") {
4927
5029
  e.preventDefault();
4928
5030
  seekBy(SEEK_STEP_S);
4929
5031
  }
@@ -4970,7 +5072,7 @@ function VideoPlayer({
4970
5072
  {
4971
5073
  ref: containerRef,
4972
5074
  "data-slot": "video-player",
4973
- "data-mode": mode,
5075
+ "data-mode": effectiveMode,
4974
5076
  "data-fit": fit,
4975
5077
  "data-css-fullscreen": cssFullscreen ? "" : void 0,
4976
5078
  className: cn(
@@ -5071,7 +5173,7 @@ function VideoPlayer({
5071
5173
  ]
5072
5174
  }
5073
5175
  ),
5074
- mode === "live" && active && state === "ready" && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "absolute top-3 left-3 flex items-center gap-2", children: [
5176
+ effectiveMode === "live" && active && state === "ready" && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "absolute top-3 left-3 flex items-center gap-2", children: [
5075
5177
  /* @__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: [
5076
5178
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "size-1.5 animate-pulse rounded-full bg-white" }),
5077
5179
  t.live
@@ -5088,7 +5190,7 @@ function VideoPlayer({
5088
5190
  ),
5089
5191
  "data-slot": "video-controls",
5090
5192
  children: [
5091
- mode === "vod" && /* @__PURE__ */ jsxRuntime.jsx(
5193
+ effectiveMode === "vod" && /* @__PURE__ */ jsxRuntime.jsx(
5092
5194
  SeekBar,
5093
5195
  {
5094
5196
  src,
@@ -5129,11 +5231,11 @@ function VideoPlayer({
5129
5231
  }
5130
5232
  ) })
5131
5233
  ] }),
5132
- mode === "vod" && /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "ml-1 shrink-0 text-xs tabular-nums", children: [
5234
+ effectiveMode === "vod" && /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "ml-1 shrink-0 text-xs tabular-nums", children: [
5133
5235
  formatTime(currentTime),
5134
5236
  !compactChrome && ` / ${formatTime(duration)}`
5135
5237
  ] }),
5136
- mode === "live" && behindLive && /* @__PURE__ */ jsxRuntime.jsxs(
5238
+ effectiveMode === "live" && behindLive && /* @__PURE__ */ jsxRuntime.jsxs(
5137
5239
  "button",
5138
5240
  {
5139
5241
  type: "button",
@@ -5146,7 +5248,7 @@ function VideoPlayer({
5146
5248
  }
5147
5249
  ),
5148
5250
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "ml-auto flex shrink-0 items-center gap-1", children: [
5149
- !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` }),
5251
+ !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` }),
5150
5252
  /* @__PURE__ */ jsxRuntime.jsxs(
5151
5253
  MenuControl,
5152
5254
  {
@@ -5175,7 +5277,7 @@ function VideoPlayer({
5175
5277
  ]
5176
5278
  }
5177
5279
  ),
5178
- !compactChrome && mode === "vod" && /* @__PURE__ */ jsxRuntime.jsx(
5280
+ !compactChrome && effectiveMode === "vod" && /* @__PURE__ */ jsxRuntime.jsx(
5179
5281
  MenuControl,
5180
5282
  {
5181
5283
  label: t.speed,
@@ -5305,7 +5407,7 @@ function VideoPlayer({
5305
5407
  q.index
5306
5408
  ))
5307
5409
  ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
5308
- mode === "vod" && /* @__PURE__ */ jsxRuntime.jsx(
5410
+ effectiveMode === "vod" && /* @__PURE__ */ jsxRuntime.jsx(
5309
5411
  MenuNavRow,
5310
5412
  {
5311
5413
  icon: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Gauge, { className: "size-4" }),
@@ -5323,7 +5425,7 @@ function VideoPlayer({
5323
5425
  onSelect: () => setMorePane("quality")
5324
5426
  }
5325
5427
  ),
5326
- (mode === "vod" || showQuality) && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "my-1 h-px bg-primary/15" }),
5428
+ (effectiveMode === "vod" || showQuality) && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "my-1 h-px bg-primary/15" }),
5327
5429
  /* @__PURE__ */ jsxRuntime.jsx(
5328
5430
  MenuAction,
5329
5431
  {
@@ -6334,10 +6436,374 @@ function avatarFallbackStyle(name) {
6334
6436
  return getAvatarColors(name);
6335
6437
  }
6336
6438
 
6439
+ // src/lib/playbackBeacon.ts
6440
+ var DEFAULT_INTERVAL_MS = 5e3;
6441
+ function canUseWindow() {
6442
+ return typeof window !== "undefined" && typeof document !== "undefined";
6443
+ }
6444
+ function createPlaybackBeaconClient({
6445
+ endpoint,
6446
+ sessionId,
6447
+ surface,
6448
+ getContext,
6449
+ fetchFn,
6450
+ intervalMs = DEFAULT_INTERVAL_MS,
6451
+ now = () => Date.now()
6452
+ }) {
6453
+ let queue = [];
6454
+ let destroyed = false;
6455
+ let timer = null;
6456
+ let flushing = null;
6457
+ function enqueue(event) {
6458
+ if (destroyed) return;
6459
+ const context = getContext?.() ?? {};
6460
+ queue.push({
6461
+ type: event.type,
6462
+ ...context,
6463
+ ...event,
6464
+ surface,
6465
+ ts: event.ts ?? now()
6466
+ });
6467
+ }
6468
+ async function send(events, keepalive) {
6469
+ if (events.length === 0) return;
6470
+ const body = JSON.stringify({ sessionId, events });
6471
+ const post = fetchFn ?? (typeof fetch === "function" ? fetch : void 0);
6472
+ if (!post) return;
6473
+ try {
6474
+ await post(endpoint, {
6475
+ method: "POST",
6476
+ headers: { "Content-Type": "application/json" },
6477
+ body,
6478
+ keepalive
6479
+ });
6480
+ } catch {
6481
+ }
6482
+ }
6483
+ async function flush(keepalive = false) {
6484
+ if (queue.length === 0) return;
6485
+ const events = queue;
6486
+ queue = [];
6487
+ await send(events, keepalive);
6488
+ }
6489
+ function scheduleFlush() {
6490
+ if (flushing) return flushing;
6491
+ flushing = flush(false).finally(() => {
6492
+ flushing = null;
6493
+ });
6494
+ return flushing;
6495
+ }
6496
+ function onPageHide() {
6497
+ void flush(true);
6498
+ }
6499
+ function onVisibility() {
6500
+ if (document.visibilityState === "hidden") void flush(true);
6501
+ }
6502
+ if (canUseWindow()) {
6503
+ timer = setInterval(() => {
6504
+ void scheduleFlush();
6505
+ }, intervalMs);
6506
+ window.addEventListener("pagehide", onPageHide);
6507
+ document.addEventListener("visibilitychange", onVisibility);
6508
+ }
6509
+ return {
6510
+ track(event) {
6511
+ enqueue(event);
6512
+ },
6513
+ flush() {
6514
+ return flush(false);
6515
+ },
6516
+ destroy() {
6517
+ if (destroyed) return;
6518
+ destroyed = true;
6519
+ if (timer !== null) {
6520
+ clearInterval(timer);
6521
+ timer = null;
6522
+ }
6523
+ if (canUseWindow()) {
6524
+ window.removeEventListener("pagehide", onPageHide);
6525
+ document.removeEventListener("visibilitychange", onVisibility);
6526
+ }
6527
+ void flush(true);
6528
+ }
6529
+ };
6530
+ }
6531
+ function StatHighlightCard({
6532
+ label,
6533
+ value,
6534
+ hint,
6535
+ delta,
6536
+ deltaTone = "neutral",
6537
+ className
6538
+ }) {
6539
+ return /* @__PURE__ */ jsxRuntime.jsxs(
6540
+ "div",
6541
+ {
6542
+ className: cn(
6543
+ "bg-card text-card-foreground rounded-xl border p-6 shadow-sm",
6544
+ className
6545
+ ),
6546
+ children: [
6547
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-muted-foreground text-sm", children: label }),
6548
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "mt-2 text-2xl font-semibold tracking-tight", children: value }),
6549
+ delta ? /* @__PURE__ */ jsxRuntime.jsx(
6550
+ "p",
6551
+ {
6552
+ className: cn(
6553
+ "mt-1 text-sm",
6554
+ deltaTone === "up" && "text-emerald-600 dark:text-emerald-400",
6555
+ deltaTone === "down" && "text-destructive",
6556
+ deltaTone === "neutral" && "text-muted-foreground"
6557
+ ),
6558
+ children: delta
6559
+ }
6560
+ ) : null,
6561
+ hint ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-muted-foreground mt-1 text-xs", children: hint }) : null
6562
+ ]
6563
+ }
6564
+ );
6565
+ }
6566
+ function MetricChartCard({
6567
+ title,
6568
+ description,
6569
+ action,
6570
+ children,
6571
+ className
6572
+ }) {
6573
+ return /* @__PURE__ */ jsxRuntime.jsxs(
6574
+ "div",
6575
+ {
6576
+ className: cn(
6577
+ "bg-card text-card-foreground rounded-xl border shadow-sm",
6578
+ className
6579
+ ),
6580
+ children: [
6581
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-start justify-between gap-3 p-6 pb-2", children: [
6582
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
6583
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "leading-none font-semibold tracking-tight", children: title }),
6584
+ description ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-muted-foreground mt-1.5 text-sm", children: description }) : null
6585
+ ] }),
6586
+ action
6587
+ ] }),
6588
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "p-6 pt-4", children })
6589
+ ]
6590
+ }
6591
+ );
6592
+ }
6593
+ function polyline(points) {
6594
+ if (points.length === 0) return "";
6595
+ const min = Math.min(...points);
6596
+ const max = Math.max(...points);
6597
+ const span = max - min || 1;
6598
+ return points.map((point, index) => {
6599
+ const x = points.length === 1 ? 50 : index / (points.length - 1) * 100;
6600
+ const y = 28 - (point - min) / span * 24;
6601
+ return `${x.toFixed(2)},${y.toFixed(2)}`;
6602
+ }).join(" ");
6603
+ }
6604
+ function SparklineStat({
6605
+ label,
6606
+ value,
6607
+ points,
6608
+ className
6609
+ }) {
6610
+ const reduced = useMediaQuery2("(prefers-reduced-motion: reduce)");
6611
+ const path = polyline(points);
6612
+ return /* @__PURE__ */ jsxRuntime.jsxs(
6613
+ "div",
6614
+ {
6615
+ className: cn(
6616
+ "bg-card text-card-foreground flex items-end justify-between gap-3 rounded-xl border p-4 shadow-sm",
6617
+ className
6618
+ ),
6619
+ children: [
6620
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
6621
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-muted-foreground text-xs", children: label }),
6622
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "mt-1 text-lg font-semibold tracking-tight", children: value })
6623
+ ] }),
6624
+ path ? /* @__PURE__ */ jsxRuntime.jsx(
6625
+ "svg",
6626
+ {
6627
+ viewBox: "0 0 100 32",
6628
+ className: cn(
6629
+ "text-primary h-8 w-24",
6630
+ !reduced && "motion-safe:transition-opacity"
6631
+ ),
6632
+ "aria-hidden": "true",
6633
+ children: /* @__PURE__ */ jsxRuntime.jsx(
6634
+ "polyline",
6635
+ {
6636
+ fill: "none",
6637
+ stroke: "currentColor",
6638
+ strokeWidth: "2",
6639
+ strokeLinejoin: "round",
6640
+ strokeLinecap: "round",
6641
+ points: path
6642
+ }
6643
+ )
6644
+ }
6645
+ ) : null
6646
+ ]
6647
+ }
6648
+ );
6649
+ }
6650
+ var TIME_RANGE_OPTIONS = ["day", "week", "month", "year"];
6651
+ var DEFAULT_LABELS4 = {
6652
+ day: "Day",
6653
+ week: "Week",
6654
+ month: "Month",
6655
+ year: "Year"
6656
+ };
6657
+ function TimeRangePicker({
6658
+ value,
6659
+ onChange,
6660
+ labels,
6661
+ className
6662
+ }) {
6663
+ const copy = { ...DEFAULT_LABELS4, ...labels };
6664
+ return /* @__PURE__ */ jsxRuntime.jsx(
6665
+ "div",
6666
+ {
6667
+ role: "group",
6668
+ "aria-label": "Time range",
6669
+ className: cn("flex flex-wrap gap-1", className),
6670
+ children: TIME_RANGE_OPTIONS.map((option) => {
6671
+ const selected = option === value;
6672
+ return /* @__PURE__ */ jsxRuntime.jsx(
6673
+ Button,
6674
+ {
6675
+ type: "button",
6676
+ size: "sm",
6677
+ variant: selected ? "default" : "outline",
6678
+ "aria-pressed": selected,
6679
+ onClick: () => onChange(option),
6680
+ children: copy[option]
6681
+ },
6682
+ option
6683
+ );
6684
+ })
6685
+ }
6686
+ );
6687
+ }
6688
+ function DimensionBreakdownTable({
6689
+ title,
6690
+ rows,
6691
+ empty,
6692
+ className
6693
+ }) {
6694
+ return /* @__PURE__ */ jsxRuntime.jsxs(
6695
+ "div",
6696
+ {
6697
+ className: cn(
6698
+ "bg-card text-card-foreground overflow-hidden rounded-xl border shadow-sm",
6699
+ className
6700
+ ),
6701
+ children: [
6702
+ title ? /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "px-6 pt-6 text-sm font-semibold tracking-tight", children: title }) : null,
6703
+ rows.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "p-6", children: empty }) : /* @__PURE__ */ jsxRuntime.jsx("table", { className: "w-full text-sm", children: /* @__PURE__ */ jsxRuntime.jsx("tbody", { children: rows.map((row) => /* @__PURE__ */ jsxRuntime.jsxs("tr", { className: "border-t first:border-t-0", children: [
6704
+ /* @__PURE__ */ jsxRuntime.jsx("th", { scope: "row", className: "px-6 py-3 text-left font-medium", children: row.label }),
6705
+ /* @__PURE__ */ jsxRuntime.jsx("td", { className: "px-6 py-3 text-right tabular-nums", children: row.value }),
6706
+ row.share ? /* @__PURE__ */ jsxRuntime.jsx("td", { className: "text-muted-foreground px-6 py-3 text-right tabular-nums", children: row.share }) : null
6707
+ ] }, row.id)) }) })
6708
+ ]
6709
+ }
6710
+ );
6711
+ }
6712
+ function CostBreakdownCard({
6713
+ title,
6714
+ total,
6715
+ items,
6716
+ className
6717
+ }) {
6718
+ return /* @__PURE__ */ jsxRuntime.jsxs(
6719
+ "div",
6720
+ {
6721
+ className: cn(
6722
+ "bg-card text-card-foreground rounded-xl border p-6 shadow-sm",
6723
+ className
6724
+ ),
6725
+ children: [
6726
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-baseline justify-between gap-3", children: [
6727
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "font-semibold tracking-tight", children: title }),
6728
+ total ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-lg font-semibold tabular-nums", children: total }) : null
6729
+ ] }),
6730
+ /* @__PURE__ */ jsxRuntime.jsx("ul", { className: "mt-4 space-y-2", children: items.map((item) => /* @__PURE__ */ jsxRuntime.jsxs(
6731
+ "li",
6732
+ {
6733
+ className: "flex items-baseline justify-between gap-3 text-sm",
6734
+ children: [
6735
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
6736
+ /* @__PURE__ */ jsxRuntime.jsx("p", { children: item.label }),
6737
+ item.basis ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-muted-foreground text-xs", children: item.basis }) : null
6738
+ ] }),
6739
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "tabular-nums", children: item.amount })
6740
+ ]
6741
+ },
6742
+ item.id
6743
+ )) })
6744
+ ]
6745
+ }
6746
+ );
6747
+ }
6748
+ function MetricEmptyState({
6749
+ title,
6750
+ description,
6751
+ action,
6752
+ icon = lucideReact.BarChart3,
6753
+ className
6754
+ }) {
6755
+ return /* @__PURE__ */ jsxRuntime.jsx(
6756
+ EmptyState,
6757
+ {
6758
+ title,
6759
+ description,
6760
+ action,
6761
+ icon,
6762
+ className
6763
+ }
6764
+ );
6765
+ }
6766
+ function MetricSkeleton({ className, bars = 4 }) {
6767
+ const reduced = useMediaQuery2("(prefers-reduced-motion: reduce)");
6768
+ const count = Math.max(1, bars);
6769
+ return /* @__PURE__ */ jsxRuntime.jsxs(
6770
+ "div",
6771
+ {
6772
+ role: "status",
6773
+ "aria-live": "polite",
6774
+ className: cn("bg-card rounded-xl border p-6 shadow-sm", className),
6775
+ children: [
6776
+ /* @__PURE__ */ jsxRuntime.jsx(
6777
+ "div",
6778
+ {
6779
+ className: cn(
6780
+ "bg-muted mb-4 h-4 w-32 rounded",
6781
+ !reduced && "animate-pulse"
6782
+ )
6783
+ }
6784
+ ),
6785
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex h-32 items-end gap-2", children: Array.from({ length: count }, (_, index) => /* @__PURE__ */ jsxRuntime.jsx(
6786
+ "div",
6787
+ {
6788
+ className: cn(
6789
+ "bg-muted flex-1 rounded-t",
6790
+ !reduced && "animate-pulse"
6791
+ ),
6792
+ style: { height: `${40 + index * 17 % 50}%` }
6793
+ },
6794
+ index
6795
+ )) }),
6796
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "sr-only", children: "Loading metrics" })
6797
+ ]
6798
+ }
6799
+ );
6800
+ }
6801
+
6337
6802
  exports.AvatarEditor = AvatarEditor;
6338
6803
  exports.AvatarEditorDialog = AvatarEditorDialog;
6339
6804
  exports.CAPTION_LOCALES = CAPTION_LOCALES;
6340
6805
  exports.ConfirmDestructiveDialog = ConfirmDestructiveDialog;
6806
+ exports.CostBreakdownCard = CostBreakdownCard;
6341
6807
  exports.CurtainPicker = CurtainPicker;
6342
6808
  exports.CurtainPickerSkeleton = CurtainPickerSkeleton;
6343
6809
  exports.CurtainPreview = CurtainPreview;
@@ -6350,6 +6816,7 @@ exports.DEFAULT_FILE_UPLOAD_TRAY_LABELS = DEFAULT_FILE_UPLOAD_TRAY_LABELS;
6350
6816
  exports.DEFAULT_NOTIFICATION_BELL_LABELS = DEFAULT_NOTIFICATION_BELL_LABELS;
6351
6817
  exports.DataList = DataList;
6352
6818
  exports.DataListItem = DataListItem;
6819
+ exports.DimensionBreakdownTable = DimensionBreakdownTable;
6353
6820
  exports.EditableSection = EditableSection;
6354
6821
  exports.Empty = Empty;
6355
6822
  exports.EmptyContent = EmptyContent;
@@ -6367,9 +6834,16 @@ exports.FileUploadTray = FileUploadTray;
6367
6834
  exports.LanguageContext = LanguageContext;
6368
6835
  exports.LanguageSwitcher = LanguageSwitcher;
6369
6836
  exports.LoadingState = LoadingState;
6837
+ exports.MetricChartCard = MetricChartCard;
6838
+ exports.MetricEmptyState = MetricEmptyState;
6839
+ exports.MetricSkeleton = MetricSkeleton;
6370
6840
  exports.NotificationBell = NotificationBell;
6371
6841
  exports.SafeImage = SafeImage;
6842
+ exports.SparklineStat = SparklineStat;
6843
+ exports.StatHighlightCard = StatHighlightCard;
6844
+ exports.TIME_RANGE_OPTIONS = TIME_RANGE_OPTIONS;
6372
6845
  exports.ThemeSwitcher = ThemeSwitcher;
6846
+ exports.TimeRangePicker = TimeRangePicker;
6373
6847
  exports.VideoPlayer = VideoPlayer;
6374
6848
  exports.WaitingRoom = WaitingRoom;
6375
6849
  exports.avatarFallbackStyle = avatarFallbackStyle;
@@ -6378,6 +6852,7 @@ exports.castHlsUrl = castHlsUrl;
6378
6852
  exports.cn = cn;
6379
6853
  exports.createLiveHlsConfig = createLiveHlsConfig;
6380
6854
  exports.createMultipartUploadController = createMultipartUploadController;
6855
+ exports.createPlaybackBeaconClient = createPlaybackBeaconClient;
6381
6856
  exports.createVodHlsConfig = createVodHlsConfig;
6382
6857
  exports.defaultLanguages = defaultLanguages;
6383
6858
  exports.describeAvResync = describeAvResync;