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