BlueGit

timfa filemanager

Files

filemanager / server / image-subtitles.js

image-subtitles.js

image-subtitles.js 20.5 KiB Download Raw
1'use strict';
2
3const { spawn } = require('child_process');
4const crypto = require('crypto');
5const fs = require('fs');
6const os = require('os');
7const path = require('path');
8const { Readable } = require('stream');
9const sharp = require('sharp');
10
11const SUBTITLE_CACHE_DIR = path.join(os.tmpdir(), 'filemanager-video-subtitles');
12const EVENT_CACHE_TTL_MS = toPositiveInt(process.env.IMAGE_SUBTITLE_EVENT_CACHE_TTL_MS, 5 * 60 * 1000);
13const FRAME_CACHE_TTL_MS = toPositiveInt(process.env.IMAGE_SUBTITLE_FRAME_CACHE_TTL_MS, 2 * 60 * 1000);
14const MAX_EVENT_CACHE_ITEMS = toPositiveInt(process.env.IMAGE_SUBTITLE_EVENT_CACHE_MAX_ITEMS, 3);
15const 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
17const MAX_EVENT_CACHE_BYTES = toPositiveInt(process.env.IMAGE_SUBTITLE_EVENT_CACHE_MAX_BYTES, 50 * 1024 * 1024);
18const MIN_EVENT_WINDOW_SECONDS = 30; // Always keep at least this much for seeking
19const MAX_FRAME_CACHE_BYTES = toPositiveInt(process.env.IMAGE_SUBTITLE_FRAME_CACHE_MAX_BYTES, 48 * 1024 * 1024);
20const IMAGE_SUBTITLE_RENDER_SCALE = toBoundedNumber(process.env.IMAGE_SUBTITLE_RENDER_SCALE, 0.75, 0.1, 1);
21const PGS_TIMEBASE = 90000;
22const IMAGE_SUBTITLE_PRUNE_GRACE_SECONDS = toPositiveInt(process.env.IMAGE_SUBTITLE_PRUNE_GRACE_SECONDS, 5);
23
24const eventCache = createCacheState(MAX_EVENT_CACHE_ITEMS, MAX_EVENT_CACHE_BYTES);
25const frameCache = createCacheState(MAX_FRAME_CACHE_ITEMS, MAX_FRAME_CACHE_BYTES);
26
27let parseDisplaySets = null;
28
29function 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
46function loadPgsParser ()
47{
48 if (parseDisplaySets) return parseDisplaySets;
49 ensureImageDataGlobal();
50 ({ parseDisplaySets } = require('pgs-parser'));
51 return parseDisplaySets;
52}
53
54function ffmpegPath ()
55{
56 return process.env.FFMPEG_PATH || 'ffmpeg';
57}
58
59function ensureSubtitleCacheDir ()
60{
61 fs.mkdirSync(SUBTITLE_CACHE_DIR, { recursive: true });
62}
63
64function 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
71function 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
79function 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
87function createCacheState (maxItems, maxBytes)
88{
89 return {
90 map: new Map(),
91 totalBytes: 0,
92 maxItems,
93 maxBytes,
94 };
95}
96
97function normaliseFilePath (filePath)
98{
99 return path.resolve(String(filePath || '').trim());
100}
101
102function cachePrefixForFile (filePath)
103{
104 const normalised = String(filePath || '').trim();
105 if (!normalised) return '';
106 return `${normaliseFilePath(normalised)}|`;
107}
108
109function eventIdentityKey (filePath, streamIndex, stat)
110{
111 const normalisedPath = normaliseFilePath(filePath);
112 const hash = hashSubtitleKey(normalisedPath, streamIndex, stat);
113 return `${normalisedPath}|${streamIndex}|${hash}`;
114}
115
116function eventCacheFileKey (identityKey)
117{
118 const hash = crypto.createHash('sha1').update(String(identityKey || '')).digest('hex');
119 return `event-${hash}`;
120}
121
122function toValidCacheSize (value)
123{
124 const number = Number(value);
125 if (!Number.isFinite(number) || number <= 0) return 0;
126 return Math.floor(number);
127}
128
129function 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
144function 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
152function 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
162function 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
171function 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
188function 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
209function 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
235async 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
260function toSeconds (pgsTimestamp)
261{
262 const numeric = Number(pgsTimestamp);
263 if (!Number.isFinite(numeric) || numeric < 0) return 0;
264 return numeric / PGS_TIMEBASE;
265}
266
267function 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
280async 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
368async 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
379async 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
407function 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
435async 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
490function 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
512async 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
563function 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
573function 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
584function 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 if (!key.startsWith(prefix)) continue;
593 const entry = frameCache.map.get(key);
594 if (!entry) continue;
595 const eventEntry = entry.value || {};
596 const { startTimeSeconds, endTimeSeconds } = eventEntry;
597 if (!Number.isFinite(startTimeSeconds) || !Number.isFinite(endTimeSeconds)) continue;
598 const duration = Math.max(0, endTimeSeconds - startTimeSeconds);
599 const dropThreshold = endTimeSeconds + duration + IMAGE_SUBTITLE_PRUNE_GRACE_SECONDS;
600 if (slowestViewerTimeSeconds >= dropThreshold) {
601 keysToDelete.push(key);
602 }
603 }
604 for (const key of keysToDelete) {
605 deleteCachedValue(frameCache, key);
606 }
607
608 // Smart eventCache pruning: only prune if over cap
609 let totalBytes = eventCache.totalBytes;
610 if (totalBytes <= MAX_EVENT_CACHE_BYTES) return;
611 // For each entry, prune events that end before (slowestViewerTimeSeconds - MIN_EVENT_WINDOW_SECONDS)
612 for (const [key, entry] of eventCache.map.entries()) {
613 if (!key.startsWith(prefix)) continue;
614 const value = entry.value;
615 if (!value || !Array.isArray(value.events)) continue;
616 let events = value.events;
617 // Find first event that ends after the retention threshold
618 const minKeepTime = Math.max(0, slowestViewerTimeSeconds - MIN_EVENT_WINDOW_SECONDS);
619 let pruneIdx = 0;
620 while (pruneIdx < events.length && events[pruneIdx].endTimeSeconds < minKeepTime) {
621 pruneIdx++;
622 }
623 if (pruneIdx > 0) {
624 // Remove pruned events and update memory usage
625 const removed = events.splice(0, pruneIdx);
626 for (const ev of removed) {
627 if (ev && Buffer.isBuffer(ev.imagePng)) {
628 entry.sizeBytes -= ev.imagePng.length + 160;
629 eventCache.totalBytes -= ev.imagePng.length + 160;
630 }
631 }
632 }
633 // If all events are pruned, remove the entry
634 if (events.length === 0) {
635 deleteSupFileForKey(key);
636 deleteCachedValue(eventCache, key);
637 }
638 // Stop pruning if under cap
639 if (eventCache.totalBytes <= MAX_EVENT_CACHE_BYTES) break;
640 }
641}
642
643function clearCachesForFile (filePath)
644{
645 const prefix = cachePrefixForFile(filePath);
646 if (!prefix) return;
647
648 const eventKeysToDelete = [];
649 const frameKeysToDelete = [];
650
651 for (const key of eventCache.map.keys())
652 {
653 if (key.startsWith(prefix)) eventKeysToDelete.push(key);
654 }
655
656 for (const key of frameCache.map.keys())
657 {
658 if (key.startsWith(prefix)) frameKeysToDelete.push(key);
659 }
660
661 for (const key of eventKeysToDelete)
662 {
663 deleteSupFileForKey(key);
664 deleteCachedValue(eventCache, key);
665 }
666
667 for (const key of frameKeysToDelete)
668 {
669 deleteCachedValue(frameCache, key);
670 }
671}
672
673function filePathFromCacheKey (key)
674{
675 const raw = String(key || '');
676 const divider = raw.indexOf('|');
677 if (divider < 0) return '';
678 return raw.slice(0, divider);
679}
680
681function getImageSubtitleDebugSnapshot ()
682{
683 const byFile = {};
684
685 for (const [key, entry] of eventCache.map.entries())
686 {
687 const filePath = filePathFromCacheKey(key);
688 if (!filePath) continue;
689
690 const row = byFile[filePath] || {
691 filePath,
692 eventEntries: 0,
693 eventBytes: 0,
694 eventCount: 0,
695 eventImageBytes: 0,
696 frameEntries: 0,
697 frameBytes: 0,
698 };
699
700 row.eventEntries += 1;
701 row.eventBytes += Number(entry && entry.sizeBytes) || 0;
702
703 const value = entry && entry.value;
704 if (value && Array.isArray(value.events))
705 {
706 row.eventCount += value.events.length;
707 for (const event of value.events)
708 {
709 if (event && Buffer.isBuffer(event.imagePng))
710 {
711 row.eventImageBytes += event.imagePng.length;
712 }
713 }
714 }
715
716 byFile[filePath] = row;
717 }
718
719 for (const [key, entry] of frameCache.map.entries())
720 {
721 const filePath = filePathFromCacheKey(key);
722 if (!filePath) continue;
723
724 const row = byFile[filePath] || {
725 filePath,
726 eventEntries: 0,
727 eventBytes: 0,
728 eventCount: 0,
729 eventImageBytes: 0,
730 frameEntries: 0,
731 frameBytes: 0,
732 };
733
734 row.frameEntries += 1;
735 row.frameBytes += Number(entry && entry.sizeBytes) || 0;
736
737 byFile[filePath] = row;
738 }
739
740 return {
741 eventCache: {
742 entries: eventCache.map.size,
743 bytes: eventCache.totalBytes,
744 maxItems: eventCache.maxItems,
745 maxBytes: eventCache.maxBytes,
746 },
747 frameCache: {
748 entries: frameCache.map.size,
749 bytes: frameCache.totalBytes,
750 maxItems: frameCache.maxItems,
751 maxBytes: frameCache.maxBytes,
752 },
753 byFile,
754 };
755}
756
757module.exports = {
758 parseRenderOptions,
759 renderImageSubtitleFrame,
760 clearCachesForFile,
761 pruneOldImageSubtitleCaches,
762 purgeSubtitleCacheDir,
763 getImageSubtitleDebugSnapshot,
764};