| 1 | 'use strict'; |
| 2 | |
| 3 | (function () |
| 4 | { |
| 5 | const VIDEO_TEXT_TRACK_SETTINGS_KEY = 'vjs-text-track-settings'; |
| 6 | const VIDEO_TEXT_TRACK_OVERRIDE_SETTINGS_RAW = JSON.stringify({ |
| 7 | backgroundOpacity: '0', |
| 8 | edgeStyle: 'uniform', |
| 9 | }); |
| 10 | const SUBTITLE_LOG_BATCH_MAX_ITEMS = 12; |
| 11 | const SUBTITLE_LOG_FLUSH_DELAY_MS = 500; |
| 12 | const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_DEFAULT = 15; |
| 13 | const IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_MAX = 30; |
| 14 | const IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS_DEFAULT = 60; |
| 15 | const IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS_MAX = 120; |
| 16 | const IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS_DEFAULT = 0.5; |
| 17 | const IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS_MIN = 0.25; |
| 18 | const IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS_MAX = 30; |
| 19 | const IMAGE_SUBTITLE_TIME_MATCH_EPSILON_SECONDS = 0.05; |
| 20 | const IMAGE_SUBTITLE_CACHE_MISS_FALLBACK_INTERVAL_MS_DEFAULT = 2000; |
| 21 | const IMAGE_SUBTITLE_CURRENT_REQUEST_TIMEOUT_MS_DEFAULT = 4000; |
| 22 | const IMAGE_SUBTITLE_PREFETCH_REQUEST_TIMEOUT_MS_DEFAULT = 4000; |
| 23 | const IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS_DEFAULT = 0; |
| 24 | const VIDEO_STREAM_CACHE_SW_URL = '/stream-cache-sw.js'; |
| 25 | const VIDEO_STREAM_CACHE_NAME = 'filemanager-stream-cache-v1'; |
| 26 | const VIDEO_STREAM_AHEAD_PREFETCH_POLL_MS_DEFAULT = 750; |
| 27 | const VIDEO_STREAM_SEGMENT_DURATION_FALLBACK_SECONDS = 4; |
| 28 | |
| 29 | function formatClockTime (value) |
| 30 | { |
| 31 | const seconds = Number(value); |
| 32 | if (!Number.isFinite(seconds) || seconds < 0) return '00:00'; |
| 33 | |
| 34 | const total = Math.floor(seconds); |
| 35 | const hours = Math.floor(total / 3600); |
| 36 | const minutes = Math.floor((total % 3600) / 60); |
| 37 | const remainingSeconds = total % 60; |
| 38 | |
| 39 | if (hours > 0) |
| 40 | { |
| 41 | return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`; |
| 42 | } |
| 43 | return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`; |
| 44 | } |
| 45 | |
| 46 | function roundLogNumber (value, digits = 3) |
| 47 | { |
| 48 | const numeric = Number(value); |
| 49 | if (!Number.isFinite(numeric)) return null; |
| 50 | return Number(numeric.toFixed(digits)); |
| 51 | } |
| 52 | |
| 53 | function parseHeaderInt (res, name) |
| 54 | { |
| 55 | if (!res || !res.headers || typeof res.headers.get !== 'function') return null; |
| 56 | const value = Number.parseInt(String(res.headers.get(name) || ''), 10); |
| 57 | return Number.isFinite(value) ? value : null; |
| 58 | } |
| 59 | |
| 60 | function parseHeaderFloat (res, name) |
| 61 | { |
| 62 | if (!res || !res.headers || typeof res.headers.get !== 'function') return null; |
| 63 | const value = Number.parseFloat(String(res.headers.get(name) || '')); |
| 64 | return Number.isFinite(value) ? value : null; |
| 65 | } |
| 66 | |
| 67 | function diffMilliseconds (later, earlier) |
| 68 | { |
| 69 | if (!Number.isFinite(later) || !Number.isFinite(earlier)) return null; |
| 70 | return Math.round(later - earlier); |
| 71 | } |
| 72 | |
| 73 | function diffSeconds (later, earlier) |
| 74 | { |
| 75 | if (!Number.isFinite(later) || !Number.isFinite(earlier)) return null; |
| 76 | return roundLogNumber(later - earlier, 3); |
| 77 | } |
| 78 | |
| 79 | function base64ToBlob (base64, contentType = 'image/png') |
| 80 | { |
| 81 | const raw = String(base64 || '').trim(); |
| 82 | if (!raw) return null; |
| 83 | |
| 84 | try |
| 85 | { |
| 86 | const decoded = window.atob(raw); |
| 87 | const bytes = new Uint8Array(decoded.length); |
| 88 | for (let index = 0; index < decoded.length; index++) |
| 89 | { |
| 90 | bytes[index] = decoded.charCodeAt(index); |
| 91 | } |
| 92 | return new Blob([bytes], { type: String(contentType || '').trim() || 'image/png' }); |
| 93 | } catch |
| 94 | { |
| 95 | return null; |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | function waitForImagePresentation (windowRef, imageEl) |
| 100 | { |
| 101 | return new Promise((resolve) => |
| 102 | { |
| 103 | let settled = false; |
| 104 | let fallbackTimer = null; |
| 105 | const raf = typeof windowRef.requestAnimationFrame === 'function' |
| 106 | ? windowRef.requestAnimationFrame.bind(windowRef) |
| 107 | : (fn) => windowRef.setTimeout(fn, 0); |
| 108 | |
| 109 | const cleanup = () => |
| 110 | { |
| 111 | imageEl.removeEventListener('load', onLoad); |
| 112 | imageEl.removeEventListener('error', onError); |
| 113 | if (fallbackTimer !== null) windowRef.clearTimeout(fallbackTimer); |
| 114 | }; |
| 115 | |
| 116 | const finish = () => |
| 117 | { |
| 118 | if (settled) return; |
| 119 | settled = true; |
| 120 | cleanup(); |
| 121 | raf(() => resolve(Date.now())); |
| 122 | }; |
| 123 | |
| 124 | const onLoad = () => finish(); |
| 125 | const onError = () => finish(); |
| 126 | |
| 127 | imageEl.addEventListener('load', onLoad); |
| 128 | imageEl.addEventListener('error', onError); |
| 129 | fallbackTimer = windowRef.setTimeout(finish, 250); |
| 130 | |
| 131 | if (imageEl.complete && imageEl.currentSrc) |
| 132 | { |
| 133 | finish(); |
| 134 | } |
| 135 | }); |
| 136 | } |
| 137 | |
| 138 | function normaliseTrackName (name) |
| 139 | { |
| 140 | return String(name || '').trim().toLowerCase(); |
| 141 | } |
| 142 | |
| 143 | function getTrackName (track) |
| 144 | { |
| 145 | if (!track || typeof track !== 'object') return ''; |
| 146 | const label = String(track.label || '').trim(); |
| 147 | if (label) return label; |
| 148 | const name = String(track.name || '').trim(); |
| 149 | if (name) return name; |
| 150 | const language = String(track.language || '').trim(); |
| 151 | if (language) return language; |
| 152 | const id = String(track.id || '').trim(); |
| 153 | if (id) return id; |
| 154 | return ''; |
| 155 | } |
| 156 | |
| 157 | function trackListToArray (trackList) |
| 158 | { |
| 159 | if (!trackList || typeof trackList.length !== 'number') return []; |
| 160 | const out = []; |
| 161 | for (let i = 0; i < trackList.length; i++) |
| 162 | { |
| 163 | const track = trackList[i] || (typeof trackList.item === 'function' ? trackList.item(i) : null); |
| 164 | if (track) out.push(track); |
| 165 | } |
| 166 | return out; |
| 167 | } |
| 168 | |
| 169 | function subtitleTracksFromPlayer (player) |
| 170 | { |
| 171 | if (!player || typeof player.textTracks !== 'function') return []; |
| 172 | return trackListToArray(player.textTracks()).filter((track) => |
| 173 | { |
| 174 | const kind = String(track.kind || '').toLowerCase(); |
| 175 | return kind === 'subtitles' || kind === 'captions'; |
| 176 | }); |
| 177 | } |
| 178 | |
| 179 | function audioTracksFromPlayer (player) |
| 180 | { |
| 181 | if (!player || typeof player.audioTracks !== 'function') return []; |
| 182 | return trackListToArray(player.audioTracks()); |
| 183 | } |
| 184 | |
| 185 | function applySavedSubtitleTrack (player, savedName) |
| 186 | { |
| 187 | if (typeof savedName !== 'string') return; |
| 188 | const tracks = subtitleTracksFromPlayer(player); |
| 189 | if (!tracks.length) return; |
| 190 | |
| 191 | const wanted = normaliseTrackName(savedName); |
| 192 | if (!wanted) |
| 193 | { |
| 194 | for (const track of tracks) track.mode = 'disabled'; |
| 195 | return; |
| 196 | } |
| 197 | |
| 198 | const match = tracks.find((track) => normaliseTrackName(getTrackName(track)) === wanted); |
| 199 | if (!match) return; |
| 200 | |
| 201 | for (const track of tracks) |
| 202 | { |
| 203 | track.mode = track === match ? 'showing' : 'disabled'; |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | function applySavedAudioTrack (player, savedName) |
| 208 | { |
| 209 | if (typeof savedName !== 'string') return; |
| 210 | const tracks = audioTracksFromPlayer(player); |
| 211 | if (!tracks.length) return; |
| 212 | |
| 213 | const wanted = normaliseTrackName(savedName); |
| 214 | if (!wanted) return; |
| 215 | |
| 216 | const match = tracks.find((track) => normaliseTrackName(getTrackName(track)) === wanted); |
| 217 | if (!match) return; |
| 218 | |
| 219 | for (const track of tracks) |
| 220 | { |
| 221 | track.enabled = track === match; |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | function getSelectedSubtitleTrackName (player) |
| 226 | { |
| 227 | const tracks = subtitleTracksFromPlayer(player); |
| 228 | if (!tracks.length) return null; |
| 229 | const active = tracks.find((track) => String(track.mode || '').toLowerCase() === 'showing'); |
| 230 | return active ? getTrackName(active) : ''; |
| 231 | } |
| 232 | |
| 233 | function getSelectedAudioTrackName (player) |
| 234 | { |
| 235 | const tracks = audioTracksFromPlayer(player); |
| 236 | if (!tracks.length) return null; |
| 237 | const active = tracks.find((track) => !!track.enabled); |
| 238 | return active ? getTrackName(active) : ''; |
| 239 | } |
| 240 | |
| 241 | function bindTrackPrefs (player, prefs, savePrefs) |
| 242 | { |
| 243 | const save = typeof savePrefs === 'function' ? savePrefs : (() => { }); |
| 244 | const applySavedTracks = () => |
| 245 | { |
| 246 | applySavedSubtitleTrack(player, prefs.subtitleTrackName); |
| 247 | applySavedAudioTrack(player, prefs.audioTrackName); |
| 248 | }; |
| 249 | |
| 250 | const captureSelectedTracks = () => |
| 251 | { |
| 252 | const subtitleTrackName = getSelectedSubtitleTrackName(player); |
| 253 | const audioTrackName = getSelectedAudioTrackName(player); |
| 254 | const patch = {}; |
| 255 | |
| 256 | if (subtitleTrackName !== null) patch.subtitleTrackName = subtitleTrackName; |
| 257 | if (audioTrackName !== null) patch.audioTrackName = audioTrackName; |
| 258 | |
| 259 | if (Object.keys(patch).length) save(patch); |
| 260 | }; |
| 261 | |
| 262 | const textTrackList = typeof player.textTracks === 'function' ? player.textTracks() : null; |
| 263 | const audioTrackList = typeof player.audioTracks === 'function' ? player.audioTracks() : null; |
| 264 | const onTrackListChange = () => captureSelectedTracks(); |
| 265 | |
| 266 | if (textTrackList && typeof textTrackList.addEventListener === 'function') |
| 267 | { |
| 268 | textTrackList.addEventListener('change', onTrackListChange); |
| 269 | } |
| 270 | |
| 271 | if (audioTrackList && typeof audioTrackList.addEventListener === 'function') |
| 272 | { |
| 273 | audioTrackList.addEventListener('change', onTrackListChange); |
| 274 | } |
| 275 | |
| 276 | return { |
| 277 | applySavedTracks, |
| 278 | captureSelectedTracks, |
| 279 | detach: () => |
| 280 | { |
| 281 | if (textTrackList && typeof textTrackList.removeEventListener === 'function') |
| 282 | { |
| 283 | textTrackList.removeEventListener('change', onTrackListChange); |
| 284 | } |
| 285 | if (audioTrackList && typeof audioTrackList.removeEventListener === 'function') |
| 286 | { |
| 287 | audioTrackList.removeEventListener('change', onTrackListChange); |
| 288 | } |
| 289 | }, |
| 290 | }; |
| 291 | } |
| 292 | |
| 293 | function bindImageSubtitleOverlay (player, videojs, prefs, session, opts = {}) |
| 294 | { |
| 295 | const imageTracks = Array.isArray(session.imageSubtitleTracks) |
| 296 | ? session.imageSubtitleTracks.map((track) => ({ |
| 297 | label: String(track.label || '').trim() || `Subtitle ${Number(track.streamIndex || 0) + 1}`, |
| 298 | language: String(track.language || '').trim(), |
| 299 | isDefault: !!track.default, |
| 300 | streamIndex: Number(track.streamIndex), |
| 301 | })).filter((track) => Number.isInteger(track.streamIndex) && track.streamIndex >= 0) |
| 302 | : []; |
| 303 | |
| 304 | if (!imageTracks.length) return null; |
| 305 | |
| 306 | const savePrefs = typeof opts.savePrefs === 'function' ? opts.savePrefs : (() => { }); |
| 307 | const buildFrameRequest = typeof opts.buildFrameRequest === 'function' ? opts.buildFrameRequest : null; |
| 308 | const buildPrefetchRequest = typeof opts.buildPrefetchRequest === 'function' ? opts.buildPrefetchRequest : buildFrameRequest; |
| 309 | const prefetchUsesRangeRequests = !!(buildFrameRequest && buildPrefetchRequest && buildPrefetchRequest !== buildFrameRequest); |
| 310 | const notifyError = typeof opts.onError === 'function' ? opts.onError : (() => { }); |
| 311 | const sendSubtitleLogBatch = typeof opts.sendSubtitleLogBatch === 'function' ? opts.sendSubtitleLogBatch : null; |
| 312 | const requestedLookaheadSeconds = Number(opts.lookaheadSeconds); |
| 313 | const lookaheadSeconds = Number.isFinite(requestedLookaheadSeconds) |
| 314 | ? Math.max(0, Math.min(IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_MAX, requestedLookaheadSeconds)) |
| 315 | : IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_DEFAULT; |
| 316 | const requestedCurrentRequestTimeoutMs = Number(opts.currentRequestTimeoutMs); |
| 317 | const currentRequestTimeoutMs = Number.isFinite(requestedCurrentRequestTimeoutMs) |
| 318 | ? Math.max(250, requestedCurrentRequestTimeoutMs) |
| 319 | : IMAGE_SUBTITLE_CURRENT_REQUEST_TIMEOUT_MS_DEFAULT; |
| 320 | const requestedInitialPrefetchSeconds = Number(opts.initialPrefetchSeconds); |
| 321 | const initialPrefetchSeconds = Number.isFinite(requestedInitialPrefetchSeconds) |
| 322 | ? Math.max(0, Math.min(IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS_MAX, requestedInitialPrefetchSeconds)) |
| 323 | : IMAGE_SUBTITLE_INITIAL_PREFETCH_SECONDS_DEFAULT; |
| 324 | const requestedPrefetchRequestTimeoutMs = Number(opts.prefetchRequestTimeoutMs); |
| 325 | const prefetchRequestTimeoutMs = Number.isFinite(requestedPrefetchRequestTimeoutMs) |
| 326 | ? Math.max(250, requestedPrefetchRequestTimeoutMs) |
| 327 | : IMAGE_SUBTITLE_PREFETCH_REQUEST_TIMEOUT_MS_DEFAULT; |
| 328 | const requestedPrefetchRequestIntervalMs = Number(opts.prefetchRequestIntervalMs); |
| 329 | const prefetchRequestIntervalMs = Number.isFinite(requestedPrefetchRequestIntervalMs) |
| 330 | ? Math.max(0, requestedPrefetchRequestIntervalMs) |
| 331 | : IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS_DEFAULT; |
| 332 | const requestedPrefetchStepSeconds = Number(opts.prefetchStepSeconds); |
| 333 | const prefetchStepSecondsFixed = Number.isFinite(requestedPrefetchStepSeconds) |
| 334 | ? Math.max(IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS_MIN, Math.min(IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS_MAX, requestedPrefetchStepSeconds)) |
| 335 | : null; |
| 336 | const prefetchAdaptiveStepEnabled = opts.prefetchAdaptiveStepEnabled === true; |
| 337 | const prefetchAdaptivePacingEnabled = opts.prefetchAdaptivePacingEnabled === true; |
| 338 | const requestedPrefetchStepSecondsMin = Number(opts.prefetchStepSecondsMin); |
| 339 | const requestedPrefetchStepSecondsMax = Number(opts.prefetchStepSecondsMax); |
| 340 | const prefetchStepSecondsMin = Number.isFinite(requestedPrefetchStepSecondsMin) |
| 341 | ? Math.max(IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS_MIN, Math.min(IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS_MAX, requestedPrefetchStepSecondsMin)) |
| 342 | : (prefetchStepSecondsFixed || IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS_DEFAULT); |
| 343 | const prefetchStepSecondsMaxRaw = Number.isFinite(requestedPrefetchStepSecondsMax) |
| 344 | ? Math.max(IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS_MIN, Math.min(IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS_MAX, requestedPrefetchStepSecondsMax)) |
| 345 | : (prefetchStepSecondsFixed || prefetchStepSecondsMin); |
| 346 | const prefetchStepSecondsMax = Math.max(prefetchStepSecondsMin, prefetchStepSecondsMaxRaw); |
| 347 | const requestedCacheMissFallbackIntervalMs = Number(opts.cacheMissFallbackIntervalMs); |
| 348 | const cacheMissFallbackIntervalMs = Number.isFinite(requestedCacheMissFallbackIntervalMs) |
| 349 | ? Math.max(500, requestedCacheMissFallbackIntervalMs) |
| 350 | : IMAGE_SUBTITLE_CACHE_MISS_FALLBACK_INTERVAL_MS_DEFAULT; |
| 351 | const cacheMissFallbackEnabled = opts.cacheMissFallbackEnabled !== false; |
| 352 | const currentFetchEnabled = opts.currentFetchEnabled !== false; |
| 353 | const logToConsole = opts.logToConsole !== false; |
| 354 | if (!buildFrameRequest) return null; |
| 355 | |
| 356 | const trackByStreamIndex = new Map(imageTracks.map((track) => [track.streamIndex, track])); |
| 357 | let selectedStreamIndex = null; |
| 358 | let menuOpen = false; |
| 359 | let activeBucket = -1; |
| 360 | let activeObjectUrl = null; |
| 361 | let overlayEl = null; |
| 362 | let overlayImgEl = null; |
| 363 | let menuEl = null; |
| 364 | let buttonEl = null; |
| 365 | let trackDisabled = false; |
| 366 | let failureNotified = false; |
| 367 | let lifecycleToken = 0; |
| 368 | let currentFrameToken = 0; |
| 369 | let currentFrameAbortController = null; |
| 370 | let prefetchWorkerToken = 0; |
| 371 | let prefetchAbortController = null; |
| 372 | let prefetchPromise = null; |
| 373 | let prefetchTargetTimeSeconds = -1; |
| 374 | let prefetchedThroughTimeSeconds = -1; |
| 375 | let queuedCurrentRefresh = false; |
| 376 | let queuedCurrentRefreshForce = false; |
| 377 | let currentFramePromise = null; |
| 378 | let seekMarkerContainerEl = null; |
| 379 | let seekMarkerRequestedEl = null; |
| 380 | let seekMarkerReceivedEl = null; |
| 381 | let lastRequestedCaptionStartTimeSeconds = null; |
| 382 | let lastReceivedCaptionStartTimeSeconds = null; |
| 383 | let subtitleLogSequence = 0; |
| 384 | let subtitleLogQueue = []; |
| 385 | let subtitleLogFlushTimer = null; |
| 386 | let lastCacheMissFallbackAtMs = 0; |
| 387 | let playbackClockSyncHandle = null; |
| 388 | const cachedSubtitleFrames = new Map(); |
| 389 | |
| 390 | const requestFrame = (fn) => |
| 391 | { |
| 392 | if (typeof window.requestAnimationFrame === 'function') |
| 393 | { |
| 394 | return { kind: 'raf', id: window.requestAnimationFrame(fn) }; |
| 395 | } |
| 396 | return { kind: 'timeout', id: window.setTimeout(fn, 16) }; |
| 397 | }; |
| 398 | |
| 399 | const cancelFrameRequest = (handle) => |
| 400 | { |
| 401 | if (!handle || !Number.isFinite(Number(handle.id))) return; |
| 402 | if (handle.kind === 'raf' && typeof window.cancelAnimationFrame === 'function') |
| 403 | { |
| 404 | window.cancelAnimationFrame(handle.id); |
| 405 | return; |
| 406 | } |
| 407 | window.clearTimeout(handle.id); |
| 408 | }; |
| 409 | |
| 410 | const flushSubtitleLogs = () => |
| 411 | { |
| 412 | if (!sendSubtitleLogBatch || !subtitleLogQueue.length) return; |
| 413 | if (subtitleLogFlushTimer) |
| 414 | { |
| 415 | window.clearTimeout(subtitleLogFlushTimer); |
| 416 | subtitleLogFlushTimer = null; |
| 417 | } |
| 418 | |
| 419 | const batch = subtitleLogQueue; |
| 420 | subtitleLogQueue = []; |
| 421 | Promise.resolve(sendSubtitleLogBatch(batch)).catch(() => |
| 422 | { |
| 423 | // Keep subtitle diagnostics best-effort only. |
| 424 | }); |
| 425 | }; |
| 426 | |
| 427 | const scheduleSubtitleLogFlush = () => |
| 428 | { |
| 429 | if (!sendSubtitleLogBatch || !subtitleLogQueue.length) return; |
| 430 | if (subtitleLogQueue.length >= SUBTITLE_LOG_BATCH_MAX_ITEMS) |
| 431 | { |
| 432 | flushSubtitleLogs(); |
| 433 | return; |
| 434 | } |
| 435 | if (subtitleLogFlushTimer) return; |
| 436 | subtitleLogFlushTimer = window.setTimeout(() => |
| 437 | { |
| 438 | subtitleLogFlushTimer = null; |
| 439 | flushSubtitleLogs(); |
| 440 | }, SUBTITLE_LOG_FLUSH_DELAY_MS); |
| 441 | }; |
| 442 | |
| 443 | const logSubtitleEvent = (eventType, details = {}) => |
| 444 | { |
| 445 | const entry = { |
| 446 | seq: ++subtitleLogSequence, |
| 447 | loggedAtMs: Date.now(), |
| 448 | eventType, |
| 449 | sessionId: String(session.sessionId || '').trim() || null, |
| 450 | streamIndex: Number.isInteger(selectedStreamIndex) ? selectedStreamIndex : null, |
| 451 | playerTimeSeconds: roundLogNumber(player.currentTime()), |
| 452 | ...details, |
| 453 | }; |
| 454 | if (logToConsole) |
| 455 | { |
| 456 | try |
| 457 | { |
| 458 | console.log('[subtitle-log]', entry); |
| 459 | } catch |
| 460 | { |
| 461 | // Ignore console availability issues. |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | if (!sendSubtitleLogBatch) return; |
| 466 | subtitleLogQueue.push(entry); |
| 467 | scheduleSubtitleLogFlush(); |
| 468 | }; |
| 469 | |
| 470 | const createAbortController = () => |
| 471 | { |
| 472 | if (typeof AbortController !== 'function') return null; |
| 473 | return new AbortController(); |
| 474 | }; |
| 475 | |
| 476 | const abortController = (controller) => |
| 477 | { |
| 478 | if (!controller || typeof controller.abort !== 'function') return; |
| 479 | try |
| 480 | { |
| 481 | controller.abort(); |
| 482 | } catch |
| 483 | { |
| 484 | // Ignore abort races during teardown. |
| 485 | } |
| 486 | }; |
| 487 | |
| 488 | const isAbortError = (error) => |
| 489 | { |
| 490 | return !!(error && typeof error === 'object' && error.name === 'AbortError'); |
| 491 | }; |
| 492 | |
| 493 | const armRequestTimeout = (controller, timeoutMs, onTimeout) => |
| 494 | { |
| 495 | if (!controller || !Number.isFinite(timeoutMs) || timeoutMs <= 0) return null; |
| 496 | return window.setTimeout(() => |
| 497 | { |
| 498 | if (typeof onTimeout === 'function') onTimeout(); |
| 499 | abortController(controller); |
| 500 | }, timeoutMs); |
| 501 | }; |
| 502 | |
| 503 | const clearRequestTimeout = (timeoutId) => |
| 504 | { |
| 505 | if (timeoutId === null || timeoutId === undefined) return; |
| 506 | window.clearTimeout(timeoutId); |
| 507 | }; |
| 508 | |
| 509 | const cancelCurrentFrameRequest = () => |
| 510 | { |
| 511 | currentFrameToken++; |
| 512 | abortController(currentFrameAbortController); |
| 513 | currentFrameAbortController = null; |
| 514 | }; |
| 515 | |
| 516 | const cancelPrefetchRequests = ({ resetProgress = false } = {}) => |
| 517 | { |
| 518 | prefetchWorkerToken++; |
| 519 | abortController(prefetchAbortController); |
| 520 | prefetchAbortController = null; |
| 521 | prefetchPromise = null; |
| 522 | if (resetProgress) |
| 523 | { |
| 524 | prefetchTargetTimeSeconds = -1; |
| 525 | prefetchedThroughTimeSeconds = -1; |
| 526 | } |
| 527 | }; |
| 528 | |
| 529 | const resetRequestState = () => |
| 530 | { |
| 531 | lifecycleToken++; |
| 532 | cancelCurrentFrameRequest(); |
| 533 | cancelPrefetchRequests({ resetProgress: true }); |
| 534 | }; |
| 535 | |
| 536 | const stopPlaybackClockSync = () => |
| 537 | { |
| 538 | if (!playbackClockSyncHandle) return; |
| 539 | cancelFrameRequest(playbackClockSyncHandle); |
| 540 | playbackClockSyncHandle = null; |
| 541 | }; |
| 542 | |
| 543 | const closeObjectUrl = () => |
| 544 | { |
| 545 | activeObjectUrl = null; |
| 546 | }; |
| 547 | |
| 548 | const hideOverlay = () => |
| 549 | { |
| 550 | if (overlayEl) overlayEl.style.display = 'none'; |
| 551 | if (overlayImgEl) overlayImgEl.removeAttribute('src'); |
| 552 | closeObjectUrl(); |
| 553 | }; |
| 554 | |
| 555 | const revokeCachedFrameUrls = () => |
| 556 | { |
| 557 | for (const frame of cachedSubtitleFrames.values()) |
| 558 | { |
| 559 | if (!frame || !frame.objectUrl) continue; |
| 560 | try |
| 561 | { |
| 562 | URL.revokeObjectURL(frame.objectUrl); |
| 563 | } catch |
| 564 | { |
| 565 | // Ignore object URL cleanup races. |
| 566 | } |
| 567 | } |
| 568 | cachedSubtitleFrames.clear(); |
| 569 | }; |
| 570 | |
| 571 | const parseFrameMetadata = (res, fallbackStartTimeSeconds, fallbackSpanSeconds = prefetchStepSecondsMin) => |
| 572 | { |
| 573 | const rawStart = parseHeaderFloat(res, 'X-Subtitle-Frame-Start-Time'); |
| 574 | const startTimeSeconds = Number.isFinite(rawStart) && rawStart >= 0 |
| 575 | ? rawStart |
| 576 | : (Number.isFinite(fallbackStartTimeSeconds) && fallbackStartTimeSeconds >= 0 ? fallbackStartTimeSeconds : null); |
| 577 | |
| 578 | const rawEnd = parseHeaderFloat(res, 'X-Subtitle-Frame-End-Time'); |
| 579 | const endTimeSeconds = Number.isFinite(rawEnd) |
| 580 | ? rawEnd |
| 581 | : (Number.isFinite(startTimeSeconds) ? startTimeSeconds + fallbackSpanSeconds : null); |
| 582 | |
| 583 | const frameWidth = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Width') || ''), 10); |
| 584 | const frameHeight = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Height') || ''), 10); |
| 585 | const canvasWidth = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Canvas-Width') || ''), 10); |
| 586 | const canvasHeight = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Canvas-Height') || ''), 10); |
| 587 | |
| 588 | return { |
| 589 | startTimeSeconds, |
| 590 | endTimeSeconds, |
| 591 | frameWidth, |
| 592 | frameHeight, |
| 593 | canvasWidth, |
| 594 | canvasHeight, |
| 595 | }; |
| 596 | }; |
| 597 | |
| 598 | const cacheFrameKey = (streamIndex, startTimeSeconds, endTimeSeconds) => |
| 599 | { |
| 600 | const startPart = Number.isFinite(startTimeSeconds) ? startTimeSeconds.toFixed(6) : 'none'; |
| 601 | const endPart = Number.isFinite(endTimeSeconds) ? endTimeSeconds.toFixed(6) : 'none'; |
| 602 | return `${streamIndex}|${startPart}|${endPart}`; |
| 603 | }; |
| 604 | |
| 605 | const cacheSubtitleFrame = ({ streamIndex, blob, metadata }) => |
| 606 | { |
| 607 | if (!Number.isInteger(streamIndex) || streamIndex < 0) return null; |
| 608 | if (!blob || typeof blob.size !== 'number' || blob.size <= 0) return null; |
| 609 | |
| 610 | const startTimeSeconds = Number.isFinite(metadata && metadata.startTimeSeconds) ? metadata.startTimeSeconds : null; |
| 611 | const endTimeSeconds = Number.isFinite(metadata && metadata.endTimeSeconds) |
| 612 | ? metadata.endTimeSeconds |
| 613 | : (Number.isFinite(startTimeSeconds) ? startTimeSeconds + prefetchStepSecondsMin : null); |
| 614 | if (!Number.isFinite(startTimeSeconds) || !Number.isFinite(endTimeSeconds) || endTimeSeconds <= startTimeSeconds) |
| 615 | { |
| 616 | return null; |
| 617 | } |
| 618 | |
| 619 | const key = cacheFrameKey(streamIndex, startTimeSeconds, endTimeSeconds); |
| 620 | const objectUrl = URL.createObjectURL(blob); |
| 621 | const previous = cachedSubtitleFrames.get(key); |
| 622 | if (previous && previous.objectUrl) |
| 623 | { |
| 624 | try |
| 625 | { |
| 626 | URL.revokeObjectURL(previous.objectUrl); |
| 627 | } catch |
| 628 | { |
| 629 | // Ignore object URL cleanup races. |
| 630 | } |
| 631 | } |
| 632 | |
| 633 | const entry = { |
| 634 | key, |
| 635 | streamIndex, |
| 636 | startTimeSeconds, |
| 637 | endTimeSeconds, |
| 638 | objectUrl, |
| 639 | frameWidth: Number(metadata && metadata.frameWidth), |
| 640 | frameHeight: Number(metadata && metadata.frameHeight), |
| 641 | canvasWidth: Number(metadata && metadata.canvasWidth), |
| 642 | canvasHeight: Number(metadata && metadata.canvasHeight), |
| 643 | }; |
| 644 | cachedSubtitleFrames.set(key, entry); |
| 645 | return entry; |
| 646 | }; |
| 647 | |
| 648 | const findCachedFrameForTime = (streamIndex, currentTime) => |
| 649 | { |
| 650 | if (!Number.isInteger(streamIndex) || streamIndex < 0) return null; |
| 651 | if (!Number.isFinite(currentTime) || currentTime < 0) return null; |
| 652 | |
| 653 | let best = null; |
| 654 | for (const frame of cachedSubtitleFrames.values()) |
| 655 | { |
| 656 | if (!frame || frame.streamIndex !== streamIndex) continue; |
| 657 | if (!Number.isFinite(frame.startTimeSeconds) || !Number.isFinite(frame.endTimeSeconds)) continue; |
| 658 | const startsAt = frame.startTimeSeconds - IMAGE_SUBTITLE_TIME_MATCH_EPSILON_SECONDS; |
| 659 | const endsAt = frame.endTimeSeconds + IMAGE_SUBTITLE_TIME_MATCH_EPSILON_SECONDS; |
| 660 | if (currentTime < startsAt || currentTime >= endsAt) continue; |
| 661 | if (!best || frame.startTimeSeconds > best.startTimeSeconds) best = frame; |
| 662 | } |
| 663 | return best; |
| 664 | }; |
| 665 | |
| 666 | const getAdaptivePrefetchStepSeconds = (currentTimeSeconds) => |
| 667 | { |
| 668 | if (!prefetchAdaptiveStepEnabled || prefetchStepSecondsMax <= prefetchStepSecondsMin) |
| 669 | { |
| 670 | return prefetchStepSecondsMax; |
| 671 | } |
| 672 | |
| 673 | const nowSeconds = Number(currentTimeSeconds); |
| 674 | const leadSeconds = Number.isFinite(prefetchedThroughTimeSeconds) && Number.isFinite(nowSeconds) |
| 675 | ? Math.max(0, prefetchedThroughTimeSeconds - nowSeconds) |
| 676 | : 0; |
| 677 | const targetLeadSeconds = Math.max(2, lookaheadSeconds * 0.75); |
| 678 | const highLeadSeconds = Math.max(targetLeadSeconds + prefetchStepSecondsMax, lookaheadSeconds * 2); |
| 679 | const ratio = highLeadSeconds > targetLeadSeconds |
| 680 | ? Math.max(0, Math.min(1, (leadSeconds - targetLeadSeconds) / (highLeadSeconds - targetLeadSeconds))) |
| 681 | : 1; |
| 682 | const rawStep = prefetchStepSecondsMin + ((prefetchStepSecondsMax - prefetchStepSecondsMin) * ratio); |
| 683 | |
| 684 | // Keep walker increments predictable while still allowing adaptation. |
| 685 | return Math.max( |
| 686 | prefetchStepSecondsMin, |
| 687 | Math.min(prefetchStepSecondsMax, Math.round(rawStep * 4) / 4), |
| 688 | ); |
| 689 | }; |
| 690 | |
| 691 | const getPrefetchDelayMs = (currentTimeSeconds) => |
| 692 | { |
| 693 | if (!prefetchAdaptivePacingEnabled) return prefetchRequestIntervalMs; |
| 694 | |
| 695 | const nowSeconds = Number(currentTimeSeconds); |
| 696 | const leadSeconds = Number.isFinite(prefetchedThroughTimeSeconds) && Number.isFinite(nowSeconds) |
| 697 | ? Math.max(0, prefetchedThroughTimeSeconds - nowSeconds) |
| 698 | : 0; |
| 699 | const softLeadSeconds = Math.max(lookaheadSeconds, prefetchStepSecondsMax * 2); |
| 700 | if (leadSeconds <= softLeadSeconds) return prefetchRequestIntervalMs; |
| 701 | |
| 702 | const excessRatio = Math.max(0, Math.min(1, (leadSeconds - softLeadSeconds) / Math.max(softLeadSeconds, 1))); |
| 703 | return Math.round(prefetchRequestIntervalMs + (excessRatio * 250)); |
| 704 | }; |
| 705 | |
| 706 | const renderSubtitleFrame = (frame) => |
| 707 | { |
| 708 | if (!overlayEl || !overlayImgEl || !frame || !frame.objectUrl) return; |
| 709 | |
| 710 | if (activeObjectUrl !== frame.objectUrl) |
| 711 | { |
| 712 | activeObjectUrl = frame.objectUrl; |
| 713 | overlayImgEl.src = frame.objectUrl; |
| 714 | } |
| 715 | |
| 716 | if (frame.frameWidth > 0 && frame.frameHeight > 0 && frame.canvasWidth > 0 && frame.canvasHeight > 0) |
| 717 | { |
| 718 | const widthPercent = (frame.frameWidth / frame.canvasWidth) * 100; |
| 719 | const heightPercent = (frame.frameHeight / frame.canvasHeight) * 100; |
| 720 | overlayImgEl.style.width = `${widthPercent}%`; |
| 721 | overlayImgEl.style.height = `${heightPercent}%`; |
| 722 | overlayImgEl.style.maxWidth = 'none'; |
| 723 | overlayImgEl.style.maxHeight = 'none'; |
| 724 | } else |
| 725 | { |
| 726 | overlayImgEl.style.width = 'auto'; |
| 727 | overlayImgEl.style.height = 'auto'; |
| 728 | overlayImgEl.style.maxWidth = '100%'; |
| 729 | overlayImgEl.style.maxHeight = '100%'; |
| 730 | } |
| 731 | |
| 732 | overlayEl.style.display = 'block'; |
| 733 | overlayImgEl.style.display = 'block'; |
| 734 | }; |
| 735 | |
| 736 | const syncOverlayToPlaybackClock = () => |
| 737 | { |
| 738 | if (selectedStreamIndex === null || trackDisabled) |
| 739 | { |
| 740 | stopPlaybackClockSync(); |
| 741 | return; |
| 742 | } |
| 743 | |
| 744 | const currentTime = Number(player.currentTime()); |
| 745 | if (Number.isFinite(currentTime) && currentTime >= 0) |
| 746 | { |
| 747 | const cachedFrame = findCachedFrameForTime(selectedStreamIndex, currentTime); |
| 748 | if (cachedFrame) renderSubtitleFrame(cachedFrame); |
| 749 | else hideOverlay(); |
| 750 | } |
| 751 | |
| 752 | playbackClockSyncHandle = requestFrame(syncOverlayToPlaybackClock); |
| 753 | }; |
| 754 | |
| 755 | const ensurePlaybackClockSync = () => |
| 756 | { |
| 757 | if (selectedStreamIndex === null || trackDisabled) return; |
| 758 | if (playbackClockSyncHandle) return; |
| 759 | playbackClockSyncHandle = requestFrame(syncOverlayToPlaybackClock); |
| 760 | }; |
| 761 | |
| 762 | const setSeekMarkerTime = (kind, timeSeconds) => |
| 763 | { |
| 764 | const numericTime = Number(timeSeconds); |
| 765 | const nextTime = Number.isFinite(numericTime) && numericTime >= 0 ? numericTime : null; |
| 766 | |
| 767 | if (kind === 'requested') |
| 768 | { |
| 769 | if (nextTime === null) |
| 770 | { |
| 771 | lastRequestedCaptionStartTimeSeconds = null; |
| 772 | } else if (!Number.isFinite(lastRequestedCaptionStartTimeSeconds) || nextTime >= lastRequestedCaptionStartTimeSeconds) |
| 773 | { |
| 774 | lastRequestedCaptionStartTimeSeconds = nextTime; |
| 775 | } |
| 776 | } else if (kind === 'received') |
| 777 | { |
| 778 | if (nextTime === null) |
| 779 | { |
| 780 | lastReceivedCaptionStartTimeSeconds = null; |
| 781 | } else if (!Number.isFinite(lastReceivedCaptionStartTimeSeconds) || nextTime >= lastReceivedCaptionStartTimeSeconds) |
| 782 | { |
| 783 | lastReceivedCaptionStartTimeSeconds = nextTime; |
| 784 | } |
| 785 | } |
| 786 | }; |
| 787 | |
| 788 | const updateSeekBarMarkers = () => |
| 789 | { |
| 790 | if (!seekMarkerRequestedEl || !seekMarkerReceivedEl) return; |
| 791 | |
| 792 | const duration = Number(player.duration && player.duration()); |
| 793 | if (!Number.isFinite(duration) || duration <= 0) |
| 794 | { |
| 795 | seekMarkerRequestedEl.style.display = 'none'; |
| 796 | seekMarkerReceivedEl.style.display = 'none'; |
| 797 | return; |
| 798 | } |
| 799 | |
| 800 | const getMarkerRatio = (markerTimeSeconds) => |
| 801 | { |
| 802 | if (!Number.isFinite(markerTimeSeconds) || markerTimeSeconds < 0) |
| 803 | { |
| 804 | return null; |
| 805 | } |
| 806 | |
| 807 | return Math.max(0, Math.min(1, markerTimeSeconds / duration)); |
| 808 | }; |
| 809 | |
| 810 | const applyMarker = (markerEl, ratio) => |
| 811 | { |
| 812 | if (!Number.isFinite(ratio)) |
| 813 | { |
| 814 | markerEl.style.display = 'none'; |
| 815 | return; |
| 816 | } |
| 817 | |
| 818 | markerEl.style.display = 'block'; |
| 819 | markerEl.style.left = `${(ratio * 100).toFixed(4)}%`; |
| 820 | }; |
| 821 | |
| 822 | const requestedRatio = getMarkerRatio(lastRequestedCaptionStartTimeSeconds); |
| 823 | const receivedRatio = getMarkerRatio(lastReceivedCaptionStartTimeSeconds); |
| 824 | applyMarker(seekMarkerRequestedEl, requestedRatio); |
| 825 | applyMarker(seekMarkerReceivedEl, receivedRatio); |
| 826 | }; |
| 827 | |
| 828 | const ensureSeekBarMarkers = () => |
| 829 | { |
| 830 | if (seekMarkerContainerEl && seekMarkerContainerEl.isConnected) |
| 831 | { |
| 832 | updateSeekBarMarkers(); |
| 833 | return; |
| 834 | } |
| 835 | |
| 836 | const playerEl = player.el && player.el(); |
| 837 | if (!playerEl) return; |
| 838 | |
| 839 | const seekBarEl = playerEl.querySelector('.vjs-seek-bar') |
| 840 | || playerEl.querySelector('.vjs-progress-holder') |
| 841 | || playerEl.querySelector('.vjs-progress-control'); |
| 842 | if (!seekBarEl) return; |
| 843 | |
| 844 | const computedPosition = window.getComputedStyle(seekBarEl).position; |
| 845 | if (computedPosition === 'static') seekBarEl.style.position = 'relative'; |
| 846 | |
| 847 | seekMarkerContainerEl = document.createElement('div'); |
| 848 | seekMarkerContainerEl.className = 'vjs-image-subtitle-seek-markers'; |
| 849 | seekMarkerContainerEl.style.position = 'absolute'; |
| 850 | seekMarkerContainerEl.style.left = '0'; |
| 851 | seekMarkerContainerEl.style.right = '0'; |
| 852 | seekMarkerContainerEl.style.top = '50%'; |
| 853 | seekMarkerContainerEl.style.height = '10px'; |
| 854 | seekMarkerContainerEl.style.transform = 'translateY(-50%)'; |
| 855 | seekMarkerContainerEl.style.pointerEvents = 'none'; |
| 856 | seekMarkerContainerEl.style.zIndex = '5'; |
| 857 | |
| 858 | const buildBracketMarker = (direction) => |
| 859 | { |
| 860 | const markerEl = document.createElement('span'); |
| 861 | markerEl.className = `vjs-image-subtitle-seek-marker vjs-image-subtitle-seek-marker-${direction}`; |
| 862 | markerEl.style.position = 'absolute'; |
| 863 | markerEl.style.top = '50%'; |
| 864 | markerEl.style.width = '10px'; |
| 865 | markerEl.style.height = '10px'; |
| 866 | markerEl.style.transform = 'translate(-50%, -50%)'; |
| 867 | markerEl.style.color = '#fff'; |
| 868 | markerEl.style.fontFamily = 'monospace'; |
| 869 | markerEl.style.fontSize = '12px'; |
| 870 | markerEl.style.fontWeight = '700'; |
| 871 | markerEl.style.lineHeight = '10px'; |
| 872 | markerEl.style.textAlign = 'center'; |
| 873 | markerEl.style.display = 'none'; |
| 874 | markerEl.textContent = direction === 'left' ? '[' : ']'; |
| 875 | markerEl.setAttribute('aria-hidden', 'true'); |
| 876 | return markerEl; |
| 877 | }; |
| 878 | |
| 879 | seekMarkerReceivedEl = buildBracketMarker('left'); |
| 880 | seekMarkerRequestedEl = buildBracketMarker('right'); |
| 881 | seekMarkerContainerEl.appendChild(seekMarkerReceivedEl); |
| 882 | seekMarkerContainerEl.appendChild(seekMarkerRequestedEl); |
| 883 | |
| 884 | seekBarEl.appendChild(seekMarkerContainerEl); |
| 885 | updateSeekBarMarkers(); |
| 886 | }; |
| 887 | |
| 888 | const updateButtonState = () => |
| 889 | { |
| 890 | if (!buttonEl) return; |
| 891 | const track = selectedStreamIndex === null ? null : trackByStreamIndex.get(selectedStreamIndex) || null; |
| 892 | buttonEl.setAttribute('title', track ? `Image subtitles: ${track.label}` : 'Image subtitles'); |
| 893 | buttonEl.setAttribute('aria-pressed', selectedStreamIndex === null ? 'false' : 'true'); |
| 894 | }; |
| 895 | |
| 896 | const updateMenuState = () => |
| 897 | { |
| 898 | if (!menuEl) return; |
| 899 | const items = menuEl.querySelectorAll('[data-image-subtitle-stream-index]'); |
| 900 | for (const itemEl of items) |
| 901 | { |
| 902 | const value = itemEl.getAttribute('data-image-subtitle-stream-index'); |
| 903 | const isSelected = value === (selectedStreamIndex === null ? 'off' : String(selectedStreamIndex)); |
| 904 | itemEl.classList.toggle('is-selected', isSelected); |
| 905 | itemEl.setAttribute('aria-checked', isSelected ? 'true' : 'false'); |
| 906 | itemEl.style.background = isSelected ? 'rgba(90, 196, 255, 0.28)' : 'transparent'; |
| 907 | itemEl.style.fontWeight = isSelected ? '600' : '400'; |
| 908 | itemEl.style.boxShadow = isSelected ? 'inset 0 0 0 1px rgba(90, 196, 255, 0.55)' : 'none'; |
| 909 | } |
| 910 | }; |
| 911 | |
| 912 | const closeMenu = () => |
| 913 | { |
| 914 | menuOpen = false; |
| 915 | if (menuEl) menuEl.style.display = 'none'; |
| 916 | }; |
| 917 | |
| 918 | const openMenu = () => |
| 919 | { |
| 920 | menuOpen = true; |
| 921 | if (menuEl) |
| 922 | { |
| 923 | updateMenuState(); |
| 924 | menuEl.style.display = 'block'; |
| 925 | } |
| 926 | }; |
| 927 | |
| 928 | const toggleMenu = () => |
| 929 | { |
| 930 | if (menuOpen) closeMenu(); |
| 931 | else openMenu(); |
| 932 | }; |
| 933 | |
| 934 | const saveSelection = () => |
| 935 | { |
| 936 | const selectedTrack = selectedStreamIndex === null ? null : trackByStreamIndex.get(selectedStreamIndex) || null; |
| 937 | savePrefs({ |
| 938 | imageSubtitleTrackStreamIndex: selectedStreamIndex, |
| 939 | imageSubtitleTrackName: selectedTrack ? selectedTrack.label : null, |
| 940 | }); |
| 941 | }; |
| 942 | |
| 943 | const disableTrack = () => |
| 944 | { |
| 945 | trackDisabled = true; |
| 946 | selectedStreamIndex = null; |
| 947 | activeBucket = -1; |
| 948 | stopPlaybackClockSync(); |
| 949 | setSeekMarkerTime('requested', null); |
| 950 | setSeekMarkerTime('received', null); |
| 951 | updateSeekBarMarkers(); |
| 952 | resetRequestState(); |
| 953 | hideOverlay(); |
| 954 | updateButtonState(); |
| 955 | updateMenuState(); |
| 956 | saveSelection(); |
| 957 | |
| 958 | if (!failureNotified) |
| 959 | { |
| 960 | failureNotified = true; |
| 961 | notifyError(); |
| 962 | } |
| 963 | }; |
| 964 | |
| 965 | const setSelectedStreamIndex = (streamIndex, { persist = true } = {}) => |
| 966 | { |
| 967 | const nextStreamIndex = Number.isInteger(streamIndex) ? streamIndex : null; |
| 968 | if (nextStreamIndex !== null && !trackByStreamIndex.has(nextStreamIndex)) return; |
| 969 | |
| 970 | trackDisabled = false; |
| 971 | failureNotified = false; |
| 972 | selectedStreamIndex = nextStreamIndex; |
| 973 | activeBucket = -1; |
| 974 | setSeekMarkerTime('requested', null); |
| 975 | setSeekMarkerTime('received', null); |
| 976 | updateSeekBarMarkers(); |
| 977 | resetRequestState(); |
| 978 | hideOverlay(); |
| 979 | updateButtonState(); |
| 980 | updateMenuState(); |
| 981 | if (persist) saveSelection(); |
| 982 | |
| 983 | if (selectedStreamIndex !== null) |
| 984 | { |
| 985 | ensurePlaybackClockSync(); |
| 986 | if (initialPrefetchSeconds > 0) |
| 987 | { |
| 988 | queueLookaheadPrefetch(0, { |
| 989 | reset: true, |
| 990 | includeCurrentTime: true, |
| 991 | maxTargetTimeSeconds: initialPrefetchSeconds, |
| 992 | }); |
| 993 | } |
| 994 | void refreshFrame(); |
| 995 | } |
| 996 | else |
| 997 | { |
| 998 | stopPlaybackClockSync(); |
| 999 | } |
| 1000 | }; |
| 1001 | |
| 1002 | const queueLookaheadPrefetch = (currentTime, { |
| 1003 | reset = false, |
| 1004 | includeCurrentTime = false, |
| 1005 | maxTargetTimeSeconds = null, |
| 1006 | } = {}) => |
| 1007 | { |
| 1008 | if (selectedStreamIndex === null) return; |
| 1009 | if (trackDisabled) return; |
| 1010 | |
| 1011 | const durationSeconds = Number(player.duration && player.duration()); |
| 1012 | const knownVideoEndSeconds = Number.isFinite(durationSeconds) && durationSeconds > 0 |
| 1013 | ? durationSeconds |
| 1014 | : null; |
| 1015 | |
| 1016 | const bufferedVideoEndSeconds = (() => |
| 1017 | { |
| 1018 | const candidates = []; |
| 1019 | |
| 1020 | const fromPlayer = Number(player.bufferedEnd && player.bufferedEnd()); |
| 1021 | if (Number.isFinite(fromPlayer) && fromPlayer >= 0) candidates.push(fromPlayer); |
| 1022 | |
| 1023 | const tech = typeof player.tech === 'function' ? player.tech(true) : null; |
| 1024 | const mediaEl = tech && typeof tech.el === 'function' |
| 1025 | ? tech.el() |
| 1026 | : (player.el && player.el() ? player.el().querySelector('video') : null); |
| 1027 | |
| 1028 | const ranges = mediaEl && mediaEl.buffered; |
| 1029 | if (ranges && typeof ranges.length === 'number' && ranges.length > 0 && typeof ranges.end === 'function') |
| 1030 | { |
| 1031 | try |
| 1032 | { |
| 1033 | const endTime = Number(ranges.end(ranges.length - 1)); |
| 1034 | if (Number.isFinite(endTime) && endTime >= 0) candidates.push(endTime); |
| 1035 | } catch |
| 1036 | { |
| 1037 | // Ignore buffered range read races. |
| 1038 | } |
| 1039 | } |
| 1040 | |
| 1041 | if (!candidates.length) return null; |
| 1042 | return Math.max(...candidates); |
| 1043 | })(); |
| 1044 | |
| 1045 | const startTime = includeCurrentTime |
| 1046 | ? currentTime |
| 1047 | : currentTime + prefetchStepSecondsMin; |
| 1048 | const uncappedEndTime = Math.max( |
| 1049 | currentTime + lookaheadSeconds, |
| 1050 | Number.isFinite(bufferedVideoEndSeconds) ? bufferedVideoEndSeconds : -1, |
| 1051 | Number.isFinite(knownVideoEndSeconds) ? knownVideoEndSeconds : -1, |
| 1052 | ); |
| 1053 | const capEndTime = Number.isFinite(maxTargetTimeSeconds) && maxTargetTimeSeconds >= 0 |
| 1054 | ? maxTargetTimeSeconds |
| 1055 | : null; |
| 1056 | let endTime = Number.isFinite(capEndTime) |
| 1057 | ? Math.min(uncappedEndTime, capEndTime) |
| 1058 | : uncappedEndTime; |
| 1059 | if (Number.isFinite(knownVideoEndSeconds)) |
| 1060 | { |
| 1061 | endTime = Math.min(endTime, knownVideoEndSeconds); |
| 1062 | } |
| 1063 | if (!Number.isFinite(startTime) || !Number.isFinite(endTime) || endTime <= startTime) return; |
| 1064 | |
| 1065 | if (reset || prefetchedThroughTimeSeconds < 0) |
| 1066 | { |
| 1067 | cancelPrefetchRequests({ resetProgress: true }); |
| 1068 | prefetchedThroughTimeSeconds = includeCurrentTime |
| 1069 | ? currentTime - prefetchStepSecondsMin |
| 1070 | : currentTime; |
| 1071 | } else if (prefetchedThroughTimeSeconds < currentTime) |
| 1072 | { |
| 1073 | // Keep the prefetch frontier at or ahead of current playback so |
| 1074 | // prefetch catches buffered-ahead range instead of replaying stale lag. |
| 1075 | prefetchedThroughTimeSeconds = currentTime; |
| 1076 | } |
| 1077 | |
| 1078 | prefetchTargetTimeSeconds = Math.max(prefetchTargetTimeSeconds, endTime); |
| 1079 | if (prefetchPromise) return; |
| 1080 | |
| 1081 | const workerToken = ++prefetchWorkerToken; |
| 1082 | const workerLifecycleToken = lifecycleToken; |
| 1083 | const controller = createAbortController(); |
| 1084 | prefetchAbortController = controller; |
| 1085 | |
| 1086 | prefetchPromise = (async () => |
| 1087 | { |
| 1088 | while (true) |
| 1089 | { |
| 1090 | if (selectedStreamIndex === null || trackDisabled) return; |
| 1091 | if (workerToken !== prefetchWorkerToken || workerLifecycleToken !== lifecycleToken) return; |
| 1092 | |
| 1093 | const stepSeconds = getAdaptivePrefetchStepSeconds(Number(player.currentTime())); |
| 1094 | |
| 1095 | const nextTime = prefetchedThroughTimeSeconds < 0 |
| 1096 | ? startTime |
| 1097 | : prefetchedThroughTimeSeconds + stepSeconds; |
| 1098 | if (!Number.isFinite(nextTime) || nextTime > prefetchTargetTimeSeconds + 1e-6) return; |
| 1099 | const requestedRangeEndTimeSeconds = Math.min(prefetchTargetTimeSeconds, nextTime + stepSeconds); |
| 1100 | const prefetchProgressTimeSeconds = prefetchUsesRangeRequests |
| 1101 | ? requestedRangeEndTimeSeconds |
| 1102 | : nextTime; |
| 1103 | |
| 1104 | const request = buildPrefetchRequest({ |
| 1105 | streamIndex: selectedStreamIndex, |
| 1106 | currentTime: nextTime, |
| 1107 | endTime: requestedRangeEndTimeSeconds, |
| 1108 | session, |
| 1109 | }); |
| 1110 | if (!request || !request.url) return; |
| 1111 | |
| 1112 | const prefetchRequestStartedAtMs = Date.now(); |
| 1113 | const prefetchRequestId = `prefetch-${workerToken}-${Math.round(nextTime * 1000)}`; |
| 1114 | logSubtitleEvent('subtitle_png_requested', { |
| 1115 | requestId: prefetchRequestId, |
| 1116 | requestKind: 'prefetch', |
| 1117 | requestUrl: String(request.url || ''), |
| 1118 | requestedAtMs: prefetchRequestStartedAtMs, |
| 1119 | requestedVideoTimeSeconds: roundLogNumber(nextTime), |
| 1120 | requestedRangeEndTimeSeconds: roundLogNumber(requestedRangeEndTimeSeconds), |
| 1121 | }); |
| 1122 | |
| 1123 | let prefetchTimedOut = false; |
| 1124 | const timeoutId = armRequestTimeout(controller, prefetchRequestTimeoutMs, () => |
| 1125 | { |
| 1126 | prefetchTimedOut = true; |
| 1127 | }); |
| 1128 | |
| 1129 | try |
| 1130 | { |
| 1131 | const res = await fetch(request.url, { |
| 1132 | method: request.method || 'GET', |
| 1133 | headers: request.headers, |
| 1134 | credentials: request.credentials, |
| 1135 | signal: controller ? controller.signal : undefined, |
| 1136 | }); |
| 1137 | clearRequestTimeout(timeoutId); |
| 1138 | |
| 1139 | if (workerToken !== prefetchWorkerToken || workerLifecycleToken !== lifecycleToken) return; |
| 1140 | |
| 1141 | const responseMeta = { |
| 1142 | requestId: prefetchRequestId, |
| 1143 | requestKind: 'prefetch', |
| 1144 | status: res.status, |
| 1145 | serverRequestReceivedAtMs: parseHeaderInt(res, 'X-Subtitle-Request-Received-At-Ms'), |
| 1146 | serverResponseSentAtMs: parseHeaderInt(res, 'X-Subtitle-Response-Sent-At-Ms'), |
| 1147 | shouldShowAtVideoTimeSeconds: parseHeaderFloat(res, 'X-Subtitle-Frame-Start-Time'), |
| 1148 | subtitleEndTimeSeconds: parseHeaderFloat(res, 'X-Subtitle-Frame-End-Time'), |
| 1149 | responseHeadersReceivedAtMs: Date.now(), |
| 1150 | requestedVideoTimeSeconds: roundLogNumber(nextTime), |
| 1151 | requestedRangeEndTimeSeconds: roundLogNumber(requestedRangeEndTimeSeconds), |
| 1152 | }; |
| 1153 | logSubtitleEvent('subtitle_png_sent', { |
| 1154 | ...responseMeta, |
| 1155 | serverProcessingMs: diffMilliseconds(responseMeta.serverResponseSentAtMs, responseMeta.serverRequestReceivedAtMs), |
| 1156 | sentToHeadersReceivedMs: diffMilliseconds(responseMeta.responseHeadersReceivedAtMs, responseMeta.serverResponseSentAtMs), |
| 1157 | }); |
| 1158 | |
| 1159 | setSeekMarkerTime('requested', prefetchProgressTimeSeconds); |
| 1160 | const receivedMarkerTime = Number.isFinite(responseMeta.shouldShowAtVideoTimeSeconds) |
| 1161 | ? responseMeta.shouldShowAtVideoTimeSeconds |
| 1162 | : prefetchProgressTimeSeconds; |
| 1163 | setSeekMarkerTime('received', receivedMarkerTime); |
| 1164 | updateSeekBarMarkers(); |
| 1165 | |
| 1166 | if (res.status === 204) |
| 1167 | { |
| 1168 | const frameStatus = String(res.headers.get('X-Subtitle-Frame-Status') || '').toLowerCase(); |
| 1169 | logSubtitleEvent('subtitle_png_not_available', { |
| 1170 | ...responseMeta, |
| 1171 | frameStatus, |
| 1172 | }); |
| 1173 | if (frameStatus === 'error') return; |
| 1174 | prefetchedThroughTimeSeconds = prefetchProgressTimeSeconds; |
| 1175 | if (prefetchUsesRangeRequests) |
| 1176 | { |
| 1177 | setSeekMarkerTime('requested', prefetchedThroughTimeSeconds); |
| 1178 | setSeekMarkerTime('received', prefetchedThroughTimeSeconds); |
| 1179 | updateSeekBarMarkers(); |
| 1180 | } |
| 1181 | const waitMs = getPrefetchDelayMs(Number(player.currentTime())); |
| 1182 | if (waitMs > 0) |
| 1183 | { |
| 1184 | await new Promise((resolve) => window.setTimeout(resolve, waitMs)); |
| 1185 | } |
| 1186 | continue; |
| 1187 | } |
| 1188 | |
| 1189 | if (!res.ok) return; |
| 1190 | const receivedAtMs = Date.now(); |
| 1191 | let cachedFrameEntry = null; |
| 1192 | let receivedBlobBytes = 0; |
| 1193 | |
| 1194 | if (/application\/json/i.test(String(res.headers.get('Content-Type') || ''))) |
| 1195 | { |
| 1196 | const body = await res.json().catch(() => null); |
| 1197 | if (String(body && body.status || '').toLowerCase() === 'error') return; |
| 1198 | const responseFrames = Array.isArray(body && body.frames) ? body.frames : []; |
| 1199 | for (const frame of responseFrames) |
| 1200 | { |
| 1201 | if (!frame) continue; |
| 1202 | const blob = base64ToBlob(frame.frameBase64, frame.contentType || 'image/png'); |
| 1203 | if (!blob || !blob.size) continue; |
| 1204 | receivedBlobBytes += Number(blob.size) || 0; |
| 1205 | const cached = cacheSubtitleFrame({ |
| 1206 | streamIndex: selectedStreamIndex, |
| 1207 | blob, |
| 1208 | metadata: { |
| 1209 | startTimeSeconds: Number(frame.startTimeSeconds), |
| 1210 | endTimeSeconds: Number(frame.endTimeSeconds), |
| 1211 | frameWidth: Number(frame.width), |
| 1212 | frameHeight: Number(frame.height), |
| 1213 | canvasWidth: Number(frame.canvasWidth), |
| 1214 | canvasHeight: Number(frame.canvasHeight), |
| 1215 | }, |
| 1216 | }); |
| 1217 | if (cached) cachedFrameEntry = cached; |
| 1218 | } |
| 1219 | responseMeta.shouldShowAtVideoTimeSeconds = Number.isFinite(Number(body && body.startTimeSeconds)) |
| 1220 | ? Number(body.startTimeSeconds) |
| 1221 | : responseMeta.shouldShowAtVideoTimeSeconds; |
| 1222 | responseMeta.subtitleEndTimeSeconds = Number.isFinite(Number(body && body.endTimeSeconds)) |
| 1223 | ? Number(body.endTimeSeconds) |
| 1224 | : responseMeta.subtitleEndTimeSeconds; |
| 1225 | } else |
| 1226 | { |
| 1227 | const payload = await res.arrayBuffer(); |
| 1228 | receivedBlobBytes = Number(payload && payload.byteLength || 0); |
| 1229 | const metadata = parseFrameMetadata(res, nextTime, stepSeconds); |
| 1230 | const blob = new Blob([payload], { |
| 1231 | type: String(res.headers.get('Content-Type') || '').trim() || 'image/png', |
| 1232 | }); |
| 1233 | cachedFrameEntry = cacheSubtitleFrame({ |
| 1234 | streamIndex: selectedStreamIndex, |
| 1235 | blob, |
| 1236 | metadata, |
| 1237 | }); |
| 1238 | } |
| 1239 | |
| 1240 | // When foreground fetches are disabled, current-time rendering is |
| 1241 | // cache-only and may otherwise wait for a later timeupdate tick. |
| 1242 | // Render immediately if this prefetched frame covers current time. |
| 1243 | if (cachedFrameEntry) |
| 1244 | { |
| 1245 | const nowTime = Number(player.currentTime()); |
| 1246 | if (Number.isFinite(nowTime) && nowTime >= 0) |
| 1247 | { |
| 1248 | const cachedForCurrentTime = findCachedFrameForTime(selectedStreamIndex, nowTime); |
| 1249 | if (cachedForCurrentTime) |
| 1250 | { |
| 1251 | renderSubtitleFrame(cachedForCurrentTime); |
| 1252 | } |
| 1253 | } |
| 1254 | } |
| 1255 | |
| 1256 | logSubtitleEvent('subtitle_png_received', { |
| 1257 | ...responseMeta, |
| 1258 | receivedAtMs, |
| 1259 | sentToReceivedMs: diffMilliseconds(receivedAtMs, responseMeta.serverResponseSentAtMs), |
| 1260 | requestedToReceivedMs: diffMilliseconds(receivedAtMs, prefetchRequestStartedAtMs), |
| 1261 | blobBytes: receivedBlobBytes, |
| 1262 | }); |
| 1263 | prefetchedThroughTimeSeconds = prefetchProgressTimeSeconds; |
| 1264 | if (prefetchUsesRangeRequests) |
| 1265 | { |
| 1266 | setSeekMarkerTime('requested', prefetchedThroughTimeSeconds); |
| 1267 | setSeekMarkerTime('received', prefetchedThroughTimeSeconds); |
| 1268 | updateSeekBarMarkers(); |
| 1269 | } |
| 1270 | const waitMs = getPrefetchDelayMs(Number(player.currentTime())); |
| 1271 | if (waitMs > 0) |
| 1272 | { |
| 1273 | await new Promise((resolve) => window.setTimeout(resolve, waitMs)); |
| 1274 | } |
| 1275 | } catch (error) |
| 1276 | { |
| 1277 | clearRequestTimeout(timeoutId); |
| 1278 | if (prefetchTimedOut) |
| 1279 | { |
| 1280 | logSubtitleEvent('subtitle_png_request_failed', { |
| 1281 | requestId: prefetchRequestId, |
| 1282 | requestKind: 'prefetch', |
| 1283 | requestedAtMs: prefetchRequestStartedAtMs, |
| 1284 | errorName: 'AbortError', |
| 1285 | errorMessage: `Prefetch subtitle request timed out after ${Math.round(prefetchRequestTimeoutMs)}ms`, |
| 1286 | }); |
| 1287 | return; |
| 1288 | } |
| 1289 | if (isAbortError(error)) return; |
| 1290 | logSubtitleEvent('subtitle_png_request_failed', { |
| 1291 | requestId: prefetchRequestId, |
| 1292 | requestKind: 'prefetch', |
| 1293 | requestedAtMs: prefetchRequestStartedAtMs, |
| 1294 | errorName: error && error.name ? String(error.name) : null, |
| 1295 | errorMessage: error && error.message ? String(error.message) : String(error || ''), |
| 1296 | }); |
| 1297 | return; |
| 1298 | } |
| 1299 | } |
| 1300 | })().finally(() => |
| 1301 | { |
| 1302 | if (workerToken !== prefetchWorkerToken) return; |
| 1303 | prefetchAbortController = null; |
| 1304 | prefetchPromise = null; |
| 1305 | }); |
| 1306 | }; |
| 1307 | |
| 1308 | const refreshFrame = async (force = false, allowCurrentFetchOverride = false, preservePrefetchState = false) => |
| 1309 | { |
| 1310 | if (selectedStreamIndex === null) return; |
| 1311 | if (!overlayEl || !overlayImgEl) return; |
| 1312 | if (trackDisabled) return; |
| 1313 | |
| 1314 | if (currentFramePromise && !force) |
| 1315 | { |
| 1316 | queuedCurrentRefresh = true; |
| 1317 | return; |
| 1318 | } |
| 1319 | |
| 1320 | const currentTime = Number(player.currentTime()); |
| 1321 | if (!Number.isFinite(currentTime) || currentTime < 0) return; |
| 1322 | |
| 1323 | const bucket = Math.floor(currentTime * 4); |
| 1324 | if (!force && bucket === activeBucket) return; |
| 1325 | activeBucket = bucket; |
| 1326 | |
| 1327 | const cachedFrame = findCachedFrameForTime(selectedStreamIndex, currentTime); |
| 1328 | if (cachedFrame) |
| 1329 | { |
| 1330 | setSeekMarkerTime('requested', currentTime); |
| 1331 | setSeekMarkerTime('received', cachedFrame.startTimeSeconds); |
| 1332 | updateSeekBarMarkers(); |
| 1333 | renderSubtitleFrame(cachedFrame); |
| 1334 | queueLookaheadPrefetch(currentTime, { reset: force }); |
| 1335 | return; |
| 1336 | } |
| 1337 | |
| 1338 | if (!currentFetchEnabled && !allowCurrentFetchOverride) |
| 1339 | { |
| 1340 | hideOverlay(); |
| 1341 | const nowMs = Date.now(); |
| 1342 | const shouldFallbackFetch = cacheMissFallbackEnabled |
| 1343 | && nowMs - lastCacheMissFallbackAtMs >= cacheMissFallbackIntervalMs; |
| 1344 | if (shouldFallbackFetch) |
| 1345 | { |
| 1346 | lastCacheMissFallbackAtMs = nowMs; |
| 1347 | logSubtitleEvent('subtitle_cache_miss_fallback_fetch', { |
| 1348 | requestKind: 'current', |
| 1349 | requestedAtMs: nowMs, |
| 1350 | requestedVideoTimeSeconds: roundLogNumber(currentTime), |
| 1351 | }); |
| 1352 | // Safety net for occasional cache key/window mismatches. |
| 1353 | // Uses normal current-frame path but does not reset prefetch state, |
| 1354 | // so background subtitle lead can continue growing while playing. |
| 1355 | return refreshFrame(true, true, true); |
| 1356 | } |
| 1357 | queueLookaheadPrefetch(currentTime, { |
| 1358 | reset: force, |
| 1359 | includeCurrentTime: true, |
| 1360 | }); |
| 1361 | return; |
| 1362 | } |
| 1363 | |
| 1364 | const refreshLifecycleToken = lifecycleToken; |
| 1365 | if (force && currentFramePromise) |
| 1366 | { |
| 1367 | cancelCurrentFrameRequest(); |
| 1368 | } |
| 1369 | if (currentFramePromise) |
| 1370 | { |
| 1371 | queuedCurrentRefresh = true; |
| 1372 | queuedCurrentRefreshForce = queuedCurrentRefreshForce || !!force; |
| 1373 | return; |
| 1374 | } |
| 1375 | cancelCurrentFrameRequest(); |
| 1376 | if (force && !preservePrefetchState) cancelPrefetchRequests({ resetProgress: true }); |
| 1377 | |
| 1378 | const token = ++currentFrameToken; |
| 1379 | const requestId = `current-${token}`; |
| 1380 | const requestStartedAtMs = Date.now(); |
| 1381 | const controller = createAbortController(); |
| 1382 | currentFrameAbortController = controller; |
| 1383 | const request = buildFrameRequest({ |
| 1384 | streamIndex: selectedStreamIndex, |
| 1385 | currentTime, |
| 1386 | session, |
| 1387 | }); |
| 1388 | |
| 1389 | if (!request || !request.url) |
| 1390 | { |
| 1391 | disableTrack(); |
| 1392 | return; |
| 1393 | } |
| 1394 | |
| 1395 | logSubtitleEvent('subtitle_png_requested', { |
| 1396 | requestId, |
| 1397 | requestKind: 'current', |
| 1398 | requestUrl: String(request.url || ''), |
| 1399 | requestedAtMs: requestStartedAtMs, |
| 1400 | requestedVideoTimeSeconds: roundLogNumber(currentTime), |
| 1401 | }); |
| 1402 | |
| 1403 | const frameRequestPromise = (async () => |
| 1404 | { |
| 1405 | let currentTimedOut = false; |
| 1406 | const timeoutId = armRequestTimeout(controller, currentRequestTimeoutMs, () => |
| 1407 | { |
| 1408 | currentTimedOut = true; |
| 1409 | }); |
| 1410 | try |
| 1411 | { |
| 1412 | const res = await fetch(request.url, { |
| 1413 | method: request.method || 'GET', |
| 1414 | headers: request.headers, |
| 1415 | credentials: request.credentials, |
| 1416 | signal: controller ? controller.signal : undefined, |
| 1417 | }); |
| 1418 | clearRequestTimeout(timeoutId); |
| 1419 | |
| 1420 | if (token !== currentFrameToken || refreshLifecycleToken !== lifecycleToken) return; |
| 1421 | |
| 1422 | const responseMeta = { |
| 1423 | requestId, |
| 1424 | requestKind: 'current', |
| 1425 | status: res.status, |
| 1426 | serverRequestReceivedAtMs: parseHeaderInt(res, 'X-Subtitle-Request-Received-At-Ms'), |
| 1427 | serverResponseSentAtMs: parseHeaderInt(res, 'X-Subtitle-Response-Sent-At-Ms'), |
| 1428 | shouldShowAtVideoTimeSeconds: parseHeaderFloat(res, 'X-Subtitle-Frame-Start-Time'), |
| 1429 | subtitleEndTimeSeconds: parseHeaderFloat(res, 'X-Subtitle-Frame-End-Time'), |
| 1430 | responseHeadersReceivedAtMs: Date.now(), |
| 1431 | requestedVideoTimeSeconds: roundLogNumber(currentTime), |
| 1432 | }; |
| 1433 | logSubtitleEvent('subtitle_png_sent', { |
| 1434 | ...responseMeta, |
| 1435 | serverProcessingMs: diffMilliseconds(responseMeta.serverResponseSentAtMs, responseMeta.serverRequestReceivedAtMs), |
| 1436 | sentToHeadersReceivedMs: diffMilliseconds(responseMeta.responseHeadersReceivedAtMs, responseMeta.serverResponseSentAtMs), |
| 1437 | }); |
| 1438 | |
| 1439 | setSeekMarkerTime('requested', currentTime); |
| 1440 | const receivedMarkerTime = Number.isFinite(responseMeta.shouldShowAtVideoTimeSeconds) |
| 1441 | ? responseMeta.shouldShowAtVideoTimeSeconds |
| 1442 | : currentTime; |
| 1443 | setSeekMarkerTime('received', receivedMarkerTime); |
| 1444 | updateSeekBarMarkers(); |
| 1445 | |
| 1446 | if (res.status === 204) |
| 1447 | { |
| 1448 | const frameStatus = String(res.headers.get('X-Subtitle-Frame-Status') || '').toLowerCase(); |
| 1449 | logSubtitleEvent('subtitle_png_not_available', { |
| 1450 | ...responseMeta, |
| 1451 | frameStatus, |
| 1452 | }); |
| 1453 | hideOverlay(); |
| 1454 | if (frameStatus === 'error') disableTrack(); |
| 1455 | else queueLookaheadPrefetch(currentTime, { reset: force && !preservePrefetchState }); |
| 1456 | return; |
| 1457 | } |
| 1458 | |
| 1459 | if (!res.ok) |
| 1460 | { |
| 1461 | disableTrack(); |
| 1462 | return; |
| 1463 | } |
| 1464 | |
| 1465 | const blob = await res.blob(); |
| 1466 | if (token !== currentFrameToken || refreshLifecycleToken !== lifecycleToken) return; |
| 1467 | |
| 1468 | const receivedAtMs = Date.now(); |
| 1469 | logSubtitleEvent('subtitle_png_received', { |
| 1470 | ...responseMeta, |
| 1471 | receivedAtMs, |
| 1472 | sentToReceivedMs: diffMilliseconds(receivedAtMs, responseMeta.serverResponseSentAtMs), |
| 1473 | requestedToReceivedMs: diffMilliseconds(receivedAtMs, requestStartedAtMs), |
| 1474 | blobBytes: Number(blob && blob.size || 0), |
| 1475 | }); |
| 1476 | |
| 1477 | if (!blob || blob.size === 0) |
| 1478 | { |
| 1479 | disableTrack(); |
| 1480 | return; |
| 1481 | } |
| 1482 | const cachedFrameEntry = cacheSubtitleFrame({ |
| 1483 | streamIndex: selectedStreamIndex, |
| 1484 | blob, |
| 1485 | metadata: parseFrameMetadata(res, currentTime, prefetchStepSecondsMin), |
| 1486 | }); |
| 1487 | if (cachedFrameEntry) renderSubtitleFrame(cachedFrameEntry); |
| 1488 | |
| 1489 | void waitForImagePresentation(window, overlayImgEl).then((shownAtMs) => |
| 1490 | { |
| 1491 | if (token !== currentFrameToken || refreshLifecycleToken !== lifecycleToken) return; |
| 1492 | const shownAtVideoTimeSeconds = roundLogNumber(player.currentTime()); |
| 1493 | logSubtitleEvent('subtitle_png_shown', { |
| 1494 | ...responseMeta, |
| 1495 | receivedAtMs, |
| 1496 | shownAtMs, |
| 1497 | shownAtVideoTimeSeconds, |
| 1498 | sentToReceivedMs: diffMilliseconds(receivedAtMs, responseMeta.serverResponseSentAtMs), |
| 1499 | receivedToShownMs: diffMilliseconds(shownAtMs, receivedAtMs), |
| 1500 | shouldVsShownDiffSeconds: diffSeconds(shownAtVideoTimeSeconds, responseMeta.shouldShowAtVideoTimeSeconds), |
| 1501 | }); |
| 1502 | }); |
| 1503 | |
| 1504 | queueLookaheadPrefetch(currentTime, { reset: force && !preservePrefetchState }); |
| 1505 | } catch (error) |
| 1506 | { |
| 1507 | clearRequestTimeout(timeoutId); |
| 1508 | if (currentTimedOut) |
| 1509 | { |
| 1510 | logSubtitleEvent('subtitle_png_request_failed', { |
| 1511 | requestId, |
| 1512 | requestKind: 'current', |
| 1513 | requestedAtMs: requestStartedAtMs, |
| 1514 | errorName: 'AbortError', |
| 1515 | errorMessage: `Current subtitle request timed out after ${Math.round(currentRequestTimeoutMs)}ms`, |
| 1516 | }); |
| 1517 | return; |
| 1518 | } |
| 1519 | if (isAbortError(error)) return; |
| 1520 | logSubtitleEvent('subtitle_png_request_failed', { |
| 1521 | requestId, |
| 1522 | requestKind: 'current', |
| 1523 | requestedAtMs: requestStartedAtMs, |
| 1524 | errorName: error && error.name ? String(error.name) : null, |
| 1525 | errorMessage: error && error.message ? String(error.message) : String(error || ''), |
| 1526 | }); |
| 1527 | if (token === currentFrameToken && refreshLifecycleToken === lifecycleToken) disableTrack(); |
| 1528 | } |
| 1529 | })(); |
| 1530 | |
| 1531 | currentFramePromise = frameRequestPromise; |
| 1532 | frameRequestPromise.finally(() => |
| 1533 | { |
| 1534 | if (currentFramePromise !== frameRequestPromise) return; |
| 1535 | currentFrameAbortController = null; |
| 1536 | currentFramePromise = null; |
| 1537 | if (!queuedCurrentRefresh) return; |
| 1538 | |
| 1539 | const queuedForce = queuedCurrentRefreshForce; |
| 1540 | queuedCurrentRefresh = false; |
| 1541 | queuedCurrentRefreshForce = false; |
| 1542 | void refreshFrame(queuedForce); |
| 1543 | }); |
| 1544 | |
| 1545 | return currentFramePromise; |
| 1546 | }; |
| 1547 | |
| 1548 | const dispose = () => |
| 1549 | { |
| 1550 | stopPlaybackClockSync(); |
| 1551 | resetRequestState(); |
| 1552 | flushSubtitleLogs(); |
| 1553 | closeMenu(); |
| 1554 | hideOverlay(); |
| 1555 | if (seekMarkerContainerEl) seekMarkerContainerEl.remove(); |
| 1556 | seekMarkerContainerEl = null; |
| 1557 | seekMarkerRequestedEl = null; |
| 1558 | seekMarkerReceivedEl = null; |
| 1559 | revokeCachedFrameUrls(); |
| 1560 | if (overlayEl) overlayEl.remove(); |
| 1561 | if (menuEl) menuEl.remove(); |
| 1562 | player.imageSubtitleOverlayController = null; |
| 1563 | buttonEl = null; |
| 1564 | }; |
| 1565 | |
| 1566 | overlayEl = document.createElement('div'); |
| 1567 | overlayEl.className = 'video-subtitle-overlay'; |
| 1568 | overlayEl.style.position = 'absolute'; |
| 1569 | overlayEl.style.left = '0'; |
| 1570 | overlayEl.style.right = '0'; |
| 1571 | overlayEl.style.bottom = '3rem'; |
| 1572 | overlayEl.style.display = 'none'; |
| 1573 | overlayEl.style.zIndex = '3'; |
| 1574 | overlayEl.style.pointerEvents = 'none'; |
| 1575 | overlayEl.style.textAlign = 'center'; |
| 1576 | overlayEl.style.padding = '0 0.75rem'; |
| 1577 | overlayEl.style.maxHeight = '70%'; |
| 1578 | overlayEl.style.overflow = 'hidden'; |
| 1579 | |
| 1580 | overlayImgEl = document.createElement('img'); |
| 1581 | overlayImgEl.alt = 'Image subtitles'; |
| 1582 | overlayImgEl.style.display = 'none'; |
| 1583 | overlayImgEl.style.margin = '0 auto'; |
| 1584 | overlayImgEl.style.objectFit = 'contain'; |
| 1585 | overlayImgEl.style.filter = 'drop-shadow(0 2px 2px rgba(0, 0, 0, 0.7))'; |
| 1586 | overlayImgEl.style.maxWidth = '100%'; |
| 1587 | overlayImgEl.style.height = 'auto'; |
| 1588 | overlayEl.appendChild(overlayImgEl); |
| 1589 | |
| 1590 | menuEl = document.createElement('div'); |
| 1591 | menuEl.className = 'video-subtitle-overlay-menu'; |
| 1592 | menuEl.style.position = 'absolute'; |
| 1593 | menuEl.style.right = '0.75rem'; |
| 1594 | menuEl.style.bottom = 'calc(3rem + 0.5rem)'; |
| 1595 | menuEl.style.minWidth = '14rem'; |
| 1596 | menuEl.style.maxWidth = '20rem'; |
| 1597 | menuEl.style.background = 'rgba(12, 12, 12, 0.96)'; |
| 1598 | menuEl.style.border = '1px solid rgba(255, 255, 255, 0.15)'; |
| 1599 | menuEl.style.borderRadius = '0.5rem'; |
| 1600 | menuEl.style.boxShadow = '0 12px 28px rgba(0, 0, 0, 0.35)'; |
| 1601 | menuEl.style.padding = '0.35rem'; |
| 1602 | menuEl.style.display = 'none'; |
| 1603 | menuEl.style.zIndex = '4'; |
| 1604 | |
| 1605 | const buildMenuItem = (label, streamIndex, isSelected) => |
| 1606 | { |
| 1607 | const itemEl = document.createElement('button'); |
| 1608 | itemEl.type = 'button'; |
| 1609 | itemEl.className = 'video-subtitle-overlay-menu-item'; |
| 1610 | itemEl.setAttribute('data-image-subtitle-stream-index', streamIndex === null ? 'off' : String(streamIndex)); |
| 1611 | itemEl.setAttribute('aria-checked', isSelected ? 'true' : 'false'); |
| 1612 | itemEl.style.display = 'block'; |
| 1613 | itemEl.style.width = '100%'; |
| 1614 | itemEl.style.margin = '0'; |
| 1615 | itemEl.style.padding = '0.5rem 0.75rem'; |
| 1616 | itemEl.style.border = '0'; |
| 1617 | itemEl.style.borderRadius = '0.35rem'; |
| 1618 | itemEl.style.background = isSelected ? 'rgba(255, 255, 255, 0.18)' : 'transparent'; |
| 1619 | itemEl.style.color = '#fff'; |
| 1620 | itemEl.style.textAlign = 'left'; |
| 1621 | itemEl.style.cursor = 'pointer'; |
| 1622 | itemEl.textContent = label; |
| 1623 | itemEl.addEventListener('click', () => |
| 1624 | { |
| 1625 | setSelectedStreamIndex(streamIndex); |
| 1626 | closeMenu(); |
| 1627 | }); |
| 1628 | return itemEl; |
| 1629 | }; |
| 1630 | |
| 1631 | menuEl.appendChild(buildMenuItem('Off', null, false)); |
| 1632 | for (const track of imageTracks) |
| 1633 | { |
| 1634 | menuEl.appendChild(buildMenuItem(track.label, track.streamIndex, false)); |
| 1635 | } |
| 1636 | |
| 1637 | const registerButton = () => |
| 1638 | { |
| 1639 | if (!videojs || typeof videojs.getComponent !== 'function' || typeof videojs.registerComponent !== 'function') return; |
| 1640 | if (videojs.getComponent('ImageSubtitleButton')) return; |
| 1641 | |
| 1642 | const Button = videojs.getComponent('Button'); |
| 1643 | class ImageSubtitleButton extends Button |
| 1644 | { |
| 1645 | buildCSSClass () |
| 1646 | { |
| 1647 | return `${super.buildCSSClass()} vjs-image-subtitle-button`; |
| 1648 | } |
| 1649 | |
| 1650 | createEl () |
| 1651 | { |
| 1652 | const el = super.createEl(); |
| 1653 | el.type = 'button'; |
| 1654 | el.setAttribute('title', 'Image subtitles'); |
| 1655 | el.setAttribute('aria-label', 'Image subtitles'); |
| 1656 | el.innerHTML = '<span aria-hidden="true">IM</span>'; |
| 1657 | return el; |
| 1658 | } |
| 1659 | |
| 1660 | handleClick () |
| 1661 | { |
| 1662 | const controller = this.player().imageSubtitleOverlayController; |
| 1663 | if (controller) controller.toggleMenu(); |
| 1664 | } |
| 1665 | } |
| 1666 | |
| 1667 | videojs.registerComponent('ImageSubtitleButton', ImageSubtitleButton); |
| 1668 | }; |
| 1669 | |
| 1670 | const attachUi = () => |
| 1671 | { |
| 1672 | if (!player.el()) return; |
| 1673 | registerButton(); |
| 1674 | if (overlayEl.parentElement !== player.el()) player.el().appendChild(overlayEl); |
| 1675 | if (menuEl.parentElement !== player.el()) player.el().appendChild(menuEl); |
| 1676 | const controlBar = typeof player.getChild === 'function' ? player.getChild('controlBar') : null; |
| 1677 | if (controlBar && typeof controlBar.addChild === 'function' && !buttonEl) |
| 1678 | { |
| 1679 | const button = controlBar.addChild('ImageSubtitleButton', {}); |
| 1680 | buttonEl = button && typeof button.el === 'function' ? button.el() : null; |
| 1681 | updateButtonState(); |
| 1682 | } |
| 1683 | }; |
| 1684 | |
| 1685 | const applySavedTracks = () => |
| 1686 | { |
| 1687 | const savedName = normaliseTrackName(prefs.imageSubtitleTrackName); |
| 1688 | if (savedName) |
| 1689 | { |
| 1690 | const savedByName = imageTracks.find((track) => normaliseTrackName(track.label) === savedName) || null; |
| 1691 | if (savedByName) |
| 1692 | { |
| 1693 | setSelectedStreamIndex(savedByName.streamIndex, { persist: false }); |
| 1694 | return; |
| 1695 | } |
| 1696 | } |
| 1697 | |
| 1698 | const savedIndex = Number(prefs.imageSubtitleTrackStreamIndex); |
| 1699 | if (Number.isInteger(savedIndex) && trackByStreamIndex.has(savedIndex)) |
| 1700 | { |
| 1701 | setSelectedStreamIndex(savedIndex, { persist: false }); |
| 1702 | return; |
| 1703 | } |
| 1704 | |
| 1705 | const defaultTrack = imageTracks.find((track) => track.isDefault) || null; |
| 1706 | if (defaultTrack) |
| 1707 | { |
| 1708 | setSelectedStreamIndex(defaultTrack.streamIndex, { persist: false }); |
| 1709 | return; |
| 1710 | } |
| 1711 | |
| 1712 | setSelectedStreamIndex(null, { persist: false }); |
| 1713 | }; |
| 1714 | |
| 1715 | player.imageSubtitleOverlayController = { |
| 1716 | toggleMenu, |
| 1717 | closeMenu, |
| 1718 | applySavedTracks, |
| 1719 | captureSelectedTracks: saveSelection, |
| 1720 | detach: dispose, |
| 1721 | }; |
| 1722 | |
| 1723 | player.on('timeupdate', () => { void refreshFrame(); }); |
| 1724 | player.on('seeking', () => { void refreshFrame(true); }); |
| 1725 | player.on('play', () => { void refreshFrame(true); }); |
| 1726 | player.on('play', ensurePlaybackClockSync); |
| 1727 | player.on('pause', stopPlaybackClockSync); |
| 1728 | player.on('ended', stopPlaybackClockSync); |
| 1729 | player.on('fullscreenchange', () => { closeMenu(); void refreshFrame(true); }); |
| 1730 | player.on('dispose', dispose); |
| 1731 | player.ready(() => |
| 1732 | { |
| 1733 | attachUi(); |
| 1734 | ensureSeekBarMarkers(); |
| 1735 | updateMenuState(); |
| 1736 | updateButtonState(); |
| 1737 | updateSeekBarMarkers(); |
| 1738 | applySavedTracks(); |
| 1739 | if (menuOpen) openMenu(); |
| 1740 | }); |
| 1741 | |
| 1742 | const onDurationHints = () => |
| 1743 | { |
| 1744 | ensureSeekBarMarkers(); |
| 1745 | updateSeekBarMarkers(); |
| 1746 | |
| 1747 | if (selectedStreamIndex === null || trackDisabled) return; |
| 1748 | const currentTime = Number(player.currentTime()); |
| 1749 | if (!Number.isFinite(currentTime) || currentTime < 0) return; |
| 1750 | |
| 1751 | queueLookaheadPrefetch(currentTime, { |
| 1752 | includeCurrentTime: true, |
| 1753 | }); |
| 1754 | }; |
| 1755 | |
| 1756 | player.on('durationchange', onDurationHints); |
| 1757 | player.on('loadedmetadata', onDurationHints); |
| 1758 | |
| 1759 | return player.imageSubtitleOverlayController; |
| 1760 | } |
| 1761 | |
| 1762 | function formatDurationForDebug (seconds) |
| 1763 | { |
| 1764 | const value = Number(seconds); |
| 1765 | if (!Number.isFinite(value) || value < 0) return 'unknown'; |
| 1766 | |
| 1767 | const totalSeconds = Math.floor(value); |
| 1768 | const hh = String(Math.floor(totalSeconds / 3600)).padStart(2, '0'); |
| 1769 | const mm = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0'); |
| 1770 | const ss = String(totalSeconds % 60).padStart(2, '0'); |
| 1771 | return `${hh}:${mm}:${ss}`; |
| 1772 | } |
| 1773 | |
| 1774 | function installDurationFallback (player, originalDuration, duration) |
| 1775 | { |
| 1776 | if (!player || !originalDuration || player.__filemanagerDurationFallback) return; |
| 1777 | |
| 1778 | player.__filemanagerDurationFallback = true; |
| 1779 | player.duration = function durationWithFallback (...args) |
| 1780 | { |
| 1781 | if (args.length) return originalDuration(...args); |
| 1782 | const current = Number(originalDuration()); |
| 1783 | return Number.isFinite(current) && current >= duration * 0.95 ? current : duration; |
| 1784 | }; |
| 1785 | } |
| 1786 | |
| 1787 | function normaliseVideoDuration (player, durationSeconds) |
| 1788 | { |
| 1789 | const duration = Number(durationSeconds); |
| 1790 | if (!player || !Number.isFinite(duration) || duration <= 0) return; |
| 1791 | |
| 1792 | let originalDuration = null; |
| 1793 | let durationWasChanged = false; |
| 1794 | try |
| 1795 | { |
| 1796 | originalDuration = typeof player.duration === 'function' ? player.duration.bind(player) : null; |
| 1797 | installDurationFallback(player, originalDuration, duration); |
| 1798 | if (player.__filemanagerDurationApplied) return; |
| 1799 | |
| 1800 | const current = originalDuration ? Number(originalDuration()) : NaN; |
| 1801 | const withinTolerance = Number.isFinite(current) && current >= duration * 0.95; |
| 1802 | console.log(`Current duration: ${formatDurationForDebug(current)}, Target time: ${formatDurationForDebug(duration)}, within 95%? ${withinTolerance ? 'yes' : 'no'}`); |
| 1803 | if (withinTolerance) |
| 1804 | { |
| 1805 | player.__filemanagerDurationApplied = true; |
| 1806 | return; |
| 1807 | } |
| 1808 | |
| 1809 | if (originalDuration) |
| 1810 | { |
| 1811 | durationWasChanged = true; |
| 1812 | originalDuration(duration); |
| 1813 | } |
| 1814 | } catch |
| 1815 | { |
| 1816 | // Ignore players that do not support setting duration. |
| 1817 | } |
| 1818 | |
| 1819 | try |
| 1820 | { |
| 1821 | const updated = originalDuration ? Number(originalDuration()) : NaN; |
| 1822 | if (Number.isFinite(updated) && updated >= duration * 0.95) |
| 1823 | { |
| 1824 | player.__filemanagerDurationApplied = true; |
| 1825 | if (durationWasChanged && typeof player.trigger === 'function') player.trigger('durationchange'); |
| 1826 | return; |
| 1827 | } |
| 1828 | |
| 1829 | player.__filemanagerDurationApplied = true; |
| 1830 | if (typeof player.trigger === 'function') player.trigger('durationchange'); |
| 1831 | } catch |
| 1832 | { |
| 1833 | // Ignore duration fallback failures. |
| 1834 | } |
| 1835 | } |
| 1836 | |
| 1837 | function ensureVideoPlaybackUi (player, durationSeconds) |
| 1838 | { |
| 1839 | if (!player || typeof player.on !== 'function') return; |
| 1840 | |
| 1841 | const forceVodUi = () => |
| 1842 | { |
| 1843 | normaliseVideoDuration(player, durationSeconds); |
| 1844 | |
| 1845 | try |
| 1846 | { |
| 1847 | if (player.liveTracker && typeof player.liveTracker.stopTracking === 'function') |
| 1848 | { |
| 1849 | player.liveTracker.stopTracking(); |
| 1850 | } |
| 1851 | } catch |
| 1852 | { |
| 1853 | // Ignore live tracker availability issues. |
| 1854 | } |
| 1855 | |
| 1856 | try |
| 1857 | { |
| 1858 | if (typeof player.removeClass === 'function') |
| 1859 | { |
| 1860 | player.removeClass('vjs-live'); |
| 1861 | } |
| 1862 | } catch |
| 1863 | { |
| 1864 | // Ignore class update failures. |
| 1865 | } |
| 1866 | |
| 1867 | try |
| 1868 | { |
| 1869 | const display = player.el && player.el() && player.el().querySelector('.vjs-live-display'); |
| 1870 | if (display) display.style.display = 'none'; |
| 1871 | } catch |
| 1872 | { |
| 1873 | // Ignore missing DOM. |
| 1874 | } |
| 1875 | }; |
| 1876 | |
| 1877 | player.ready(forceVodUi); |
| 1878 | player.on('loadedmetadata', forceVodUi); |
| 1879 | player.on('durationchange', forceVodUi); |
| 1880 | player.on('loadedplaylist', forceVodUi); |
| 1881 | } |
| 1882 | |
| 1883 | function configureVideoJsBuffering (videojs, opts = {}) |
| 1884 | { |
| 1885 | if (opts.enabled === false) return; |
| 1886 | if (!videojs || !videojs.Vhs || videojs.__filemanagerBufferingConfigured) return; |
| 1887 | videojs.__filemanagerBufferingConfigured = true; |
| 1888 | |
| 1889 | const seconds = Number(opts.seconds); |
| 1890 | const bufferSeconds = Number.isFinite(seconds) && seconds > 0 ? seconds : 60 * 60; |
| 1891 | |
| 1892 | try |
| 1893 | { |
| 1894 | videojs.Vhs.GOAL_BUFFER_LENGTH = bufferSeconds; |
| 1895 | videojs.Vhs.MAX_GOAL_BUFFER_LENGTH = bufferSeconds; |
| 1896 | videojs.Vhs.BUFFER_LOW_WATER_LINE = Math.max(30, Math.floor(bufferSeconds / 2)); |
| 1897 | videojs.Vhs.MAX_BUFFER_LOW_WATER_LINE = bufferSeconds; |
| 1898 | } catch |
| 1899 | { |
| 1900 | // Ignore builds that do not expose VHS buffer configuration. |
| 1901 | } |
| 1902 | } |
| 1903 | |
| 1904 | function enableVideoStreamClientCache () |
| 1905 | { |
| 1906 | if (typeof navigator === 'undefined' || !navigator.serviceWorker || typeof navigator.serviceWorker.register !== 'function') |
| 1907 | { |
| 1908 | return Promise.resolve(false); |
| 1909 | } |
| 1910 | |
| 1911 | if (window.__filemanagerVideoStreamCacheSwPromise) |
| 1912 | { |
| 1913 | return window.__filemanagerVideoStreamCacheSwPromise; |
| 1914 | } |
| 1915 | |
| 1916 | window.__filemanagerVideoStreamCacheSwPromise = navigator.serviceWorker.register(VIDEO_STREAM_CACHE_SW_URL, { |
| 1917 | scope: '/', |
| 1918 | updateViaCache: 'none', |
| 1919 | }).then(() => true).catch(() => false); |
| 1920 | |
| 1921 | return window.__filemanagerVideoStreamCacheSwPromise; |
| 1922 | } |
| 1923 | |
| 1924 | function videoStreamCachePrefixFromPlaylistUrl (playlistUrl) |
| 1925 | { |
| 1926 | const raw = String(playlistUrl || '').trim(); |
| 1927 | if (!raw) return null; |
| 1928 | |
| 1929 | let parsed = null; |
| 1930 | try |
| 1931 | { |
| 1932 | parsed = new URL(raw, window.location.origin); |
| 1933 | } catch |
| 1934 | { |
| 1935 | return null; |
| 1936 | } |
| 1937 | |
| 1938 | const pathname = String(parsed.pathname || ''); |
| 1939 | if (!pathname) return null; |
| 1940 | const lastSlashIndex = pathname.lastIndexOf('/'); |
| 1941 | const basePath = lastSlashIndex >= 0 ? pathname.slice(0, lastSlashIndex + 1) : '/'; |
| 1942 | return `${parsed.origin}${basePath}`; |
| 1943 | } |
| 1944 | |
| 1945 | function clearVideoStreamClientCache (playlistUrl) |
| 1946 | { |
| 1947 | const prefix = videoStreamCachePrefixFromPlaylistUrl(playlistUrl); |
| 1948 | if (!prefix || typeof caches === 'undefined' || typeof caches.open !== 'function') |
| 1949 | { |
| 1950 | return Promise.resolve(); |
| 1951 | } |
| 1952 | |
| 1953 | return caches.open(VIDEO_STREAM_CACHE_NAME).then(async (cache) => |
| 1954 | { |
| 1955 | const requests = await cache.keys(); |
| 1956 | const deletions = []; |
| 1957 | for (const request of requests) |
| 1958 | { |
| 1959 | const requestUrl = request && request.url ? String(request.url) : ''; |
| 1960 | if (!requestUrl.startsWith(prefix)) continue; |
| 1961 | deletions.push(cache.delete(request)); |
| 1962 | } |
| 1963 | await Promise.all(deletions); |
| 1964 | }).catch(() => |
| 1965 | { |
| 1966 | // Keep cache cleanup best-effort only. |
| 1967 | }); |
| 1968 | } |
| 1969 | |
| 1970 | function parseHlsManifest (manifestText) |
| 1971 | { |
| 1972 | const lines = String(manifestText || '').split(/\r?\n/); |
| 1973 | const childPlaylists = []; |
| 1974 | const mediaAssets = []; |
| 1975 | const mediaSegmentUris = []; |
| 1976 | const mediaSegments = []; |
| 1977 | let expectPlaylistUri = false; |
| 1978 | let segmentCursorSeconds = 0; |
| 1979 | let pendingSegmentDurationSeconds = null; |
| 1980 | |
| 1981 | for (const rawLine of lines) |
| 1982 | { |
| 1983 | const line = String(rawLine || '').trim(); |
| 1984 | if (!line) continue; |
| 1985 | |
| 1986 | if (line.startsWith('#')) |
| 1987 | { |
| 1988 | if (/^#EXT-X-STREAM-INF/i.test(line)) |
| 1989 | { |
| 1990 | expectPlaylistUri = true; |
| 1991 | continue; |
| 1992 | } |
| 1993 | |
| 1994 | const segmentDurationMatch = line.match(/^#EXTINF\s*:\s*([0-9]+(?:\.[0-9]+)?)/i); |
| 1995 | if (segmentDurationMatch) |
| 1996 | { |
| 1997 | const parsed = Number.parseFloat(segmentDurationMatch[1]); |
| 1998 | pendingSegmentDurationSeconds = Number.isFinite(parsed) && parsed > 0 |
| 1999 | ? parsed |
| 2000 | : VIDEO_STREAM_SEGMENT_DURATION_FALLBACK_SECONDS; |
| 2001 | continue; |
| 2002 | } |
| 2003 | |
| 2004 | const mapMatch = line.match(/^#EXT-X-MAP\s*:\s*.*?URI="([^"]+)"/i); |
| 2005 | if (mapMatch && mapMatch[1]) mediaAssets.push(mapMatch[1]); |
| 2006 | continue; |
| 2007 | } |
| 2008 | |
| 2009 | if (expectPlaylistUri || /\.m3u8(?:$|\?)/i.test(line)) |
| 2010 | { |
| 2011 | childPlaylists.push(line); |
| 2012 | expectPlaylistUri = false; |
| 2013 | } else |
| 2014 | { |
| 2015 | mediaAssets.push(line); |
| 2016 | mediaSegmentUris.push(line); |
| 2017 | if (Number.isFinite(pendingSegmentDurationSeconds) && pendingSegmentDurationSeconds > 0) |
| 2018 | { |
| 2019 | const startTimeSeconds = segmentCursorSeconds; |
| 2020 | segmentCursorSeconds += pendingSegmentDurationSeconds; |
| 2021 | mediaSegments.push({ |
| 2022 | uri: line, |
| 2023 | startTimeSeconds, |
| 2024 | endTimeSeconds: segmentCursorSeconds, |
| 2025 | }); |
| 2026 | } |
| 2027 | pendingSegmentDurationSeconds = null; |
| 2028 | } |
| 2029 | } |
| 2030 | |
| 2031 | return { |
| 2032 | childPlaylists, |
| 2033 | mediaAssets, |
| 2034 | mediaSegmentUris, |
| 2035 | mediaSegments, |
| 2036 | endList: /#EXT-X-ENDLIST/i.test(String(manifestText || '')), |
| 2037 | }; |
| 2038 | } |
| 2039 | |
| 2040 | function inferSegmentEndSecondsFromAssetUrl (assetUrl) |
| 2041 | { |
| 2042 | const value = String(assetUrl || ''); |
| 2043 | if (!value) return null; |
| 2044 | |
| 2045 | let pathname = value; |
| 2046 | try |
| 2047 | { |
| 2048 | pathname = new URL(value, window.location.href).pathname || value; |
| 2049 | } catch |
| 2050 | { |
| 2051 | // Ignore URL parsing failures and fall back to raw value matching. |
| 2052 | } |
| 2053 | |
| 2054 | const match = pathname.match(/_segment_(\d+)(?:\.[a-z0-9]+)?(?:$|\?)/i) |
| 2055 | || pathname.match(/(?:^|[/._-])seg(?:ment)?[_-]?(\d+)(?:\.[a-z0-9]+)?(?:$|\?)/i); |
| 2056 | if (!match) return null; |
| 2057 | |
| 2058 | const segmentIndex = Number.parseInt(match[1], 10); |
| 2059 | if (!Number.isInteger(segmentIndex) || segmentIndex < 0) return null; |
| 2060 | return (segmentIndex + 1) * VIDEO_STREAM_SEGMENT_DURATION_FALLBACK_SECONDS; |
| 2061 | } |
| 2062 | |
| 2063 | function bindStreamAheadSeekMarker (player, streamAheadPrefetch, opts = {}) |
| 2064 | { |
| 2065 | if (!player || typeof player.on !== 'function' || !streamAheadPrefetch) return null; |
| 2066 | |
| 2067 | const markerChar = String(opts.markerChar || ':').slice(0, 1) || ':'; |
| 2068 | const markerColor = String(opts.markerColor || '#d6d6d6'); |
| 2069 | const showTimeTooltip = opts.showTimeTooltip === true; |
| 2070 | let markerEl = null; |
| 2071 | let markerContainerEl = null; |
| 2072 | let cachedThroughSeconds = null; |
| 2073 | let cachedThroughRatio = null; |
| 2074 | let detachProgressListener = null; |
| 2075 | |
| 2076 | const currentDuration = () => |
| 2077 | { |
| 2078 | const duration = Number(player.duration && player.duration()); |
| 2079 | return Number.isFinite(duration) && duration > 0 ? duration : null; |
| 2080 | }; |
| 2081 | |
| 2082 | const updateMarker = () => |
| 2083 | { |
| 2084 | if (!markerEl) return; |
| 2085 | |
| 2086 | const duration = currentDuration(); |
| 2087 | if (!duration || !Number.isFinite(cachedThroughSeconds) || cachedThroughSeconds < 0) |
| 2088 | { |
| 2089 | markerEl.style.display = 'none'; |
| 2090 | return; |
| 2091 | } |
| 2092 | |
| 2093 | const ratioFromSeconds = Number.isFinite(cachedThroughSeconds) |
| 2094 | ? Math.max(0, Math.min(1, cachedThroughSeconds / duration)) |
| 2095 | : null; |
| 2096 | const ratioFromSections = Number.isFinite(cachedThroughRatio) |
| 2097 | ? Math.max(0, Math.min(1, cachedThroughRatio)) |
| 2098 | : null; |
| 2099 | const ratio = Number.isFinite(ratioFromSeconds) |
| 2100 | ? ratioFromSeconds |
| 2101 | : ratioFromSections; |
| 2102 | if (!Number.isFinite(ratio) || ratio <= 0) |
| 2103 | { |
| 2104 | markerEl.style.display = 'none'; |
| 2105 | return; |
| 2106 | } |
| 2107 | |
| 2108 | markerEl.style.display = 'block'; |
| 2109 | markerEl.style.left = `${(ratio * 100).toFixed(4)}%`; |
| 2110 | if (showTimeTooltip) |
| 2111 | { |
| 2112 | if (Number.isFinite(cachedThroughSeconds)) |
| 2113 | { |
| 2114 | markerEl.title = `Walker cached through ${formatClockTime(cachedThroughSeconds)}`; |
| 2115 | } else if (Number.isFinite(cachedThroughRatio)) |
| 2116 | { |
| 2117 | markerEl.title = `Walker cached through ${Math.round(cachedThroughRatio * 100)}%`; |
| 2118 | } else |
| 2119 | { |
| 2120 | markerEl.title = 'Walker cached through'; |
| 2121 | } |
| 2122 | } else |
| 2123 | { |
| 2124 | markerEl.removeAttribute('title'); |
| 2125 | } |
| 2126 | }; |
| 2127 | |
| 2128 | const ensureMarker = () => |
| 2129 | { |
| 2130 | if (markerContainerEl && markerContainerEl.isConnected) |
| 2131 | { |
| 2132 | updateMarker(); |
| 2133 | return; |
| 2134 | } |
| 2135 | |
| 2136 | const playerEl = player.el && player.el(); |
| 2137 | if (!playerEl) return; |
| 2138 | |
| 2139 | const seekBarEl = playerEl.querySelector('.vjs-seek-bar') |
| 2140 | || playerEl.querySelector('.vjs-progress-holder') |
| 2141 | || playerEl.querySelector('.vjs-progress-control'); |
| 2142 | if (!seekBarEl) return; |
| 2143 | |
| 2144 | const computedPosition = window.getComputedStyle(seekBarEl).position; |
| 2145 | if (computedPosition === 'static') seekBarEl.style.position = 'relative'; |
| 2146 | |
| 2147 | markerContainerEl = document.createElement('div'); |
| 2148 | markerContainerEl.className = 'vjs-stream-ahead-cache-marker-container'; |
| 2149 | markerContainerEl.style.position = 'absolute'; |
| 2150 | markerContainerEl.style.left = '0'; |
| 2151 | markerContainerEl.style.right = '0'; |
| 2152 | markerContainerEl.style.top = '50%'; |
| 2153 | markerContainerEl.style.height = '10px'; |
| 2154 | markerContainerEl.style.transform = 'translateY(-50%)'; |
| 2155 | markerContainerEl.style.pointerEvents = 'none'; |
| 2156 | markerContainerEl.style.zIndex = '4'; |
| 2157 | |
| 2158 | markerEl = document.createElement('span'); |
| 2159 | markerEl.className = 'vjs-stream-ahead-cache-marker'; |
| 2160 | markerEl.style.position = 'absolute'; |
| 2161 | markerEl.style.top = '50%'; |
| 2162 | markerEl.style.width = '10px'; |
| 2163 | markerEl.style.height = '10px'; |
| 2164 | markerEl.style.transform = 'translate(-50%, -50%)'; |
| 2165 | markerEl.style.color = markerColor; |
| 2166 | markerEl.style.fontFamily = 'monospace'; |
| 2167 | markerEl.style.fontSize = '12px'; |
| 2168 | markerEl.style.fontWeight = '700'; |
| 2169 | markerEl.style.lineHeight = '10px'; |
| 2170 | markerEl.style.textAlign = 'center'; |
| 2171 | markerEl.style.display = 'none'; |
| 2172 | markerEl.style.textShadow = '0 0 2px rgba(0, 0, 0, 0.65)'; |
| 2173 | markerEl.textContent = markerChar; |
| 2174 | markerEl.setAttribute('aria-hidden', 'true'); |
| 2175 | if (showTimeTooltip) |
| 2176 | { |
| 2177 | markerEl.title = 'Walker cached through 00:00'; |
| 2178 | } |
| 2179 | |
| 2180 | markerContainerEl.appendChild(markerEl); |
| 2181 | seekBarEl.appendChild(markerContainerEl); |
| 2182 | updateMarker(); |
| 2183 | }; |
| 2184 | |
| 2185 | const onDurationHint = () => |
| 2186 | { |
| 2187 | ensureMarker(); |
| 2188 | updateMarker(); |
| 2189 | }; |
| 2190 | |
| 2191 | player.on('loadedmetadata', onDurationHint); |
| 2192 | player.on('durationchange', onDurationHint); |
| 2193 | player.on('loadedplaylist', onDurationHint); |
| 2194 | player.ready(onDurationHint); |
| 2195 | |
| 2196 | if (typeof streamAheadPrefetch.subscribe === 'function') |
| 2197 | { |
| 2198 | detachProgressListener = streamAheadPrefetch.subscribe((status) => |
| 2199 | { |
| 2200 | const nextCachedThrough = status && Number.isFinite(Number(status.cachedThroughSeconds)) |
| 2201 | ? Number(status.cachedThroughSeconds) |
| 2202 | : null; |
| 2203 | cachedThroughSeconds = nextCachedThrough; |
| 2204 | cachedThroughRatio = status && Number.isFinite(Number(status.cachedThroughRatio)) |
| 2205 | ? Number(status.cachedThroughRatio) |
| 2206 | : null; |
| 2207 | ensureMarker(); |
| 2208 | updateMarker(); |
| 2209 | }); |
| 2210 | } else if (typeof streamAheadPrefetch.getStatus === 'function') |
| 2211 | { |
| 2212 | const status = streamAheadPrefetch.getStatus(); |
| 2213 | cachedThroughSeconds = status && Number.isFinite(Number(status.cachedThroughSeconds)) |
| 2214 | ? Number(status.cachedThroughSeconds) |
| 2215 | : null; |
| 2216 | cachedThroughRatio = status && Number.isFinite(Number(status.cachedThroughRatio)) |
| 2217 | ? Number(status.cachedThroughRatio) |
| 2218 | : null; |
| 2219 | ensureMarker(); |
| 2220 | updateMarker(); |
| 2221 | } |
| 2222 | |
| 2223 | return { |
| 2224 | detach: () => |
| 2225 | { |
| 2226 | if (typeof detachProgressListener === 'function') |
| 2227 | { |
| 2228 | try { detachProgressListener(); } catch { /* ignore detach races */ } |
| 2229 | detachProgressListener = null; |
| 2230 | } |
| 2231 | |
| 2232 | if (markerContainerEl && markerContainerEl.parentNode) |
| 2233 | { |
| 2234 | markerContainerEl.parentNode.removeChild(markerContainerEl); |
| 2235 | } |
| 2236 | markerContainerEl = null; |
| 2237 | markerEl = null; |
| 2238 | }, |
| 2239 | }; |
| 2240 | } |
| 2241 | |
| 2242 | function bindStreamAheadPrefetch (opts = {}) |
| 2243 | { |
| 2244 | const basePlaylistUrl = String(opts.playlistUrl || '').trim(); |
| 2245 | if (!basePlaylistUrl) return null; |
| 2246 | |
| 2247 | const pollIntervalMsRaw = Number(opts.pollIntervalMs); |
| 2248 | const pollIntervalMs = Number.isFinite(pollIntervalMsRaw) && pollIntervalMsRaw >= 0 |
| 2249 | ? pollIntervalMsRaw |
| 2250 | : VIDEO_STREAM_AHEAD_PREFETCH_POLL_MS_DEFAULT; |
| 2251 | const headers = opts.headers; |
| 2252 | const credentials = opts.credentials; |
| 2253 | |
| 2254 | const playlistStatusByUrl = new Map(); |
| 2255 | const knownPlaylistUrls = new Set([basePlaylistUrl]); |
| 2256 | const fetchedAssetUrls = new Set(); |
| 2257 | const segmentEndSecondsByAssetUrl = new Map(); |
| 2258 | const discoveredSegmentUrls = new Set(); |
| 2259 | const fetchedSegmentUrls = new Set(); |
| 2260 | const progressListeners = new Set(); |
| 2261 | const controller = typeof AbortController === 'function' ? new AbortController() : null; |
| 2262 | let stopped = false; |
| 2263 | let cachedThroughSeconds = null; |
| 2264 | let cachedThroughRatio = null; |
| 2265 | let fetchedTimelineAssetCount = 0; |
| 2266 | |
| 2267 | const recalculateSegmentRatio = () => |
| 2268 | { |
| 2269 | const totalSegments = discoveredSegmentUrls.size; |
| 2270 | if (totalSegments <= 0) |
| 2271 | { |
| 2272 | cachedThroughRatio = null; |
| 2273 | return; |
| 2274 | } |
| 2275 | cachedThroughRatio = Math.max(0, Math.min(1, fetchedSegmentUrls.size / totalSegments)); |
| 2276 | }; |
| 2277 | |
| 2278 | const resolveUrl = (value, parentUrl) => |
| 2279 | { |
| 2280 | try |
| 2281 | { |
| 2282 | return new URL(String(value || '').trim(), parentUrl || window.location.href).toString(); |
| 2283 | } catch |
| 2284 | { |
| 2285 | return null; |
| 2286 | } |
| 2287 | }; |
| 2288 | |
| 2289 | const wait = (ms) => new Promise((resolve) => window.setTimeout(resolve, ms)); |
| 2290 | |
| 2291 | const fetchText = async (url) => |
| 2292 | { |
| 2293 | const res = await fetch(url, { |
| 2294 | method: 'GET', |
| 2295 | headers, |
| 2296 | credentials, |
| 2297 | cache: 'no-store', |
| 2298 | signal: controller ? controller.signal : undefined, |
| 2299 | }); |
| 2300 | if (!res || !res.ok) return null; |
| 2301 | return res.text(); |
| 2302 | }; |
| 2303 | |
| 2304 | const fetchAsset = async (url) => |
| 2305 | { |
| 2306 | const res = await fetch(url, { |
| 2307 | method: 'GET', |
| 2308 | headers, |
| 2309 | credentials, |
| 2310 | signal: controller ? controller.signal : undefined, |
| 2311 | }); |
| 2312 | if (!res || !res.ok) return false; |
| 2313 | // Ensure body fully reads so browser/service-worker caches the asset bytes. |
| 2314 | await res.arrayBuffer(); |
| 2315 | return true; |
| 2316 | }; |
| 2317 | |
| 2318 | const getStatus = () => ({ |
| 2319 | cachedThroughSeconds, |
| 2320 | cachedThroughRatio, |
| 2321 | knownPlaylistCount: knownPlaylistUrls.size, |
| 2322 | fetchedAssetCount: fetchedAssetUrls.size, |
| 2323 | fetchedTimelineAssetCount, |
| 2324 | totalSegmentCount: discoveredSegmentUrls.size, |
| 2325 | fetchedSegmentCount: fetchedSegmentUrls.size, |
| 2326 | allPlaylistsComplete: Array.from(knownPlaylistUrls).every((url) => playlistStatusByUrl.get(url) === true), |
| 2327 | stopped, |
| 2328 | }); |
| 2329 | |
| 2330 | const appearsTimelineAsset = (assetUrl) => |
| 2331 | /(?:\.ts|\.m4s|\.mp4|\.aac|\.m4a)(?:$|\?)/i.test(String(assetUrl || '')); |
| 2332 | |
| 2333 | const emitProgress = () => |
| 2334 | { |
| 2335 | const status = getStatus(); |
| 2336 | for (const listener of Array.from(progressListeners)) |
| 2337 | { |
| 2338 | try |
| 2339 | { |
| 2340 | listener(status); |
| 2341 | } catch |
| 2342 | { |
| 2343 | // Keep progress listeners best-effort only. |
| 2344 | } |
| 2345 | } |
| 2346 | }; |
| 2347 | |
| 2348 | const workerPromise = (async () => |
| 2349 | { |
| 2350 | while (!stopped) |
| 2351 | { |
| 2352 | const nextAssetUrlSet = new Set(); |
| 2353 | |
| 2354 | for (const playlistUrl of Array.from(knownPlaylistUrls)) |
| 2355 | { |
| 2356 | if (stopped) return; |
| 2357 | const manifestText = await fetchText(playlistUrl).catch(() => null); |
| 2358 | if (!manifestText) continue; |
| 2359 | |
| 2360 | const parsed = parseHlsManifest(manifestText); |
| 2361 | playlistStatusByUrl.set(playlistUrl, !!parsed.endList); |
| 2362 | |
| 2363 | for (const child of parsed.childPlaylists) |
| 2364 | { |
| 2365 | const resolved = resolveUrl(child, playlistUrl); |
| 2366 | if (!resolved) continue; |
| 2367 | knownPlaylistUrls.add(resolved); |
| 2368 | if (!playlistStatusByUrl.has(resolved)) playlistStatusByUrl.set(resolved, false); |
| 2369 | } |
| 2370 | |
| 2371 | for (const asset of parsed.mediaAssets) |
| 2372 | { |
| 2373 | const resolved = resolveUrl(asset, playlistUrl); |
| 2374 | if (!resolved || fetchedAssetUrls.has(resolved)) continue; |
| 2375 | nextAssetUrlSet.add(resolved); |
| 2376 | } |
| 2377 | |
| 2378 | for (const segment of parsed.mediaSegments) |
| 2379 | { |
| 2380 | if (!segment || !segment.uri) continue; |
| 2381 | const resolved = resolveUrl(segment.uri, playlistUrl); |
| 2382 | if (!resolved) continue; |
| 2383 | if (!Number.isFinite(segment.endTimeSeconds) || segment.endTimeSeconds < 0) continue; |
| 2384 | segmentEndSecondsByAssetUrl.set(resolved, Number(segment.endTimeSeconds)); |
| 2385 | } |
| 2386 | |
| 2387 | for (const segmentUri of parsed.mediaSegmentUris) |
| 2388 | { |
| 2389 | const resolved = resolveUrl(segmentUri, playlistUrl); |
| 2390 | if (!resolved) continue; |
| 2391 | discoveredSegmentUrls.add(resolved); |
| 2392 | } |
| 2393 | } |
| 2394 | |
| 2395 | recalculateSegmentRatio(); |
| 2396 | emitProgress(); |
| 2397 | |
| 2398 | const nextAssetUrls = Array.from(nextAssetUrlSet); |
| 2399 | for (const assetUrl of nextAssetUrls) |
| 2400 | { |
| 2401 | if (stopped) return; |
| 2402 | const fetched = await fetchAsset(assetUrl).catch(() => false); |
| 2403 | if (!fetched) continue; |
| 2404 | |
| 2405 | fetchedAssetUrls.add(assetUrl); |
| 2406 | if (discoveredSegmentUrls.has(assetUrl)) |
| 2407 | { |
| 2408 | fetchedSegmentUrls.add(assetUrl); |
| 2409 | } |
| 2410 | const mappedSegmentEndSeconds = segmentEndSecondsByAssetUrl.get(assetUrl); |
| 2411 | const inferredSegmentEndSeconds = inferSegmentEndSecondsFromAssetUrl(assetUrl); |
| 2412 | let fallbackSegmentEndSeconds = null; |
| 2413 | if (!Number.isFinite(mappedSegmentEndSeconds) && !Number.isFinite(inferredSegmentEndSeconds) && appearsTimelineAsset(assetUrl)) |
| 2414 | { |
| 2415 | fetchedTimelineAssetCount += 1; |
| 2416 | fallbackSegmentEndSeconds = fetchedTimelineAssetCount * VIDEO_STREAM_SEGMENT_DURATION_FALLBACK_SECONDS; |
| 2417 | } |
| 2418 | |
| 2419 | const segmentEndSeconds = [mappedSegmentEndSeconds, inferredSegmentEndSeconds, fallbackSegmentEndSeconds] |
| 2420 | .filter((value) => Number.isFinite(value)) |
| 2421 | .reduce((maxValue, value) => (value > maxValue ? value : maxValue), -1); |
| 2422 | |
| 2423 | if (Number.isFinite(segmentEndSeconds)) |
| 2424 | { |
| 2425 | if (!Number.isFinite(cachedThroughSeconds) || segmentEndSeconds > cachedThroughSeconds) |
| 2426 | { |
| 2427 | cachedThroughSeconds = segmentEndSeconds; |
| 2428 | } |
| 2429 | } |
| 2430 | |
| 2431 | recalculateSegmentRatio(); |
| 2432 | emitProgress(); |
| 2433 | } |
| 2434 | |
| 2435 | const allPlaylistsComplete = Array.from(knownPlaylistUrls).every((url) => playlistStatusByUrl.get(url) === true); |
| 2436 | if (allPlaylistsComplete && !nextAssetUrls.length) |
| 2437 | { |
| 2438 | emitProgress(); |
| 2439 | return; |
| 2440 | } |
| 2441 | |
| 2442 | if (pollIntervalMs > 0) |
| 2443 | { |
| 2444 | await wait(pollIntervalMs); |
| 2445 | } |
| 2446 | } |
| 2447 | })(); |
| 2448 | |
| 2449 | return { |
| 2450 | stop: () => |
| 2451 | { |
| 2452 | stopped = true; |
| 2453 | if (controller && typeof controller.abort === 'function') |
| 2454 | { |
| 2455 | try { controller.abort(); } catch { /* ignore abort races */ } |
| 2456 | } |
| 2457 | emitProgress(); |
| 2458 | }, |
| 2459 | done: () => workerPromise, |
| 2460 | getStatus, |
| 2461 | subscribe: (listener) => |
| 2462 | { |
| 2463 | if (typeof listener !== 'function') return () => { }; |
| 2464 | progressListeners.add(listener); |
| 2465 | try { listener(getStatus()); } catch { /* ignore listener failures */ } |
| 2466 | return () => |
| 2467 | { |
| 2468 | progressListeners.delete(listener); |
| 2469 | }; |
| 2470 | }, |
| 2471 | }; |
| 2472 | } |
| 2473 | |
| 2474 | function applyDefaultTextTrackPrefs () |
| 2475 | { |
| 2476 | try |
| 2477 | { |
| 2478 | localStorage.setItem(VIDEO_TEXT_TRACK_SETTINGS_KEY, VIDEO_TEXT_TRACK_OVERRIDE_SETTINGS_RAW); |
| 2479 | } catch |
| 2480 | { |
| 2481 | // Ignore localStorage failures. |
| 2482 | } |
| 2483 | } |
| 2484 | |
| 2485 | window.FilemanagerSharedVideoPlayer = { |
| 2486 | applyDefaultTextTrackPrefs, |
| 2487 | bindImageSubtitleOverlay, |
| 2488 | bindStreamAheadPrefetch, |
| 2489 | bindStreamAheadSeekMarker, |
| 2490 | bindTrackPrefs, |
| 2491 | clearVideoStreamClientCache, |
| 2492 | configureVideoJsBuffering, |
| 2493 | enableVideoStreamClientCache, |
| 2494 | ensureVideoPlaybackUi, |
| 2495 | normaliseVideoDuration, |
| 2496 | }; |
| 2497 | }()); |