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