| 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_PREFETCH_STEP_SECONDS = 0.5; |
| 15 | const IMAGE_SUBTITLE_CURRENT_REQUEST_TIMEOUT_MS_DEFAULT = 4000; |
| 16 | const IMAGE_SUBTITLE_PREFETCH_REQUEST_TIMEOUT_MS_DEFAULT = 4000; |
| 17 | const IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS_DEFAULT = 0; |
| 18 | |
| 19 | function roundLogNumber (value, digits = 3) |
| 20 | { |
| 21 | const numeric = Number(value); |
| 22 | if (!Number.isFinite(numeric)) return null; |
| 23 | return Number(numeric.toFixed(digits)); |
| 24 | } |
| 25 | |
| 26 | function parseHeaderInt (res, name) |
| 27 | { |
| 28 | if (!res || !res.headers || typeof res.headers.get !== 'function') return null; |
| 29 | const value = Number.parseInt(String(res.headers.get(name) || ''), 10); |
| 30 | return Number.isFinite(value) ? value : null; |
| 31 | } |
| 32 | |
| 33 | function parseHeaderFloat (res, name) |
| 34 | { |
| 35 | if (!res || !res.headers || typeof res.headers.get !== 'function') return null; |
| 36 | const value = Number.parseFloat(String(res.headers.get(name) || '')); |
| 37 | return Number.isFinite(value) ? value : null; |
| 38 | } |
| 39 | |
| 40 | function diffMilliseconds (later, earlier) |
| 41 | { |
| 42 | if (!Number.isFinite(later) || !Number.isFinite(earlier)) return null; |
| 43 | return Math.round(later - earlier); |
| 44 | } |
| 45 | |
| 46 | function diffSeconds (later, earlier) |
| 47 | { |
| 48 | if (!Number.isFinite(later) || !Number.isFinite(earlier)) return null; |
| 49 | return roundLogNumber(later - earlier, 3); |
| 50 | } |
| 51 | |
| 52 | function waitForImagePresentation (windowRef, imageEl) |
| 53 | { |
| 54 | return new Promise((resolve) => |
| 55 | { |
| 56 | let settled = false; |
| 57 | let fallbackTimer = null; |
| 58 | const raf = typeof windowRef.requestAnimationFrame === 'function' |
| 59 | ? windowRef.requestAnimationFrame.bind(windowRef) |
| 60 | : (fn) => windowRef.setTimeout(fn, 0); |
| 61 | |
| 62 | const cleanup = () => |
| 63 | { |
| 64 | imageEl.removeEventListener('load', onLoad); |
| 65 | imageEl.removeEventListener('error', onError); |
| 66 | if (fallbackTimer !== null) windowRef.clearTimeout(fallbackTimer); |
| 67 | }; |
| 68 | |
| 69 | const finish = () => |
| 70 | { |
| 71 | if (settled) return; |
| 72 | settled = true; |
| 73 | cleanup(); |
| 74 | raf(() => resolve(Date.now())); |
| 75 | }; |
| 76 | |
| 77 | const onLoad = () => finish(); |
| 78 | const onError = () => finish(); |
| 79 | |
| 80 | imageEl.addEventListener('load', onLoad); |
| 81 | imageEl.addEventListener('error', onError); |
| 82 | fallbackTimer = windowRef.setTimeout(finish, 250); |
| 83 | |
| 84 | if (imageEl.complete && imageEl.currentSrc) |
| 85 | { |
| 86 | finish(); |
| 87 | } |
| 88 | }); |
| 89 | } |
| 90 | |
| 91 | function normaliseTrackName (name) |
| 92 | { |
| 93 | return String(name || '').trim().toLowerCase(); |
| 94 | } |
| 95 | |
| 96 | function getTrackName (track) |
| 97 | { |
| 98 | if (!track || typeof track !== 'object') return ''; |
| 99 | const label = String(track.label || '').trim(); |
| 100 | if (label) return label; |
| 101 | const name = String(track.name || '').trim(); |
| 102 | if (name) return name; |
| 103 | const language = String(track.language || '').trim(); |
| 104 | if (language) return language; |
| 105 | const id = String(track.id || '').trim(); |
| 106 | if (id) return id; |
| 107 | return ''; |
| 108 | } |
| 109 | |
| 110 | function trackListToArray (trackList) |
| 111 | { |
| 112 | if (!trackList || typeof trackList.length !== 'number') return []; |
| 113 | const out = []; |
| 114 | for (let i = 0; i < trackList.length; i++) |
| 115 | { |
| 116 | const track = trackList[i] || (typeof trackList.item === 'function' ? trackList.item(i) : null); |
| 117 | if (track) out.push(track); |
| 118 | } |
| 119 | return out; |
| 120 | } |
| 121 | |
| 122 | function subtitleTracksFromPlayer (player) |
| 123 | { |
| 124 | if (!player || typeof player.textTracks !== 'function') return []; |
| 125 | return trackListToArray(player.textTracks()).filter((track) => |
| 126 | { |
| 127 | const kind = String(track.kind || '').toLowerCase(); |
| 128 | return kind === 'subtitles' || kind === 'captions'; |
| 129 | }); |
| 130 | } |
| 131 | |
| 132 | function audioTracksFromPlayer (player) |
| 133 | { |
| 134 | if (!player || typeof player.audioTracks !== 'function') return []; |
| 135 | return trackListToArray(player.audioTracks()); |
| 136 | } |
| 137 | |
| 138 | function applySavedSubtitleTrack (player, savedName) |
| 139 | { |
| 140 | if (typeof savedName !== 'string') return; |
| 141 | const tracks = subtitleTracksFromPlayer(player); |
| 142 | if (!tracks.length) return; |
| 143 | |
| 144 | const wanted = normaliseTrackName(savedName); |
| 145 | if (!wanted) |
| 146 | { |
| 147 | for (const track of tracks) track.mode = 'disabled'; |
| 148 | return; |
| 149 | } |
| 150 | |
| 151 | const match = tracks.find((track) => normaliseTrackName(getTrackName(track)) === wanted); |
| 152 | if (!match) return; |
| 153 | |
| 154 | for (const track of tracks) |
| 155 | { |
| 156 | track.mode = track === match ? 'showing' : 'disabled'; |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | function applySavedAudioTrack (player, savedName) |
| 161 | { |
| 162 | if (typeof savedName !== 'string') return; |
| 163 | const tracks = audioTracksFromPlayer(player); |
| 164 | if (!tracks.length) return; |
| 165 | |
| 166 | const wanted = normaliseTrackName(savedName); |
| 167 | if (!wanted) return; |
| 168 | |
| 169 | const match = tracks.find((track) => normaliseTrackName(getTrackName(track)) === wanted); |
| 170 | if (!match) return; |
| 171 | |
| 172 | for (const track of tracks) |
| 173 | { |
| 174 | track.enabled = track === match; |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | function getSelectedSubtitleTrackName (player) |
| 179 | { |
| 180 | const tracks = subtitleTracksFromPlayer(player); |
| 181 | if (!tracks.length) return null; |
| 182 | const active = tracks.find((track) => String(track.mode || '').toLowerCase() === 'showing'); |
| 183 | return active ? getTrackName(active) : ''; |
| 184 | } |
| 185 | |
| 186 | function getSelectedAudioTrackName (player) |
| 187 | { |
| 188 | const tracks = audioTracksFromPlayer(player); |
| 189 | if (!tracks.length) return null; |
| 190 | const active = tracks.find((track) => !!track.enabled); |
| 191 | return active ? getTrackName(active) : ''; |
| 192 | } |
| 193 | |
| 194 | function bindTrackPrefs (player, prefs, savePrefs) |
| 195 | { |
| 196 | const save = typeof savePrefs === 'function' ? savePrefs : (() => { }); |
| 197 | const applySavedTracks = () => |
| 198 | { |
| 199 | applySavedSubtitleTrack(player, prefs.subtitleTrackName); |
| 200 | applySavedAudioTrack(player, prefs.audioTrackName); |
| 201 | }; |
| 202 | |
| 203 | const captureSelectedTracks = () => |
| 204 | { |
| 205 | const subtitleTrackName = getSelectedSubtitleTrackName(player); |
| 206 | const audioTrackName = getSelectedAudioTrackName(player); |
| 207 | const patch = {}; |
| 208 | |
| 209 | if (subtitleTrackName !== null) patch.subtitleTrackName = subtitleTrackName; |
| 210 | if (audioTrackName !== null) patch.audioTrackName = audioTrackName; |
| 211 | |
| 212 | if (Object.keys(patch).length) save(patch); |
| 213 | }; |
| 214 | |
| 215 | const textTrackList = typeof player.textTracks === 'function' ? player.textTracks() : null; |
| 216 | const audioTrackList = typeof player.audioTracks === 'function' ? player.audioTracks() : null; |
| 217 | const onTrackListChange = () => captureSelectedTracks(); |
| 218 | |
| 219 | if (textTrackList && typeof textTrackList.addEventListener === 'function') |
| 220 | { |
| 221 | textTrackList.addEventListener('change', onTrackListChange); |
| 222 | } |
| 223 | |
| 224 | if (audioTrackList && typeof audioTrackList.addEventListener === 'function') |
| 225 | { |
| 226 | audioTrackList.addEventListener('change', onTrackListChange); |
| 227 | } |
| 228 | |
| 229 | return { |
| 230 | applySavedTracks, |
| 231 | captureSelectedTracks, |
| 232 | detach: () => |
| 233 | { |
| 234 | if (textTrackList && typeof textTrackList.removeEventListener === 'function') |
| 235 | { |
| 236 | textTrackList.removeEventListener('change', onTrackListChange); |
| 237 | } |
| 238 | if (audioTrackList && typeof audioTrackList.removeEventListener === 'function') |
| 239 | { |
| 240 | audioTrackList.removeEventListener('change', onTrackListChange); |
| 241 | } |
| 242 | }, |
| 243 | }; |
| 244 | } |
| 245 | |
| 246 | function bindImageSubtitleOverlay (player, videojs, prefs, session, opts = {}) |
| 247 | { |
| 248 | const imageTracks = Array.isArray(session.imageSubtitleTracks) |
| 249 | ? session.imageSubtitleTracks.map((track) => ({ |
| 250 | label: String(track.label || '').trim() || `Subtitle ${Number(track.streamIndex || 0) + 1}`, |
| 251 | language: String(track.language || '').trim(), |
| 252 | isDefault: !!track.default, |
| 253 | streamIndex: Number(track.streamIndex), |
| 254 | })).filter((track) => Number.isInteger(track.streamIndex) && track.streamIndex >= 0) |
| 255 | : []; |
| 256 | |
| 257 | if (!imageTracks.length) return null; |
| 258 | |
| 259 | const savePrefs = typeof opts.savePrefs === 'function' ? opts.savePrefs : (() => { }); |
| 260 | const buildFrameRequest = typeof opts.buildFrameRequest === 'function' ? opts.buildFrameRequest : null; |
| 261 | const notifyError = typeof opts.onError === 'function' ? opts.onError : (() => { }); |
| 262 | const sendSubtitleLogBatch = typeof opts.sendSubtitleLogBatch === 'function' ? opts.sendSubtitleLogBatch : null; |
| 263 | const requestedLookaheadSeconds = Number(opts.lookaheadSeconds); |
| 264 | const lookaheadSeconds = Number.isFinite(requestedLookaheadSeconds) |
| 265 | ? Math.max(0, Math.min(IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_MAX, requestedLookaheadSeconds)) |
| 266 | : IMAGE_SUBTITLE_LOOKAHEAD_SECONDS_DEFAULT; |
| 267 | const requestedCurrentRequestTimeoutMs = Number(opts.currentRequestTimeoutMs); |
| 268 | const currentRequestTimeoutMs = Number.isFinite(requestedCurrentRequestTimeoutMs) |
| 269 | ? Math.max(250, requestedCurrentRequestTimeoutMs) |
| 270 | : IMAGE_SUBTITLE_CURRENT_REQUEST_TIMEOUT_MS_DEFAULT; |
| 271 | const requestedPrefetchRequestTimeoutMs = Number(opts.prefetchRequestTimeoutMs); |
| 272 | const prefetchRequestTimeoutMs = Number.isFinite(requestedPrefetchRequestTimeoutMs) |
| 273 | ? Math.max(250, requestedPrefetchRequestTimeoutMs) |
| 274 | : IMAGE_SUBTITLE_PREFETCH_REQUEST_TIMEOUT_MS_DEFAULT; |
| 275 | const requestedPrefetchRequestIntervalMs = Number(opts.prefetchRequestIntervalMs); |
| 276 | const prefetchRequestIntervalMs = Number.isFinite(requestedPrefetchRequestIntervalMs) |
| 277 | ? Math.max(0, requestedPrefetchRequestIntervalMs) |
| 278 | : IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS_DEFAULT; |
| 279 | const logToConsole = opts.logToConsole !== false; |
| 280 | if (!buildFrameRequest) return null; |
| 281 | |
| 282 | const trackByStreamIndex = new Map(imageTracks.map((track) => [track.streamIndex, track])); |
| 283 | let selectedStreamIndex = null; |
| 284 | let menuOpen = false; |
| 285 | let activeBucket = -1; |
| 286 | let activeObjectUrl = null; |
| 287 | let overlayEl = null; |
| 288 | let overlayImgEl = null; |
| 289 | let menuEl = null; |
| 290 | let buttonEl = null; |
| 291 | let trackDisabled = false; |
| 292 | let failureNotified = false; |
| 293 | let lifecycleToken = 0; |
| 294 | let currentFrameToken = 0; |
| 295 | let currentFrameAbortController = null; |
| 296 | let prefetchWorkerToken = 0; |
| 297 | let prefetchAbortController = null; |
| 298 | let prefetchPromise = null; |
| 299 | let prefetchTargetTimeSeconds = -1; |
| 300 | let prefetchedThroughTimeSeconds = -1; |
| 301 | let queuedCurrentRefresh = false; |
| 302 | let queuedCurrentRefreshForce = false; |
| 303 | let currentFramePromise = null; |
| 304 | let seekMarkerContainerEl = null; |
| 305 | let seekMarkerRequestedEl = null; |
| 306 | let seekMarkerReceivedEl = null; |
| 307 | let lastRequestedCaptionStartTimeSeconds = null; |
| 308 | let lastReceivedCaptionStartTimeSeconds = null; |
| 309 | let subtitleLogSequence = 0; |
| 310 | let subtitleLogQueue = []; |
| 311 | let subtitleLogFlushTimer = null; |
| 312 | |
| 313 | const flushSubtitleLogs = () => |
| 314 | { |
| 315 | if (!sendSubtitleLogBatch || !subtitleLogQueue.length) return; |
| 316 | if (subtitleLogFlushTimer) |
| 317 | { |
| 318 | window.clearTimeout(subtitleLogFlushTimer); |
| 319 | subtitleLogFlushTimer = null; |
| 320 | } |
| 321 | |
| 322 | const batch = subtitleLogQueue; |
| 323 | subtitleLogQueue = []; |
| 324 | Promise.resolve(sendSubtitleLogBatch(batch)).catch(() => |
| 325 | { |
| 326 | // Keep subtitle diagnostics best-effort only. |
| 327 | }); |
| 328 | }; |
| 329 | |
| 330 | const scheduleSubtitleLogFlush = () => |
| 331 | { |
| 332 | if (!sendSubtitleLogBatch || !subtitleLogQueue.length) return; |
| 333 | if (subtitleLogQueue.length >= SUBTITLE_LOG_BATCH_MAX_ITEMS) |
| 334 | { |
| 335 | flushSubtitleLogs(); |
| 336 | return; |
| 337 | } |
| 338 | if (subtitleLogFlushTimer) return; |
| 339 | subtitleLogFlushTimer = window.setTimeout(() => |
| 340 | { |
| 341 | subtitleLogFlushTimer = null; |
| 342 | flushSubtitleLogs(); |
| 343 | }, SUBTITLE_LOG_FLUSH_DELAY_MS); |
| 344 | }; |
| 345 | |
| 346 | const logSubtitleEvent = (eventType, details = {}) => |
| 347 | { |
| 348 | const entry = { |
| 349 | seq: ++subtitleLogSequence, |
| 350 | loggedAtMs: Date.now(), |
| 351 | eventType, |
| 352 | sessionId: String(session.sessionId || '').trim() || null, |
| 353 | streamIndex: Number.isInteger(selectedStreamIndex) ? selectedStreamIndex : null, |
| 354 | playerTimeSeconds: roundLogNumber(player.currentTime()), |
| 355 | ...details, |
| 356 | }; |
| 357 | if (logToConsole) |
| 358 | { |
| 359 | try |
| 360 | { |
| 361 | console.log('[subtitle-log]', entry); |
| 362 | } catch |
| 363 | { |
| 364 | // Ignore console availability issues. |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | if (!sendSubtitleLogBatch) return; |
| 369 | subtitleLogQueue.push(entry); |
| 370 | scheduleSubtitleLogFlush(); |
| 371 | }; |
| 372 | |
| 373 | const createAbortController = () => |
| 374 | { |
| 375 | if (typeof AbortController !== 'function') return null; |
| 376 | return new AbortController(); |
| 377 | }; |
| 378 | |
| 379 | const abortController = (controller) => |
| 380 | { |
| 381 | if (!controller || typeof controller.abort !== 'function') return; |
| 382 | try |
| 383 | { |
| 384 | controller.abort(); |
| 385 | } catch |
| 386 | { |
| 387 | // Ignore abort races during teardown. |
| 388 | } |
| 389 | }; |
| 390 | |
| 391 | const isAbortError = (error) => |
| 392 | { |
| 393 | return !!(error && typeof error === 'object' && error.name === 'AbortError'); |
| 394 | }; |
| 395 | |
| 396 | const armRequestTimeout = (controller, timeoutMs, onTimeout) => |
| 397 | { |
| 398 | if (!controller || !Number.isFinite(timeoutMs) || timeoutMs <= 0) return null; |
| 399 | return window.setTimeout(() => |
| 400 | { |
| 401 | if (typeof onTimeout === 'function') onTimeout(); |
| 402 | abortController(controller); |
| 403 | }, timeoutMs); |
| 404 | }; |
| 405 | |
| 406 | const clearRequestTimeout = (timeoutId) => |
| 407 | { |
| 408 | if (timeoutId === null || timeoutId === undefined) return; |
| 409 | window.clearTimeout(timeoutId); |
| 410 | }; |
| 411 | |
| 412 | const cancelCurrentFrameRequest = () => |
| 413 | { |
| 414 | currentFrameToken++; |
| 415 | abortController(currentFrameAbortController); |
| 416 | currentFrameAbortController = null; |
| 417 | }; |
| 418 | |
| 419 | const cancelPrefetchRequests = ({ resetProgress = false } = {}) => |
| 420 | { |
| 421 | prefetchWorkerToken++; |
| 422 | abortController(prefetchAbortController); |
| 423 | prefetchAbortController = null; |
| 424 | prefetchPromise = null; |
| 425 | if (resetProgress) |
| 426 | { |
| 427 | prefetchTargetTimeSeconds = -1; |
| 428 | prefetchedThroughTimeSeconds = -1; |
| 429 | } |
| 430 | }; |
| 431 | |
| 432 | const resetRequestState = () => |
| 433 | { |
| 434 | lifecycleToken++; |
| 435 | cancelCurrentFrameRequest(); |
| 436 | cancelPrefetchRequests({ resetProgress: true }); |
| 437 | }; |
| 438 | |
| 439 | const closeObjectUrl = () => |
| 440 | { |
| 441 | if (activeObjectUrl) |
| 442 | { |
| 443 | URL.revokeObjectURL(activeObjectUrl); |
| 444 | activeObjectUrl = null; |
| 445 | } |
| 446 | }; |
| 447 | |
| 448 | const hideOverlay = () => |
| 449 | { |
| 450 | if (overlayEl) overlayEl.style.display = 'none'; |
| 451 | if (overlayImgEl) overlayImgEl.removeAttribute('src'); |
| 452 | closeObjectUrl(); |
| 453 | }; |
| 454 | |
| 455 | const setSeekMarkerTime = (kind, timeSeconds) => |
| 456 | { |
| 457 | const numericTime = Number(timeSeconds); |
| 458 | const nextTime = Number.isFinite(numericTime) && numericTime >= 0 ? numericTime : null; |
| 459 | |
| 460 | if (kind === 'requested') |
| 461 | { |
| 462 | lastRequestedCaptionStartTimeSeconds = nextTime; |
| 463 | } else if (kind === 'received') |
| 464 | { |
| 465 | lastReceivedCaptionStartTimeSeconds = nextTime; |
| 466 | } |
| 467 | }; |
| 468 | |
| 469 | const updateSeekBarMarkers = () => |
| 470 | { |
| 471 | if (!seekMarkerRequestedEl || !seekMarkerReceivedEl) return; |
| 472 | |
| 473 | const duration = Number(player.duration && player.duration()); |
| 474 | if (!Number.isFinite(duration) || duration <= 0) |
| 475 | { |
| 476 | seekMarkerRequestedEl.style.display = 'none'; |
| 477 | seekMarkerReceivedEl.style.display = 'none'; |
| 478 | return; |
| 479 | } |
| 480 | |
| 481 | const applyMarker = (markerEl, markerTimeSeconds) => |
| 482 | { |
| 483 | if (!Number.isFinite(markerTimeSeconds) || markerTimeSeconds < 0) |
| 484 | { |
| 485 | markerEl.style.display = 'none'; |
| 486 | return; |
| 487 | } |
| 488 | |
| 489 | const ratio = Math.max(0, Math.min(1, markerTimeSeconds / duration)); |
| 490 | markerEl.style.display = 'block'; |
| 491 | markerEl.style.left = `${(ratio * 100).toFixed(4)}%`; |
| 492 | }; |
| 493 | |
| 494 | applyMarker(seekMarkerRequestedEl, lastRequestedCaptionStartTimeSeconds); |
| 495 | applyMarker(seekMarkerReceivedEl, lastReceivedCaptionStartTimeSeconds); |
| 496 | }; |
| 497 | |
| 498 | const ensureSeekBarMarkers = () => |
| 499 | { |
| 500 | if (seekMarkerContainerEl && seekMarkerContainerEl.isConnected) |
| 501 | { |
| 502 | updateSeekBarMarkers(); |
| 503 | return; |
| 504 | } |
| 505 | |
| 506 | const playerEl = player.el && player.el(); |
| 507 | if (!playerEl) return; |
| 508 | |
| 509 | const seekBarEl = playerEl.querySelector('.vjs-seek-bar') |
| 510 | || playerEl.querySelector('.vjs-progress-holder') |
| 511 | || playerEl.querySelector('.vjs-progress-control'); |
| 512 | if (!seekBarEl) return; |
| 513 | |
| 514 | const computedPosition = window.getComputedStyle(seekBarEl).position; |
| 515 | if (computedPosition === 'static') seekBarEl.style.position = 'relative'; |
| 516 | |
| 517 | seekMarkerContainerEl = document.createElement('div'); |
| 518 | seekMarkerContainerEl.className = 'vjs-image-subtitle-seek-markers'; |
| 519 | seekMarkerContainerEl.style.position = 'absolute'; |
| 520 | seekMarkerContainerEl.style.left = '0'; |
| 521 | seekMarkerContainerEl.style.right = '0'; |
| 522 | seekMarkerContainerEl.style.top = '50%'; |
| 523 | seekMarkerContainerEl.style.height = '10px'; |
| 524 | seekMarkerContainerEl.style.transform = 'translateY(-50%)'; |
| 525 | seekMarkerContainerEl.style.pointerEvents = 'none'; |
| 526 | seekMarkerContainerEl.style.zIndex = '5'; |
| 527 | |
| 528 | const buildBracketMarker = (direction) => |
| 529 | { |
| 530 | const markerEl = document.createElement('span'); |
| 531 | markerEl.className = `vjs-image-subtitle-seek-marker vjs-image-subtitle-seek-marker-${direction}`; |
| 532 | markerEl.style.position = 'absolute'; |
| 533 | markerEl.style.top = '50%'; |
| 534 | markerEl.style.width = '10px'; |
| 535 | markerEl.style.height = '10px'; |
| 536 | markerEl.style.transform = 'translate(-50%, -50%)'; |
| 537 | markerEl.style.color = '#fff'; |
| 538 | markerEl.style.fontFamily = 'monospace'; |
| 539 | markerEl.style.fontSize = '12px'; |
| 540 | markerEl.style.fontWeight = '700'; |
| 541 | markerEl.style.lineHeight = '10px'; |
| 542 | markerEl.style.textAlign = 'center'; |
| 543 | markerEl.style.textShadow = '-1px 0 #000, 0 1px #000, 1px 0 #000, 0 -1px #000'; |
| 544 | markerEl.style.display = 'none'; |
| 545 | markerEl.textContent = direction === 'left' ? '[' : ']'; |
| 546 | markerEl.setAttribute('aria-hidden', 'true'); |
| 547 | return markerEl; |
| 548 | }; |
| 549 | |
| 550 | seekMarkerReceivedEl = buildBracketMarker('left'); |
| 551 | seekMarkerRequestedEl = buildBracketMarker('right'); |
| 552 | seekMarkerContainerEl.appendChild(seekMarkerReceivedEl); |
| 553 | seekMarkerContainerEl.appendChild(seekMarkerRequestedEl); |
| 554 | |
| 555 | seekBarEl.appendChild(seekMarkerContainerEl); |
| 556 | updateSeekBarMarkers(); |
| 557 | }; |
| 558 | |
| 559 | const updateButtonState = () => |
| 560 | { |
| 561 | if (!buttonEl) return; |
| 562 | const track = selectedStreamIndex === null ? null : trackByStreamIndex.get(selectedStreamIndex) || null; |
| 563 | buttonEl.setAttribute('title', track ? `Image subtitles: ${track.label}` : 'Image subtitles'); |
| 564 | buttonEl.setAttribute('aria-pressed', selectedStreamIndex === null ? 'false' : 'true'); |
| 565 | }; |
| 566 | |
| 567 | const updateMenuState = () => |
| 568 | { |
| 569 | if (!menuEl) return; |
| 570 | const items = menuEl.querySelectorAll('[data-image-subtitle-stream-index]'); |
| 571 | for (const itemEl of items) |
| 572 | { |
| 573 | const value = itemEl.getAttribute('data-image-subtitle-stream-index'); |
| 574 | const isSelected = value === (selectedStreamIndex === null ? 'off' : String(selectedStreamIndex)); |
| 575 | itemEl.classList.toggle('is-selected', isSelected); |
| 576 | itemEl.setAttribute('aria-checked', isSelected ? 'true' : 'false'); |
| 577 | itemEl.style.background = isSelected ? 'rgba(90, 196, 255, 0.28)' : 'transparent'; |
| 578 | itemEl.style.fontWeight = isSelected ? '600' : '400'; |
| 579 | itemEl.style.boxShadow = isSelected ? 'inset 0 0 0 1px rgba(90, 196, 255, 0.55)' : 'none'; |
| 580 | } |
| 581 | }; |
| 582 | |
| 583 | const closeMenu = () => |
| 584 | { |
| 585 | menuOpen = false; |
| 586 | if (menuEl) menuEl.style.display = 'none'; |
| 587 | }; |
| 588 | |
| 589 | const openMenu = () => |
| 590 | { |
| 591 | menuOpen = true; |
| 592 | if (menuEl) |
| 593 | { |
| 594 | updateMenuState(); |
| 595 | menuEl.style.display = 'block'; |
| 596 | } |
| 597 | }; |
| 598 | |
| 599 | const toggleMenu = () => |
| 600 | { |
| 601 | if (menuOpen) closeMenu(); |
| 602 | else openMenu(); |
| 603 | }; |
| 604 | |
| 605 | const saveSelection = () => |
| 606 | { |
| 607 | const selectedTrack = selectedStreamIndex === null ? null : trackByStreamIndex.get(selectedStreamIndex) || null; |
| 608 | savePrefs({ |
| 609 | imageSubtitleTrackStreamIndex: selectedStreamIndex, |
| 610 | imageSubtitleTrackName: selectedTrack ? selectedTrack.label : null, |
| 611 | }); |
| 612 | }; |
| 613 | |
| 614 | const disableTrack = () => |
| 615 | { |
| 616 | trackDisabled = true; |
| 617 | selectedStreamIndex = null; |
| 618 | activeBucket = -1; |
| 619 | setSeekMarkerTime('requested', null); |
| 620 | setSeekMarkerTime('received', null); |
| 621 | updateSeekBarMarkers(); |
| 622 | resetRequestState(); |
| 623 | hideOverlay(); |
| 624 | updateButtonState(); |
| 625 | updateMenuState(); |
| 626 | saveSelection(); |
| 627 | |
| 628 | if (!failureNotified) |
| 629 | { |
| 630 | failureNotified = true; |
| 631 | notifyError(); |
| 632 | } |
| 633 | }; |
| 634 | |
| 635 | const setSelectedStreamIndex = (streamIndex, { persist = true } = {}) => |
| 636 | { |
| 637 | const nextStreamIndex = Number.isInteger(streamIndex) ? streamIndex : null; |
| 638 | if (nextStreamIndex !== null && !trackByStreamIndex.has(nextStreamIndex)) return; |
| 639 | |
| 640 | trackDisabled = false; |
| 641 | failureNotified = false; |
| 642 | selectedStreamIndex = nextStreamIndex; |
| 643 | activeBucket = -1; |
| 644 | setSeekMarkerTime('requested', null); |
| 645 | setSeekMarkerTime('received', null); |
| 646 | updateSeekBarMarkers(); |
| 647 | resetRequestState(); |
| 648 | hideOverlay(); |
| 649 | updateButtonState(); |
| 650 | updateMenuState(); |
| 651 | if (persist) saveSelection(); |
| 652 | |
| 653 | if (selectedStreamIndex !== null) |
| 654 | { |
| 655 | void refreshFrame(true); |
| 656 | } |
| 657 | }; |
| 658 | |
| 659 | const queueLookaheadPrefetch = (currentTime, { reset = false } = {}) => |
| 660 | { |
| 661 | if (selectedStreamIndex === null) return; |
| 662 | if (trackDisabled) return; |
| 663 | |
| 664 | const bufferedVideoEndSeconds = (() => |
| 665 | { |
| 666 | const fromPlayer = Number(player.bufferedEnd && player.bufferedEnd()); |
| 667 | if (Number.isFinite(fromPlayer) && fromPlayer >= 0) return fromPlayer; |
| 668 | |
| 669 | const tech = typeof player.tech === 'function' ? player.tech(true) : null; |
| 670 | const mediaEl = tech && typeof tech.el === 'function' |
| 671 | ? tech.el() |
| 672 | : (player.el && player.el() ? player.el().querySelector('video') : null); |
| 673 | |
| 674 | const ranges = mediaEl && mediaEl.buffered; |
| 675 | if (!ranges || typeof ranges.length !== 'number' || ranges.length <= 0 || typeof ranges.end !== 'function') |
| 676 | { |
| 677 | return null; |
| 678 | } |
| 679 | |
| 680 | try |
| 681 | { |
| 682 | const endTime = Number(ranges.end(ranges.length - 1)); |
| 683 | return Number.isFinite(endTime) && endTime >= 0 ? endTime : null; |
| 684 | } catch |
| 685 | { |
| 686 | return null; |
| 687 | } |
| 688 | })(); |
| 689 | |
| 690 | const startTime = currentTime + IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS; |
| 691 | const endTime = Math.max(currentTime + lookaheadSeconds, Number.isFinite(bufferedVideoEndSeconds) ? bufferedVideoEndSeconds : -1); |
| 692 | if (!Number.isFinite(startTime) || !Number.isFinite(endTime) || endTime <= startTime) return; |
| 693 | |
| 694 | if (reset || prefetchedThroughTimeSeconds < 0 || prefetchedThroughTimeSeconds < currentTime - IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS) |
| 695 | { |
| 696 | cancelPrefetchRequests({ resetProgress: true }); |
| 697 | prefetchedThroughTimeSeconds = currentTime; |
| 698 | } |
| 699 | |
| 700 | prefetchTargetTimeSeconds = Math.max(prefetchTargetTimeSeconds, endTime); |
| 701 | if (prefetchPromise) return; |
| 702 | |
| 703 | const workerToken = ++prefetchWorkerToken; |
| 704 | const workerLifecycleToken = lifecycleToken; |
| 705 | const controller = createAbortController(); |
| 706 | prefetchAbortController = controller; |
| 707 | |
| 708 | prefetchPromise = (async () => |
| 709 | { |
| 710 | while (true) |
| 711 | { |
| 712 | if (selectedStreamIndex === null || trackDisabled) return; |
| 713 | if (workerToken !== prefetchWorkerToken || workerLifecycleToken !== lifecycleToken) return; |
| 714 | |
| 715 | const nextTime = prefetchedThroughTimeSeconds < 0 |
| 716 | ? startTime |
| 717 | : prefetchedThroughTimeSeconds + IMAGE_SUBTITLE_PREFETCH_STEP_SECONDS; |
| 718 | if (!Number.isFinite(nextTime) || nextTime > prefetchTargetTimeSeconds + 1e-6) return; |
| 719 | |
| 720 | const request = buildFrameRequest({ |
| 721 | streamIndex: selectedStreamIndex, |
| 722 | currentTime: nextTime, |
| 723 | session, |
| 724 | }); |
| 725 | if (!request || !request.url) return; |
| 726 | |
| 727 | const prefetchRequestStartedAtMs = Date.now(); |
| 728 | const prefetchRequestId = `prefetch-${workerToken}-${Math.round(nextTime * 1000)}`; |
| 729 | logSubtitleEvent('subtitle_png_requested', { |
| 730 | requestId: prefetchRequestId, |
| 731 | requestKind: 'prefetch', |
| 732 | requestUrl: String(request.url || ''), |
| 733 | requestedAtMs: prefetchRequestStartedAtMs, |
| 734 | requestedVideoTimeSeconds: roundLogNumber(nextTime), |
| 735 | }); |
| 736 | setSeekMarkerTime('requested', nextTime); |
| 737 | updateSeekBarMarkers(); |
| 738 | |
| 739 | let prefetchTimedOut = false; |
| 740 | const timeoutId = armRequestTimeout(controller, prefetchRequestTimeoutMs, () => |
| 741 | { |
| 742 | prefetchTimedOut = true; |
| 743 | }); |
| 744 | |
| 745 | try |
| 746 | { |
| 747 | const res = await fetch(request.url, { |
| 748 | method: request.method || 'GET', |
| 749 | headers: request.headers, |
| 750 | credentials: request.credentials, |
| 751 | signal: controller ? controller.signal : undefined, |
| 752 | }); |
| 753 | clearRequestTimeout(timeoutId); |
| 754 | |
| 755 | if (workerToken !== prefetchWorkerToken || workerLifecycleToken !== lifecycleToken) return; |
| 756 | |
| 757 | const responseMeta = { |
| 758 | requestId: prefetchRequestId, |
| 759 | requestKind: 'prefetch', |
| 760 | status: res.status, |
| 761 | serverRequestReceivedAtMs: parseHeaderInt(res, 'X-Subtitle-Request-Received-At-Ms'), |
| 762 | serverResponseSentAtMs: parseHeaderInt(res, 'X-Subtitle-Response-Sent-At-Ms'), |
| 763 | shouldShowAtVideoTimeSeconds: parseHeaderFloat(res, 'X-Subtitle-Frame-Start-Time'), |
| 764 | subtitleEndTimeSeconds: parseHeaderFloat(res, 'X-Subtitle-Frame-End-Time'), |
| 765 | responseHeadersReceivedAtMs: Date.now(), |
| 766 | requestedVideoTimeSeconds: roundLogNumber(nextTime), |
| 767 | }; |
| 768 | logSubtitleEvent('subtitle_png_sent', { |
| 769 | ...responseMeta, |
| 770 | serverProcessingMs: diffMilliseconds(responseMeta.serverResponseSentAtMs, responseMeta.serverRequestReceivedAtMs), |
| 771 | sentToHeadersReceivedMs: diffMilliseconds(responseMeta.responseHeadersReceivedAtMs, responseMeta.serverResponseSentAtMs), |
| 772 | }); |
| 773 | |
| 774 | const receivedMarkerTime = Number.isFinite(responseMeta.shouldShowAtVideoTimeSeconds) |
| 775 | ? responseMeta.shouldShowAtVideoTimeSeconds |
| 776 | : nextTime; |
| 777 | setSeekMarkerTime('received', receivedMarkerTime); |
| 778 | updateSeekBarMarkers(); |
| 779 | |
| 780 | if (res.status === 204) |
| 781 | { |
| 782 | const frameStatus = String(res.headers.get('X-Subtitle-Frame-Status') || '').toLowerCase(); |
| 783 | logSubtitleEvent('subtitle_png_not_available', { |
| 784 | ...responseMeta, |
| 785 | frameStatus, |
| 786 | }); |
| 787 | if (frameStatus === 'error') return; |
| 788 | prefetchedThroughTimeSeconds = nextTime; |
| 789 | if (prefetchRequestIntervalMs > 0) |
| 790 | { |
| 791 | await new Promise((resolve) => window.setTimeout(resolve, prefetchRequestIntervalMs)); |
| 792 | } |
| 793 | continue; |
| 794 | } |
| 795 | |
| 796 | if (!res.ok) return; |
| 797 | const payload = await res.arrayBuffer(); |
| 798 | const receivedAtMs = Date.now(); |
| 799 | logSubtitleEvent('subtitle_png_received', { |
| 800 | ...responseMeta, |
| 801 | receivedAtMs, |
| 802 | sentToReceivedMs: diffMilliseconds(receivedAtMs, responseMeta.serverResponseSentAtMs), |
| 803 | requestedToReceivedMs: diffMilliseconds(receivedAtMs, prefetchRequestStartedAtMs), |
| 804 | blobBytes: Number(payload && payload.byteLength || 0), |
| 805 | }); |
| 806 | prefetchedThroughTimeSeconds = nextTime; |
| 807 | if (prefetchRequestIntervalMs > 0) |
| 808 | { |
| 809 | await new Promise((resolve) => window.setTimeout(resolve, prefetchRequestIntervalMs)); |
| 810 | } |
| 811 | } catch (error) |
| 812 | { |
| 813 | clearRequestTimeout(timeoutId); |
| 814 | if (prefetchTimedOut) |
| 815 | { |
| 816 | logSubtitleEvent('subtitle_png_request_failed', { |
| 817 | requestId: prefetchRequestId, |
| 818 | requestKind: 'prefetch', |
| 819 | requestedAtMs: prefetchRequestStartedAtMs, |
| 820 | errorName: 'AbortError', |
| 821 | errorMessage: `Prefetch subtitle request timed out after ${Math.round(prefetchRequestTimeoutMs)}ms`, |
| 822 | }); |
| 823 | return; |
| 824 | } |
| 825 | if (isAbortError(error)) return; |
| 826 | logSubtitleEvent('subtitle_png_request_failed', { |
| 827 | requestId: prefetchRequestId, |
| 828 | requestKind: 'prefetch', |
| 829 | requestedAtMs: prefetchRequestStartedAtMs, |
| 830 | errorName: error && error.name ? String(error.name) : null, |
| 831 | errorMessage: error && error.message ? String(error.message) : String(error || ''), |
| 832 | }); |
| 833 | return; |
| 834 | } |
| 835 | } |
| 836 | })().finally(() => |
| 837 | { |
| 838 | if (workerToken !== prefetchWorkerToken) return; |
| 839 | prefetchAbortController = null; |
| 840 | prefetchPromise = null; |
| 841 | }); |
| 842 | }; |
| 843 | |
| 844 | const refreshFrame = async (force = false) => |
| 845 | { |
| 846 | if (selectedStreamIndex === null) return; |
| 847 | if (!overlayEl || !overlayImgEl) return; |
| 848 | if (trackDisabled) return; |
| 849 | |
| 850 | if (currentFramePromise && !force) |
| 851 | { |
| 852 | queuedCurrentRefresh = true; |
| 853 | return; |
| 854 | } |
| 855 | |
| 856 | const currentTime = Number(player.currentTime()); |
| 857 | if (!Number.isFinite(currentTime) || currentTime < 0) return; |
| 858 | |
| 859 | const bucket = Math.floor(currentTime * 4); |
| 860 | if (!force && bucket === activeBucket) return; |
| 861 | activeBucket = bucket; |
| 862 | |
| 863 | const refreshLifecycleToken = lifecycleToken; |
| 864 | if (force && currentFramePromise) |
| 865 | { |
| 866 | cancelCurrentFrameRequest(); |
| 867 | } |
| 868 | if (currentFramePromise) |
| 869 | { |
| 870 | queuedCurrentRefresh = true; |
| 871 | queuedCurrentRefreshForce = queuedCurrentRefreshForce || !!force; |
| 872 | return; |
| 873 | } |
| 874 | cancelCurrentFrameRequest(); |
| 875 | if (force) cancelPrefetchRequests({ resetProgress: true }); |
| 876 | |
| 877 | const token = ++currentFrameToken; |
| 878 | const requestId = `current-${token}`; |
| 879 | const requestStartedAtMs = Date.now(); |
| 880 | const controller = createAbortController(); |
| 881 | currentFrameAbortController = controller; |
| 882 | const request = buildFrameRequest({ |
| 883 | streamIndex: selectedStreamIndex, |
| 884 | currentTime, |
| 885 | session, |
| 886 | }); |
| 887 | |
| 888 | if (!request || !request.url) |
| 889 | { |
| 890 | disableTrack(); |
| 891 | return; |
| 892 | } |
| 893 | |
| 894 | logSubtitleEvent('subtitle_png_requested', { |
| 895 | requestId, |
| 896 | requestKind: 'current', |
| 897 | requestUrl: String(request.url || ''), |
| 898 | requestedAtMs: requestStartedAtMs, |
| 899 | requestedVideoTimeSeconds: roundLogNumber(currentTime), |
| 900 | }); |
| 901 | setSeekMarkerTime('requested', currentTime); |
| 902 | updateSeekBarMarkers(); |
| 903 | |
| 904 | currentFramePromise = (async () => |
| 905 | { |
| 906 | let currentTimedOut = false; |
| 907 | const timeoutId = armRequestTimeout(controller, currentRequestTimeoutMs, () => |
| 908 | { |
| 909 | currentTimedOut = true; |
| 910 | }); |
| 911 | try |
| 912 | { |
| 913 | const res = await fetch(request.url, { |
| 914 | method: request.method || 'GET', |
| 915 | headers: request.headers, |
| 916 | credentials: request.credentials, |
| 917 | signal: controller ? controller.signal : undefined, |
| 918 | }); |
| 919 | clearRequestTimeout(timeoutId); |
| 920 | |
| 921 | if (token !== currentFrameToken || refreshLifecycleToken !== lifecycleToken) return; |
| 922 | |
| 923 | const responseMeta = { |
| 924 | requestId, |
| 925 | requestKind: 'current', |
| 926 | status: res.status, |
| 927 | serverRequestReceivedAtMs: parseHeaderInt(res, 'X-Subtitle-Request-Received-At-Ms'), |
| 928 | serverResponseSentAtMs: parseHeaderInt(res, 'X-Subtitle-Response-Sent-At-Ms'), |
| 929 | shouldShowAtVideoTimeSeconds: parseHeaderFloat(res, 'X-Subtitle-Frame-Start-Time'), |
| 930 | subtitleEndTimeSeconds: parseHeaderFloat(res, 'X-Subtitle-Frame-End-Time'), |
| 931 | responseHeadersReceivedAtMs: Date.now(), |
| 932 | requestedVideoTimeSeconds: roundLogNumber(currentTime), |
| 933 | }; |
| 934 | logSubtitleEvent('subtitle_png_sent', { |
| 935 | ...responseMeta, |
| 936 | serverProcessingMs: diffMilliseconds(responseMeta.serverResponseSentAtMs, responseMeta.serverRequestReceivedAtMs), |
| 937 | sentToHeadersReceivedMs: diffMilliseconds(responseMeta.responseHeadersReceivedAtMs, responseMeta.serverResponseSentAtMs), |
| 938 | }); |
| 939 | |
| 940 | const receivedMarkerTime = Number.isFinite(responseMeta.shouldShowAtVideoTimeSeconds) |
| 941 | ? responseMeta.shouldShowAtVideoTimeSeconds |
| 942 | : currentTime; |
| 943 | setSeekMarkerTime('received', receivedMarkerTime); |
| 944 | updateSeekBarMarkers(); |
| 945 | |
| 946 | if (res.status === 204) |
| 947 | { |
| 948 | const frameStatus = String(res.headers.get('X-Subtitle-Frame-Status') || '').toLowerCase(); |
| 949 | logSubtitleEvent('subtitle_png_not_available', { |
| 950 | ...responseMeta, |
| 951 | frameStatus, |
| 952 | }); |
| 953 | hideOverlay(); |
| 954 | if (frameStatus === 'error') disableTrack(); |
| 955 | else queueLookaheadPrefetch(currentTime, { reset: force }); |
| 956 | return; |
| 957 | } |
| 958 | |
| 959 | if (!res.ok) |
| 960 | { |
| 961 | disableTrack(); |
| 962 | return; |
| 963 | } |
| 964 | |
| 965 | const blob = await res.blob(); |
| 966 | if (token !== currentFrameToken || refreshLifecycleToken !== lifecycleToken) return; |
| 967 | |
| 968 | const receivedAtMs = Date.now(); |
| 969 | logSubtitleEvent('subtitle_png_received', { |
| 970 | ...responseMeta, |
| 971 | receivedAtMs, |
| 972 | sentToReceivedMs: diffMilliseconds(receivedAtMs, responseMeta.serverResponseSentAtMs), |
| 973 | requestedToReceivedMs: diffMilliseconds(receivedAtMs, requestStartedAtMs), |
| 974 | blobBytes: Number(blob && blob.size || 0), |
| 975 | }); |
| 976 | |
| 977 | if (!blob || blob.size === 0) |
| 978 | { |
| 979 | disableTrack(); |
| 980 | return; |
| 981 | } |
| 982 | |
| 983 | closeObjectUrl(); |
| 984 | activeObjectUrl = URL.createObjectURL(blob); |
| 985 | overlayImgEl.src = activeObjectUrl; |
| 986 | |
| 987 | const frameWidth = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Width') || ''), 10); |
| 988 | const frameHeight = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Height') || ''), 10); |
| 989 | const canvasWidth = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Canvas-Width') || ''), 10); |
| 990 | const canvasHeight = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Canvas-Height') || ''), 10); |
| 991 | |
| 992 | if (frameWidth > 0 && frameHeight > 0 && canvasWidth > 0 && canvasHeight > 0) |
| 993 | { |
| 994 | const widthPercent = (frameWidth / canvasWidth) * 100; |
| 995 | const heightPercent = (frameHeight / canvasHeight) * 100; |
| 996 | overlayImgEl.style.width = `${widthPercent}%`; |
| 997 | overlayImgEl.style.height = `${heightPercent}%`; |
| 998 | overlayImgEl.style.maxWidth = 'none'; |
| 999 | overlayImgEl.style.maxHeight = 'none'; |
| 1000 | } else |
| 1001 | { |
| 1002 | overlayImgEl.style.width = 'auto'; |
| 1003 | overlayImgEl.style.height = 'auto'; |
| 1004 | overlayImgEl.style.maxWidth = '100%'; |
| 1005 | overlayImgEl.style.maxHeight = '100%'; |
| 1006 | } |
| 1007 | |
| 1008 | overlayEl.style.display = 'block'; |
| 1009 | overlayImgEl.style.display = 'block'; |
| 1010 | |
| 1011 | void waitForImagePresentation(window, overlayImgEl).then((shownAtMs) => |
| 1012 | { |
| 1013 | if (token !== currentFrameToken || refreshLifecycleToken !== lifecycleToken) return; |
| 1014 | const shownAtVideoTimeSeconds = roundLogNumber(player.currentTime()); |
| 1015 | logSubtitleEvent('subtitle_png_shown', { |
| 1016 | ...responseMeta, |
| 1017 | receivedAtMs, |
| 1018 | shownAtMs, |
| 1019 | shownAtVideoTimeSeconds, |
| 1020 | sentToReceivedMs: diffMilliseconds(receivedAtMs, responseMeta.serverResponseSentAtMs), |
| 1021 | receivedToShownMs: diffMilliseconds(shownAtMs, receivedAtMs), |
| 1022 | shouldVsShownDiffSeconds: diffSeconds(shownAtVideoTimeSeconds, responseMeta.shouldShowAtVideoTimeSeconds), |
| 1023 | }); |
| 1024 | }); |
| 1025 | |
| 1026 | queueLookaheadPrefetch(currentTime, { reset: force }); |
| 1027 | } catch (error) |
| 1028 | { |
| 1029 | clearRequestTimeout(timeoutId); |
| 1030 | if (currentTimedOut) |
| 1031 | { |
| 1032 | logSubtitleEvent('subtitle_png_request_failed', { |
| 1033 | requestId, |
| 1034 | requestKind: 'current', |
| 1035 | requestedAtMs: requestStartedAtMs, |
| 1036 | errorName: 'AbortError', |
| 1037 | errorMessage: `Current subtitle request timed out after ${Math.round(currentRequestTimeoutMs)}ms`, |
| 1038 | }); |
| 1039 | return; |
| 1040 | } |
| 1041 | if (isAbortError(error)) return; |
| 1042 | logSubtitleEvent('subtitle_png_request_failed', { |
| 1043 | requestId, |
| 1044 | requestKind: 'current', |
| 1045 | requestedAtMs: requestStartedAtMs, |
| 1046 | errorName: error && error.name ? String(error.name) : null, |
| 1047 | errorMessage: error && error.message ? String(error.message) : String(error || ''), |
| 1048 | }); |
| 1049 | if (token === currentFrameToken && refreshLifecycleToken === lifecycleToken) disableTrack(); |
| 1050 | } |
| 1051 | })().finally(() => |
| 1052 | { |
| 1053 | if (token !== currentFrameToken) return; |
| 1054 | currentFrameAbortController = null; |
| 1055 | currentFramePromise = null; |
| 1056 | if (!queuedCurrentRefresh) return; |
| 1057 | |
| 1058 | const queuedForce = queuedCurrentRefreshForce; |
| 1059 | queuedCurrentRefresh = false; |
| 1060 | queuedCurrentRefreshForce = false; |
| 1061 | void refreshFrame(queuedForce); |
| 1062 | }); |
| 1063 | |
| 1064 | return currentFramePromise; |
| 1065 | }; |
| 1066 | |
| 1067 | const dispose = () => |
| 1068 | { |
| 1069 | resetRequestState(); |
| 1070 | flushSubtitleLogs(); |
| 1071 | closeMenu(); |
| 1072 | hideOverlay(); |
| 1073 | if (seekMarkerContainerEl) seekMarkerContainerEl.remove(); |
| 1074 | seekMarkerContainerEl = null; |
| 1075 | seekMarkerRequestedEl = null; |
| 1076 | seekMarkerReceivedEl = null; |
| 1077 | if (overlayEl) overlayEl.remove(); |
| 1078 | if (menuEl) menuEl.remove(); |
| 1079 | player.imageSubtitleOverlayController = null; |
| 1080 | buttonEl = null; |
| 1081 | }; |
| 1082 | |
| 1083 | overlayEl = document.createElement('div'); |
| 1084 | overlayEl.className = 'video-subtitle-overlay'; |
| 1085 | overlayEl.style.position = 'absolute'; |
| 1086 | overlayEl.style.left = '0'; |
| 1087 | overlayEl.style.right = '0'; |
| 1088 | overlayEl.style.bottom = '3rem'; |
| 1089 | overlayEl.style.display = 'none'; |
| 1090 | overlayEl.style.zIndex = '3'; |
| 1091 | overlayEl.style.pointerEvents = 'none'; |
| 1092 | overlayEl.style.textAlign = 'center'; |
| 1093 | overlayEl.style.padding = '0 0.75rem'; |
| 1094 | overlayEl.style.maxHeight = '70%'; |
| 1095 | overlayEl.style.overflow = 'hidden'; |
| 1096 | |
| 1097 | overlayImgEl = document.createElement('img'); |
| 1098 | overlayImgEl.alt = 'Image subtitles'; |
| 1099 | overlayImgEl.style.display = 'none'; |
| 1100 | overlayImgEl.style.margin = '0 auto'; |
| 1101 | overlayImgEl.style.objectFit = 'contain'; |
| 1102 | overlayImgEl.style.filter = 'drop-shadow(0 2px 2px rgba(0, 0, 0, 0.7))'; |
| 1103 | overlayImgEl.style.maxWidth = '100%'; |
| 1104 | overlayImgEl.style.height = 'auto'; |
| 1105 | overlayEl.appendChild(overlayImgEl); |
| 1106 | |
| 1107 | menuEl = document.createElement('div'); |
| 1108 | menuEl.className = 'video-subtitle-overlay-menu'; |
| 1109 | menuEl.style.position = 'absolute'; |
| 1110 | menuEl.style.right = '0.75rem'; |
| 1111 | menuEl.style.bottom = 'calc(3rem + 0.5rem)'; |
| 1112 | menuEl.style.minWidth = '14rem'; |
| 1113 | menuEl.style.maxWidth = '20rem'; |
| 1114 | menuEl.style.background = 'rgba(12, 12, 12, 0.96)'; |
| 1115 | menuEl.style.border = '1px solid rgba(255, 255, 255, 0.15)'; |
| 1116 | menuEl.style.borderRadius = '0.5rem'; |
| 1117 | menuEl.style.boxShadow = '0 12px 28px rgba(0, 0, 0, 0.35)'; |
| 1118 | menuEl.style.padding = '0.35rem'; |
| 1119 | menuEl.style.display = 'none'; |
| 1120 | menuEl.style.zIndex = '4'; |
| 1121 | |
| 1122 | const buildMenuItem = (label, streamIndex, isSelected) => |
| 1123 | { |
| 1124 | const itemEl = document.createElement('button'); |
| 1125 | itemEl.type = 'button'; |
| 1126 | itemEl.className = 'video-subtitle-overlay-menu-item'; |
| 1127 | itemEl.setAttribute('data-image-subtitle-stream-index', streamIndex === null ? 'off' : String(streamIndex)); |
| 1128 | itemEl.setAttribute('aria-checked', isSelected ? 'true' : 'false'); |
| 1129 | itemEl.style.display = 'block'; |
| 1130 | itemEl.style.width = '100%'; |
| 1131 | itemEl.style.margin = '0'; |
| 1132 | itemEl.style.padding = '0.5rem 0.75rem'; |
| 1133 | itemEl.style.border = '0'; |
| 1134 | itemEl.style.borderRadius = '0.35rem'; |
| 1135 | itemEl.style.background = isSelected ? 'rgba(255, 255, 255, 0.18)' : 'transparent'; |
| 1136 | itemEl.style.color = '#fff'; |
| 1137 | itemEl.style.textAlign = 'left'; |
| 1138 | itemEl.style.cursor = 'pointer'; |
| 1139 | itemEl.textContent = label; |
| 1140 | itemEl.addEventListener('click', () => |
| 1141 | { |
| 1142 | setSelectedStreamIndex(streamIndex); |
| 1143 | closeMenu(); |
| 1144 | }); |
| 1145 | return itemEl; |
| 1146 | }; |
| 1147 | |
| 1148 | menuEl.appendChild(buildMenuItem('Off', null, false)); |
| 1149 | for (const track of imageTracks) |
| 1150 | { |
| 1151 | menuEl.appendChild(buildMenuItem(track.label, track.streamIndex, false)); |
| 1152 | } |
| 1153 | |
| 1154 | const registerButton = () => |
| 1155 | { |
| 1156 | if (!videojs || typeof videojs.getComponent !== 'function' || typeof videojs.registerComponent !== 'function') return; |
| 1157 | if (videojs.getComponent('ImageSubtitleButton')) return; |
| 1158 | |
| 1159 | const Button = videojs.getComponent('Button'); |
| 1160 | class ImageSubtitleButton extends Button |
| 1161 | { |
| 1162 | buildCSSClass () |
| 1163 | { |
| 1164 | return `${super.buildCSSClass()} vjs-image-subtitle-button`; |
| 1165 | } |
| 1166 | |
| 1167 | createEl () |
| 1168 | { |
| 1169 | const el = super.createEl(); |
| 1170 | el.type = 'button'; |
| 1171 | el.setAttribute('title', 'Image subtitles'); |
| 1172 | el.setAttribute('aria-label', 'Image subtitles'); |
| 1173 | el.innerHTML = '<span aria-hidden="true">IM</span>'; |
| 1174 | return el; |
| 1175 | } |
| 1176 | |
| 1177 | handleClick () |
| 1178 | { |
| 1179 | const controller = this.player().imageSubtitleOverlayController; |
| 1180 | if (controller) controller.toggleMenu(); |
| 1181 | } |
| 1182 | } |
| 1183 | |
| 1184 | videojs.registerComponent('ImageSubtitleButton', ImageSubtitleButton); |
| 1185 | }; |
| 1186 | |
| 1187 | const attachUi = () => |
| 1188 | { |
| 1189 | if (!player.el()) return; |
| 1190 | registerButton(); |
| 1191 | if (overlayEl.parentElement !== player.el()) player.el().appendChild(overlayEl); |
| 1192 | if (menuEl.parentElement !== player.el()) player.el().appendChild(menuEl); |
| 1193 | const controlBar = typeof player.getChild === 'function' ? player.getChild('controlBar') : null; |
| 1194 | if (controlBar && typeof controlBar.addChild === 'function' && !buttonEl) |
| 1195 | { |
| 1196 | const button = controlBar.addChild('ImageSubtitleButton', {}); |
| 1197 | buttonEl = button && typeof button.el === 'function' ? button.el() : null; |
| 1198 | updateButtonState(); |
| 1199 | } |
| 1200 | }; |
| 1201 | |
| 1202 | const applySavedTracks = () => |
| 1203 | { |
| 1204 | const savedName = normaliseTrackName(prefs.imageSubtitleTrackName); |
| 1205 | if (savedName) |
| 1206 | { |
| 1207 | const savedByName = imageTracks.find((track) => normaliseTrackName(track.label) === savedName) || null; |
| 1208 | if (savedByName) |
| 1209 | { |
| 1210 | setSelectedStreamIndex(savedByName.streamIndex, { persist: false }); |
| 1211 | return; |
| 1212 | } |
| 1213 | } |
| 1214 | |
| 1215 | const savedIndex = Number(prefs.imageSubtitleTrackStreamIndex); |
| 1216 | if (Number.isInteger(savedIndex) && trackByStreamIndex.has(savedIndex)) |
| 1217 | { |
| 1218 | setSelectedStreamIndex(savedIndex, { persist: false }); |
| 1219 | return; |
| 1220 | } |
| 1221 | |
| 1222 | const defaultTrack = imageTracks.find((track) => track.isDefault) || null; |
| 1223 | if (defaultTrack) |
| 1224 | { |
| 1225 | setSelectedStreamIndex(defaultTrack.streamIndex, { persist: false }); |
| 1226 | return; |
| 1227 | } |
| 1228 | |
| 1229 | setSelectedStreamIndex(null, { persist: false }); |
| 1230 | }; |
| 1231 | |
| 1232 | player.imageSubtitleOverlayController = { |
| 1233 | toggleMenu, |
| 1234 | closeMenu, |
| 1235 | applySavedTracks, |
| 1236 | captureSelectedTracks: saveSelection, |
| 1237 | detach: dispose, |
| 1238 | }; |
| 1239 | |
| 1240 | player.on('timeupdate', () => { void refreshFrame(); }); |
| 1241 | player.on('seeking', () => { void refreshFrame(true); }); |
| 1242 | player.on('play', () => { void refreshFrame(true); }); |
| 1243 | player.on('fullscreenchange', () => { closeMenu(); void refreshFrame(true); }); |
| 1244 | player.on('dispose', dispose); |
| 1245 | player.ready(() => |
| 1246 | { |
| 1247 | attachUi(); |
| 1248 | ensureSeekBarMarkers(); |
| 1249 | updateMenuState(); |
| 1250 | updateButtonState(); |
| 1251 | updateSeekBarMarkers(); |
| 1252 | applySavedTracks(); |
| 1253 | if (menuOpen) openMenu(); |
| 1254 | }); |
| 1255 | |
| 1256 | player.on('durationchange', () => { ensureSeekBarMarkers(); updateSeekBarMarkers(); }); |
| 1257 | player.on('loadedmetadata', () => { ensureSeekBarMarkers(); updateSeekBarMarkers(); }); |
| 1258 | |
| 1259 | return player.imageSubtitleOverlayController; |
| 1260 | } |
| 1261 | |
| 1262 | function formatDurationForDebug (seconds) |
| 1263 | { |
| 1264 | const value = Number(seconds); |
| 1265 | if (!Number.isFinite(value) || value < 0) return 'unknown'; |
| 1266 | |
| 1267 | const totalSeconds = Math.floor(value); |
| 1268 | const hh = String(Math.floor(totalSeconds / 3600)).padStart(2, '0'); |
| 1269 | const mm = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0'); |
| 1270 | const ss = String(totalSeconds % 60).padStart(2, '0'); |
| 1271 | return `${hh}:${mm}:${ss}`; |
| 1272 | } |
| 1273 | |
| 1274 | function installDurationFallback (player, originalDuration, duration) |
| 1275 | { |
| 1276 | if (!player || !originalDuration || player.__filemanagerDurationFallback) return; |
| 1277 | |
| 1278 | player.__filemanagerDurationFallback = true; |
| 1279 | player.duration = function durationWithFallback (...args) |
| 1280 | { |
| 1281 | if (args.length) return originalDuration(...args); |
| 1282 | const current = Number(originalDuration()); |
| 1283 | return Number.isFinite(current) && current >= duration * 0.95 ? current : duration; |
| 1284 | }; |
| 1285 | } |
| 1286 | |
| 1287 | function normaliseVideoDuration (player, durationSeconds) |
| 1288 | { |
| 1289 | const duration = Number(durationSeconds); |
| 1290 | if (!player || !Number.isFinite(duration) || duration <= 0) return; |
| 1291 | |
| 1292 | let originalDuration = null; |
| 1293 | let durationWasChanged = false; |
| 1294 | try |
| 1295 | { |
| 1296 | originalDuration = typeof player.duration === 'function' ? player.duration.bind(player) : null; |
| 1297 | installDurationFallback(player, originalDuration, duration); |
| 1298 | if (player.__filemanagerDurationApplied) return; |
| 1299 | |
| 1300 | const current = originalDuration ? Number(originalDuration()) : NaN; |
| 1301 | const withinTolerance = Number.isFinite(current) && current >= duration * 0.95; |
| 1302 | console.log(`Current duration: ${formatDurationForDebug(current)}, Target time: ${formatDurationForDebug(duration)}, within 95%? ${withinTolerance ? 'yes' : 'no'}`); |
| 1303 | if (withinTolerance) |
| 1304 | { |
| 1305 | player.__filemanagerDurationApplied = true; |
| 1306 | return; |
| 1307 | } |
| 1308 | |
| 1309 | if (originalDuration) |
| 1310 | { |
| 1311 | durationWasChanged = true; |
| 1312 | originalDuration(duration); |
| 1313 | } |
| 1314 | } catch |
| 1315 | { |
| 1316 | // Ignore players that do not support setting duration. |
| 1317 | } |
| 1318 | |
| 1319 | try |
| 1320 | { |
| 1321 | const updated = originalDuration ? Number(originalDuration()) : NaN; |
| 1322 | if (Number.isFinite(updated) && updated >= duration * 0.95) |
| 1323 | { |
| 1324 | player.__filemanagerDurationApplied = true; |
| 1325 | if (durationWasChanged && typeof player.trigger === 'function') player.trigger('durationchange'); |
| 1326 | return; |
| 1327 | } |
| 1328 | |
| 1329 | player.__filemanagerDurationApplied = true; |
| 1330 | if (typeof player.trigger === 'function') player.trigger('durationchange'); |
| 1331 | } catch |
| 1332 | { |
| 1333 | // Ignore duration fallback failures. |
| 1334 | } |
| 1335 | } |
| 1336 | |
| 1337 | function ensureVideoPlaybackUi (player, durationSeconds) |
| 1338 | { |
| 1339 | if (!player || typeof player.on !== 'function') return; |
| 1340 | |
| 1341 | const forceVodUi = () => |
| 1342 | { |
| 1343 | normaliseVideoDuration(player, durationSeconds); |
| 1344 | |
| 1345 | try |
| 1346 | { |
| 1347 | if (player.liveTracker && typeof player.liveTracker.stopTracking === 'function') |
| 1348 | { |
| 1349 | player.liveTracker.stopTracking(); |
| 1350 | } |
| 1351 | } catch |
| 1352 | { |
| 1353 | // Ignore live tracker availability issues. |
| 1354 | } |
| 1355 | |
| 1356 | try |
| 1357 | { |
| 1358 | if (typeof player.removeClass === 'function') |
| 1359 | { |
| 1360 | player.removeClass('vjs-live'); |
| 1361 | } |
| 1362 | } catch |
| 1363 | { |
| 1364 | // Ignore class update failures. |
| 1365 | } |
| 1366 | |
| 1367 | try |
| 1368 | { |
| 1369 | const display = player.el && player.el() && player.el().querySelector('.vjs-live-display'); |
| 1370 | if (display) display.style.display = 'none'; |
| 1371 | } catch |
| 1372 | { |
| 1373 | // Ignore missing DOM. |
| 1374 | } |
| 1375 | }; |
| 1376 | |
| 1377 | player.ready(forceVodUi); |
| 1378 | player.on('loadedmetadata', forceVodUi); |
| 1379 | player.on('durationchange', forceVodUi); |
| 1380 | player.on('loadedplaylist', forceVodUi); |
| 1381 | } |
| 1382 | |
| 1383 | function configureVideoJsBuffering (videojs, opts = {}) |
| 1384 | { |
| 1385 | if (opts.enabled === false) return; |
| 1386 | if (!videojs || !videojs.Vhs || videojs.__filemanagerBufferingConfigured) return; |
| 1387 | videojs.__filemanagerBufferingConfigured = true; |
| 1388 | |
| 1389 | const seconds = Number(opts.seconds); |
| 1390 | const bufferSeconds = Number.isFinite(seconds) && seconds > 0 ? seconds : 60 * 60; |
| 1391 | |
| 1392 | try |
| 1393 | { |
| 1394 | videojs.Vhs.GOAL_BUFFER_LENGTH = bufferSeconds; |
| 1395 | videojs.Vhs.MAX_GOAL_BUFFER_LENGTH = bufferSeconds; |
| 1396 | } catch |
| 1397 | { |
| 1398 | // Ignore builds that do not expose VHS buffer configuration. |
| 1399 | } |
| 1400 | } |
| 1401 | |
| 1402 | function applyDefaultTextTrackPrefs () |
| 1403 | { |
| 1404 | try |
| 1405 | { |
| 1406 | localStorage.setItem(VIDEO_TEXT_TRACK_SETTINGS_KEY, VIDEO_TEXT_TRACK_OVERRIDE_SETTINGS_RAW); |
| 1407 | } catch |
| 1408 | { |
| 1409 | // Ignore localStorage failures. |
| 1410 | } |
| 1411 | } |
| 1412 | |
| 1413 | window.FilemanagerSharedVideoPlayer = { |
| 1414 | applyDefaultTextTrackPrefs, |
| 1415 | bindImageSubtitleOverlay, |
| 1416 | bindTrackPrefs, |
| 1417 | configureVideoJsBuffering, |
| 1418 | ensureVideoPlaybackUi, |
| 1419 | normaliseVideoDuration, |
| 1420 | }; |
| 1421 | }()); |