| 1 | 'use strict'; |
| 2 | |
| 3 | const { spawn } = require('child_process'); |
| 4 | const crypto = require('crypto'); |
| 5 | const fs = require('fs'); |
| 6 | const os = require('os'); |
| 7 | const path = require('path'); |
| 8 | const { Readable } = require('stream'); |
| 9 | const sharp = require('sharp'); |
| 10 | |
| 11 | const SUBTITLE_CACHE_DIR = path.join(os.tmpdir(), 'filemanager-video-subtitles'); |
| 12 | const EVENT_CACHE_TTL_MS = toPositiveInt(process.env.IMAGE_SUBTITLE_EVENT_CACHE_TTL_MS, 5 * 60 * 1000); |
| 13 | const FRAME_CACHE_TTL_MS = toPositiveInt(process.env.IMAGE_SUBTITLE_FRAME_CACHE_TTL_MS, 2 * 60 * 1000); |
| 14 | const MAX_EVENT_CACHE_ITEMS = toPositiveInt(process.env.IMAGE_SUBTITLE_EVENT_CACHE_MAX_ITEMS, 3); |
| 15 | const MAX_FRAME_CACHE_ITEMS = toPositiveInt(process.env.IMAGE_SUBTITLE_FRAME_CACHE_MAX_ITEMS, 50); |
| 16 | // Removed byte size cap for event cache to prevent thrashing |
| 17 | const MAX_EVENT_CACHE_BYTES = toPositiveInt(process.env.IMAGE_SUBTITLE_EVENT_CACHE_MAX_BYTES, 50 * 1024 * 1024); |
| 18 | const MIN_EVENT_WINDOW_SECONDS = 30; // Always keep at least this much for seeking |
| 19 | const MAX_FRAME_CACHE_BYTES = toPositiveInt(process.env.IMAGE_SUBTITLE_FRAME_CACHE_MAX_BYTES, 48 * 1024 * 1024); |
| 20 | const IMAGE_SUBTITLE_RENDER_SCALE = toBoundedNumber(process.env.IMAGE_SUBTITLE_RENDER_SCALE, 0.75, 0.1, 1); |
| 21 | const PGS_TIMEBASE = 90000; |
| 22 | const IMAGE_SUBTITLE_PRUNE_GRACE_SECONDS = toPositiveInt(process.env.IMAGE_SUBTITLE_PRUNE_GRACE_SECONDS, 5); |
| 23 | |
| 24 | const eventCache = createCacheState(MAX_EVENT_CACHE_ITEMS, MAX_EVENT_CACHE_BYTES); |
| 25 | const frameCache = createCacheState(MAX_FRAME_CACHE_ITEMS, MAX_FRAME_CACHE_BYTES); |
| 26 | |
| 27 | let parseDisplaySets = null; |
| 28 | |
| 29 | function ensureImageDataGlobal () |
| 30 | { |
| 31 | if (typeof globalThis.ImageData === 'function') return; |
| 32 | |
| 33 | class ImageDataPolyfill |
| 34 | { |
| 35 | constructor(data, width, height) |
| 36 | { |
| 37 | this.data = data; |
| 38 | this.width = width; |
| 39 | this.height = height; |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | globalThis.ImageData = ImageDataPolyfill; |
| 44 | } |
| 45 | |
| 46 | function loadPgsParser () |
| 47 | { |
| 48 | if (parseDisplaySets) return parseDisplaySets; |
| 49 | ensureImageDataGlobal(); |
| 50 | ({ parseDisplaySets } = require('pgs-parser')); |
| 51 | return parseDisplaySets; |
| 52 | } |
| 53 | |
| 54 | function ffmpegPath () |
| 55 | { |
| 56 | return process.env.FFMPEG_PATH || 'ffmpeg'; |
| 57 | } |
| 58 | |
| 59 | function ensureSubtitleCacheDir () |
| 60 | { |
| 61 | fs.mkdirSync(SUBTITLE_CACHE_DIR, { recursive: true }); |
| 62 | } |
| 63 | |
| 64 | function toPositiveInt (value, fallback) |
| 65 | { |
| 66 | const number = Number.parseInt(String(value || ''), 10); |
| 67 | if (Number.isInteger(number) && number > 0) return number; |
| 68 | return fallback; |
| 69 | } |
| 70 | |
| 71 | function toBoundedNumber (value, fallback, min, max) |
| 72 | { |
| 73 | const numeric = Number.parseFloat(String(value || '')); |
| 74 | if (!Number.isFinite(numeric)) return fallback; |
| 75 | if (numeric < min || numeric > max) return fallback; |
| 76 | return numeric; |
| 77 | } |
| 78 | |
| 79 | function hashSubtitleKey (filePath, streamIndex, stat) |
| 80 | { |
| 81 | return crypto |
| 82 | .createHash('sha1') |
| 83 | .update(`${filePath}|${streamIndex}|${stat.size}|${Math.floor(stat.mtimeMs)}`) |
| 84 | .digest('hex'); |
| 85 | } |
| 86 | |
| 87 | function createCacheState (maxItems, maxBytes) |
| 88 | { |
| 89 | return { |
| 90 | map: new Map(), |
| 91 | totalBytes: 0, |
| 92 | maxItems, |
| 93 | maxBytes, |
| 94 | }; |
| 95 | } |
| 96 | |
| 97 | function normaliseFilePath (filePath) |
| 98 | { |
| 99 | return path.resolve(String(filePath || '').trim()); |
| 100 | } |
| 101 | |
| 102 | function cachePrefixForFile (filePath) |
| 103 | { |
| 104 | const normalised = String(filePath || '').trim(); |
| 105 | if (!normalised) return ''; |
| 106 | return `${normaliseFilePath(normalised)}|`; |
| 107 | } |
| 108 | |
| 109 | function eventIdentityKey (filePath, streamIndex, stat) |
| 110 | { |
| 111 | const normalisedPath = normaliseFilePath(filePath); |
| 112 | const hash = hashSubtitleKey(normalisedPath, streamIndex, stat); |
| 113 | return `${normalisedPath}|${streamIndex}|${hash}`; |
| 114 | } |
| 115 | |
| 116 | function eventCacheFileKey (identityKey) |
| 117 | { |
| 118 | const hash = crypto.createHash('sha1').update(String(identityKey || '')).digest('hex'); |
| 119 | return `event-${hash}`; |
| 120 | } |
| 121 | |
| 122 | function toValidCacheSize (value) |
| 123 | { |
| 124 | const number = Number(value); |
| 125 | if (!Number.isFinite(number) || number <= 0) return 0; |
| 126 | return Math.floor(number); |
| 127 | } |
| 128 | |
| 129 | function estimateEventCacheBytes (value) |
| 130 | { |
| 131 | if (!value) return 0; |
| 132 | if (typeof value.then === 'function') return 1024; |
| 133 | if (!Array.isArray(value.events)) return 1024; |
| 134 | |
| 135 | let bytes = 1024; |
| 136 | for (const event of value.events) |
| 137 | { |
| 138 | if (event && Buffer.isBuffer(event.imagePng)) bytes += event.imagePng.length; |
| 139 | bytes += 160; |
| 140 | } |
| 141 | return bytes; |
| 142 | } |
| 143 | |
| 144 | function estimateFrameCacheBytes (value) |
| 145 | { |
| 146 | if (!value) return 0; |
| 147 | if (Buffer.isBuffer(value)) return value.length; |
| 148 | if (value && Buffer.isBuffer(value.frame)) return value.frame.length + 96; |
| 149 | return 1024; |
| 150 | } |
| 151 | |
| 152 | function deleteCachedValue (cache, key) |
| 153 | { |
| 154 | const entry = cache.map.get(key); |
| 155 | if (!entry) return false; |
| 156 | |
| 157 | cache.map.delete(key); |
| 158 | cache.totalBytes = Math.max(0, cache.totalBytes - toValidCacheSize(entry.sizeBytes)); |
| 159 | return true; |
| 160 | } |
| 161 | |
| 162 | function touchCachedEntry (cache, key, ttlMs) |
| 163 | { |
| 164 | const entry = cache.map.get(key); |
| 165 | if (!entry) return; |
| 166 | entry.expiresAt = Date.now() + ttlMs; |
| 167 | cache.map.delete(key); |
| 168 | cache.map.set(key, entry); |
| 169 | } |
| 170 | |
| 171 | function getCachedValue (cache, key) |
| 172 | { |
| 173 | const now = Date.now(); |
| 174 | const entry = cache.map.get(key); |
| 175 | if (!entry) return null; |
| 176 | |
| 177 | if (entry.expiresAt <= now) |
| 178 | { |
| 179 | deleteCachedValue(cache, key); |
| 180 | return null; |
| 181 | } |
| 182 | |
| 183 | cache.map.delete(key); |
| 184 | cache.map.set(key, entry); |
| 185 | return entry.value; |
| 186 | } |
| 187 | |
| 188 | function setCachedValue (cache, key, value, ttlMs, estimateBytes) |
| 189 | { |
| 190 | const now = Date.now(); |
| 191 | deleteCachedValue(cache, key); |
| 192 | |
| 193 | const sizeBytes = toValidCacheSize(typeof estimateBytes === 'function' ? estimateBytes(value) : 0); |
| 194 | |
| 195 | cache.map.set(key, { |
| 196 | value, |
| 197 | expiresAt: now + ttlMs, |
| 198 | sizeBytes, |
| 199 | }); |
| 200 | cache.totalBytes += sizeBytes; |
| 201 | |
| 202 | while (cache.map.size > cache.maxItems || cache.maxBytes !== Infinity && cache.totalBytes > cache.maxBytes) |
| 203 | { |
| 204 | const oldestKey = cache.map.keys().next().value; |
| 205 | deleteCachedValue(cache, oldestKey); |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | function runCommand (command, args) |
| 210 | { |
| 211 | return new Promise((resolve, reject) => |
| 212 | { |
| 213 | const child = spawn(command, args, { stdio: ['ignore', 'ignore', 'pipe'] }); |
| 214 | let stderr = ''; |
| 215 | |
| 216 | child.stderr.on('data', (chunk) => |
| 217 | { |
| 218 | stderr += chunk.toString(); |
| 219 | if (stderr.length > 16000) stderr = stderr.slice(-16000); |
| 220 | }); |
| 221 | |
| 222 | child.on('error', reject); |
| 223 | child.on('close', (code) => |
| 224 | { |
| 225 | if (code === 0) |
| 226 | { |
| 227 | resolve(); |
| 228 | return; |
| 229 | } |
| 230 | reject(new Error(stderr.trim() || `ffmpeg exited with code ${code}`)); |
| 231 | }); |
| 232 | }); |
| 233 | } |
| 234 | |
| 235 | async function extractSupFile (sourcePath, streamIndex, cacheKey) |
| 236 | { |
| 237 | ensureSubtitleCacheDir(); |
| 238 | const supPath = path.join(SUBTITLE_CACHE_DIR, `${cacheKey}.sup`); |
| 239 | |
| 240 | if (fs.existsSync(supPath) && fs.statSync(supPath).size > 0) |
| 241 | { |
| 242 | return supPath; |
| 243 | } |
| 244 | |
| 245 | await runCommand(ffmpegPath(), [ |
| 246 | '-hide_banner', |
| 247 | '-loglevel', 'error', |
| 248 | '-nostdin', |
| 249 | '-y', |
| 250 | '-i', sourcePath, |
| 251 | '-map', `0:s:${streamIndex}`, |
| 252 | '-c:s', 'copy', |
| 253 | '-f', 'sup', |
| 254 | supPath, |
| 255 | ]); |
| 256 | |
| 257 | return supPath; |
| 258 | } |
| 259 | |
| 260 | function toSeconds (pgsTimestamp) |
| 261 | { |
| 262 | const numeric = Number(pgsTimestamp); |
| 263 | if (!Number.isFinite(numeric) || numeric < 0) return 0; |
| 264 | return numeric / PGS_TIMEBASE; |
| 265 | } |
| 266 | |
| 267 | function parseDisplaySetTimestamp (displaySet) |
| 268 | { |
| 269 | if (displaySet && displaySet.presentationCompositionSegment && displaySet.presentationCompositionSegment.header) |
| 270 | { |
| 271 | return toSeconds(displaySet.presentationCompositionSegment.header.presentationTimestamp); |
| 272 | } |
| 273 | if (displaySet && displaySet.endDefinitionSegment && displaySet.endDefinitionSegment.header) |
| 274 | { |
| 275 | return toSeconds(displaySet.endDefinitionSegment.header.presentationTimestamp); |
| 276 | } |
| 277 | return 0; |
| 278 | } |
| 279 | |
| 280 | async function parseSupEvents (supPath) |
| 281 | { |
| 282 | const parserFactory = loadPgsParser(); |
| 283 | if (typeof Readable.toWeb !== 'function') |
| 284 | { |
| 285 | throw new Error('Node.js stream bridge is unavailable for subtitle parsing.'); |
| 286 | } |
| 287 | |
| 288 | const subtitleStream = Readable.toWeb(fs.createReadStream(supPath)); |
| 289 | const parserStream = subtitleStream.pipeThrough(parserFactory()); |
| 290 | const reader = parserStream.getReader(); |
| 291 | |
| 292 | const events = []; |
| 293 | let currentEvent = null; |
| 294 | let scratchBuffer = null; |
| 295 | |
| 296 | while (true) |
| 297 | { |
| 298 | const { done, value: displaySet } = await reader.read(); |
| 299 | if (done) break; |
| 300 | |
| 301 | const timestampSeconds = parseDisplaySetTimestamp(displaySet); |
| 302 | |
| 303 | if (currentEvent && timestampSeconds > currentEvent.startTimeSeconds) |
| 304 | { |
| 305 | currentEvent.endTimeSeconds = timestampSeconds; |
| 306 | events.push(currentEvent); |
| 307 | currentEvent = null; |
| 308 | } |
| 309 | |
| 310 | if (!displaySet || !Array.isArray(displaySet.objectDefinitionSegments) || displaySet.objectDefinitionSegments.length === 0) |
| 311 | { |
| 312 | continue; |
| 313 | } |
| 314 | |
| 315 | const pcs = displaySet.presentationCompositionSegment; |
| 316 | if (!pcs) continue; |
| 317 | |
| 318 | const neededPixels = Number(pcs.width || 0) * Number(pcs.height || 0) * 4; |
| 319 | if (!scratchBuffer || !Number.isInteger(neededPixels) || neededPixels <= 0 || scratchBuffer.length < neededPixels) |
| 320 | { |
| 321 | scratchBuffer = neededPixels > 0 ? new Uint8ClampedArray(neededPixels) : null; |
| 322 | } |
| 323 | |
| 324 | let imageData; |
| 325 | try |
| 326 | { |
| 327 | imageData = displaySet.imageData(scratchBuffer || undefined); |
| 328 | } catch |
| 329 | { |
| 330 | continue; |
| 331 | } |
| 332 | |
| 333 | if (!imageData || !imageData.data || !Number.isInteger(imageData.width) || !Number.isInteger(imageData.height)) |
| 334 | { |
| 335 | continue; |
| 336 | } |
| 337 | |
| 338 | const rawPixels = Buffer.from(imageData.data); |
| 339 | const imagePng = await sharp(rawPixels, { |
| 340 | raw: { |
| 341 | width: imageData.width, |
| 342 | height: imageData.height, |
| 343 | channels: 4, |
| 344 | }, |
| 345 | }).png().toBuffer(); |
| 346 | |
| 347 | currentEvent = { |
| 348 | startTimeSeconds: timestampSeconds, |
| 349 | endTimeSeconds: Number.POSITIVE_INFINITY, |
| 350 | screenWidth: toPositiveInt(pcs.width, imageData.width), |
| 351 | screenHeight: toPositiveInt(pcs.height, imageData.height), |
| 352 | left: toPositiveInt(pcs.objectHorizontalPosition, 0), |
| 353 | top: toPositiveInt(pcs.objectVerticalPosition, 0), |
| 354 | imageWidth: imageData.width, |
| 355 | imageHeight: imageData.height, |
| 356 | imagePng, |
| 357 | }; |
| 358 | } |
| 359 | |
| 360 | if (currentEvent) |
| 361 | { |
| 362 | events.push(currentEvent); |
| 363 | } |
| 364 | |
| 365 | return events; |
| 366 | } |
| 367 | |
| 368 | async function buildEventCacheEntry (filePath, streamIndex, identityKey) |
| 369 | { |
| 370 | const subtitleFileCacheKey = eventCacheFileKey(identityKey); |
| 371 | const supPath = await extractSupFile(filePath, streamIndex, subtitleFileCacheKey); |
| 372 | const events = await parseSupEvents(supPath); |
| 373 | return { |
| 374 | cacheKey: identityKey, |
| 375 | events, |
| 376 | }; |
| 377 | } |
| 378 | |
| 379 | async function getEventCacheEntry (filePath, streamIndex) |
| 380 | { |
| 381 | const normalisedPath = normaliseFilePath(filePath); |
| 382 | const stat = await fs.promises.stat(normalisedPath); |
| 383 | const identityKey = eventIdentityKey(normalisedPath, streamIndex, stat); |
| 384 | |
| 385 | const cached = getCachedValue(eventCache, identityKey); |
| 386 | if (cached) |
| 387 | { |
| 388 | touchCachedEntry(eventCache, identityKey, EVENT_CACHE_TTL_MS); |
| 389 | return cached; |
| 390 | } |
| 391 | |
| 392 | const pending = buildEventCacheEntry(normalisedPath, streamIndex, identityKey); |
| 393 | setCachedValue(eventCache, identityKey, pending, EVENT_CACHE_TTL_MS, estimateEventCacheBytes); |
| 394 | |
| 395 | try |
| 396 | { |
| 397 | const resolved = await pending; |
| 398 | setCachedValue(eventCache, identityKey, resolved, EVENT_CACHE_TTL_MS, estimateEventCacheBytes); |
| 399 | return resolved; |
| 400 | } catch (error) |
| 401 | { |
| 402 | deleteCachedValue(eventCache, identityKey); |
| 403 | throw error; |
| 404 | } |
| 405 | } |
| 406 | |
| 407 | function findActiveEventIndex (events, timeSeconds) |
| 408 | { |
| 409 | let left = 0; |
| 410 | let right = events.length - 1; |
| 411 | let candidate = -1; |
| 412 | |
| 413 | while (left <= right) |
| 414 | { |
| 415 | const middle = Math.floor((left + right) / 2); |
| 416 | const event = events[middle]; |
| 417 | |
| 418 | if (event.startTimeSeconds <= timeSeconds) |
| 419 | { |
| 420 | candidate = middle; |
| 421 | left = middle + 1; |
| 422 | } else |
| 423 | { |
| 424 | right = middle - 1; |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | if (candidate < 0) return -1; |
| 429 | |
| 430 | const active = events[candidate]; |
| 431 | if (timeSeconds >= active.endTimeSeconds) return -1; |
| 432 | return candidate; |
| 433 | } |
| 434 | |
| 435 | async function renderEventFrame (event, canvasWidth, canvasHeight) |
| 436 | { |
| 437 | const sourceWidth = Math.max(1, toPositiveInt(event.screenWidth, canvasWidth)); |
| 438 | const sourceHeight = Math.max(1, toPositiveInt(event.screenHeight, canvasHeight)); |
| 439 | |
| 440 | const scaleX = canvasWidth / sourceWidth; |
| 441 | const scaleY = canvasHeight / sourceHeight; |
| 442 | |
| 443 | const targetWidth = Math.max(1, Math.round(event.imageWidth * scaleX)); |
| 444 | const targetHeight = Math.max(1, Math.round(event.imageHeight * scaleY)); |
| 445 | const left = Math.round(event.left * scaleX); |
| 446 | const top = Math.round(event.top * scaleY); |
| 447 | const right = left + targetWidth; |
| 448 | const bottom = top + targetHeight; |
| 449 | |
| 450 | const visibleLeft = Math.max(0, left); |
| 451 | const visibleTop = Math.max(0, top); |
| 452 | const visibleRight = Math.min(canvasWidth, right); |
| 453 | const visibleBottom = Math.min(canvasHeight, bottom); |
| 454 | const visibleWidth = Math.max(0, visibleRight - visibleLeft); |
| 455 | const visibleHeight = Math.max(0, visibleBottom - visibleTop); |
| 456 | |
| 457 | if (visibleWidth <= 0 || visibleHeight <= 0) |
| 458 | { |
| 459 | return null; |
| 460 | } |
| 461 | |
| 462 | let imageBuffer = (targetWidth === event.imageWidth && targetHeight === event.imageHeight) |
| 463 | ? event.imagePng |
| 464 | : await sharp(event.imagePng).resize({ width: targetWidth, height: targetHeight, fit: 'fill' }).png().toBuffer(); |
| 465 | |
| 466 | if (visibleWidth < targetWidth || visibleHeight < targetHeight) |
| 467 | { |
| 468 | imageBuffer = await sharp(imageBuffer) |
| 469 | .extract({ |
| 470 | left: Math.max(0, visibleLeft - left), |
| 471 | top: Math.max(0, visibleTop - top), |
| 472 | width: visibleWidth, |
| 473 | height: visibleHeight, |
| 474 | }) |
| 475 | .png() |
| 476 | .toBuffer(); |
| 477 | } |
| 478 | |
| 479 | return { |
| 480 | frame: imageBuffer, |
| 481 | left: visibleLeft, |
| 482 | top: visibleTop, |
| 483 | width: visibleWidth, |
| 484 | height: visibleHeight, |
| 485 | canvasWidth, |
| 486 | canvasHeight, |
| 487 | }; |
| 488 | } |
| 489 | |
| 490 | function parseRenderOptions (options) |
| 491 | { |
| 492 | const input = options || {}; |
| 493 | const filePath = String(input.filePath ?? '').trim(); |
| 494 | const streamIndex = Number.parseInt(String(input.streamIndex ?? ''), 10); |
| 495 | const timeSeconds = Number.parseFloat(String(input.timeSeconds ?? ''), 10); |
| 496 | const requestedWidth = Math.max(1, toPositiveInt(input.canvasWidth ?? '', 1280)); |
| 497 | const requestedHeight = Math.max(1, toPositiveInt(input.canvasHeight ?? '', 720)); |
| 498 | const scale = Math.min(1, 1280 / requestedWidth, 720 / requestedHeight) * IMAGE_SUBTITLE_RENDER_SCALE; |
| 499 | const canvasWidth = Math.max(1, Math.round(requestedWidth * scale)); |
| 500 | const canvasHeight = Math.max(1, Math.round(requestedHeight * scale)); |
| 501 | |
| 502 | return { |
| 503 | filePath, |
| 504 | streamIndex, |
| 505 | timeSeconds, |
| 506 | canvasWidth, |
| 507 | canvasHeight, |
| 508 | isValid: !!(filePath && Number.isInteger(streamIndex) && streamIndex >= 0 && Number.isFinite(timeSeconds) && timeSeconds >= 0), |
| 509 | }; |
| 510 | } |
| 511 | |
| 512 | async function renderImageSubtitleFrame (options) |
| 513 | { |
| 514 | const parsed = parseRenderOptions(options); |
| 515 | const { filePath, streamIndex, timeSeconds, canvasWidth, canvasHeight } = parsed; |
| 516 | |
| 517 | if (!parsed.isValid) |
| 518 | { |
| 519 | return null; |
| 520 | } |
| 521 | |
| 522 | const entry = await getEventCacheEntry(filePath, streamIndex); |
| 523 | if (!entry || !Array.isArray(entry.events) || entry.events.length === 0) return null; |
| 524 | |
| 525 | const eventIndex = findActiveEventIndex(entry.events, timeSeconds); |
| 526 | if (eventIndex < 0) return null; |
| 527 | |
| 528 | const frameKey = `${entry.cacheKey}|${eventIndex}|${canvasWidth}x${canvasHeight}`; |
| 529 | const cachedFrame = getCachedValue(frameCache, frameKey); |
| 530 | if (cachedFrame) |
| 531 | { |
| 532 | return cachedFrame; |
| 533 | } |
| 534 | |
| 535 | const frameData = await renderEventFrame(entry.events[eventIndex], canvasWidth, canvasHeight); |
| 536 | if (!frameData) |
| 537 | { |
| 538 | return null; |
| 539 | } |
| 540 | |
| 541 | const event = entry.events[eventIndex]; |
| 542 | const cacheValue = { |
| 543 | frame: frameData.frame, |
| 544 | left: frameData.left, |
| 545 | top: frameData.top, |
| 546 | width: frameData.width, |
| 547 | height: frameData.height, |
| 548 | canvasWidth: frameData.canvasWidth, |
| 549 | canvasHeight: frameData.canvasHeight, |
| 550 | startTimeSeconds: event.startTimeSeconds, |
| 551 | endTimeSeconds: event.endTimeSeconds, |
| 552 | }; |
| 553 | setCachedValue( |
| 554 | frameCache, |
| 555 | frameKey, |
| 556 | cacheValue, |
| 557 | FRAME_CACHE_TTL_MS, |
| 558 | estimateFrameCacheBytes, |
| 559 | ); |
| 560 | return cacheValue; |
| 561 | } |
| 562 | |
| 563 | function deleteSupFileForKey (identityKey) |
| 564 | { |
| 565 | const cacheKey = eventCacheFileKey(identityKey); |
| 566 | const supPath = path.join(SUBTITLE_CACHE_DIR, `${cacheKey}.sup`); |
| 567 | fs.unlink(supPath, () => |
| 568 | { |
| 569 | // Best-effort; file may not exist if extraction never completed. |
| 570 | }); |
| 571 | } |
| 572 | |
| 573 | function purgeSubtitleCacheDir () |
| 574 | { |
| 575 | try |
| 576 | { |
| 577 | fs.rmSync(SUBTITLE_CACHE_DIR, { recursive: true, force: true }); |
| 578 | } catch |
| 579 | { |
| 580 | // Best-effort; directory may not exist. |
| 581 | } |
| 582 | } |
| 583 | |
| 584 | function pruneOldImageSubtitleCaches (filePath, slowestViewerTimeSeconds) |
| 585 | { |
| 586 | const prefix = cachePrefixForFile(filePath); |
| 587 | if (!prefix || !Number.isFinite(slowestViewerTimeSeconds)) return; |
| 588 | |
| 589 | // Prune frameCache as before |
| 590 | const keysToDelete = []; |
| 591 | for (const key of frameCache.map.keys()) |
| 592 | { |
| 593 | if (!key.startsWith(prefix)) continue; |
| 594 | const entry = frameCache.map.get(key); |
| 595 | if (!entry) continue; |
| 596 | const eventEntry = entry.value || {}; |
| 597 | const { startTimeSeconds, endTimeSeconds } = eventEntry; |
| 598 | if (!Number.isFinite(startTimeSeconds) || !Number.isFinite(endTimeSeconds)) continue; |
| 599 | const duration = Math.max(0, endTimeSeconds - startTimeSeconds); |
| 600 | const dropThreshold = endTimeSeconds + duration + IMAGE_SUBTITLE_PRUNE_GRACE_SECONDS; |
| 601 | if (slowestViewerTimeSeconds >= dropThreshold) |
| 602 | { |
| 603 | keysToDelete.push(key); |
| 604 | } |
| 605 | } |
| 606 | for (const key of keysToDelete) |
| 607 | { |
| 608 | deleteCachedValue(frameCache, key); |
| 609 | } |
| 610 | |
| 611 | // Smart eventCache pruning: only prune if over cap |
| 612 | let totalBytes = eventCache.totalBytes; |
| 613 | if (totalBytes <= MAX_EVENT_CACHE_BYTES) return; |
| 614 | // For each entry, prune events that end before (slowestViewerTimeSeconds - MIN_EVENT_WINDOW_SECONDS) |
| 615 | for (const [key, entry] of eventCache.map.entries()) |
| 616 | { |
| 617 | if (!key.startsWith(prefix)) continue; |
| 618 | const value = entry.value; |
| 619 | if (!value || !Array.isArray(value.events)) continue; |
| 620 | let events = value.events; |
| 621 | // Find first event that ends after the retention threshold |
| 622 | const minKeepTime = Math.max(0, slowestViewerTimeSeconds - MIN_EVENT_WINDOW_SECONDS); |
| 623 | let pruneIdx = 0; |
| 624 | while (pruneIdx < events.length && events[pruneIdx].endTimeSeconds < minKeepTime) |
| 625 | { |
| 626 | pruneIdx++; |
| 627 | } |
| 628 | if (pruneIdx > 0) |
| 629 | { |
| 630 | // Remove pruned events and update memory usage |
| 631 | const removed = events.splice(0, pruneIdx); |
| 632 | for (const ev of removed) |
| 633 | { |
| 634 | if (ev && Buffer.isBuffer(ev.imagePng)) |
| 635 | { |
| 636 | entry.sizeBytes -= ev.imagePng.length + 160; |
| 637 | eventCache.totalBytes -= ev.imagePng.length + 160; |
| 638 | } |
| 639 | } |
| 640 | } |
| 641 | // If all events are pruned, remove the entry |
| 642 | if (events.length === 0) |
| 643 | { |
| 644 | deleteSupFileForKey(key); |
| 645 | deleteCachedValue(eventCache, key); |
| 646 | } |
| 647 | // Stop pruning if under cap |
| 648 | if (eventCache.totalBytes <= MAX_EVENT_CACHE_BYTES) break; |
| 649 | } |
| 650 | } |
| 651 | |
| 652 | function clearCachesForFile (filePath) |
| 653 | { |
| 654 | const prefix = cachePrefixForFile(filePath); |
| 655 | if (!prefix) return; |
| 656 | |
| 657 | const eventKeysToDelete = []; |
| 658 | const frameKeysToDelete = []; |
| 659 | |
| 660 | for (const key of eventCache.map.keys()) |
| 661 | { |
| 662 | if (key.startsWith(prefix)) eventKeysToDelete.push(key); |
| 663 | } |
| 664 | |
| 665 | for (const key of frameCache.map.keys()) |
| 666 | { |
| 667 | if (key.startsWith(prefix)) frameKeysToDelete.push(key); |
| 668 | } |
| 669 | |
| 670 | for (const key of eventKeysToDelete) |
| 671 | { |
| 672 | deleteSupFileForKey(key); |
| 673 | deleteCachedValue(eventCache, key); |
| 674 | } |
| 675 | |
| 676 | for (const key of frameKeysToDelete) |
| 677 | { |
| 678 | deleteCachedValue(frameCache, key); |
| 679 | } |
| 680 | } |
| 681 | |
| 682 | function filePathFromCacheKey (key) |
| 683 | { |
| 684 | const raw = String(key || ''); |
| 685 | const divider = raw.indexOf('|'); |
| 686 | if (divider < 0) return ''; |
| 687 | return raw.slice(0, divider); |
| 688 | } |
| 689 | |
| 690 | function getImageSubtitleDebugSnapshot () |
| 691 | { |
| 692 | const byFile = {}; |
| 693 | |
| 694 | for (const [key, entry] of eventCache.map.entries()) |
| 695 | { |
| 696 | const filePath = filePathFromCacheKey(key); |
| 697 | if (!filePath) continue; |
| 698 | |
| 699 | const row = byFile[filePath] || { |
| 700 | filePath, |
| 701 | eventEntries: 0, |
| 702 | eventBytes: 0, |
| 703 | eventCount: 0, |
| 704 | eventImageBytes: 0, |
| 705 | frameEntries: 0, |
| 706 | frameBytes: 0, |
| 707 | }; |
| 708 | |
| 709 | row.eventEntries += 1; |
| 710 | row.eventBytes += Number(entry && entry.sizeBytes) || 0; |
| 711 | |
| 712 | const value = entry && entry.value; |
| 713 | if (value && Array.isArray(value.events)) |
| 714 | { |
| 715 | row.eventCount += value.events.length; |
| 716 | for (const event of value.events) |
| 717 | { |
| 718 | if (event && Buffer.isBuffer(event.imagePng)) |
| 719 | { |
| 720 | row.eventImageBytes += event.imagePng.length; |
| 721 | } |
| 722 | } |
| 723 | } |
| 724 | |
| 725 | byFile[filePath] = row; |
| 726 | } |
| 727 | |
| 728 | for (const [key, entry] of frameCache.map.entries()) |
| 729 | { |
| 730 | const filePath = filePathFromCacheKey(key); |
| 731 | if (!filePath) continue; |
| 732 | |
| 733 | const row = byFile[filePath] || { |
| 734 | filePath, |
| 735 | eventEntries: 0, |
| 736 | eventBytes: 0, |
| 737 | eventCount: 0, |
| 738 | eventImageBytes: 0, |
| 739 | frameEntries: 0, |
| 740 | frameBytes: 0, |
| 741 | }; |
| 742 | |
| 743 | row.frameEntries += 1; |
| 744 | row.frameBytes += Number(entry && entry.sizeBytes) || 0; |
| 745 | |
| 746 | byFile[filePath] = row; |
| 747 | } |
| 748 | |
| 749 | return { |
| 750 | eventCache: { |
| 751 | entries: eventCache.map.size, |
| 752 | bytes: eventCache.totalBytes, |
| 753 | maxItems: eventCache.maxItems, |
| 754 | maxBytes: eventCache.maxBytes, |
| 755 | }, |
| 756 | frameCache: { |
| 757 | entries: frameCache.map.size, |
| 758 | bytes: frameCache.totalBytes, |
| 759 | maxItems: frameCache.maxItems, |
| 760 | maxBytes: frameCache.maxBytes, |
| 761 | }, |
| 762 | byFile, |
| 763 | }; |
| 764 | } |
| 765 | |
| 766 | module.exports = { |
| 767 | parseRenderOptions, |
| 768 | renderImageSubtitleFrame, |
| 769 | clearCachesForFile, |
| 770 | pruneOldImageSubtitleCaches, |
| 771 | purgeSubtitleCacheDir, |
| 772 | getImageSubtitleDebugSnapshot, |
| 773 | }; |