'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 = 20 * 60 * 1000; const FRAME_CACHE_TTL_MS = 10 * 60 * 1000; const MAX_EVENT_CACHE_ITEMS = 6; const MAX_FRAME_CACHE_ITEMS = 400; const PGS_TIMEBASE = 90000; const eventCache = new Map(); const frameCache = new Map(); let parseDisplaySets = 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 hashSubtitleKey (filePath, streamIndex, stat) { return crypto .createHash('sha1') .update(`${filePath}|${streamIndex}|${stat.size}|${Math.floor(stat.mtimeMs)}`) .digest('hex'); } function getCachedValue (cache, key) { const now = Date.now(); const entry = cache.get(key); if (!entry) return null; if (entry.expiresAt <= now) { cache.delete(key); return null; } cache.delete(key); cache.set(key, entry); return entry.value; } function setCachedValue (cache, key, value, ttlMs, maxItems) { const now = Date.now(); cache.delete(key); cache.set(key, { value, expiresAt: now + ttlMs, }); while (cache.size > maxItems) { const oldestKey = cache.keys().next().value; cache.delete(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) { const stat = await fs.promises.stat(filePath); const cacheKey = hashSubtitleKey(filePath, streamIndex, stat); const supPath = await extractSupFile(filePath, streamIndex, cacheKey); const events = await parseSupEvents(supPath); return { cacheKey, events, }; } async function getEventCacheEntry (filePath, streamIndex) { const stat = await fs.promises.stat(filePath); const identityKey = hashSubtitleKey(filePath, streamIndex, stat); const cached = getCachedValue(eventCache, identityKey); if (cached) { return cached; } const pending = buildEventCacheEntry(filePath, streamIndex); setCachedValue(eventCache, identityKey, pending, EVENT_CACHE_TTL_MS, MAX_EVENT_CACHE_ITEMS); try { const resolved = await pending; setCachedValue(eventCache, identityKey, resolved, EVENT_CACHE_TTL_MS, MAX_EVENT_CACHE_ITEMS); return resolved; } catch (error) { eventCache.delete(identityKey); throw error; } } 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.max(0, Math.round(event.left * scaleX)); const top = Math.max(0, Math.round(event.top * scaleY)); if (left >= canvasWidth || top >= canvasHeight) { return sharp({ create: { width: canvasWidth, height: canvasHeight, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 }, }, }).png().toBuffer(); } const imageBuffer = (targetWidth === event.imageWidth && targetHeight === event.imageHeight) ? event.imagePng : await sharp(event.imagePng).resize({ width: targetWidth, height: targetHeight, fit: 'fill' }).png().toBuffer(); return sharp({ create: { width: canvasWidth, height: canvasHeight, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 }, }, }).composite([ { input: imageBuffer, left, top, }, ]).png().toBuffer(); } 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 canvasWidth = Math.max(1, Math.min(8192, toPositiveInt(input.canvasWidth ?? '', 1280))); const canvasHeight = Math.max(1, Math.min(8192, toPositiveInt(input.canvasHeight ?? '', 720))); return { filePath, streamIndex, timeSeconds, canvasWidth, canvasHeight, isValid: !!(filePath && Number.isInteger(streamIndex) && streamIndex >= 0 && Number.isFinite(timeSeconds) && timeSeconds >= 0), }; } async function renderImageSubtitleFrame (options) { const parsed = parseRenderOptions(options); const { filePath, streamIndex, timeSeconds, canvasWidth, canvasHeight } = parsed; if (!parsed.isValid) { return null; } const entry = await getEventCacheEntry(filePath, streamIndex); if (!entry || !Array.isArray(entry.events) || entry.events.length === 0) return null; const eventIndex = findActiveEventIndex(entry.events, timeSeconds); if (eventIndex < 0) return null; const frameKey = `${entry.cacheKey}|${eventIndex}|${canvasWidth}x${canvasHeight}`; const cachedFrame = getCachedValue(frameCache, frameKey); if (cachedFrame) { return cachedFrame; } const frame = await renderEventFrame(entry.events[eventIndex], canvasWidth, canvasHeight); const event = entry.events[eventIndex]; setCachedValue(frameCache, frameKey, { frame, startTimeSeconds: event.startTimeSeconds, endTimeSeconds: event.endTimeSeconds }, FRAME_CACHE_TTL_MS, MAX_FRAME_CACHE_ITEMS); return frame; } function pruneOldImageSubtitleCaches (filePath, slowestViewerTimeSeconds) { const normalised = String(filePath || '').trim(); if (!normalised || !Number.isFinite(slowestViewerTimeSeconds)) return; const keysToDelete = []; for (const key of frameCache.keys()) { if (!key.startsWith(normalised)) continue; const entry = frameCache.get(key); if (!entry) continue; const eventEntry = entry.value || {}; const { startTimeSeconds, endTimeSeconds } = eventEntry; if (!Number.isFinite(startTimeSeconds) || !Number.isFinite(endTimeSeconds)) continue; const duration = endTimeSeconds - startTimeSeconds; const dropThreshold = endTimeSeconds + duration; if (slowestViewerTimeSeconds >= dropThreshold) { keysToDelete.push(key); } } for (const key of keysToDelete) { frameCache.delete(key); } } function clearCachesForFile (filePath) { const normalised = String(filePath || '').trim(); if (!normalised) return; const keysToDelete = []; for (const key of eventCache.keys()) { if (key.startsWith(normalised)) { keysToDelete.push(key); } } for (const key of frameCache.keys()) { if (key.startsWith(normalised)) { keysToDelete.push(key); } } for (const key of keysToDelete) { eventCache.delete(key); frameCache.delete(key); } } module.exports = { parseRenderOptions, renderImageSubtitleFrame, clearCachesForFile, pruneOldImageSubtitleCaches, };