@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.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
  import * as React9 from 'react';
3
3
  import { createContext, useContext, useState, useRef, useId, useEffect, useCallback, useLayoutEffect } from 'react';
4
- import { Loader2, AlertTriangle, Inbox, Bell, Monitor, Sun, Moon, Languages, Upload, Move, ZoomOut, ZoomIn, RotateCcw, RotateCw, Grid3X3, RefreshCw, X, User, Pencil, Check, Play, AlertCircle, VolumeX, Pause, Volume1, Volume2, Captions, Settings, Cast, PictureInPicture2, Gauge, EllipsisVertical, Minimize, Maximize, ChevronRight, ChevronLeft, XIcon } from 'lucide-react';
4
+ import { Loader2, AlertTriangle, Inbox, Bell, Monitor, Sun, Moon, Languages, Upload, Move, ZoomOut, ZoomIn, RotateCcw, RotateCw, Grid3X3, RefreshCw, X, User, Pencil, Check, Play, AlertCircle, VolumeX, Pause, Volume1, Volume2, Captions, Settings, Cast, PictureInPicture2, Gauge, EllipsisVertical, Minimize, Maximize, ChevronRight, ChevronLeft, BarChart3, XIcon } from 'lucide-react';
5
5
  import { clsx } from 'clsx';
6
6
  import { twMerge } from 'tailwind-merge';
7
7
  import { cva } from 'class-variance-authority';
@@ -3365,853 +3365,928 @@ function SeekBar({
3365
3365
  );
3366
3366
  }
3367
3367
 
