'use strict'; const { spawn } = require('child_process'); const crypto = require('crypto'); const fs = require('fs'); const os = require('os'); const path = require('path'); const { Readable } = require('stream'); const sharp = require('sharp'); const SUBTITLE_CACHE_DIR = path.join(os.tmpdir(), 'filemanager-video-subtitles'); const EVENT_CACHE_TTL_MS = toPositiveInt(process.env.IMAGE_SUBTITLE_EVENT_CACHE_TTL_MS, 5 * 60 * 1000); const FRAME_CACHE_TTL_MS = toPositiveInt(process.env.IMAGE_SUBTITLE_FRAME_CACHE_TTL_MS, 2 * 60 * 1000); const MAX_EVENT_CACHE_ITEMS = toCacheItemLimit(process.env.IMAGE_SUBTITLE_EVENT_CACHE_MAX_ITEMS, Infinity); const MAX_FRAME_CACHE_ITEMS = toCacheItemLimit(process.env.IMAGE_SUBTITLE_FRAME_CACHE_MAX_ITEMS, Infinity); // Removed byte size cap for event cache to prevent thrashing const MAX_EVENT_CACHE_BYTES = toPositiveInt(process.env.IMAGE_SUBTITLE_EVENT_CACHE_MAX_BYTES, 50 * 1024 * 1024); const MAX_FRAME_CACHE_BYTES = toPositiveInt(process.env.IMAGE_SUBTITLE_FRAME_CACHE_MAX_BYTES, 48 * 1024 * 1024); const IMAGE_SUBTITLE_RENDER_SCALE = toBoundedNumber(process.env.IMAGE_SUBTITLE_RENDER_SCALE, 0.75, 0.1, 1); const PGS_TIMEBASE = 90000; const IMAGE_SUBTITLE_PRUNE_GRACE_SECONDS = toPositiveInt(process.env.IMAGE_SUBTITLE_PRUNE_GRACE_SECONDS, 5); const eventCache = createCacheState(MAX_EVENT_CACHE_ITEMS, MAX_EVENT_CACHE_BYTES); const frameCache = createCacheState(MAX_FRAME_CACHE_ITEMS, MAX_FRAME_CACHE_BYTES); const subtitleDebugStats = createSubtitleDebugStats(); let parseDisplaySets = null; function createDurationStats () { return { count: 0, totalMs: 0, maxMs: 0, lastMs: 0, }; } function createSubtitleDebugStats () { return { eventCacheHits: 0, eventCacheMisses: 0, eventCachePendingHits: 0, eventCacheBuilds: 0, eventCacheBuildErrors: 0, frameCacheHits: 0, frameCacheMisses: 0, frameRenders: 0, eventBuildDurationMs: createDurationStats(), frameRenderDurationMs: createDurationStats(), frameRequestDurationMs: createDurationStats(), }; } function recordDuration (stats, startedAt) { if (!stats || !Number.isFinite(startedAt)) return 0; const elapsedMs = Math.max(0, Date.now() - startedAt); stats.count += 1; stats.totalMs += elapsedMs; stats.lastMs = elapsedMs; if (elapsedMs > stats.maxMs) stats.maxMs = elapsedMs; return elapsedMs; } function averageDurationMs (stats) { if (!stats || !stats.count) return 0; return Number((stats.totalMs / stats.count).toFixed(1)); } function debugLimitValue (value) { return Number.isFinite(value) ? value : null; } function ensureImageDataGlobal () { if (typeof globalThis.ImageData === 'function') return; class ImageDataPolyfill { constructor(data, width, height) { this.data = data; this.width = width; this.height = height; } } globalThis.ImageData = ImageDataPolyfill; } function loadPgsParser () { if (parseDisplaySets) return parseDisplaySets; ensureImageDataGlobal(); ({ parseDisplaySets } = require('pgs-parser')); return parseDisplaySets; } function ffmpegPath () { return process.env.FFMPEG_PATH || 'ffmpeg'; } function ensureSubtitleCacheDir () { fs.mkdirSync(SUBTITLE_CACHE_DIR, { recursive: true }); } function toPositiveInt (value, fallback) { const number = Number.parseInt(String(value || ''), 10); if (Number.isInteger(number) && number > 0) return number; return fallback; } function toCacheItemLimit (value, fallback) { const raw = String(value || '').trim().toLowerCase(); if (!raw) return fallback; if (raw === '0' || raw === 'none' || raw === 'infinity' || raw === 'inf' || raw === 'unbounded' || raw === 'unlimited') { return Infinity; } const number = Number.parseInt(raw, 10); if (Number.isInteger(number) && number > 0) return number; return fallback; } function toBoundedNumber (value, fallback, min, max) { const numeric = Number.parseFloat(String(value || '')); if (!Number.isFinite(numeric)) return fallback; if (numeric < min || numeric > max) return fallback; return numeric; } function hashSubtitleKey (filePath, streamIndex, stat) { return crypto .createHash('sha1') .update(`${filePath}|${streamIndex}|${stat.size}|${Math.floor(stat.mtimeMs)}`) .digest('hex'); } function createCacheState (maxItems, maxBytes) { return { map: new Map(), totalBytes: 0, maxItems, maxBytes, }; } function normaliseFilePath (filePath) { return path.resolve(String(filePath || '').trim()); } function cachePrefixForFile (filePath) { const normalised = String(filePath || '').trim(); if (!normalised) return ''; return `${normaliseFilePath(normalised)}|`; } function eventIdentityKey (filePath, streamIndex, stat) { const normalisedPath = normaliseFilePath(filePath); const hash = hashSubtitleKey(normalisedPath, streamIndex, stat); return `${normalisedPath}|${streamIndex}|${hash}`; } function eventCacheFileKey (identityKey) { const hash = crypto.createHash('sha1').update(String(identityKey || '')).digest('hex'); return `event-${hash}`; } function toValidCacheSize (value) { const number = Number(value); if (!Number.isFinite(number) || number <= 0) return 0; return Math.floor(number); } function estimateEventCacheBytes (value) { if (!value) return 0; if (typeof value.then === 'function') return 1024; if (!Array.isArray(value.events)) return 1024; let bytes = 1024; for (const event of value.events) { if (event && Buffer.isBuffer(event.imagePng)) bytes += event.imagePng.length; bytes += 160; } return bytes; } function estimateFrameCacheBytes (value) { if (!value) return 0; if (Buffer.isBuffer(value)) return value.length; if (value && Buffer.isBuffer(value.frame)) return value.frame.length + 96; return 1024; } function deleteCachedValue (cache, key) { const entry = cache.map.get(key); if (!entry) return false; cache.map.delete(key); cache.totalBytes = Math.max(0, cache.totalBytes - toValidCacheSize(entry.sizeBytes)); return true; } function touchCachedEntry (cache, key, ttlMs) { const entry = cache.map.get(key); if (!entry) return; entry.expiresAt = Date.now() + ttlMs; cache.map.delete(key); cache.map.set(key, entry); } function getCachedValue (cache, key) { const now = Date.now(); const entry = cache.map.get(key); if (!entry) return null; if (entry.expiresAt <= now) { deleteCachedValue(cache, key); return null; } cache.map.delete(key); cache.map.set(key, entry); return entry.value; } function setCachedValue (cache, key, value, ttlMs, estimateBytes) { const now = Date.now(); deleteCachedValue(cache, key); const sizeBytes = toValidCacheSize(typeof estimateBytes === 'function' ? estimateBytes(value) : 0); cache.map.set(key, { value, expiresAt: now + ttlMs, sizeBytes, }); cache.totalBytes += sizeBytes; while (cache.map.size > cache.maxItems || cache.maxBytes !== Infinity && cache.totalBytes > cache.maxBytes) { const oldestKey = cache.map.keys().next().value; deleteCachedValue(cache, oldestKey); } } function runCommand (command, args) { return new Promise((resolve, reject) => { const child = spawn(command, args, { stdio: ['ignore', 'ignore', 'pipe'] }); let stderr = ''; child.stderr.on('data', (chunk) => { stderr += chunk.toString(); if (stderr.length > 16000) stderr = stderr.slice(-16000); }); child.on('error', reject); child.on('close', (code) => { if (code === 0) { resolve(); return; } reject(new Error(stderr.trim() || `ffmpeg exited with code ${code}`)); }); }); } async function extractSupFile (sourcePath, streamIndex, cacheKey) { ensureSubtitleCacheDir(); const supPath = path.join(SUBTITLE_CACHE_DIR, `${cacheKey}.sup`); if (fs.existsSync(supPath) && fs.statSync(supPath).size > 0) { return supPath; } await runCommand(ffmpegPath(), [ '-hide_banner', '-loglevel', 'error', '-nostdin', '-y', '-i', sourcePath, '-map', `0:s:${streamIndex}`, '-c:s', 'copy', '-f', 'sup', supPath, ]); return supPath; } function toSeconds (pgsTimestamp) { const numeric = Number(pgsTimestamp); if (!Number.isFinite(numeric) || numeric < 0) return 0; return numeric / PGS_TIMEBASE; } function parseDisplaySetTimestamp (displaySet) { if (displaySet && displaySet.presentationCompositionSegment && displaySet.presentationCompositionSegment.header) { return toSeconds(displaySet.presentationCompositionSegment.header.presentationTimestamp); } if (displaySet && displaySet.endDefinitionSegment && displaySet.endDefinitionSegment.header) { return toSeconds(displaySet.endDefinitionSegment.header.presentationTimestamp); } return 0; } async function parseSupEvents (supPath) { const parserFactory = loadPgsParser(); if (typeof Readable.toWeb !== 'function') { throw new Error('Node.js stream bridge is unavailable for subtitle parsing.'); } const subtitleStream = Readable.toWeb(fs.createReadStream(supPath)); const parserStream = subtitleStream.pipeThrough(parserFactory()); const reader = parserStream.getReader(); const events = []; let currentEvent = null; let scratchBuffer = null; while (true) { const { done, value: displaySet } = await reader.read(); if (done) break; const timestampSeconds = parseDisplaySetTimestamp(displaySet); if (currentEvent && timestampSeconds > currentEvent.startTimeSeconds) { currentEvent.endTimeSeconds = timestampSeconds; events.push(currentEvent); currentEvent = null; } if (!displaySet || !Array.isArray(displaySet.objectDefinitionSegments) || displaySet.objectDefinitionSegments.length === 0) { continue; } const pcs = displaySet.presentationCompositionSegment; if (!pcs) continue; const neededPixels = Number(pcs.width || 0) * Number(pcs.height || 0) * 4; if (!scratchBuffer || !Number.isInteger(neededPixels) || neededPixels <= 0 || scratchBuffer.length < neededPixels) { scratchBuffer = neededPixels > 0 ? new Uint8ClampedArray(neededPixels) : null; } let imageData; try { imageData = displaySet.imageData(scratchBuffer || undefined); } catch { continue; } if (!imageData || !imageData.data || !Number.isInteger(imageData.width) || !Number.isInteger(imageData.height)) { continue; } const rawPixels = Buffer.from(imageData.data); const imagePng = await sharp(rawPixels, { raw: { width: imageData.width, height: imageData.height, channels: 4, }, }).png().toBuffer(); currentEvent = { startTimeSeconds: timestampSeconds, endTimeSeconds: Number.POSITIVE_INFINITY, screenWidth: toPositiveInt(pcs.width, imageData.width), screenHeight: toPositiveInt(pcs.height, imageData.height), left: toPositiveInt(pcs.objectHorizontalPosition, 0), top: toPositiveInt(pcs.objectVerticalPosition, 0), imageWidth: imageData.width, imageHeight: imageData.height, imagePng, }; } if (currentEvent) { events.push(currentEvent); } return events; } async function buildEventCacheEntry (filePath, streamIndex, identityKey) { const subtitleFileCacheKey = eventCacheFileKey(identityKey); const supPath = await extractSupFile(filePath, streamIndex, subtitleFileCacheKey); const events = await parseSupEvents(supPath); return { cacheKey: identityKey, events, }; } function beginEventCacheBuild (normalisedPath, streamIndex, identityKey) { subtitleDebugStats.eventCacheBuilds += 1; const buildStartedAt = Date.now(); const pending = buildEventCacheEntry(normalisedPath, streamIndex, identityKey); setCachedValue(eventCache, identityKey, pending, EVENT_CACHE_TTL_MS, estimateEventCacheBytes); pending .then((resolved) => { recordDuration(subtitleDebugStats.eventBuildDurationMs, buildStartedAt); setCachedValue(eventCache, identityKey, resolved, EVENT_CACHE_TTL_MS, estimateEventCacheBytes); return resolved; }) .catch(() => { subtitleDebugStats.eventCacheBuildErrors += 1; deleteCachedValue(eventCache, identityKey); }); return pending; } async function getEventCacheEntry (filePath, streamIndex, options = {}) { const waitForBuild = options.waitForBuild !== false; const normalisedPath = normaliseFilePath(filePath); const stat = await fs.promises.stat(normalisedPath); const identityKey = eventIdentityKey(normalisedPath, streamIndex, stat); const cached = getCachedValue(eventCache, identityKey); if (cached) { if (typeof cached.then === 'function') subtitleDebugStats.eventCachePendingHits += 1; else subtitleDebugStats.eventCacheHits += 1; touchCachedEntry(eventCache, identityKey, EVENT_CACHE_TTL_MS); if (typeof cached.then === 'function') { return waitForBuild ? cached : null; } return cached; } subtitleDebugStats.eventCacheMisses += 1; const pending = beginEventCacheBuild(normalisedPath, streamIndex, identityKey); return waitForBuild ? pending : null; } function findActiveEventIndex (events, timeSeconds) { let left = 0; let right = events.length - 1; let candidate = -1; while (left <= right) { const middle = Math.floor((left + right) / 2); const event = events[middle]; if (event.startTimeSeconds <= timeSeconds) { candidate = middle; left = middle + 1; } else { right = middle - 1; } } if (candidate < 0) return -1; const active = events[candidate]; if (timeSeconds >= active.endTimeSeconds) return -1; return candidate; } async function renderEventFrame (event, canvasWidth, canvasHeight) { const sourceWidth = Math.max(1, toPositiveInt(event.screenWidth, canvasWidth)); const sourceHeight = Math.max(1, toPositiveInt(event.screenHeight, canvasHeight)); const scaleX = canvasWidth / sourceWidth; const scaleY = canvasHeight / sourceHeight; const targetWidth = Math.max(1, Math.round(event.imageWidth * scaleX)); const targetHeight = Math.max(1, Math.round(event.imageHeight * scaleY)); const left = Math.round(event.left * scaleX); const top = Math.round(event.top * scaleY); const right = left + targetWidth; const bottom = top + targetHeight; const visibleLeft = Math.max(0, left); const visibleTop = Math.max(0, top); const visibleRight = Math.min(canvasWidth, right); const visibleBottom = Math.min(canvasHeight, bottom); const visibleWidth = Math.max(0, visibleRight - visibleLeft); const visibleHeight = Math.max(0, visibleBottom - visibleTop); if (visibleWidth <= 0 || visibleHeight <= 0) { return null; } let imageBuffer = (targetWidth === event.imageWidth && targetHeight === event.imageHeight) ? event.imagePng : await sharp(event.imagePng).resize({ width: targetWidth, height: targetHeight, fit: 'fill' }).png().toBuffer(); if (visibleWidth < targetWidth || visibleHeight < targetHeight) { imageBuffer = await sharp(imageBuffer) .extract({ left: Math.max(0, visibleLeft - left), top: Math.max(0, visibleTop - top), width: visibleWidth, height: visibleHeight, }) .png() .toBuffer(); } return { frame: imageBuffer, left: visibleLeft, top: visibleTop, width: visibleWidth, height: visibleHeight, canvasWidth, canvasHeight, }; } function parseRenderOptions (options) { const input = options || {}; const filePath = String(input.filePath ?? '').trim(); const streamIndex = Number.parseInt(String(input.streamIndex ?? ''), 10); const timeSeconds = Number.parseFloat(String(input.timeSeconds ?? ''), 10); const requestedWidth = Math.max(1, toPositiveInt(input.canvasWidth ?? '', 1280)); const requestedHeight = Math.max(1, toPositiveInt(input.canvasHeight ?? '', 720)); const scale = Math.min(1, 1280 / requestedWidth, 720 / requestedHeight) * IMAGE_SUBTITLE_RENDER_SCALE; const canvasWidth = Math.max(1, Math.round(requestedWidth * scale)); const canvasHeight = Math.max(1, Math.round(requestedHeight * scale)); return { filePath, streamIndex, timeSeconds, canvasWidth, canvasHeight, isValid: !!(filePath && Number.isInteger(streamIndex) && streamIndex >= 0 && Number.isFinite(timeSeconds) && timeSeconds >= 0), }; } function parseRenderRangeOptions (options) { const parsed = parseRenderOptions({ ...options, timeSeconds: options && options.startTimeSeconds, }); const startTimeSeconds = parsed.timeSeconds; const endTimeSeconds = Number.parseFloat(String((options && options.endTimeSeconds) ?? ''), 10); return { filePath: parsed.filePath, streamIndex: parsed.streamIndex, startTimeSeconds, endTimeSeconds, canvasWidth: parsed.canvasWidth, canvasHeight: parsed.canvasHeight, isValid: !!(parsed.isValid && Number.isFinite(endTimeSeconds) && endTimeSeconds >= startTimeSeconds), }; } async function getRenderedFrameForEvent (entry, eventIndex, canvasWidth, canvasHeight) { if (!entry || !Array.isArray(entry.events) || eventIndex < 0 || eventIndex >= entry.events.length) return null; const frameKey = `${entry.cacheKey}|${eventIndex}|${canvasWidth}x${canvasHeight}`; const cachedFrame = getCachedValue(frameCache, frameKey); if (cachedFrame) { subtitleDebugStats.frameCacheHits += 1; return cachedFrame; } subtitleDebugStats.frameCacheMisses += 1; subtitleDebugStats.frameRenders += 1; const renderStartedAt = Date.now(); const frameData = await renderEventFrame(entry.events[eventIndex], canvasWidth, canvasHeight); if (!frameData) { recordDuration(subtitleDebugStats.frameRenderDurationMs, renderStartedAt); return null; } recordDuration(subtitleDebugStats.frameRenderDurationMs, renderStartedAt); const event = entry.events[eventIndex]; const cacheValue = { frame: frameData.frame, left: frameData.left, top: frameData.top, width: frameData.width, height: frameData.height, canvasWidth: frameData.canvasWidth, canvasHeight: frameData.canvasHeight, startTimeSeconds: event.startTimeSeconds, endTimeSeconds: event.endTimeSeconds, }; setCachedValue( frameCache, frameKey, cacheValue, FRAME_CACHE_TTL_MS, estimateFrameCacheBytes, ); return cacheValue; } async function renderImageSubtitleFrame (options) { const requestStartedAt = Date.now(); const parsed = parseRenderOptions(options); const { filePath, streamIndex, timeSeconds, canvasWidth, canvasHeight } = parsed; if (!parsed.isValid) { recordDuration(subtitleDebugStats.frameRequestDurationMs, requestStartedAt); return null; } const entry = await getEventCacheEntry(filePath, streamIndex, { waitForBuild: false }); if (!entry || !Array.isArray(entry.events) || entry.events.length === 0) { recordDuration(subtitleDebugStats.frameRequestDurationMs, requestStartedAt); return null; } const eventIndex = findActiveEventIndex(entry.events, timeSeconds); if (eventIndex < 0) { recordDuration(subtitleDebugStats.frameRequestDurationMs, requestStartedAt); return null; } const cacheValue = await getRenderedFrameForEvent(entry, eventIndex, canvasWidth, canvasHeight); if (!cacheValue) { recordDuration(subtitleDebugStats.frameRequestDurationMs, requestStartedAt); return null; } recordDuration(subtitleDebugStats.frameRequestDurationMs, requestStartedAt); return cacheValue; } async function renderImageSubtitleFramesInRange (options) { const requestStartedAt = Date.now(); const parsed = parseRenderRangeOptions(options); const { filePath, streamIndex, startTimeSeconds, endTimeSeconds, canvasWidth, canvasHeight } = parsed; if (!parsed.isValid) { recordDuration(subtitleDebugStats.frameRequestDurationMs, requestStartedAt); return { frames: [], startTimeSeconds, endTimeSeconds, }; } const entry = await getEventCacheEntry(filePath, streamIndex, { waitForBuild: false }); if (!entry || !Array.isArray(entry.events) || entry.events.length === 0) { recordDuration(subtitleDebugStats.frameRequestDurationMs, requestStartedAt); return { frames: [], startTimeSeconds, endTimeSeconds, }; } let eventIndex = findActiveEventIndex(entry.events, startTimeSeconds); if (eventIndex < 0) { eventIndex = entry.events.findIndex((event) => event && Number(event.endTimeSeconds) > startTimeSeconds); } const frames = []; for (let index = Math.max(0, eventIndex); index < entry.events.length; index++) { const event = entry.events[index]; if (!event) continue; if (Number(event.startTimeSeconds) >= endTimeSeconds) break; if (Number(event.endTimeSeconds) <= startTimeSeconds) continue; const frame = await getRenderedFrameForEvent(entry, index, canvasWidth, canvasHeight); if (!frame || !frame.frame) continue; frames.push(frame); } recordDuration(subtitleDebugStats.frameRequestDurationMs, requestStartedAt); return { frames, startTimeSeconds, endTimeSeconds, }; } function deleteSupFileForKey (identityKey) { const cacheKey = eventCacheFileKey(identityKey); const supPath = path.join(SUBTITLE_CACHE_DIR, `${cacheKey}.sup`); fs.unlink(supPath, () => { // Best-effort; file may not exist if extraction never completed. }); } function purgeSubtitleCacheDir () { try { fs.rmSync(SUBTITLE_CACHE_DIR, { recursive: true, force: true }); } catch { // Best-effort; directory may not exist. } } function pruneOldImageSubtitleCaches (filePath, slowestViewerTimeSeconds) { const prefix = cachePrefixForFile(filePath); if (!prefix || !Number.isFinite(slowestViewerTimeSeconds)) return; const pruneThresholdSeconds = slowestViewerTimeSeconds - IMAGE_SUBTITLE_PRUNE_GRACE_SECONDS; // Prune frame cache entries that ended before the slowest viewer + grace. const keysToDelete = []; for (const key of frameCache.map.keys()) { if (!key.startsWith(prefix)) continue; const entry = frameCache.map.get(key); if (!entry) continue; const eventEntry = entry.value || {}; const endTimeSeconds = Number(eventEntry.endTimeSeconds); if (!Number.isFinite(endTimeSeconds)) continue; if (endTimeSeconds <= pruneThresholdSeconds) { keysToDelete.push(key); } } for (const key of keysToDelete) { deleteCachedValue(frameCache, key); } // Prune event cache entries unconditionally as viewer frontier advances. for (const [key, entry] of eventCache.map.entries()) { if (!key.startsWith(prefix)) continue; const value = entry.value; if (!value || !Array.isArray(value.events)) continue; let events = value.events; // Keep only events not yet passed by the slowest viewer (+ grace). let pruneIdx = 0; while (pruneIdx < events.length) { const event = events[pruneIdx]; const endTimeSeconds = Number(event && event.endTimeSeconds); if (!Number.isFinite(endTimeSeconds) || endTimeSeconds > pruneThresholdSeconds) break; pruneIdx++; } if (pruneIdx > 0) { // Remove pruned events and update cache accounting. const removed = events.splice(0, pruneIdx); for (const ev of removed) { const estimatedBytes = (ev && Buffer.isBuffer(ev.imagePng) ? ev.imagePng.length : 0) + 160; entry.sizeBytes = Math.max(0, toValidCacheSize(entry.sizeBytes) - estimatedBytes); eventCache.totalBytes = Math.max(0, toValidCacheSize(eventCache.totalBytes) - estimatedBytes); } } // If all events are pruned, remove the entry and extracted sup file. if (events.length === 0) { deleteSupFileForKey(key); deleteCachedValue(eventCache, key); } } } function clearCachesForFile (filePath) { const prefix = cachePrefixForFile(filePath); if (!prefix) return; const eventKeysToDelete = []; const frameKeysToDelete = []; for (const key of eventCache.map.keys()) { if (key.startsWith(prefix)) eventKeysToDelete.push(key); } for (const key of frameCache.map.keys()) { if (key.startsWith(prefix)) frameKeysToDelete.push(key); } for (const key of eventKeysToDelete) { deleteSupFileForKey(key); deleteCachedValue(eventCache, key); } for (const key of frameKeysToDelete) { deleteCachedValue(frameCache, key); } } function filePathFromCacheKey (key) { const raw = String(key || ''); const divider = raw.indexOf('|'); if (divider < 0) return ''; return raw.slice(0, divider); } function getImageSubtitleDebugSnapshot () { const byFile = {}; for (const [key, entry] of eventCache.map.entries()) { const filePath = filePathFromCacheKey(key); if (!filePath) continue; const row = byFile[filePath] || { filePath, eventEntries: 0, eventBytes: 0, eventCount: 0, eventImageBytes: 0, frameEntries: 0, frameBytes: 0, }; row.eventEntries += 1; row.eventBytes += Number(entry && entry.sizeBytes) || 0; const value = entry && entry.value; if (value && Array.isArray(value.events)) { row.eventCount += value.events.length; for (const event of value.events) { if (event && Buffer.isBuffer(event.imagePng)) { row.eventImageBytes += event.imagePng.length; } } } byFile[filePath] = row; } for (const [key, entry] of frameCache.map.entries()) { const filePath = filePathFromCacheKey(key); if (!filePath) continue; const row = byFile[filePath] || { filePath, eventEntries: 0, eventBytes: 0, eventCount: 0, eventImageBytes: 0, frameEntries: 0, frameBytes: 0, }; row.frameEntries += 1; row.frameBytes += Number(entry && entry.sizeBytes) || 0; byFile[filePath] = row; } return { eventCache: { entries: eventCache.map.size, bytes: eventCache.totalBytes, maxItems: debugLimitValue(eventCache.maxItems), maxBytes: eventCache.maxBytes, }, frameCache: { entries: frameCache.map.size, bytes: frameCache.totalBytes, maxItems: debugLimitValue(frameCache.maxItems), maxBytes: frameCache.maxBytes, }, metrics: { eventCacheHits: subtitleDebugStats.eventCacheHits, eventCacheMisses: subtitleDebugStats.eventCacheMisses, eventCachePendingHits: subtitleDebugStats.eventCachePendingHits, eventCacheBuilds: subtitleDebugStats.eventCacheBuilds, eventCacheBuildErrors: subtitleDebugStats.eventCacheBuildErrors, frameCacheHits: subtitleDebugStats.frameCacheHits, frameCacheMisses: subtitleDebugStats.frameCacheMisses, frameRenders: subtitleDebugStats.frameRenders, eventBuildDurationMs: { last: subtitleDebugStats.eventBuildDurationMs.lastMs, max: subtitleDebugStats.eventBuildDurationMs.maxMs, average: averageDurationMs(subtitleDebugStats.eventBuildDurationMs), }, frameRenderDurationMs: { last: subtitleDebugStats.frameRenderDurationMs.lastMs, max: subtitleDebugStats.frameRenderDurationMs.maxMs, average: averageDurationMs(subtitleDebugStats.frameRenderDurationMs), }, frameRequestDurationMs: { last: subtitleDebugStats.frameRequestDurationMs.lastMs, max: subtitleDebugStats.frameRequestDurationMs.maxMs, average: averageDurationMs(subtitleDebugStats.frameRequestDurationMs), }, }, byFile, }; } module.exports = { parseRenderOptions, parseRenderRangeOptions, renderImageSubtitleFrame, renderImageSubtitleFramesInRange, clearCachesForFile, pruneOldImageSubtitleCaches, purgeSubtitleCacheDir, getImageSubtitleDebugSnapshot, };