3368
- // src/components/video/hls-config.ts
3369
- function shouldRetryLiveEdge404(retryConfig, retryCount, _isTimeout, loaderResponse, defaultRetry) {
3370
- if (loaderResponse?.code === 404) {
3371
- return retryConfig != null && retryCount < retryConfig.maxNumRetry;
3368
+ // src/components/video/captions.ts
3369
+ var CAPTION_LOCALES = ["en", "es", "pt"];
3370
+ var LIVE_CUE_EXTRA_LAG_MS = 2e3;
3371
+ var LIVE_STACK_MAX_CUES = 150;
3372
+ var CAPTION_CHARS_PER_SECOND = 17;
3373
+ var CAPTION_MIN_DWELL_MS = 1200;
3374
+ var CAPTION_MAX_DWELL_MS = 6e3;
3375
+ var CAPTION_RUSH_DWELL_MS = 2500;
3376
+ var CAPTION_MAX_CHARS_PER_LINE = 42;
3377
+ var CAPTION_COMPACT_CHARS_PER_LINE = 32;
3378
+ var CAPTION_MAX_LINES = 2;
3379
+ var CAPTION_BACKLOG_DROP = 8;
3380
+ var CAPTION_GAP_FILL_MS = 1e3;
3381
+ var LIVE_LAG_SPIKE_MS = 2500;
3382
+ var CAPTION_BREAK_PUNCT = /[.,;:?!]$/;
3383
+ var CAPTION_MIN_PUNCT_LINE = 8;
3384
+ var EMPTY_LIVE_CAPTION_PLAYOUT = {
3385
+ screen: null,
3386
+ hideAt: 0,
3387
+ cursor: 0,
3388
+ queue: []
3389
+ };
3390
+ function stabilizeLiveLagMs(previous, next) {
3391
+ if (previous == null || !Number.isFinite(previous)) return next;
3392
+ if (next <= previous) return next;
3393
+ if (next - previous < LIVE_LAG_SPIKE_MS) return previous;
3394
+ return next;
3395
+ }
3396
+ function isCaptionLocale(value) {
3397
+ return CAPTION_LOCALES.includes(value);
3398
+ }
3399
+ function isLivePlaylistSrc(src) {
3400
+ return /\/live\//i.test(src);
3401
+ }
3402
+ function captionsVttUrlFromPlayback(src, locale) {
3403
+ const trimmed = src.trim();
3404
+ if (!trimmed) return null;
3405
+ const replaced = trimmed.replace(
3406
+ /index\.m3u8(?:\?.*)?$/i,
3407
+ `subs/${locale}.vtt`
3408
+ );
3409
+ if (replaced === trimmed) return null;
3410
+ return replaced;
3411
+ }
3412
+ function liveCaptionsUrl(base, locale) {
3413
+ return `${base.replace(/\/$/, "")}/${locale}`;
3414
+ }
3415
+ function parseCaptionVtt(text) {
3416
+ const cues = [];
3417
+ const blocks = text.replace(/^\uFEFF?WEBVTT[^\n]*\n/i, "").split(/\n\s*\n/);
3418
+ for (const block of blocks) {
3419
+ const lines = block.split("\n").map((line) => line.trim()).filter(Boolean);
3420
+ const timing = lines.find((line) => line.includes("-->"));
3421
+ if (!timing) continue;
3422
+ const [startRaw, endRaw] = timing.split("-->").map((part) => part.trim());
3423
+ if (!startRaw || !endRaw) continue;
3424
+ const textLines = lines.filter(
3425
+ (line) => line !== timing && !/^\d+$/.test(line)
3426
+ );
3427
+ const payload = textLines.join("\n").trim();
3428
+ if (!payload) continue;
3429
+ cues.push({
3430
+ start: parseVttTimestamp(startRaw.split(" ")[0] ?? startRaw),
3431
+ end: parseVttTimestamp(endRaw.split(" ")[0] ?? endRaw),
3432
+ text: payload
3433
+ });
3372
3434
  }
3373
- return defaultRetry;
3435
+ return cues;
3374
3436
  }
3375
- var liveEdgeErrorRetry = {
3376
- maxNumRetry: 8,
3377
- retryDelayMs: 250,
3378
- maxRetryDelayMs: 4e3,
3379
- backoff: "exponential",
3380
- shouldRetry: shouldRetryLiveEdge404
3381
- };
3382
- function createLiveHlsConfig() {
3383
- return {
3384
- enableWorker: true,
3385
- // No custom request headers: Cache-Control/Pragma are not
3386
- // CORS-safelisted and would force an OPTIONS preflight before every
3387
- // manifest poll and segment fetch. Freshness is controlled by the
3388
- // origin's response Cache-Control headers instead.
3389
- liveSyncDurationCount: 4,
3390
- liveMaxLatencyDurationCount: 12,
3391
- fragLoadPolicy: {
3392
- default: {
3393
- maxTimeToFirstByteMs: 1e4,
3394
- maxLoadTimeMs: 12e4,
3395
- timeoutRetry: {
3396
- maxNumRetry: 4,
3397
- retryDelayMs: 0,
3398
- maxRetryDelayMs: 0
3399
- },
3400
- errorRetry: liveEdgeErrorRetry
3401
- }
3402
- },
3403
- playlistLoadPolicy: {
3404
- default: {
3405
- maxTimeToFirstByteMs: 1e4,
3406
- maxLoadTimeMs: 3e4,
3407
- timeoutRetry: {
3408
- maxNumRetry: 2,
3409
- retryDelayMs: 0,
3410
- maxRetryDelayMs: 0
3411
- },
3412
- errorRetry: {
3413
- ...liveEdgeErrorRetry,
3414
- maxNumRetry: 6
3437
+ function captionScreenRow(text, speaker) {
3438
+ return speaker == null ? { text } : { text, speaker };
3439
+ }
3440
+ function chunkLongWord(word, maxCharsPerLine) {
3441
+ if (word.length <= maxCharsPerLine) return [word];
3442
+ const parts = [];
3443
+ for (let index = 0; index < word.length; index += maxCharsPerLine) {
3444
+ parts.push(word.slice(index, index + maxCharsPerLine));
3445
+ }
3446
+ return parts;
3447
+ }
3448
+ function wrapCaptionLines(text, maxCharsPerLine) {
3449
+ const tokens = text.split(" ").filter(Boolean).flatMap((word) => chunkLongWord(word, maxCharsPerLine));
3450
+ const lines = [];
3451
+ let index = 0;
3452
+ while (index < tokens.length) {
3453
+ let end = index;
3454
+ let length = 0;
3455
+ while (end < tokens.length) {
3456
+ const added = tokens[end].length + (end > index ? 1 : 0);
3457
+ if (length + added > maxCharsPerLine && end > index) break;
3458
+ length += added;
3459
+ end += 1;
3460
+ }
3461
+ let breakAt = end;
3462
+ if (end < tokens.length) {
3463
+ for (let cursor = end - 1; cursor > index; cursor -= 1) {
3464
+ if (!CAPTION_BREAK_PUNCT.test(tokens[cursor])) continue;
3465
+ const firstLen = tokens.slice(index, cursor + 1).join(" ").length;
3466
+ if (firstLen >= Math.min(CAPTION_MIN_PUNCT_LINE, maxCharsPerLine)) {
3467
+ breakAt = cursor + 1;
3415
3468
  }
3469
+ break;
3416
3470
  }
3417
3471
  }
3418
- };
3472
+ lines.push(tokens.slice(index, breakAt).join(" "));
3473
+ index = breakAt;
3474
+ }
3475
+ return lines;
3419
3476
  }
3420
- function createVodHlsConfig() {
3421
- return {
3422
- enableWorker: true,
3423
- startPosition: 0
3424
- };
3477
+ function balanceCaptionLines(lines, maxCharsPerLine) {
3478
+ const next = [...lines];
3479
+ for (let index = 0; index + 1 < next.length; index += CAPTION_MAX_LINES) {
3480
+ const left = next[index].split(" ");
3481
+ const right = next[index + 1].split(" ");
3482
+ if (right.length !== 1 || left.length < 3) continue;
3483
+ const moved = left[left.length - 1];
3484
+ const newRight = `${moved} ${right[0]}`;
3485
+ if (newRight.length > maxCharsPerLine) continue;
3486
+ next[index] = left.slice(0, -1).join(" ");
3487
+ next[index + 1] = newRight;
3488
+ }
3489
+ return next;
3425
3490
  }
3426
-
3427
- // src/components/video/hls-errors.ts
3428
- var MEDIA_ERROR_NAMES = {
3429
- 1: "MEDIA_ERR_ABORTED",
3430
- 2: "MEDIA_ERR_NETWORK",
3431
- 3: "MEDIA_ERR_DECODE",
3432
- 4: "MEDIA_ERR_SRC_NOT_SUPPORTED"
3433
- };
3434
- var MEDIA_ERR_NETWORK = 2;
3435
- var MEDIA_ERR_DECODE = 3;
3436
- var MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
3437
- function errorMessageFromUnknown(error) {
3438
- if (error instanceof Error) return error.message;
3439
- if (typeof error === "string") return error;
3440
- return void 0;
3491
+ function splitCaptionScreens(text, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
3492
+ const trimmed = text.trim().replace(/\s+/g, " ");
3493
+ if (!trimmed) return [];
3494
+ const lines = balanceCaptionLines(
3495
+ wrapCaptionLines(trimmed, maxCharsPerLine),
3496
+ maxCharsPerLine
3497
+ );
3498
+ const screens = [];
3499
+ for (let index = 0; index < lines.length; index += CAPTION_MAX_LINES) {
3500
+ screens.push(lines.slice(index, index + CAPTION_MAX_LINES).join("\n"));
3501
+ }
3502
+ return screens;
3441
3503
  }
3442
- function isNotFound(httpStatus, details) {
3443
- return httpStatus === 404 || details === "manifestLoadError" || details === "levelLoadError" || details === "fragLoadError";
3504
+ function captionDwellMs(text, backlog = 0) {
3505
+ const chars = text.replace(/\s+/g, " ").trim().length;
3506
+ const raw = chars / CAPTION_CHARS_PER_SECOND * 1e3;
3507
+ const max = backlog > 0 ? CAPTION_RUSH_DWELL_MS : CAPTION_MAX_DWELL_MS;
3508
+ return Math.min(max, Math.max(CAPTION_MIN_DWELL_MS, raw));
3444
3509
  }
3445
- function kindForHls(input) {
3446
- const httpStatus = input.response?.code;
3447
- if (input.type === "networkError" && isNotFound(httpStatus, input.details)) {
3448
- return input.context.mode === "vod" || !input.context.manifestParsed ? "unavailable" : "network";
3510
+ function advanceLiveCaptionPlayout(state, cues, now, lagMs, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
3511
+ let screen = state.screen;
3512
+ let hideAt = state.hideAt;
3513
+ let cursor = state.cursor;
3514
+ let queue = state.queue.slice();
3515
+ if (lagMs != null && Number.isFinite(lagMs) && lagMs >= 0) {
3516
+ const threshold = lagMs + LIVE_CUE_EXTRA_LAG_MS;
3517
+ const incoming = cues.filter(
3518
+ (cue) => Boolean(cue.text.trim()) && Number.isFinite(cue.receivedAt) && cue.receivedAt > cursor && now - cue.receivedAt >= threshold
3519
+ ).sort((left, right) => left.receivedAt - right.receivedAt);
3520
+ for (const cue of incoming) {
3521
+ for (const text of splitCaptionScreens(cue.text, maxCharsPerLine)) {
3522
+ queue.push(captionScreenRow(text, cue.speaker));
3523
+ }
3524
+ cursor = cue.receivedAt;
3525
+ }
3526
+ if (queue.length > CAPTION_BACKLOG_DROP) {
3527
+ queue = queue.slice(queue.length - CAPTION_BACKLOG_DROP);
3528
+ }
3449
3529
  }
3450
- if (input.type === "mediaError" || input.details === "bufferAppendError" || input.details === "bufferSeekOverHole") {
3451
- return "media";
3530
+ if (now >= hideAt) {
3531
+ const next = queue.shift();
3532
+ if (next) {
3533
+ screen = next;
3534
+ hideAt = now + captionDwellMs(next.text, queue.length);
3535
+ } else {
3536
+ screen = null;
3537
+ }
3452
3538
  }
3453
- return "generic";
3539
+ return { screen, hideAt, cursor, queue };
3454
3540
  }
3455
- function kindForNative(input) {
3456
- const code = input.mediaError?.code;
3457
- if (code === MEDIA_ERR_DECODE) return "media";
3458
- if (code === MEDIA_ERR_SRC_NOT_SUPPORTED) return "unsupported";
3459
- if (code === MEDIA_ERR_NETWORK) return "unavailable";
3460
- return "generic";
3541
+ function cueEndWithGapFill(cues, index) {
3542
+ const cue = cues[index];
3543
+ if (!cue) return 0;
3544
+ const next = cues[index + 1];
3545
+ if (!next || !Number.isFinite(next.start)) return cue.end;
3546
+ const gapMs = (next.start - cue.end) * 1e3;
3547
+ if (gapMs > 0 && gapMs < CAPTION_GAP_FILL_MS) return next.start;
3548
+ return cue.end;
3461
3549
  }
3462
- function describeAvResync(input) {
3463
- const lag = Number.isFinite(input.lagSeconds) ? input.lagSeconds : 0;
3464
- return {
3465
- summary: `av-resync lag=${lag.toFixed(3)}s (non-fatal)`,
3466
- kind: "resync",
3467
- detail: {
3468
- source: input.context.source,
3469
- kind: "resync",
3470
- fatal: false,
3471
- reason: `presented frame lag ${lag.toFixed(3)}s`,
3472
- context: input.context
3550
+ function captionScreenAtTime(cues, time, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
3551
+ if (!Number.isFinite(time)) return null;
3552
+ const ordered = cues.filter(
3553
+ (cue) => Boolean(cue.text.trim()) && Number.isFinite(cue.start) && Number.isFinite(cue.end)
3554
+ ).sort((left, right) => left.start - right.start);
3555
+ for (let index = 0; index < ordered.length; index += 1) {
3556
+ const cue = ordered[index];
3557
+ const end = cueEndWithGapFill(ordered, index);
3558
+ if (time < cue.start || time >= end) continue;
3559
+ const screens = splitCaptionScreens(cue.text, maxCharsPerLine);
3560
+ if (screens.length === 0) return null;
3561
+ const weights = screens.map(
3562
+ (text) => Math.max(1, text.replace(/\s+/g, "").length)
3563
+ );
3564
+ const total = weights.reduce((sum, weight) => sum + weight, 0);
3565
+ const duration = Math.max(end - cue.start, 0);
3566
+ let cursor = cue.start;
3567
+ for (let screenIndex = 0; screenIndex < screens.length; screenIndex += 1) {
3568
+ const isLast = screenIndex === screens.length - 1;
3569
+ const slice = isLast ? end - cursor : duration * (weights[screenIndex] / total);
3570
+ const sliceEnd = cursor + slice;
3571
+ if (time >= cursor && time < sliceEnd) {
3572
+ return captionScreenRow(screens[screenIndex]);
3573
+ }
3574
+ cursor = sliceEnd;
3473
3575
  }
3474
- };
3576
+ return captionScreenRow(screens[screens.length - 1]);
3577
+ }
3578
+ return null;
3475
3579
  }
3476
- function describePlaybackError(input) {
3477
- if (input.source === "unsupported") {
3478
- return {
3479
- summary: "playback unsupported (hls.js unavailable, native HLS unsupported)",
3480
- kind: "unsupported",
3481
- detail: {
3482
- source: "unsupported",
3483
- kind: "unsupported",
3484
- context: input.context
3580
+ var LIVE_OVERLAP_MIN_WORDS = 4;
3581
+ function normalizeLiveCaptionText(text) {
3582
+ return text.trim().replace(/\s+/g, " ").toLowerCase();
3583
+ }
3584
+ function lastSubseqIndex(haystack, needle) {
3585
+ if (needle.length === 0 || needle.length > haystack.length) return -1;
3586
+ let found = -1;
3587
+ for (let index = 0; index <= haystack.length - needle.length; index += 1) {
3588
+ let match = true;
3589
+ for (let offset = 0; offset < needle.length; offset += 1) {
3590
+ if (haystack[index + offset] !== needle[offset]) {
3591
+ match = false;
3592
+ break;
3485
3593
  }
3486
- };
3487
- }
3488
- if (input.source === "native") {
3489
- const code = input.mediaError?.code;
3490
- const kind2 = kindForNative(input);
3491
- const detail2 = {
3492
- source: "native",
3493
- kind: kind2,
3494
- mediaErrorCode: code,
3495
- mediaErrorName: code !== void 0 ? MEDIA_ERROR_NAMES[code] : void 0,
3496
- errorMessage: input.mediaError?.message,
3497
- context: input.context
3498
- };
3499
- const name = detail2.mediaErrorName ?? "MEDIA_ERR_UNKNOWN";
3500
- return {
3501
- summary: `native ${name}${input.mediaError?.message ? `: ${input.mediaError.message}` : ""}`,
3502
- kind: kind2,
3503
- detail: detail2
3504
- };
3594
+ }
3595
+ if (match) found = index;
3505
3596
  }
3506
- const httpStatus = input.response?.code;
3507
- const kind = kindForHls(input);
3508
- const detail = {
3509
- source: "hls",
3510
- kind,
3511
- type: input.type,
3512
- details: input.details,
3513
- fatal: input.fatal,
3514
- httpStatus,
3515
- url: input.url,
3516
- reason: input.reason,
3517
- errorMessage: errorMessageFromUnknown(input.error),
3518
- context: input.context
3519
- };
3520
- const statusSuffix = httpStatus !== void 0 ? ` ${httpStatus}` : "";
3521
- const summary = [
3522
- "hls",
3523
- input.type ?? "unknown",
3524
- input.details ?? "unknown",
3525
- input.fatal ? "(fatal)" : "(non-fatal)",
3526
- statusSuffix.trim()
3527
- ].filter(Boolean).join(" ");
3528
- return { summary, kind, detail };
3597
+ return found;
3529
3598
  }
3530
-
3531
- // src/components/video/useHlsPlayback.ts
3532
- var RETRY_INTERVAL_MS = 3e3;
3533
- var MAX_MEDIA_ERROR_RETRIES = 5;
3534
- var DRIFT_THRESHOLD_S = 0.4;
3535
- var DRIFT_CONSECUTIVE_SAMPLES = 3;
3536
- var RESYNC_COOLDOWN_MS = 1e4;
3537
- var LIVE_EDGE_RESYNC_THRESHOLD_S = 8;
3538
- function useHlsPlayback({
3539
- src,
3540
- mode,
3541
- active,
3542
- autoPlay = false,
3543
- muted = false,
3544
- onError,
3545
- onPlayingChange
3546
- }) {
3547
- const videoRef = React9.useRef(null);
3548
- const hlsRef = React9.useRef(null);
3549
- const [state, setState] = React9.useState("idle");
3550
- const [qualities, setQualities] = React9.useState([]);
3551
- const [activeLevel, setActiveLevel] = React9.useState(-1);
3552
- const [autoplayState, setAutoplayState] = React9.useState("none");
3553
- const [error, setError] = React9.useState(null);
3554
- const [reloadKey, setReloadKey] = React9.useState(0);
3555
- const onErrorRef = React9.useRef(onError);
3556
- const onPlayingChangeRef = React9.useRef(onPlayingChange);
3557
- React9.useEffect(() => {
3558
- onErrorRef.current = onError;
3559
- onPlayingChangeRef.current = onPlayingChange;
3560
- }, [onError, onPlayingChange]);
3561
- const retry = React9.useCallback(() => {
3562
- setError(null);
3563
- setState("loading");
3564
- setAutoplayState("none");
3565
- setReloadKey((k) => k + 1);
3566
- }, []);
3567
- React9.useEffect(() => {
3568
- const media = videoRef.current;
3569
- if (!media || !src || !active) {
3570
- setState("idle");
3571
- return;
3572
- }
3573
- let cancelled = false;
3574
- let retryTimer = null;
3575
- let manifestParsed = false;
3576
- let mediaErrorRetries = 0;
3577
- let playbackSource = "hls";
3578
- const teardown = [];
3579
- applyMute(media);
3580
- setState("loading");
3581
- setError(null);
3582
- setAutoplayState("none");
3583
- setQualities([]);
3584
- setActiveLevel(-1);
3585
- function baseContext() {
3586
- return {
3587
- mode,
3588
- src,
3589
- manifestParsed,
3590
- retryCount: mediaErrorRetries,
3591
- source: playbackSource
3592
- };
3593
- }
3594
- function clearRetryTimer() {
3595
- if (retryTimer !== null) {
3596
- clearTimeout(retryTimer);
3597
- retryTimer = null;
3599
+ function remainderAfterOverlap(previous, next) {
3600
+ const prevWords = normalizeLiveCaptionText(previous).split(" ").filter(Boolean);
3601
+ const nextWords = next.trim().replace(/\s+/g, " ").split(" ").filter(Boolean);
3602
+ const nextNorm = nextWords.map((word) => word.toLowerCase());
3603
+ const maxN = Math.min(prevWords.length, nextNorm.length);
3604
+ for (let size = maxN; size >= LIVE_OVERLAP_MIN_WORDS; size -= 1) {
3605
+ for (let start = prevWords.length - size; start >= 0; start -= 1) {
3606
+ const gram = prevWords.slice(start, start + size);
3607
+ const index = lastSubseqIndex(nextNorm, gram);
3608
+ if (index !== -1) {
3609
+ return nextWords.slice(index + size).join(" ");
3598
3610
  }
3599
3611
  }
3600
- function destroyHls() {
3601
- hlsRef.current?.destroy();
3602
- hlsRef.current = null;
3603
- }
3604
- function reportFatal(input) {
3605
- const described = describePlaybackError(input);
3606
- onErrorRef.current?.(described);
3607
- setError(described);
3608
- setState("error");
3609
- }
3610
- function applyMute(el) {
3611
- el.muted = muted;
3612
+ }
3613
+ return null;
3614
+ }
3615
+ function liveCaptionRow(text, receivedAt, speaker) {
3616
+ return speaker == null ? { text, receivedAt } : { text, receivedAt, speaker };
3617
+ }
3618
+ function coalesceLiveCaptionCues(cues) {
3619
+ const out = [];
3620
+ for (const cue of cues) {
3621
+ const text = cue.text.trim();
3622
+ if (!text) continue;
3623
+ const last = out[out.length - 1];
3624
+ if (!last) {
3625
+ out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
3626
+ continue;
3612
3627
  }
3613
- function preserveMute(el, fn) {
3614
- const wasMuted = el.muted;
3615
- fn();
3616
- el.muted = wasMuted;
3628
+ if (last.speaker !== cue.speaker && (last.speaker != null || cue.speaker != null)) {
3629
+ out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
3630
+ continue;
3617
3631
  }
3618
- function attemptAutoplay(el) {
3619
- applyMute(el);
3620
- void el.play().then(
3621
- () => {
3622
- applyMute(el);
3623
- setAutoplayState("playing");
3624
- },
3625
- () => {
3626
- el.muted = true;
3627
- void el.play().then(
3628
- () => setAutoplayState(muted ? "playing" : "muted"),
3629
- () => {
3630
- if (el.paused) {
3631
- setAutoplayState("blocked");
3632
- return;
3633
- }
3634
- setAutoplayState(el.muted && !muted ? "muted" : "playing");
3635
- }
3636
- );
3637
- }
3632
+ const lastNorm = normalizeLiveCaptionText(last.text);
3633
+ const nextNorm = normalizeLiveCaptionText(text);
3634
+ if (lastNorm === nextNorm) continue;
3635
+ if (nextNorm.startsWith(lastNorm) || lastNorm.startsWith(nextNorm)) {
3636
+ out[out.length - 1] = liveCaptionRow(
3637
+ nextNorm.length >= lastNorm.length ? text : last.text,
3638
+ cue.receivedAt,
3639
+ cue.speaker ?? last.speaker
3638
3640
  );
3641
+ continue;
3639
3642
  }
3640
- function scheduleRetry(retryFn) {
3641
- clearRetryTimer();
3642
- if (cancelled) return;
3643
- setState("waiting");
3644
- retryTimer = setTimeout(() => {
3645
- retryTimer = null;
3646
- if (!cancelled) retryFn();
3647
- }, RETRY_INTERVAL_MS);
3643
+ const remainder = remainderAfterOverlap(last.text, text);
3644
+ if (remainder !== null) {
3645
+ if (!remainder) continue;
3646
+ out.push(liveCaptionRow(remainder, cue.receivedAt, cue.speaker));
3647
+ continue;
3648
3648
  }
3649
- function startDriftWatchdog(el) {
3650
- if (typeof el.requestVideoFrameCallback !== "function") return;
3651
- let consecutiveLagSamples = 0;
3652
- let lastResyncAt = 0;
3653
- let handle = null;
3654
- const tick = (_now, metadata) => {
3655
- if (cancelled) return;
3656
- handle = el.requestVideoFrameCallback(tick);
3657
- if (el.paused || el.ended) {
3658
- consecutiveLagSamples = 0;
3659
- return;
3660
- }
3661
- const lag = el.currentTime - metadata.mediaTime;
3662
- if (!(lag > DRIFT_THRESHOLD_S)) {
3663
- consecutiveLagSamples = 0;
3664
- return;
3665
- }
3666
- consecutiveLagSamples += 1;
3667
- if (consecutiveLagSamples < DRIFT_CONSECUTIVE_SAMPLES) return;
3668
- const nowMs = performance.now();
3669
- if (nowMs - lastResyncAt < RESYNC_COOLDOWN_MS) return;
3670
- lastResyncAt = nowMs;
3671
- consecutiveLagSamples = 0;
3672
- if (mode === "live" && el.seekable.length > 0) {
3673
- const edge = el.seekable.end(el.seekable.length - 1);
3674
- if (edge - el.currentTime > LIVE_EDGE_RESYNC_THRESHOLD_S) {
3675
- el.currentTime = edge;
3676
- } else {
3677
- el.currentTime = el.currentTime + 1e-3;
3678
- }
3679
- } else {
3680
- el.currentTime = el.currentTime + 1e-3;
3681
- }
3682
- onErrorRef.current?.(
3683
- describeAvResync({
3684
- lagSeconds: lag,
3685
- context: baseContext()
3686
- })
3687
- );
3688
- };
3689
- handle = el.requestVideoFrameCallback(tick);
3690
- teardown.push(() => {
3691
- if (handle != null && typeof el.cancelVideoFrameCallback === "function") {
3692
- el.cancelVideoFrameCallback(handle);
3693
- }
3694
- });
3695
- }
3696
- function onPlaying() {
3697
- manifestParsed = true;
3698
- mediaErrorRetries = 0;
3699
- clearRetryTimer();
3700
- setState("ready");
3701
- setAutoplayState(
3702
- (prev) => prev === "blocked" || prev === "none" ? "playing" : prev
3703
- );
3704
- onPlayingChangeRef.current?.(true);
3705
- }
3706
- function onPaused() {
3707
- onPlayingChangeRef.current?.(false);
3708
- }
3709
- media.addEventListener("playing", onPlaying);
3710
- media.addEventListener("pause", onPaused);
3711
- media.addEventListener("ended", onPaused);
3712
- teardown.push(() => {
3713
- media.removeEventListener("playing", onPlaying);
3714
- media.removeEventListener("pause", onPaused);
3715
- media.removeEventListener("ended", onPaused);
3716
- });
3717
- startDriftWatchdog(media);
3718
- function initNative() {
3719
- playbackSource = "native";
3720
- manifestParsed = false;
3721
- media.removeAttribute("src");
3722
- media.load();
3723
- media.src = src;
3724
- applyMute(media);
3725
- const onReady = () => {
3726
- manifestParsed = true;
3727
- clearRetryTimer();
3728
- setState("ready");
3729
- if (mode === "live" || autoPlay) attemptAutoplay(media);
3730
- };
3731
- const onErr = () => {
3732
- if (manifestParsed) {
3733
- reportFatal({
3734
- source: "native",
3735
- mediaError: media.error,
3736
- context: baseContext()
3737
- });
3738
- return;
3739
- }
3740
- onErrorRef.current?.(
3741
- describePlaybackError({
3742
- source: "native",
3743
- mediaError: media.error,
3744
- context: baseContext()
3745
- })
3746
- );
3747
- scheduleRetry(() => {
3748
- media.src = src;
3749
- media.load();
3750
- });
3751
- };
3752
- media.addEventListener("loadedmetadata", onReady);
3753
- media.addEventListener("error", onErr);
3754
- teardown.push(() => {
3755
- media.removeEventListener("loadedmetadata", onReady);
3756
- media.removeEventListener("error", onErr);
3757
- });
3758
- }
3759
- function initHlsJs(Hls) {
3760
- playbackSource = "hls";
3761
- destroyHls();
3762
- manifestParsed = false;
3763
- const config = mode === "live" ? createLiveHlsConfig() : createVodHlsConfig();
3764
- const hls = new Hls(config);
3765
- hlsRef.current = hls;
3766
- hls.loadSource(src);
3767
- hls.attachMedia(media);
3768
- applyMute(media);
3769
- hls.on(Hls.Events.MANIFEST_PARSED, (_e, data) => {
3770
- manifestParsed = true;
3771
- clearRetryTimer();
3772
- setQualities(
3773
- data.levels.map((l, index) => ({ index, height: l.height }))
3774
- );
3775
- setState("ready");
3776
- if (mode === "live" || autoPlay) attemptAutoplay(media);
3777
- });
3778
- hls.on(Hls.Events.LEVEL_SWITCHED, (_e, data) => {
3779
- if (hls.autoLevelEnabled) setActiveLevel(-1);
3780
- else setActiveLevel(data.level);
3781
- });
3782
- hls.on(Hls.Events.ERROR, (_e, data) => {
3783
- onErrorRef.current?.(
3784
- describePlaybackError({
3785
- source: "hls",
3786
- type: data.type,
3787
- details: data.details,
3788
- fatal: data.fatal,
3789
- url: data.url,
3790
- response: data.response,
3791
- reason: data.reason,
3792
- error: data.error,
3793
- context: baseContext()
3794
- })
3795
- );
3796
- if (!data.fatal) return;
3797
- if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
3798
- if (!manifestParsed) {
3799
- scheduleRetry(() => initHlsJs(Hls));
3800
- return;
3801
- }
3802
- hls.startLoad();
3803
- return;
3804
- }
3805
- mediaErrorRetries += 1;
3806
- if (mediaErrorRetries === 1) {
3807
- preserveMute(media, () => hls.recoverMediaError());
3808
- return;
3809
- }
3810
- if (mediaErrorRetries === 2) {
3811
- preserveMute(media, () => {
3812
- hls.swapAudioCodec();
3813
- hls.recoverMediaError();
3814
- });
3815
- return;
3816
- }
3817
- if (mediaErrorRetries < MAX_MEDIA_ERROR_RETRIES) {
3818
- scheduleRetry(() => initHlsJs(Hls));
3819
- return;
3820
- }
3821
- reportFatal({
3822
- source: "hls",
3823
- type: data.type,
3824
- details: data.details,
3825
- fatal: true,
3826
- url: data.url,
3827
- response: data.response,
3828
- reason: data.reason,
3829
- error: data.error,
3830
- context: baseContext()
3831
- });
3832
- });
3833
- }
3834
- async function setup() {
3835
- let Hls = null;
3836
- try {
3837
- Hls = (await import('hls.js')).default;
3838
- } catch {
3839
- Hls = null;
3840
- }
3841
- if (cancelled) return;
3842
- if (Hls && Hls.isSupported()) {
3843
- initHlsJs(Hls);
3844
- } else if (media.canPlayType("application/vnd.apple.mpegurl")) {
3845
- initNative();
3846
- } else {
3847
- playbackSource = "unsupported";
3848
- reportFatal({
3849
- source: "unsupported",
3850
- context: baseContext()
3851
- });
3852
- }
3853
- }
3854
- void setup();
3855
- return () => {
3856
- cancelled = true;
3857
- clearRetryTimer();
3858
- for (const fn of teardown) fn();
3859
- destroyHls();
3860
- };
3861
- }, [src, mode, active, autoPlay, muted, reloadKey]);
3862
- const setLevel = React9.useCallback((index) => {
3863
- const hls = hlsRef.current;
3864
- if (!hls) return;
3865
- hls.nextLevel = index;
3866
- setActiveLevel(index);
3867
- }, []);
3868
- return {
3869
- videoRef,
3870
- state,
3871
- qualities,
3872
- activeLevel,
3873
- setLevel,
3874
- autoplayState,
3875
- error,
3876
- retry
3877
- };
3878
- }
3879
-
3880
- // src/components/video/captions.ts
3881
- var CAPTION_LOCALES = ["en", "es", "pt"];
3882
- var LIVE_CUE_EXTRA_LAG_MS = 2e3;
3883
- var LIVE_STACK_MAX_CUES = 150;
3884
- var CAPTION_CHARS_PER_SECOND = 17;
3885
- var CAPTION_MIN_DWELL_MS = 1200;
3886
- var CAPTION_MAX_DWELL_MS = 6e3;
3887
- var CAPTION_RUSH_DWELL_MS = 2500;
3888
- var CAPTION_MAX_CHARS_PER_LINE = 42;
3889
- var CAPTION_COMPACT_CHARS_PER_LINE = 32;
3890
- var CAPTION_MAX_LINES = 2;
3891
- var CAPTION_BACKLOG_DROP = 8;
3892
- var CAPTION_GAP_FILL_MS = 1e3;
3893
- var LIVE_LAG_SPIKE_MS = 2500;
3894
- var CAPTION_BREAK_PUNCT = /[.,;:?!]$/;
3895
- var CAPTION_MIN_PUNCT_LINE = 8;
3896
- var EMPTY_LIVE_CAPTION_PLAYOUT = {
3897
- screen: null,
3898
- hideAt: 0,
3899
- cursor: 0,
3900
- queue: []
3901
- };
3902
- function stabilizeLiveLagMs(previous, next) {
3903
- if (previous == null || !Number.isFinite(previous)) return next;
3904
- if (next <= previous) return next;
3905
- if (next - previous < LIVE_LAG_SPIKE_MS) return previous;
3906
- return next;
3907
- }
3908
- function isCaptionLocale(value) {
3909
- return CAPTION_LOCALES.includes(value);
3910
- }
3911
- function captionsVttUrlFromPlayback(src, locale) {
3912
- const trimmed = src.trim();
3913
- if (!trimmed) return null;
3914
- const replaced = trimmed.replace(
3915
- /index\.m3u8(?:\?.*)?$/i,
3916
- `subs/${locale}.vtt`
3917
- );
3918
- if (replaced === trimmed) return null;
3919
- return replaced;
3920
- }
3921
- function liveCaptionsUrl(base, locale) {
3922
- return `${base.replace(/\/$/, "")}/${locale}`;
3923
- }
3924
- function parseCaptionVtt(text) {
3925
- const cues = [];
3926
- const blocks = text.replace(/^\uFEFF?WEBVTT[^\n]*\n/i, "").split(/\n\s*\n/);
3927
- for (const block of blocks) {
3928
- const lines = block.split("\n").map((line) => line.trim()).filter(Boolean);
3929
- const timing = lines.find((line) => line.includes("-->"));
3930
- if (!timing) continue;
3931
- const [startRaw, endRaw] = timing.split("-->").map((part) => part.trim());
3932
- if (!startRaw || !endRaw) continue;
3933
- const textLines = lines.filter(
3934
- (line) => line !== timing && !/^\d+$/.test(line)
3935
- );
3936
- const payload = textLines.join("\n").trim();
3937
- if (!payload) continue;
3938
- cues.push({
3939
- start: parseVttTimestamp(startRaw.split(" ")[0] ?? startRaw),
3940
- end: parseVttTimestamp(endRaw.split(" ")[0] ?? endRaw),
3941
- text: payload
3942
- });
3649
+ out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
3943
3650
  }
3944
- return cues;
3651
+ return out;
3945
3652
  }
3946
- function captionScreenRow(text, speaker) {
3947
- return speaker == null ? { text } : { text, speaker };
3653
+ function mergeLiveCaptionCues(existing, incoming, cap = LIVE_STACK_MAX_CUES) {
3654
+ const map = /* @__PURE__ */ new Map();
3655
+ for (const cue of existing) {
3656
+ if (Number.isFinite(cue.receivedAt)) map.set(cue.receivedAt, cue);
3657
+ }
3658
+ for (const cue of incoming) {
3659
+ if (Number.isFinite(cue.receivedAt)) map.set(cue.receivedAt, cue);
3660
+ }
3661
+ return [...map.values()].sort((left, right) => left.receivedAt - right.receivedAt).slice(-Math.max(1, cap));
3948
3662
  }
3949
- function chunkLongWord(word, maxCharsPerLine) {
3950
- if (word.length <= maxCharsPerLine) return [word];
3951
- const parts = [];
3952
- for (let index = 0; index < word.length; index += maxCharsPerLine) {
3953
- parts.push(word.slice(index, index + maxCharsPerLine));
3663
+ async function loadCaptionVtt(url) {
3664
+ try {
3665
+ const response = await fetch(url, { cache: "no-store" });
3666
+ if (!response.ok) return [];
3667
+ return parseCaptionVtt(await response.text());
3668
+ } catch {
3669
+ return [];
3954
3670
  }
3955
- return parts;
3956
3671
  }
3957
- function wrapCaptionLines(text, maxCharsPerLine) {
3958
- const tokens = text.split(" ").filter(Boolean).flatMap((word) => chunkLongWord(word, maxCharsPerLine));
3959
- const lines = [];
3960
- let index = 0;
3961
- while (index < tokens.length) {
3962
- let end = index;
3963
- let length = 0;
3964
- while (end < tokens.length) {
3965
- const added = tokens[end].length + (end > index ? 1 : 0);
3966
- if (length + added > maxCharsPerLine && end > index) break;
3967
- length += added;
3968
- end += 1;
3672
+ async function loadLiveCaptions(url) {
3673
+ try {
3674
+ const response = await fetch(url, {
3675
+ cache: "no-store",
3676
+ headers: { Accept: "application/json" }
3677
+ });
3678
+ if (!response.ok) return { ok: false, cues: [] };
3679
+ const body = await response.json();
3680
+ if (!body || typeof body !== "object" || !("cues" in body)) {
3681
+ return { ok: false, cues: [] };
3969
3682
  }
3970
- let breakAt = end;
3971
- if (end < tokens.length) {
3972
- for (let cursor = end - 1; cursor > index; cursor -= 1) {
3973
- if (!CAPTION_BREAK_PUNCT.test(tokens[cursor])) continue;
3974
- const firstLen = tokens.slice(index, cursor + 1).join(" ").length;
3975
- if (firstLen >= Math.min(CAPTION_MIN_PUNCT_LINE, maxCharsPerLine)) {
3976
- breakAt = cursor + 1;
3977
- }
3978
- break;
3683
+ const rows = body.cues;
3684
+ if (!Array.isArray(rows)) return { ok: false, cues: [] };
3685
+ const cues = [];
3686
+ for (const row of rows) {
3687
+ if (!row || typeof row !== "object") continue;
3688
+ const record = row;
3689
+ if (typeof record.text !== "string" || !record.text.trim()) continue;
3690
+ if (typeof record.receivedAt !== "number" || !Number.isFinite(record.receivedAt)) {
3691
+ continue;
3692
+ }
3693
+ const parsed = {
3694
+ text: record.text.trim(),
3695
+ receivedAt: record.receivedAt
3696
+ };
3697
+ if (typeof record.speaker === "number" && Number.isFinite(record.speaker)) {
3698
+ parsed.speaker = record.speaker;
3979
3699
  }
3700
+ cues.push(parsed);
3980
3701
  }
3981
- lines.push(tokens.slice(index, breakAt).join(" "));
3982
- index = breakAt;
3983
- }
3984
- return lines;
3985
- }
3986
- function balanceCaptionLines(lines, maxCharsPerLine) {
3987
- const next = [...lines];
3988
- for (let index = 0; index + 1 < next.length; index += CAPTION_MAX_LINES) {
3989
- const left = next[index].split(" ");
3990
- const right = next[index + 1].split(" ");
3991
- if (right.length !== 1 || left.length < 3) continue;
3992
- const moved = left[left.length - 1];
3993
- const newRight = `${moved} ${right[0]}`;
3994
- if (newRight.length > maxCharsPerLine) continue;
3995
- next[index] = left.slice(0, -1).join(" ");
3996
- next[index + 1] = newRight;
3702
+ return { ok: true, cues };
3703
+ } catch {
3704
+ return { ok: false, cues: [] };
3997
3705
  }
3998
- return next;
3999
3706
  }
4000
- function splitCaptionScreens(text, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
4001
- const trimmed = text.trim().replace(/\s+/g, " ");
4002
- if (!trimmed) return [];
4003
- const lines = balanceCaptionLines(
4004
- wrapCaptionLines(trimmed, maxCharsPerLine),
4005
- maxCharsPerLine
4006
- );
4007
- const screens = [];
4008
- for (let index = 0; index < lines.length; index += CAPTION_MAX_LINES) {
4009
- screens.push(lines.slice(index, index + CAPTION_MAX_LINES).join("\n"));
3707
+
3708
+ // src/components/video/hls-config.ts
3709
+ function shouldRetryLiveEdge404(retryConfig, retryCount, _isTimeout, loaderResponse, defaultRetry) {
3710
+ if (loaderResponse?.code === 404) {
3711
+ return retryConfig != null && retryCount < retryConfig.maxNumRetry;
4010
3712
  }
4011
- return screens;
4012
- }
4013
- function captionDwellMs(text, backlog = 0) {
4014
- const chars = text.replace(/\s+/g, " ").trim().length;
4015
- const raw = chars / CAPTION_CHARS_PER_SECOND * 1e3;
4016
- const max = backlog > 0 ? CAPTION_RUSH_DWELL_MS : CAPTION_MAX_DWELL_MS;
4017
- return Math.min(max, Math.max(CAPTION_MIN_DWELL_MS, raw));
3713
+ return defaultRetry;
4018
3714
  }
4019
- function advanceLiveCaptionPlayout(state, cues, now, lagMs, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
4020
- let screen = state.screen;
4021
- let hideAt = state.hideAt;
4022
- let cursor = state.cursor;
4023
- let queue = state.queue.slice();
4024
- if (lagMs != null && Number.isFinite(lagMs) && lagMs >= 0) {
4025
- const threshold = lagMs + LIVE_CUE_EXTRA_LAG_MS;
4026
- const incoming = cues.filter(
4027
- (cue) => Boolean(cue.text.trim()) && Number.isFinite(cue.receivedAt) && cue.receivedAt > cursor && now - cue.receivedAt >= threshold
4028
- ).sort((left, right) => left.receivedAt - right.receivedAt);
4029
- for (const cue of incoming) {
4030
- for (const text of splitCaptionScreens(cue.text, maxCharsPerLine)) {
4031
- queue.push(captionScreenRow(text, cue.speaker));
3715
+ var liveEdgeErrorRetry = {
3716
+ maxNumRetry: 8,
3717
+ retryDelayMs: 250,
3718
+ maxRetryDelayMs: 4e3,
3719
+ backoff: "exponential",
3720
+ shouldRetry: shouldRetryLiveEdge404
3721
+ };
3722
+ function createLiveHlsConfig() {
3723
+ return {
3724
+ enableWorker: true,
3725
+ // No custom request headers: Cache-Control/Pragma are not
3726
+ // CORS-safelisted and would force an OPTIONS preflight before every
3727
+ // manifest poll and segment fetch. Freshness is controlled by the
3728
+ // origin's response Cache-Control headers instead.
3729
+ liveSyncDurationCount: 4,
3730
+ liveMaxLatencyDurationCount: 12,
3731
+ fragLoadPolicy: {
3732
+ default: {
3733
+ maxTimeToFirstByteMs: 1e4,
3734
+ maxLoadTimeMs: 12e4,
3735
+ timeoutRetry: {
3736
+ maxNumRetry: 4,
3737
+ retryDelayMs: 0,
3738
+ maxRetryDelayMs: 0
3739
+ },
3740
+ errorRetry: liveEdgeErrorRetry
3741
+ }
3742
+ },
3743
+ playlistLoadPolicy: {
3744
+ default: {
3745
+ maxTimeToFirstByteMs: 1e4,
3746
+ maxLoadTimeMs: 3e4,
3747
+ timeoutRetry: {
3748
+ maxNumRetry: 2,
3749
+ retryDelayMs: 0,
3750
+ maxRetryDelayMs: 0
3751
+ },
3752
+ errorRetry: {
3753
+ ...liveEdgeErrorRetry,
3754
+ maxNumRetry: 6
3755
+ }
4032
3756
  }
4033
- cursor = cue.receivedAt;
4034
- }
4035
- if (queue.length > CAPTION_BACKLOG_DROP) {
4036
- queue = queue.slice(queue.length - CAPTION_BACKLOG_DROP);
4037
3757
  }
3758
+ };
3759
+ }
3760
+ function createVodHlsConfig() {
3761
+ return {
3762
+ enableWorker: true,
3763
+ startPosition: 0
3764
+ };
3765
+ }
3766
+
3767
+ // src/components/video/hls-errors.ts
3768
+ var MEDIA_ERROR_NAMES = {
3769
+ 1: "MEDIA_ERR_ABORTED",
3770
+ 2: "MEDIA_ERR_NETWORK",
3771
+ 3: "MEDIA_ERR_DECODE",
3772
+ 4: "MEDIA_ERR_SRC_NOT_SUPPORTED"
3773
+ };
3774
+ var MEDIA_ERR_NETWORK = 2;
3775
+ var MEDIA_ERR_DECODE = 3;
3776
+ var MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
3777
+ function errorMessageFromUnknown(error) {
3778
+ if (error instanceof Error) return error.message;
3779
+ if (typeof error === "string") return error;
3780
+ return void 0;
3781
+ }
3782
+ function isNotFound(httpStatus, details) {
3783
+ return httpStatus === 404 || details === "manifestLoadError" || details === "levelLoadError" || details === "fragLoadError";
3784
+ }
3785
+ function kindForHls(input) {
3786
+ const httpStatus = input.response?.code;
3787
+ if (input.type === "networkError" && isNotFound(httpStatus, input.details)) {
3788
+ return input.context.mode === "vod" || !input.context.manifestParsed ? "unavailable" : "network";
4038
3789
  }
4039
- if (now >= hideAt) {
4040
- const next = queue.shift();
4041
- if (next) {
4042
- screen = next;
4043
- hideAt = now + captionDwellMs(next.text, queue.length);
4044
- } else {
4045
- screen = null;
4046
- }
3790
+ if (input.type === "mediaError" || input.details === "bufferAppendError" || input.details === "bufferSeekOverHole") {
3791
+ return "media";
4047
3792
  }
4048
- return { screen, hideAt, cursor, queue };
3793
+ return "generic";
4049
3794
  }
4050
- function cueEndWithGapFill(cues, index) {
4051
- const cue = cues[index];
4052
- if (!cue) return 0;
4053
- const next = cues[index + 1];
4054
- if (!next || !Number.isFinite(next.start)) return cue.end;
4055
- const gapMs = (next.start - cue.end) * 1e3;
4056
- if (gapMs > 0 && gapMs < CAPTION_GAP_FILL_MS) return next.start;
4057
- return cue.end;
3795
+ function kindForNative(input) {
3796
+ const code = input.mediaError?.code;
3797
+ if (code === MEDIA_ERR_DECODE) return "media";
3798
+ if (code === MEDIA_ERR_SRC_NOT_SUPPORTED) return "unsupported";
3799
+ if (code === MEDIA_ERR_NETWORK) return "unavailable";
3800
+ return "generic";
4058
3801
  }
4059
- function captionScreenAtTime(cues, time, maxCharsPerLine = CAPTION_MAX_CHARS_PER_LINE) {
4060
- if (!Number.isFinite(time)) return null;
4061
- const ordered = cues.filter(
4062
- (cue) => Boolean(cue.text.trim()) && Number.isFinite(cue.start) && Number.isFinite(cue.end)
4063
- ).sort((left, right) => left.start - right.start);
4064
- for (let index = 0; index < ordered.length; index += 1) {
4065
- const cue = ordered[index];
4066
- const end = cueEndWithGapFill(ordered, index);
4067
- if (time < cue.start || time >= end) continue;
4068
- const screens = splitCaptionScreens(cue.text, maxCharsPerLine);
4069
- if (screens.length === 0) return null;
4070
- const weights = screens.map(
4071
- (text) => Math.max(1, text.replace(/\s+/g, "").length)
4072
- );
4073
- const total = weights.reduce((sum, weight) => sum + weight, 0);
4074
- const duration = Math.max(end - cue.start, 0);
4075
- let cursor = cue.start;
4076
- for (let screenIndex = 0; screenIndex < screens.length; screenIndex += 1) {
4077
- const isLast = screenIndex === screens.length - 1;
4078
- const slice = isLast ? end - cursor : duration * (weights[screenIndex] / total);
4079
- const sliceEnd = cursor + slice;
4080
- if (time >= cursor && time < sliceEnd) {
4081
- return captionScreenRow(screens[screenIndex]);
4082
- }
4083
- cursor = sliceEnd;
3802
+ function describeAvResync(input) {
3803
+ const lag = Number.isFinite(input.lagSeconds) ? input.lagSeconds : 0;
3804
+ return {
3805
+ summary: `av-resync lag=${lag.toFixed(3)}s (non-fatal)`,
3806
+ kind: "resync",
3807
+ detail: {
3808
+ source: input.context.source,
3809
+ kind: "resync",
3810
+ fatal: false,
3811
+ reason: `presented frame lag ${lag.toFixed(3)}s`,
3812
+ context: input.context
4084
3813
  }
4085
- return captionScreenRow(screens[screens.length - 1]);
3814
+ };
3815
+ }
3816
+ function describePlaybackError(input) {
3817
+ if (input.source === "unsupported") {
3818
+ return {
3819
+ summary: "playback unsupported (hls.js unavailable, native HLS unsupported)",
3820
+ kind: "unsupported",
3821
+ detail: {
3822
+ source: "unsupported",
3823
+ kind: "unsupported",
3824
+ context: input.context
3825
+ }
3826
+ };
4086
3827
  }
4087
- return null;
3828
+ if (input.source === "native") {
3829
+ const code = input.mediaError?.code;
3830
+ const kind2 = kindForNative(input);
3831
+ const detail2 = {
3832
+ source: "native",
3833
+ kind: kind2,
3834
+ mediaErrorCode: code,
3835
+ mediaErrorName: code !== void 0 ? MEDIA_ERROR_NAMES[code] : void 0,
3836
+ errorMessage: input.mediaError?.message,
3837
+ context: input.context
3838
+ };
3839
+ const name = detail2.mediaErrorName ?? "MEDIA_ERR_UNKNOWN";
3840
+ return {
3841
+ summary: `native ${name}${input.mediaError?.message ? `: ${input.mediaError.message}` : ""}`,
3842
+ kind: kind2,
3843
+ detail: detail2
3844
+ };
3845
+ }
3846
+ const httpStatus = input.response?.code;
3847
+ const kind = kindForHls(input);
3848
+ const detail = {
3849
+ source: "hls",
3850
+ kind,
3851
+ type: input.type,
3852
+ details: input.details,
3853
+ fatal: input.fatal,
3854
+ httpStatus,
3855
+ url: input.url,
3856
+ reason: input.reason,
3857
+ errorMessage: errorMessageFromUnknown(input.error),
3858
+ context: input.context
3859
+ };
3860
+ const statusSuffix = httpStatus !== void 0 ? ` ${httpStatus}` : "";
3861
+ const summary = [
3862
+ "hls",
3863
+ input.type ?? "unknown",
3864
+ input.details ?? "unknown",
3865
+ input.fatal ? "(fatal)" : "(non-fatal)",
3866
+ statusSuffix.trim()
3867
+ ].filter(Boolean).join(" ");
3868
+ return { summary, kind, detail };
4088
3869
  }
4089
- var LIVE_OVERLAP_MIN_WORDS = 4;
4090
- function normalizeLiveCaptionText(text) {
4091
- return text.trim().replace(/\s+/g, " ").toLowerCase();
3870
+
3871
+ // src/components/video/useHlsPlayback.ts
3872
+ function effectivePlaybackMode(src, mode, sealed) {
3873
+ if (isLivePlaylistSrc(src)) return sealed ? "vod" : "live";
3874
+ return mode;
4092
3875
  }
4093
- function lastSubseqIndex(haystack, needle) {
4094
- if (needle.length === 0 || needle.length > haystack.length) return -1;
4095
- let found = -1;
4096
- for (let index = 0; index <= haystack.length - needle.length; index += 1) {
4097
- let match = true;
4098
- for (let offset = 0; offset < needle.length; offset += 1) {
4099
- if (haystack[index + offset] !== needle[offset]) {
4100
- match = false;
4101
- break;
3876
+ var RETRY_INTERVAL_MS = 3e3;
3877
+ var MAX_MEDIA_ERROR_RETRIES = 5;
3878
+ var DRIFT_THRESHOLD_S = 0.4;
3879
+ var DRIFT_CONSECUTIVE_SAMPLES = 3;
3880
+ var RESYNC_COOLDOWN_MS = 1e4;
3881
+ var LIVE_EDGE_RESYNC_THRESHOLD_S = 8;
3882
+ function useHlsPlayback({
3883
+ src,
3884
+ mode,
3885
+ active,
3886
+ autoPlay = false,
3887
+ muted = false,
3888
+ onError,
3889
+ onPlayingChange,
3890
+ onRebuffer,
3891
+ onQualityChange
3892
+ }) {
3893
+ const videoRef = React9.useRef(null);
3894
+ const hlsRef = React9.useRef(null);
3895
+ const [state, setState] = React9.useState("idle");
3896
+ const [qualities, setQualities] = React9.useState([]);
3897
+ const [activeLevel, setActiveLevel] = React9.useState(-1);
3898
+ const [autoplayState, setAutoplayState] = React9.useState("none");
3899
+ const [error, setError] = React9.useState(null);
3900
+ const [reloadKey, setReloadKey] = React9.useState(0);
3901
+ const [sealed, setSealed] = React9.useState(false);
3902
+ const modeRef = React9.useRef(mode);
3903
+ const lastSrcRef = React9.useRef(src);
3904
+ const sealedRef = React9.useRef(false);
3905
+ const sawLiveRef = React9.useRef(false);
3906
+ const sealedDuringSessionRef = React9.useRef(false);
3907
+ React9.useEffect(() => {
3908
+ modeRef.current = mode;
3909
+ }, [mode]);
3910
+ const onErrorRef = React9.useRef(onError);
3911
+ const onPlayingChangeRef = React9.useRef(onPlayingChange);
3912
+ const onRebufferRef = React9.useRef(onRebuffer);
3913
+ const onQualityChangeRef = React9.useRef(onQualityChange);
3914
+ React9.useEffect(() => {
3915
+ onErrorRef.current = onError;
3916
+ onPlayingChangeRef.current = onPlayingChange;
3917
+ onRebufferRef.current = onRebuffer;
3918
+ onQualityChangeRef.current = onQualityChange;
3919
+ }, [onError, onPlayingChange, onRebuffer, onQualityChange]);
3920
+ const retry = React9.useCallback(() => {
3921
+ setError(null);
3922
+ setState("loading");
3923
+ setAutoplayState("none");
3924
+ setReloadKey((k) => k + 1);
3925
+ }, []);
3926
+ React9.useEffect(() => {
3927
+ const media = videoRef.current;
3928
+ if (!media || !src || !active) {
3929
+ setState("idle");
3930
+ return;
3931
+ }
3932
+ let cancelled = false;
3933
+ let retryTimer = null;
3934
+ let manifestParsed = false;
3935
+ let mediaErrorRetries = 0;
3936
+ let playbackSource = "hls";
3937
+ const teardown = [];
3938
+ const liveSrc = isLivePlaylistSrc(src);
3939
+ if (lastSrcRef.current !== src) {
3940
+ lastSrcRef.current = src;
3941
+ sealedRef.current = false;
3942
+ sawLiveRef.current = false;
3943
+ sealedDuringSessionRef.current = false;
3944
+ setSealed(false);
3945
+ }
3946
+ applyMute(media);
3947
+ setState("loading");
3948
+ setError(null);
3949
+ setAutoplayState("none");
3950
+ setQualities([]);
3951
+ setActiveLevel(-1);
3952
+ function baseContext() {
3953
+ return {
3954
+ mode: modeRef.current,
3955
+ src,
3956
+ manifestParsed,
3957
+ retryCount: mediaErrorRetries,
3958
+ source: playbackSource
3959
+ };
3960
+ }
3961
+ function shouldAutoplay() {
3962
+ if (sealedDuringSessionRef.current) return false;
3963
+ return modeRef.current === "live" || autoPlay;
3964
+ }
3965
+ function hlsConfig() {
3966
+ if (liveSrc) {
3967
+ return sealedRef.current ? createVodHlsConfig() : createLiveHlsConfig();
4102
3968
  }
3969
+ return modeRef.current === "live" ? createLiveHlsConfig() : createVodHlsConfig();
4103
3970
  }
4104
- if (match) found = index;
4105
- }
4106
- return found;
4107
- }
4108
- function remainderAfterOverlap(previous, next) {
4109
- const prevWords = normalizeLiveCaptionText(previous).split(" ").filter(Boolean);
4110
- const nextWords = next.trim().replace(/\s+/g, " ").split(" ").filter(Boolean);
4111
- const nextNorm = nextWords.map((word) => word.toLowerCase());
4112
- const maxN = Math.min(prevWords.length, nextNorm.length);
4113
- for (let size = maxN; size >= LIVE_OVERLAP_MIN_WORDS; size -= 1) {
4114
- for (let start = prevWords.length - size; start >= 0; start -= 1) {
4115
- const gram = prevWords.slice(start, start + size);
4116
- const index = lastSubseqIndex(nextNorm, gram);
4117
- if (index !== -1) {
4118
- return nextWords.slice(index + size).join(" ");
3971
+ function clearRetryTimer() {
3972
+ if (retryTimer !== null) {
3973
+ clearTimeout(retryTimer);
3974
+ retryTimer = null;
4119
3975
  }
4120
3976
  }
4121
- }
4122
- return null;
4123
- }
4124
- function liveCaptionRow(text, receivedAt, speaker) {
4125
- return speaker == null ? { text, receivedAt } : { text, receivedAt, speaker };
4126
- }
4127
- function coalesceLiveCaptionCues(cues) {
4128
- const out = [];
4129
- for (const cue of cues) {
4130
- const text = cue.text.trim();
4131
- if (!text) continue;
4132
- const last = out[out.length - 1];
4133
- if (!last) {
4134
- out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
4135
- continue;
3977
+ function destroyHls() {
3978
+ hlsRef.current?.destroy();
3979
+ hlsRef.current = null;
3980
+ }
3981
+ function reportFatal(input) {
3982
+ const described = describePlaybackError(input);
3983
+ onErrorRef.current?.(described);
3984
+ setError(described);
3985
+ setState("error");
3986
+ }
3987
+ function applyMute(el) {
3988
+ el.muted = muted;
3989
+ }
3990
+ function preserveMute(el, fn) {
3991
+ const wasMuted = el.muted;
3992
+ fn();
3993
+ el.muted = wasMuted;
3994
+ }
3995
+ function attemptAutoplay(el) {
3996
+ applyMute(el);
3997
+ void el.play().then(
3998
+ () => {
3999
+ applyMute(el);
4000
+ setAutoplayState("playing");
4001
+ },
4002
+ () => {
4003
+ el.muted = true;
4004
+ void el.play().then(
4005
+ () => setAutoplayState(muted ? "playing" : "muted"),
4006
+ () => {
4007
+ if (el.paused) {
4008
+ setAutoplayState("blocked");
4009
+ return;
4010
+ }
4011
+ setAutoplayState(el.muted && !muted ? "muted" : "playing");
4012
+ }
4013
+ );
4014
+ }
4015
+ );
4016
+ }
4017
+ function scheduleRetry(retryFn) {
4018
+ clearRetryTimer();
4019
+ if (cancelled) return;
4020
+ setState("waiting");
4021
+ retryTimer = setTimeout(() => {
4022
+ retryTimer = null;
4023
+ if (!cancelled) retryFn();
4024
+ }, RETRY_INTERVAL_MS);
4136
4025
  }
4137
- if (last.speaker !== cue.speaker && (last.speaker != null || cue.speaker != null)) {
4138
- out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
4139
- continue;
4026
+ function startDriftWatchdog(el) {
4027
+ if (typeof el.requestVideoFrameCallback !== "function") return;
4028
+ let consecutiveLagSamples = 0;
4029
+ let lastResyncAt = 0;
4030
+ let handle = null;
4031
+ const tick = (_now, metadata) => {
4032
+ if (cancelled) return;
4033
+ handle = el.requestVideoFrameCallback(tick);
4034
+ if (el.paused || el.ended) {
4035
+ consecutiveLagSamples = 0;
4036
+ return;
4037
+ }
4038
+ const lag = el.currentTime - metadata.mediaTime;
4039
+ if (!(lag > DRIFT_THRESHOLD_S)) {
4040
+ consecutiveLagSamples = 0;
4041
+ return;
4042
+ }
4043
+ consecutiveLagSamples += 1;
4044
+ if (consecutiveLagSamples < DRIFT_CONSECUTIVE_SAMPLES) return;
4045
+ const nowMs = performance.now();
4046
+ if (nowMs - lastResyncAt < RESYNC_COOLDOWN_MS) return;
4047
+ lastResyncAt = nowMs;
4048
+ consecutiveLagSamples = 0;
4049
+ if (modeRef.current === "live" && el.seekable.length > 0) {
4050
+ const edge = el.seekable.end(el.seekable.length - 1);
4051
+ if (edge - el.currentTime > LIVE_EDGE_RESYNC_THRESHOLD_S) {
4052
+ el.currentTime = edge;
4053
+ } else {
4054
+ el.currentTime = el.currentTime + 1e-3;
4055
+ }
4056
+ } else {
4057
+ el.currentTime = el.currentTime + 1e-3;
4058
+ }
4059
+ onErrorRef.current?.(
4060
+ describeAvResync({
4061
+ lagSeconds: lag,
4062
+ context: baseContext()
4063
+ })
4064
+ );
4065
+ };
4066
+ handle = el.requestVideoFrameCallback(tick);
4067
+ teardown.push(() => {
4068
+ if (handle != null && typeof el.cancelVideoFrameCallback === "function") {
4069
+ el.cancelVideoFrameCallback(handle);
4070
+ }
4071
+ });
4140
4072
  }
4141
- const lastNorm = normalizeLiveCaptionText(last.text);
4142
- const nextNorm = normalizeLiveCaptionText(text);
4143
- if (lastNorm === nextNorm) continue;
4144
- if (nextNorm.startsWith(lastNorm) || lastNorm.startsWith(nextNorm)) {
4145
- out[out.length - 1] = liveCaptionRow(
4146
- nextNorm.length >= lastNorm.length ? text : last.text,
4147
- cue.receivedAt,
4148
- cue.speaker ?? last.speaker
4073
+ let hasPlayed = false;
4074
+ let waitingSince = null;
4075
+ function onPlaying() {
4076
+ manifestParsed = true;
4077
+ mediaErrorRetries = 0;
4078
+ clearRetryTimer();
4079
+ setState("ready");
4080
+ setAutoplayState(
4081
+ (prev) => prev === "blocked" || prev === "none" ? "playing" : prev
4149
4082
  );
4150
- continue;
4083
+ if (waitingSince != null) {
4084
+ const seconds = (performance.now() - waitingSince) / 1e3;
4085
+ waitingSince = null;
4086
+ if (seconds > 0) onRebufferRef.current?.(seconds);
4087
+ }
4088
+ hasPlayed = true;
4089
+ onPlayingChangeRef.current?.(true);
4151
4090
  }
4152
- const remainder = remainderAfterOverlap(last.text, text);
4153
- if (remainder !== null) {
4154
- if (!remainder) continue;
4155
- out.push(liveCaptionRow(remainder, cue.receivedAt, cue.speaker));
4156
- continue;
4091
+ function onPaused() {
4092
+ onPlayingChangeRef.current?.(false);
4157
4093
  }
4158
- out.push(liveCaptionRow(text, cue.receivedAt, cue.speaker));
4159
- }
4160
- return out;
4161
- }
4162
- function mergeLiveCaptionCues(existing, incoming, cap = LIVE_STACK_MAX_CUES) {
4163
- const map = /* @__PURE__ */ new Map();
4164
- for (const cue of existing) {
4165
- if (Number.isFinite(cue.receivedAt)) map.set(cue.receivedAt, cue);
4166
- }
4167
- for (const cue of incoming) {
4168
- if (Number.isFinite(cue.receivedAt)) map.set(cue.receivedAt, cue);
4169
- }
4170
- return [...map.values()].sort((left, right) => left.receivedAt - right.receivedAt).slice(-Math.max(1, cap));
4171
- }
4172
- async function loadCaptionVtt(url) {
4173
- try {
4174
- const response = await fetch(url, { cache: "no-store" });
4175
- if (!response.ok) return [];
4176
- return parseCaptionVtt(await response.text());
4177
- } catch {
4178
- return [];
4179
- }
4180
- }
4181
- async function loadLiveCaptions(url) {
4182
- try {
4183
- const response = await fetch(url, {
4184
- cache: "no-store",
4185
- headers: { Accept: "application/json" }
4094
+ function onWaiting() {
4095
+ if (!hasPlayed || waitingSince != null) return;
4096
+ waitingSince = performance.now();
4097
+ }
4098
+ media.addEventListener("playing", onPlaying);
4099
+ media.addEventListener("pause", onPaused);
4100
+ media.addEventListener("ended", onPaused);
4101
+ media.addEventListener("waiting", onWaiting);
4102
+ teardown.push(() => {
4103
+ media.removeEventListener("playing", onPlaying);
4104
+ media.removeEventListener("pause", onPaused);
4105
+ media.removeEventListener("ended", onPaused);
4106
+ media.removeEventListener("waiting", onWaiting);
4186
4107
  });
4187
- if (!response.ok) return { ok: false, cues: [] };
4188
- const body = await response.json();
4189
- if (!body || typeof body !== "object" || !("cues" in body)) {
4190
- return { ok: false, cues: [] };
4108
+ startDriftWatchdog(media);
4109
+ function initNative() {
4110
+ playbackSource = "native";
4111
+ manifestParsed = false;
4112
+ media.removeAttribute("src");
4113
+ media.load();
4114
+ media.src = src;
4115
+ applyMute(media);
4116
+ const onReady = () => {
4117
+ manifestParsed = true;
4118
+ clearRetryTimer();
4119
+ setState("ready");
4120
+ if (shouldAutoplay()) attemptAutoplay(media);
4121
+ };
4122
+ const onErr = () => {
4123
+ if (manifestParsed) {
4124
+ reportFatal({
4125
+ source: "native",
4126
+ mediaError: media.error,
4127
+ context: baseContext()
4128
+ });
4129
+ return;
4130
+ }
4131
+ onErrorRef.current?.(
4132
+ describePlaybackError({
4133
+ source: "native",
4134
+ mediaError: media.error,
4135
+ context: baseContext()
4136
+ })
4137
+ );
4138
+ scheduleRetry(() => {
4139
+ media.src = src;
4140
+ media.load();
4141
+ });
4142
+ };
4143
+ media.addEventListener("loadedmetadata", onReady);
4144
+ media.addEventListener("error", onErr);
4145
+ teardown.push(() => {
4146
+ media.removeEventListener("loadedmetadata", onReady);
4147
+ media.removeEventListener("error", onErr);
4148
+ });
4149
+ }
4150
+ function initHlsJs(Hls) {
4151
+ playbackSource = "hls";
4152
+ destroyHls();
4153
+ manifestParsed = false;
4154
+ const config = hlsConfig();
4155
+ const hls = new Hls(config);
4156
+ hlsRef.current = hls;
4157
+ hls.loadSource(src);
4158
+ hls.attachMedia(media);
4159
+ applyMute(media);
4160
+ hls.on(Hls.Events.LEVEL_LOADED, (_e, data) => {
4161
+ if (!liveSrc || cancelled) return;
4162
+ const details = data.details;
4163
+ if (!details) return;
4164
+ if (details.live) {
4165
+ sawLiveRef.current = true;
4166
+ return;
4167
+ }
4168
+ if (sealedRef.current) return;
4169
+ sealedRef.current = true;
4170
+ setSealed(true);
4171
+ if (sawLiveRef.current) {
4172
+ sealedDuringSessionRef.current = true;
4173
+ }
4174
+ setReloadKey((k) => k + 1);
4175
+ });
4176
+ hls.on(Hls.Events.MANIFEST_PARSED, (_e, data) => {
4177
+ manifestParsed = true;
4178
+ clearRetryTimer();
4179
+ setQualities(
4180
+ data.levels.map((l, index) => ({ index, height: l.height }))
4181
+ );
4182
+ setState("ready");
4183
+ if (shouldAutoplay()) attemptAutoplay(media);
4184
+ });
4185
+ hls.on(Hls.Events.LEVEL_SWITCHED, (_e, data) => {
4186
+ if (hls.autoLevelEnabled) setActiveLevel(-1);
4187
+ else setActiveLevel(data.level);
4188
+ const height = hls.levels?.[data.level]?.height;
4189
+ onQualityChangeRef.current?.(
4190
+ typeof height === "number" && height > 0 ? `${height}p` : "auto"
4191
+ );
4192
+ });
4193
+ hls.on(Hls.Events.ERROR, (_e, data) => {
4194
+ onErrorRef.current?.(
4195
+ describePlaybackError({
4196
+ source: "hls",
4197
+ type: data.type,
4198
+ details: data.details,
4199
+ fatal: data.fatal,
4200
+ url: data.url,
4201
+ response: data.response,
4202
+ reason: data.reason,
4203
+ error: data.error,
4204
+ context: baseContext()
4205
+ })
4206
+ );
4207
+ if (!data.fatal) return;
4208
+ if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
4209
+ if (!manifestParsed) {
4210
+ scheduleRetry(() => initHlsJs(Hls));
4211
+ return;
4212
+ }
4213
+ hls.startLoad();
4214
+ return;
4215
+ }
4216
+ mediaErrorRetries += 1;
4217
+ if (mediaErrorRetries === 1) {
4218
+ preserveMute(media, () => hls.recoverMediaError());
4219
+ return;
4220
+ }
4221
+ if (mediaErrorRetries === 2) {
4222
+ preserveMute(media, () => {
4223
+ hls.swapAudioCodec();
4224
+ hls.recoverMediaError();
4225
+ });
4226
+ return;
4227
+ }
4228
+ if (mediaErrorRetries < MAX_MEDIA_ERROR_RETRIES) {
4229
+ scheduleRetry(() => initHlsJs(Hls));
4230
+ return;
4231
+ }
4232
+ reportFatal({
4233
+ source: "hls",
4234
+ type: data.type,
4235
+ details: data.details,
4236
+ fatal: true,
4237
+ url: data.url,
4238
+ response: data.response,
4239
+ reason: data.reason,
4240
+ error: data.error,
4241
+ context: baseContext()
4242
+ });
4243
+ });
4191
4244
  }
4192
- const rows = body.cues;
4193
- if (!Array.isArray(rows)) return { ok: false, cues: [] };
4194
- const cues = [];
4195
- for (const row of rows) {
4196
- if (!row || typeof row !== "object") continue;
4197
- const record = row;
4198
- if (typeof record.text !== "string" || !record.text.trim()) continue;
4199
- if (typeof record.receivedAt !== "number" || !Number.isFinite(record.receivedAt)) {
4200
- continue;
4245
+ async function setup() {
4246
+ let Hls = null;
4247
+ try {
4248
+ Hls = (await import('hls.js')).default;
4249
+ } catch {
4250
+ Hls = null;
4201
4251
  }
4202
- const parsed = {
4203
- text: record.text.trim(),
4204
- receivedAt: record.receivedAt
4205
- };
4206
- if (typeof record.speaker === "number" && Number.isFinite(record.speaker)) {
4207
- parsed.speaker = record.speaker;
4252
+ if (cancelled) return;
4253
+ if (Hls && Hls.isSupported()) {
4254
+ initHlsJs(Hls);
4255
+ } else if (media.canPlayType("application/vnd.apple.mpegurl")) {
4256
+ initNative();
4257
+ } else {
4258
+ playbackSource = "unsupported";
4259
+ reportFatal({
4260
+ source: "unsupported",
4261
+ context: baseContext()
4262
+ });
4208
4263
  }
4209
- cues.push(parsed);
4210
4264
  }
4211
- return { ok: true, cues };
4212
- } catch {
4213
- return { ok: false, cues: [] };
4214
- }
4265
+ void setup();
4266
+ return () => {
4267
+ cancelled = true;
4268
+ clearRetryTimer();
4269
+ for (const fn of teardown) fn();
4270
+ destroyHls();
4271
+ };
4272
+ }, [src, active, autoPlay, muted, reloadKey]);
4273
+ const setLevel = React9.useCallback((index) => {
4274
+ const hls = hlsRef.current;
4275
+ if (!hls) return;
4276
+ hls.nextLevel = index;
4277
+ setActiveLevel(index);
4278
+ }, []);
4279
+ return {
4280
+ videoRef,
4281
+ state,
4282
+ qualities,
4283
+ activeLevel,
4284
+ setLevel,
4285
+ autoplayState,
4286
+ error,
4287
+ retry,
4288
+ effectiveMode: effectivePlaybackMode(src, mode, sealed)
4289
+ };
4215
4290
  }
4216
4291
 
4217
4292
  // src/components/video/fullscreen.ts
@@ -4372,6 +4447,7 @@ var PLAYBACK_RATES = [0.75, 1, 1.25, 1.5, 2];
4372
4447
  var CONTROLS_HIDE_MS = 3e3;
4373
4448
  var LIVE_EDGE_THRESHOLD_S = 8;
4374
4449
  var SEEK_STEP_S = 5;
4450
+ var PROGRESS_THROTTLE_MS = 5e3;
4375
4451
  var LIVE_CAPTION_PLAYOUT_MS = 250;
4376
4452
  var COMPACT_CHROME_PX = 640;
4377
4453
  var VIDEO_MEDIA_STYLE = `
@@ -4420,6 +4496,9 @@ function VideoPlayer({
4420
4496
  onPlayingChange,
4421
4497
  onFirstPlay,
4422
4498
  onError,
4499
+ onPlaybackProgress,
4500
+ onRebuffer,
4501
+ onQualityChange,
4423
4502
  fit = "aspect-video",
4424
4503
  className,
4425
4504
  defaultCaptionLocale,
@@ -4428,6 +4507,9 @@ function VideoPlayer({
4428
4507
  const t = { ...DEFAULT_LABELS3, ...labels };
4429
4508
  const containerRef = React9.useRef(null);
4430
4509
  const firstPlayFiredRef = React9.useRef(false);
4510
+ const lastProgressAtRef = React9.useRef(-PROGRESS_THROTTLE_MS);
4511
+ const onPlaybackProgressRef = React9.useRef(onPlaybackProgress);
4512
+ onPlaybackProgressRef.current = onPlaybackProgress;
4431
4513
  const applyingTrackModesRef = React9.useRef(false);
4432
4514
  const captionLocaleRef = React9.useRef("off");
4433
4515
  const cssFullscreenRef = React9.useRef(false);
@@ -4454,7 +4536,8 @@ function VideoPlayer({
4454
4536
  setLevel,
4455
4537
  autoplayState,
4456
4538
  error,
4457
- retry
4539
+ retry,
4540
+ effectiveMode
4458
4541
  } = useHlsPlayback({
4459
4542
  src,
4460
4543
  mode,
@@ -4462,7 +4545,9 @@ function VideoPlayer({
4462
4545
  autoPlay: autoplayActive,
4463
4546
  muted,
4464
4547
  onError,
4465
- onPlayingChange: handlePlayingChange
4548
+ onPlayingChange: handlePlayingChange,
4549
+ onRebuffer,
4550
+ onQualityChange
4466
4551
  });
4467
4552
  const [isPlaying, setIsPlaying] = React9.useState(false);
4468
4553
  const [isMuted, setIsMuted] = React9.useState(muted);
@@ -4530,7 +4615,22 @@ function VideoPlayer({
4530
4615
  if (video.buffered.length > 0) {
4531
4616
  setBuffered(video.buffered.end(video.buffered.length - 1));
4532
4617
  }
4533
- if (mode === "live" && video.seekable.length > 0) {
4618
+ const progress = onPlaybackProgressRef.current;
4619
+ if (progress) {
4620
+ const now = performance.now();
4621
+ if (now - lastProgressAtRef.current >= PROGRESS_THROTTLE_MS) {
4622
+ lastProgressAtRef.current = now;
4623
+ progress(
4624
+ video.currentTime,
4625
+ finitePlaybackDuration(
4626
+ video.duration,
4627
+ video.seekable,
4628
+ effectiveMode
4629
+ )
4630
+ );
4631
+ }
4632
+ }
4633
+ if (effectiveMode === "live" && video.seekable.length > 0) {
4534
4634
  const edge = video.seekable.end(video.seekable.length - 1);
4535
4635
  const lagSeconds = edge - video.currentTime;
4536
4636
  setBehindLive(lagSeconds > LIVE_EDGE_THRESHOLD_S);
@@ -4539,7 +4639,9 @@ function VideoPlayer({
4539
4639
  }
4540
4640
  }
4541
4641
  };
4542
- const onDuration = () => setDuration(finitePlaybackDuration(video.duration, video.seekable, mode));
4642
+ const onDuration = () => setDuration(
4643
+ finitePlaybackDuration(video.duration, video.seekable, effectiveMode)
4644
+ );
4543
4645
  const onVolume = () => {
4544
4646
  setIsMuted(video.muted);
4545
4647
  setVolume(video.volume);
@@ -4563,7 +4665,7 @@ function VideoPlayer({
4563
4665
  video.removeEventListener("ratechange", onRate);
4564
4666
  video.removeEventListener("playing", onPlaying);
4565
4667
  };
4566
- }, [videoRef, active, mode, liveCaptionsBaseUrl]);
4668
+ }, [videoRef, active, effectiveMode, liveCaptionsBaseUrl]);
4567
4669
  React9.useLayoutEffect(() => {
4568
4670
  const video = videoRef.current;
4569
4671
  if (video) video.muted = isMuted;
@@ -4891,13 +4993,13 @@ function VideoPlayer({
4891
4993
  }
4892
4994
  break;
4893
4995
  case "ArrowLeft":
4894
- if (mode === "vod") {
4996
+ if (effectiveMode === "vod") {
4895
4997
  e.preventDefault();
4896
4998
  seekBy(-SEEK_STEP_S);
4897
4999
  }
4898
5000
  break;
4899
5001
  case "ArrowRight":
4900
- if (mode === "vod") {
5002
+ if (effectiveMode === "vod") {
4901
5003
  e.preventDefault();
4902
5004
  seekBy(SEEK_STEP_S);
4903
5005
  }
@@ -4944,7 +5046,7 @@ function VideoPlayer({
4944
5046
  {
4945
5047
  ref: containerRef,
4946
5048
  "data-slot": "video-player",
4947
- "data-mode": mode,
5049
+ "data-mode": effectiveMode,
4948
5050
  "data-fit": fit,
4949
5051
  "data-css-fullscreen": cssFullscreen ? "" : void 0,
4950
5052
  className: cn(
@@ -5045,7 +5147,7 @@ function VideoPlayer({
5045
5147
  ]
5046
5148
  }
5047
5149
  ),
5048
- mode === "live" && active && state === "ready" && /* @__PURE__ */ jsxs("div", { className: "absolute top-3 left-3 flex items-center gap-2", children: [
5150
+ effectiveMode === "live" && active && state === "ready" && /* @__PURE__ */ jsxs("div", { className: "absolute top-3 left-3 flex items-center gap-2", children: [
5049
5151
  /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1.5 rounded bg-red-600 px-2 py-0.5 text-xs font-semibold tracking-wide", children: [
5050
5152
  /* @__PURE__ */ jsx("span", { className: "size-1.5 animate-pulse rounded-full bg-white" }),
5051
5153
  t.live
@@ -5062,7 +5164,7 @@ function VideoPlayer({
5062
5164
  ),
5063
5165
  "data-slot": "video-controls",
5064
5166
  children: [
5065
- mode === "vod" && /* @__PURE__ */ jsx(
5167
+ effectiveMode === "vod" && /* @__PURE__ */ jsx(
5066
5168
  SeekBar,
5067
5169
  {
5068
5170
  src,
@@ -5103,11 +5205,11 @@ function VideoPlayer({
5103
5205
  }
5104
5206
  ) })
5105
5207
  ] }),
5106
- mode === "vod" && /* @__PURE__ */ jsxs("span", { className: "ml-1 shrink-0 text-xs tabular-nums", children: [
5208
+ effectiveMode === "vod" && /* @__PURE__ */ jsxs("span", { className: "ml-1 shrink-0 text-xs tabular-nums", children: [
5107
5209
  formatTime(currentTime),
5108
5210
  !compactChrome && ` / ${formatTime(duration)}`
5109
5211
  ] }),
5110
- mode === "live" && behindLive && /* @__PURE__ */ jsxs(
5212
+ effectiveMode === "live" && behindLive && /* @__PURE__ */ jsxs(
5111
5213
  "button",
5112
5214
  {
5113
5215
  type: "button",
@@ -5120,7 +5222,7 @@ function VideoPlayer({
5120
5222
  }
5121
5223
  ),
5122
5224
  /* @__PURE__ */ jsxs("div", { className: "ml-auto flex shrink-0 items-center gap-1", children: [
5123
- !compactChrome && mode === "vod" && typeof stats?.views === "number" && /* @__PURE__ */ jsx("span", { className: "mr-1 text-xs", children: t.formatViews ? t.formatViews(stats.views) : `${stats.views} views` }),
5225
+ !compactChrome && effectiveMode === "vod" && typeof stats?.views === "number" && /* @__PURE__ */ jsx("span", { className: "mr-1 text-xs", children: t.formatViews ? t.formatViews(stats.views) : `${stats.views} views` }),
5124
5226
  /* @__PURE__ */ jsxs(
5125
5227
  MenuControl,
5126
5228
  {
@@ -5149,7 +5251,7 @@ function VideoPlayer({
5149
5251
  ]
5150
5252
  }
5151
5253
  ),
5152
- !compactChrome && mode === "vod" && /* @__PURE__ */ jsx(
5254
+ !compactChrome && effectiveMode === "vod" && /* @__PURE__ */ jsx(
5153
5255
  MenuControl,
5154
5256
  {
5155
5257
  label: t.speed,
@@ -5279,7 +5381,7 @@ function VideoPlayer({
5279
5381
  q.index
5280
5382
  ))
5281
5383
  ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
5282
- mode === "vod" && /* @__PURE__ */ jsx(
5384
+ effectiveMode === "vod" && /* @__PURE__ */ jsx(
5283
5385
  MenuNavRow,
5284
5386
  {
5285
5387
  icon: /* @__PURE__ */ jsx(Gauge, { className: "size-4" }),
@@ -5297,7 +5399,7 @@ function VideoPlayer({
5297
5399
  onSelect: () => setMorePane("quality")
5298
5400
  }
5299
5401
  ),
5300
- (mode === "vod" || showQuality) && /* @__PURE__ */ jsx("div", { className: "my-1 h-px bg-primary/15" }),
5402
+ (effectiveMode === "vod" || showQuality) && /* @__PURE__ */ jsx("div", { className: "my-1 h-px bg-primary/15" }),
5301
5403
  /* @__PURE__ */ jsx(
5302
5404
  MenuAction,
5303
5405
  {
@@ -6308,6 +6410,369 @@ function avatarFallbackStyle(name) {
6308
6410
  return getAvatarColors(name);
6309
6411
  }
6310
6412
 
6311
- export { AvatarEditor, AvatarEditorDialog, CAPTION_LOCALES, ConfirmDestructiveDialog, CurtainPicker, CurtainPickerSkeleton, CurtainPreview, CurtainStage, DEFAULT_CURTAIN_PICKER_LABELS, DEFAULT_EDITABLE_SECTION_LABELS, DEFAULT_FILE_DROPZONE_LABELS, DEFAULT_FILE_UPLOAD_LABELS, DEFAULT_FILE_UPLOAD_TRAY_LABELS, DEFAULT_NOTIFICATION_BELL_LABELS, DataList, DataListItem, EditableSection, Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyState, EmptyTitle, ErrorState, FeedVideoPlayer, FieldMessage, FileDropzone, FileUploadMenu, FileUploadTray, LanguageContext, LanguageSwitcher, LoadingState, NotificationBell, SafeImage, ThemeSwitcher, VideoPlayer, WaitingRoom, avatarFallbackStyle, captionsVttUrlFromPlayback, castHlsUrl, cn, createLiveHlsConfig, createMultipartUploadController, createVodHlsConfig, defaultLanguages, describeAvResync, describePlaybackError, fileMatchesAccept, getAvatarColors, getInitials, isCaptionLocale, loadCastSender, partRanges, progressFromBytes, shouldRetryLiveEdge404, useEditableSection, useFeedExclusivePlayback, useHlsPlayback, useLanguageContext, useMediaQuery2 as useMediaQuery, usePlaybackStats };
6413
+ // src/lib/playbackBeacon.ts
6414
+ var DEFAULT_INTERVAL_MS = 5e3;
6415
+ function canUseWindow() {
6416
+ return typeof window !== "undefined" && typeof document !== "undefined";
6417
+ }
6418
+ function createPlaybackBeaconClient({
6419
+ endpoint,
6420
+ sessionId,
6421
+ surface,
6422
+ getContext,
6423
+ fetchFn,
6424
+ intervalMs = DEFAULT_INTERVAL_MS,
6425
+ now = () => Date.now()
6426
+ }) {
6427
+ let queue = [];
6428
+ let destroyed = false;
6429
+ let timer = null;
6430
+ let flushing = null;
6431
+ function enqueue(event) {
6432
+ if (destroyed) return;
6433
+ const context = getContext?.() ?? {};
6434
+ queue.push({
6435
+ type: event.type,
6436
+ ...context,
6437
+ ...event,
6438
+ surface,
6439
+ ts: event.ts ?? now()
6440
+ });
6441
+ }
6442
+ async function send(events, keepalive) {
6443
+ if (events.length === 0) return;
6444
+ const body = JSON.stringify({ sessionId, events });
6445
+ const post = fetchFn ?? (typeof fetch === "function" ? fetch : void 0);
6446
+ if (!post) return;
6447
+ try {
6448
+ await post(endpoint, {
6449
+ method: "POST",
6450
+ headers: { "Content-Type": "application/json" },
6451
+ body,
6452
+ keepalive
6453
+ });
6454
+ } catch {
6455
+ }
6456
+ }
6457
+ async function flush(keepalive = false) {
6458
+ if (queue.length === 0) return;
6459
+ const events = queue;
6460
+ queue = [];
6461
+ await send(events, keepalive);
6462
+ }
6463
+ function scheduleFlush() {
6464
+ if (flushing) return flushing;
6465
+ flushing = flush(false).finally(() => {
6466
+ flushing = null;
6467
+ });
6468
+ return flushing;
6469
+ }
6470
+ function onPageHide() {
6471
+ void flush(true);
6472
+ }
6473
+ function onVisibility() {
6474
+ if (document.visibilityState === "hidden") void flush(true);
6475
+ }
6476
+ if (canUseWindow()) {
6477
+ timer = setInterval(() => {
6478
+ void scheduleFlush();
6479
+ }, intervalMs);
6480
+ window.addEventListener("pagehide", onPageHide);
6481
+ document.addEventListener("visibilitychange", onVisibility);
6482
+ }
6483
+ return {
6484
+ track(event) {
6485
+ enqueue(event);
6486
+ },
6487
+ flush() {
6488
+ return flush(false);
6489
+ },
6490
+ destroy() {
6491
+ if (destroyed) return;
6492
+ destroyed = true;
6493
+ if (timer !== null) {
6494
+ clearInterval(timer);
6495
+ timer = null;
6496
+ }
6497
+ if (canUseWindow()) {
6498
+ window.removeEventListener("pagehide", onPageHide);
6499
+ document.removeEventListener("visibilitychange", onVisibility);
6500
+ }
6501
+ void flush(true);
6502
+ }
6503
+ };
6504
+ }
6505
+ function StatHighlightCard({
6506
+ label,
6507
+ value,
6508
+ hint,
6509
+ delta,
6510
+ deltaTone = "neutral",
6511
+ className
6512
+ }) {
6513
+ return /* @__PURE__ */ jsxs(
6514
+ "div",
6515
+ {
6516
+ className: cn(
6517
+ "bg-card text-card-foreground rounded-xl border p-6 shadow-sm",
6518
+ className
6519
+ ),
6520
+ children: [
6521
+ /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-sm", children: label }),
6522
+ /* @__PURE__ */ jsx("p", { className: "mt-2 text-2xl font-semibold tracking-tight", children: value }),
6523
+ delta ? /* @__PURE__ */ jsx(
6524
+ "p",
6525
+ {
6526
+ className: cn(
6527
+ "mt-1 text-sm",
6528
+ deltaTone === "up" && "text-emerald-600 dark:text-emerald-400",
6529
+ deltaTone === "down" && "text-destructive",
6530
+ deltaTone === "neutral" && "text-muted-foreground"
6531
+ ),
6532
+ children: delta
6533
+ }
6534
+ ) : null,
6535
+ hint ? /* @__PURE__ */ jsx("p", { className: "text-muted-foreground mt-1 text-xs", children: hint }) : null
6536
+ ]
6537
+ }
6538
+ );
6539
+ }
6540
+ function MetricChartCard({
6541
+ title,
6542
+ description,
6543
+ action,
6544
+ children,
6545
+ className
6546
+ }) {
6547
+ return /* @__PURE__ */ jsxs(
6548
+ "div",
6549
+ {
6550
+ className: cn(
6551
+ "bg-card text-card-foreground rounded-xl border shadow-sm",
6552
+ className
6553
+ ),
6554
+ children: [
6555
+ /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-3 p-6 pb-2", children: [
6556
+ /* @__PURE__ */ jsxs("div", { children: [
6557
+ /* @__PURE__ */ jsx("h3", { className: "leading-none font-semibold tracking-tight", children: title }),
6558
+ description ? /* @__PURE__ */ jsx("p", { className: "text-muted-foreground mt-1.5 text-sm", children: description }) : null
6559
+ ] }),
6560
+ action
6561
+ ] }),
6562
+ /* @__PURE__ */ jsx("div", { className: "p-6 pt-4", children })
6563
+ ]
6564
+ }
6565
+ );
6566
+ }
6567
+ function polyline(points) {
6568
+ if (points.length === 0) return "";
6569
+ const min = Math.min(...points);
6570
+ const max = Math.max(...points);
6571
+ const span = max - min || 1;
6572
+ return points.map((point, index) => {
6573
+ const x = points.length === 1 ? 50 : index / (points.length - 1) * 100;
6574
+ const y = 28 - (point - min) / span * 24;
6575
+ return `${x.toFixed(2)},${y.toFixed(2)}`;
6576
+ }).join(" ");
6577
+ }
6578
+ function SparklineStat({
6579
+ label,
6580
+ value,
6581
+ points,
6582
+ className
6583
+ }) {
6584
+ const reduced = useMediaQuery2("(prefers-reduced-motion: reduce)");
6585
+ const path = polyline(points);
6586
+ return /* @__PURE__ */ jsxs(
6587
+ "div",
6588
+ {
6589
+ className: cn(
6590
+ "bg-card text-card-foreground flex items-end justify-between gap-3 rounded-xl border p-4 shadow-sm",
6591
+ className
6592
+ ),
6593
+ children: [
6594
+ /* @__PURE__ */ jsxs("div", { children: [
6595
+ /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs", children: label }),
6596
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-lg font-semibold tracking-tight", children: value })
6597
+ ] }),
6598
+ path ? /* @__PURE__ */ jsx(
6599
+ "svg",
6600
+ {
6601
+ viewBox: "0 0 100 32",
6602
+ className: cn(
6603
+ "text-primary h-8 w-24",
6604
+ !reduced && "motion-safe:transition-opacity"
6605
+ ),
6606
+ "aria-hidden": "true",
6607
+ children: /* @__PURE__ */ jsx(
6608
+ "polyline",
6609
+ {
6610
+ fill: "none",
6611
+ stroke: "currentColor",
6612
+ strokeWidth: "2",
6613
+ strokeLinejoin: "round",
6614
+ strokeLinecap: "round",
6615
+ points: path
6616
+ }
6617
+ )
6618
+ }
6619
+ ) : null
6620
+ ]
6621
+ }
6622
+ );
6623
+ }
6624
+ var TIME_RANGE_OPTIONS = ["day", "week", "month", "year"];
6625
+ var DEFAULT_LABELS4 = {
6626
+ day: "Day",
6627
+ week: "Week",
6628
+ month: "Month",
6629
+ year: "Year"
6630
+ };
6631
+ function TimeRangePicker({
6632
+ value,
6633
+ onChange,
6634
+ labels,
6635
+ className
6636
+ }) {
6637
+ const copy = { ...DEFAULT_LABELS4, ...labels };
6638
+ return /* @__PURE__ */ jsx(
6639
+ "div",
6640
+ {
6641
+ role: "group",
6642
+ "aria-label": "Time range",
6643
+ className: cn("flex flex-wrap gap-1", className),
6644
+ children: TIME_RANGE_OPTIONS.map((option) => {
6645
+ const selected = option === value;
6646
+ return /* @__PURE__ */ jsx(
6647
+ Button,
6648
+ {
6649
+ type: "button",
6650
+ size: "sm",
6651
+ variant: selected ? "default" : "outline",
6652
+ "aria-pressed": selected,
6653
+ onClick: () => onChange(option),
6654
+ children: copy[option]
6655
+ },
6656
+ option
6657
+ );
6658
+ })
6659
+ }
6660
+ );
6661
+ }
6662
+ function DimensionBreakdownTable({
6663
+ title,
6664
+ rows,
6665
+ empty,
6666
+ className
6667
+ }) {
6668
+ return /* @__PURE__ */ jsxs(
6669
+ "div",
6670
+ {
6671
+ className: cn(
6672
+ "bg-card text-card-foreground overflow-hidden rounded-xl border shadow-sm",
6673
+ className
6674
+ ),
6675
+ children: [
6676
+ title ? /* @__PURE__ */ jsx("h3", { className: "px-6 pt-6 text-sm font-semibold tracking-tight", children: title }) : null,
6677
+ rows.length === 0 ? /* @__PURE__ */ jsx("div", { className: "p-6", children: empty }) : /* @__PURE__ */ jsx("table", { className: "w-full text-sm", children: /* @__PURE__ */ jsx("tbody", { children: rows.map((row) => /* @__PURE__ */ jsxs("tr", { className: "border-t first:border-t-0", children: [
6678
+ /* @__PURE__ */ jsx("th", { scope: "row", className: "px-6 py-3 text-left font-medium", children: row.label }),
6679
+ /* @__PURE__ */ jsx("td", { className: "px-6 py-3 text-right tabular-nums", children: row.value }),
6680
+ row.share ? /* @__PURE__ */ jsx("td", { className: "text-muted-foreground px-6 py-3 text-right tabular-nums", children: row.share }) : null
6681
+ ] }, row.id)) }) })
6682
+ ]
6683
+ }
6684
+ );
6685
+ }
6686
+ function CostBreakdownCard({
6687
+ title,
6688
+ total,
6689
+ items,
6690
+ className
6691
+ }) {
6692
+ return /* @__PURE__ */ jsxs(
6693
+ "div",
6694
+ {
6695
+ className: cn(
6696
+ "bg-card text-card-foreground rounded-xl border p-6 shadow-sm",
6697
+ className
6698
+ ),
6699
+ children: [
6700
+ /* @__PURE__ */ jsxs("div", { className: "flex items-baseline justify-between gap-3", children: [
6701
+ /* @__PURE__ */ jsx("h3", { className: "font-semibold tracking-tight", children: title }),
6702
+ total ? /* @__PURE__ */ jsx("p", { className: "text-lg font-semibold tabular-nums", children: total }) : null
6703
+ ] }),
6704
+ /* @__PURE__ */ jsx("ul", { className: "mt-4 space-y-2", children: items.map((item) => /* @__PURE__ */ jsxs(
6705
+ "li",
6706
+ {
6707
+ className: "flex items-baseline justify-between gap-3 text-sm",
6708
+ children: [
6709
+ /* @__PURE__ */ jsxs("div", { children: [
6710
+ /* @__PURE__ */ jsx("p", { children: item.label }),
6711
+ item.basis ? /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs", children: item.basis }) : null
6712
+ ] }),
6713
+ /* @__PURE__ */ jsx("p", { className: "tabular-nums", children: item.amount })
6714
+ ]
6715
+ },
6716
+ item.id
6717
+ )) })
6718
+ ]
6719
+ }
6720
+ );
6721
+ }
6722
+ function MetricEmptyState({
6723
+ title,
6724
+ description,
6725
+ action,
6726
+ icon = BarChart3,
6727
+ className
6728
+ }) {
6729
+ return /* @__PURE__ */ jsx(
6730
+ EmptyState,
6731
+ {
6732
+ title,
6733
+ description,
6734
+ action,
6735
+ icon,
6736
+ className
6737
+ }
6738
+ );
6739
+ }
6740
+ function MetricSkeleton({ className, bars = 4 }) {
6741
+ const reduced = useMediaQuery2("(prefers-reduced-motion: reduce)");
6742
+ const count = Math.max(1, bars);
6743
+ return /* @__PURE__ */ jsxs(
6744
+ "div",
6745
+ {
6746
+ role: "status",
6747
+ "aria-live": "polite",
6748
+ className: cn("bg-card rounded-xl border p-6 shadow-sm", className),
6749
+ children: [
6750
+ /* @__PURE__ */ jsx(
6751
+ "div",
6752
+ {
6753
+ className: cn(
6754
+ "bg-muted mb-4 h-4 w-32 rounded",
6755
+ !reduced && "animate-pulse"
6756
+ )
6757
+ }
6758
+ ),
6759
+ /* @__PURE__ */ jsx("div", { className: "flex h-32 items-end gap-2", children: Array.from({ length: count }, (_, index) => /* @__PURE__ */ jsx(
6760
+ "div",
6761
+ {
6762
+ className: cn(
6763
+ "bg-muted flex-1 rounded-t",
6764
+ !reduced && "animate-pulse"
6765
+ ),
6766
+ style: { height: `${40 + index * 17 % 50}%` }
6767
+ },
6768
+ index
6769
+ )) }),
6770
+ /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Loading metrics" })
6771
+ ]
6772
+ }
6773
+ );
6774
+ }
6775
+
6776
+ export { AvatarEditor, AvatarEditorDialog, CAPTION_LOCALES, ConfirmDestructiveDialog, CostBreakdownCard, CurtainPicker, CurtainPickerSkeleton, CurtainPreview, CurtainStage, DEFAULT_CURTAIN_PICKER_LABELS, DEFAULT_EDITABLE_SECTION_LABELS, DEFAULT_FILE_DROPZONE_LABELS, DEFAULT_FILE_UPLOAD_LABELS, DEFAULT_FILE_UPLOAD_TRAY_LABELS, DEFAULT_NOTIFICATION_BELL_LABELS, DataList, DataListItem, DimensionBreakdownTable, EditableSection, Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyState, EmptyTitle, ErrorState, FeedVideoPlayer, FieldMessage, FileDropzone, FileUploadMenu, FileUploadTray, LanguageContext, LanguageSwitcher, LoadingState, MetricChartCard, MetricEmptyState, MetricSkeleton, NotificationBell, SafeImage, SparklineStat, StatHighlightCard, TIME_RANGE_OPTIONS, ThemeSwitcher, TimeRangePicker, VideoPlayer, WaitingRoom, avatarFallbackStyle, captionsVttUrlFromPlayback, castHlsUrl, cn, createLiveHlsConfig, createMultipartUploadController, createPlaybackBeaconClient, createVodHlsConfig, defaultLanguages, describeAvResync, describePlaybackError, fileMatchesAccept, getAvatarColors, getInitials, isCaptionLocale, loadCastSender, partRanges, progressFromBytes, shouldRetryLiveEdge404, useEditableSection, useFeedExclusivePlayback, useHlsPlayback, useLanguageContext, useMediaQuery2 as useMediaQuery, usePlaybackStats };
6312
6777
  //# sourceMappingURL=index.js.map
6313
6778
  //# sourceMappingURL=index.js.map