-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-caption-pngs.js
More file actions
807 lines (690 loc) · 26.5 KB
/
generate-caption-pngs.js
File metadata and controls
807 lines (690 loc) · 26.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
#!/usr/bin/env node
const fs = require("fs");
const path = require("path");
const { createCanvas, registerFont } = require("canvas");
const mkdirp = require("mkdirp");
const crypto = require("crypto");
// Configuration
const FPS = 30;
const WIDTH = 1280;
const HEIGHT = 720;
const CAPTION_AREA_HEIGHT = 400;
const PADDING_X = 15;
const PADDING_Y = 5;
const BG_COLOR = "rgba(18, 46, 73, 1)";
const ACTIVE_COLOR = "#fcfaef";
const INACTIVE_COLOR = "#bbbbbb";
const HIGHLIGHT_COLOR = "#76b1af"; // Bright orange highlight color
const BORDER_RADIUS = 20;
const REMOVE_PERIODS = true;
const TEXT_CASE = "lowercase";
const FONT_SIZE = 60;
const LINE_HEIGHT = 75;
const UNSPOKEN_OPACITY = 0.0; // Opacity for unspoken words (0 = invisible, 1 = fully visible)
// Drop shadow configuration
const SHADOW_COLOR = "rgba(0, 0, 0, 0.6)";
const INACTIVE_SHADOW_BLUR = 2;
const INACTIVE_SHADOW_OFFSET_X = 2;
const INACTIVE_SHADOW_OFFSET_Y = 2;
const ACTIVE_SHADOW_BLUR = 4;
const ACTIVE_SHADOW_OFFSET_X = 3;
const ACTIVE_SHADOW_OFFSET_Y = 3;
// Parse command line arguments
const args = process.argv.slice(2);
let jsonFile = null;
let outputDir = null;
let startTime = 0;
let duration = 0;
let removePeriods = REMOVE_PERIODS;
let textCase = TEXT_CASE;
let highlightWords = [];
let hideUnspoken = false;
for (let i = 0; i < args.length; i++) {
if (args[i] === "-json" && i + 1 < args.length) {
jsonFile = args[i + 1];
i++;
} else if (args[i] === "-output" && i + 1 < args.length) {
outputDir = args[i + 1];
i++;
} else if (args[i] === "-start" && i + 1 < args.length) {
startTime = parseFloat(args[i + 1]);
i++;
} else if (args[i] === "-duration" && i + 1 < args.length) {
duration = parseFloat(args[i + 1]);
i++;
} else if (args[i] === "-remove-periods" && i + 1 < args.length) {
removePeriods = args[i + 1].toLowerCase() === "true";
i++;
} else if (args[i] === "-case" && i + 1 < args.length) {
textCase = args[i + 1].toLowerCase();
if (!["lowercase", "uppercase", "original"].includes(textCase)) {
console.warn(
`Invalid case option "${textCase}", using default "${TEXT_CASE}"`
);
textCase = TEXT_CASE;
}
i++;
} else if (args[i] === "-highlight" && i + 1 < args.length) {
// Add words to highlight (comma-separated list)
highlightWords = args[i + 1]
.split(",")
.map((word) => word.trim().toLowerCase());
console.log(`Highlighting words: ${highlightWords.join(", ")}`);
i++;
} else if (args[i] === "-hide-unspoken" && i + 1 < args.length) {
hideUnspoken = args[i + 1].toLowerCase() === "true";
console.log(`Hide unspoken words: ${hideUnspoken}`);
i++;
}
}
if (!jsonFile) {
console.error(
"Usage: node generate-caption-pngs.js -json [group.json] -output [output_dir] -start [start_time] -duration [duration_in_seconds] -remove-periods [true/false] -case [lowercase/uppercase/original] -highlight [word1,word2,...] -hide-unspoken [true/false]"
);
process.exit(1);
}
if (!outputDir) {
// Default output directory
const jsonBaseName = path.basename(jsonFile, path.extname(jsonFile));
outputDir = `${jsonBaseName}_frames`;
}
// Create output directory if it doesn't exist
try {
mkdirp.sync(outputDir);
} catch (error) {
console.error(`Error creating output directory: ${error.message}`);
process.exit(1);
}
// Try to register Arial font - adjust path as needed for your system
try {
// Different font paths for different operating systems
if (process.platform === "win32") {
registerFont("C:\\Windows\\Fonts\\arial.ttf", { family: "Arial" });
registerFont("C:\\Windows\\Fonts\\arialbd.ttf", {
family: "Arial",
weight: "bold",
});
registerFont("A:\\Procaci-Amamenta\\OUTPUT\\Reels\\Metropolis-Bold.ttf", {
family: "Metropolis",
weight: "bold",
});
} else if (process.platform === "darwin") {
registerFont("/Library/Fonts/Arial.ttf", { family: "Arial" });
registerFont("/Library/Fonts/Arial Bold.ttf", {
family: "Arial",
weight: "bold",
});
} else {
registerFont("/usr/share/fonts/truetype/msttcorefonts/Arial.ttf", {
family: "Arial",
});
registerFont("/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf", {
family: "Arial",
weight: "bold",
});
}
} catch (error) {
console.warn(`Warning: Could not register Arial font: ${error.message}`);
console.warn("Using system default font instead");
}
// Read the JSON file
let captionsData;
try {
const jsonContent = fs.readFileSync(jsonFile, "utf8");
captionsData = JSON.parse(jsonContent);
} catch (error) {
console.error(`Error reading JSON file: ${error.message}`);
process.exit(1);
}
// Calculate end time if duration is specified
const endTime =
duration > 0
? startTime + duration
: Math.max(...captionsData.captions.map((caption) => caption.end));
// Calculate total number of frames
const totalFrames = Math.ceil((endTime - startTime) * FPS);
// Initialize cross-run caching
const cacheFile = path.join(outputDir, ".cache.json");
let oldCache = {};
try {
oldCache = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
} catch (err) {
// No existing cache
}
const newCache = { totalFrames, mapping: {} };
console.log(
`Generating ${totalFrames} frames at ${FPS}fps from ${startTime}s to ${endTime}s`
);
// Function to format text based on options
function formatText(text, forceUpperCase = false) {
let formatted = text;
// Remove periods if enabled
if (removePeriods) {
formatted = formatted.replace(/\./g, "");
}
// Apply case formatting
if (forceUpperCase) {
formatted = formatted.toUpperCase();
} else if (textCase === "lowercase") {
formatted = formatted.toLowerCase();
} else if (textCase === "uppercase") {
formatted = formatted.toUpperCase();
}
return formatted;
}
// Function to check if a word should be highlighted (now checks word object or falls back to the list)
function shouldHighlight(wordText, wordObj) {
// First check if the word object has a highlighted property
if (wordObj && wordObj.highlighted === true) {
return true;
}
// Fall back to the command-line provided list for backward compatibility
const normalizedWord = wordText.toLowerCase().trim();
return highlightWords.includes(normalizedWord);
}
// New function to determine word formatting and color state
function getWordState(word, time) {
// Clean up the word text
const wordTextRaw = word.word.replace(/^\s+/, "");
// Basic states
const isActive = time >= word.start && time <= word.end;
const hasBeenSpoken = time >= word.start;
// Check if this is a single digit (0-9)
const isSingleDigit =
/^\s*\d\s*$/.test(wordTextRaw) || /^\s*\d[,\.]\s*$/.test(wordTextRaw);
// Whether this word should be highlighted (based on JSON or highlight list)
const isMarkedForHighlight = shouldHighlight(wordTextRaw, word);
// Whether to apply highlight color (only if highlighted AND spoken)
const shouldApplyHighlightColor = hasBeenSpoken && isMarkedForHighlight;
// Always uppercase highlighted words regardless of spoken state
const shouldBeUppercase = isMarkedForHighlight;
// Format the base text (without uppercase yet)
const baseText = formatText(wordTextRaw, false);
// Apply uppercase if needed
const finalText = shouldBeUppercase ? baseText.toUpperCase() : baseText;
return {
isActive,
hasBeenSpoken,
shouldApplyHighlightColor,
shouldBeUppercase,
baseText,
finalText,
isSingleDigit,
};
}
// Function to get the active caption for a given time
function getActiveCaptionAt(time) {
return captionsData.captions.find(
(caption) => time >= caption.start && time <= caption.end
);
}
// Function to get active words for a caption at a specific time
function getActiveWordsAt(caption, time) {
if (!caption || !caption.words || caption.words.length === 0) {
return { active: caption ? formatText(caption.text) : "", inactive: "" };
}
// First pass: find all the line breaks to create proper line segments
const lineBreakIndices = [];
caption.words.forEach((word, index) => {
if (word.lineBreak) {
lineBreakIndices.push(index);
}
});
// Create line segments
const lineSegments = [];
let startIdx = 0;
// Handle line breaks
for (const breakIdx of lineBreakIndices) {
lineSegments.push(caption.words.slice(startIdx, breakIdx + 1));
startIdx = breakIdx + 1;
}
// Add the last segment if any words remain
if (startIdx < caption.words.length) {
lineSegments.push(caption.words.slice(startIdx));
}
// If no line breaks, just use all words as one segment
if (lineSegments.length === 0) {
lineSegments.push(caption.words);
}
// Now process each segment to build text parts
let activeText = "";
let inactiveText = "";
let foundDivider = false;
for (const segment of lineSegments) {
let segmentActive = "";
let segmentInactive = "";
for (const word of segment) {
const wordTextRaw = word.word.replace(/^\s+/, "");
const isHighlighted = shouldHighlight(wordTextRaw, word);
// Note: we're not applying forceUpperCase here as we'll handle it in the drawing code
const wordText = formatText(wordTextRaw, false);
if (!wordText) continue;
if (time >= word.start && time <= word.end) {
// Word is active
if (segmentActive) segmentActive += " ";
segmentActive += wordText;
foundDivider = true;
} else if (time < word.start) {
// Word has not been reached yet
if (segmentInactive) segmentInactive += " ";
segmentInactive += wordText;
} else {
// Word has already been spoken
if (segmentActive) segmentActive += " ";
segmentActive += wordText;
}
}
// Add a newline between segments if this isn't the first segment
if (activeText && segmentActive) {
activeText += "\n";
}
if (inactiveText && segmentInactive) {
inactiveText += "\n";
}
// Add this segment's text
activeText += segmentActive;
inactiveText += segmentInactive;
}
// If no divider found (all words active or inactive), use the entire caption
if (!foundDivider) {
if (time < caption.start) {
// Before caption starts
return { active: "", inactive: formatText(caption.text.trim()) };
} else {
// After caption ends
return { active: formatText(caption.text.trim()), inactive: "" };
}
}
return { active: activeText, inactive: inactiveText };
}
// Helper function to draw a rounded rectangle
function drawRoundedRect(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
ctx.fill();
}
// Function to draw caption text on canvas
function drawCaption(ctx, caption, time) {
if (!caption) return;
// Set font for measurement
ctx.font = `bold ${FONT_SIZE}px Metropolis`;
// Generate text lines and their constituent words
let linesInfo = []; // Array of { text: string, words: WordObject[] }
if (caption.words && caption.words.length > 0) {
const hasLineBreakWords = caption.words.some((word) => word.lineBreak);
if (hasLineBreakWords) {
// Use lineBreak property from words to generate lines
let currentLineText = "";
let currentLineWords = [];
for (let i = 0; i < caption.words.length; i++) {
const word = caption.words[i];
// Use getWordState to get consistently formatted text for line construction
// Pass a dummy time or handle formatting directly if getWordState is too heavy here
const wordState = getWordState(word, time); // Get finalText for line construction
const wordText = wordState.baseText; // Use baseText to match formatText's behavior without forced case
if (currentLineText) currentLineText += " ";
currentLineText += wordText;
currentLineWords.push(word);
if (word.lineBreak || i === caption.words.length - 1) {
linesInfo.push({ text: currentLineText, words: currentLineWords });
currentLineText = "";
currentLineWords = [];
}
}
} else {
// No explicit lineBreak properties. Use caption.text.split('\n') and map words.
const textLinesFromCaptionText = caption.text.split("\n");
let currentGlobalWordIndex = 0;
for (const rawTextLine of textLinesFromCaptionText) {
const formattedTextLineTarget = formatText(rawTextLine.trim());
let wordsForThisLine = [];
let reconstructedFormattedLine = "";
// Keep track of words forming the current reconstructed line
let tempWordsForLine = [];
let tempReconstructed = "";
let lastSuccessfulWordIndex = currentGlobalWordIndex;
for (let i = currentGlobalWordIndex; i < caption.words.length; i++) {
const wordObj = caption.words[i];
// Match formatting used for formattedTextLineTarget
const wordState = getWordState(wordObj, time); // Get baseText for matching
const formattedWord = wordState.baseText;
const potentialNewLine = tempReconstructed
? tempReconstructed + " " + formattedWord
: formattedWord;
if (formattedTextLineTarget.startsWith(potentialNewLine)) {
tempReconstructed = potentialNewLine;
tempWordsForLine.push(wordObj);
lastSuccessfulWordIndex = i + 1; // Next word to try
if (tempReconstructed === formattedTextLineTarget) {
break; // Exact match for the line
}
} else {
// This word makes it no longer a prefix, so stop for this line
break;
}
}
// Only accept the match if it's substantial or exact
if (
tempReconstructed === formattedTextLineTarget ||
(tempWordsForLine.length > 0 &&
formattedTextLineTarget.startsWith(tempReconstructed))
) {
wordsForThisLine = tempWordsForLine;
reconstructedFormattedLine = tempReconstructed;
currentGlobalWordIndex = lastSuccessfulWordIndex;
}
// If no words could be matched to a non-empty text line, wordsForThisLine will be empty.
// This ensures that even if word mapping is imperfect, the text from caption.text is preserved.
linesInfo.push({
text: formattedTextLineTarget,
words: wordsForThisLine,
});
}
}
} else {
// Fallback to original text if no words are present at all
linesInfo = caption.text
.split("\n")
.map((line) => ({ text: formatText(line.trim()), words: [] }));
}
if (linesInfo.length === 0) return; // Nothing to draw
// Calculate maximum line width with extra buffer for safety
let maxLineWidth = 0;
// First measure each line's full text width (using the text part of linesInfo)
for (const lineInfo of linesInfo) {
const lineWidth = ctx.measureText(lineInfo.text).width;
maxLineWidth = Math.max(maxLineWidth, lineWidth);
}
// Then check if we have words to measure for more accurate width
// This part accounts for specific word styling like highlighting causing width changes
for (const lineInfo of linesInfo) {
if (lineInfo.words && lineInfo.words.length > 0) {
let currentLineMeasuredWidth = 0;
for (const word of lineInfo.words) {
const wordState = getWordState(word, time);
if (!wordState.finalText) continue;
currentLineMeasuredWidth += ctx.measureText(
wordState.finalText + " "
).width;
}
if (lineInfo.words.length > 0) {
currentLineMeasuredWidth -= ctx.measureText(" ").width; // Remove last space
}
maxLineWidth = Math.max(maxLineWidth, currentLineMeasuredWidth);
}
}
// Add extra safety margin
maxLineWidth += 30;
// Account for shadow offset in background width
const shadowMargin =
Math.max(ACTIVE_SHADOW_OFFSET_X, ACTIVE_SHADOW_OFFSET_Y) * 2 +
ACTIVE_SHADOW_BLUR;
// Calculate background dimensions with padding
let bgWidth = maxLineWidth + PADDING_X * 2 + shadowMargin;
// Limit the width to 90% of canvas width for very long lines
const maxAllowedWidth = WIDTH * 0.9;
if (bgWidth > maxAllowedWidth) {
bgWidth = maxAllowedWidth;
}
const bgHeight =
linesInfo.length * LINE_HEIGHT + PADDING_Y * 2 + shadowMargin;
// Center the background on the canvas
const bgX = (WIDTH - bgWidth) / 2;
const bgY = (HEIGHT - bgHeight) / 2;
// Draw background rectangle with rounded corners
ctx.fillStyle = BG_COLOR;
drawRoundedRect(ctx, bgX, bgY, bgWidth, bgHeight, BORDER_RADIUS);
// Set text properties
ctx.textAlign = "center";
ctx.textBaseline = "middle";
// Calculate starting Y position for text
const startY = bgY + PADDING_Y + LINE_HEIGHT / 2;
// Draw each line
for (let i = 0; i < linesInfo.length; i++) {
const y = startY + i * LINE_HEIGHT;
const currentLine = linesInfo[i];
const wordsOfThisLine = currentLine.words;
// If we have word timing for this specific line
if (wordsOfThisLine && wordsOfThisLine.length > 0) {
// Reset text alignment to left for word-by-word rendering
ctx.textAlign = "left";
// Calculate the width of all words for precise centering
let totalWidth = 0;
for (const word of wordsOfThisLine) {
const wordState = getWordState(word, time);
if (!wordState.finalText) continue;
totalWidth += ctx.measureText(wordState.finalText + " ").width;
}
if (wordsOfThisLine.length > 0) {
totalWidth -= ctx.measureText(" ").width; // Remove last space
}
// If total width exceeds the bgWidth, scale down the start position
const scaleFactor = Math.min(1, (bgWidth - PADDING_X * 2) / totalWidth);
// totalWidth *= scaleFactor; // Apply scale factor to totalWidth if fitting, or let words overflow and clip
// Center-align the text block
const startXText = bgX + (bgWidth - totalWidth * scaleFactor) / 2;
let currentX = startXText;
// Process each word separately
for (const word of wordsOfThisLine) {
const wordState = getWordState(word, time);
if (!wordState.finalText) continue;
// Apply appropriate shadow effect based on active state
if (wordState.isActive) {
ctx.shadowColor = SHADOW_COLOR;
ctx.shadowBlur = ACTIVE_SHADOW_BLUR;
ctx.shadowOffsetX = ACTIVE_SHADOW_OFFSET_X;
ctx.shadowOffsetY = ACTIVE_SHADOW_OFFSET_Y;
} else {
ctx.shadowColor = SHADOW_COLOR;
ctx.shadowBlur = INACTIVE_SHADOW_BLUR;
ctx.shadowOffsetX = INACTIVE_SHADOW_OFFSET_X;
ctx.shadowOffsetY = INACTIVE_SHADOW_OFFSET_Y;
}
ctx.save();
if (hideUnspoken && !wordState.hasBeenSpoken) {
ctx.globalAlpha = UNSPOKEN_OPACITY;
}
if (wordState.shouldApplyHighlightColor) {
ctx.fillStyle = HIGHLIGHT_COLOR;
} else if (wordState.isSingleDigit && wordState.hasBeenSpoken) {
ctx.fillStyle = ACTIVE_COLOR;
// ctx.font = `bold ${FONT_SIZE}px Metropolis`; // Font is already set globally for words
} else {
ctx.fillStyle = wordState.isActive ? ACTIVE_COLOR : INACTIVE_COLOR;
}
ctx.font = `bold ${FONT_SIZE}px Metropolis`; // Ensure font is set before fillText
ctx.fillText(wordState.finalText, currentX, y);
ctx.restore();
currentX +=
ctx.measureText(wordState.finalText + " ").width * scaleFactor;
}
ctx.shadowColor = "transparent";
ctx.shadowBlur = 0;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.textAlign = "center";
} else {
// No word timing for this specific line, or words array was empty for this line.
// Render the full line text based on overall caption timing or simple active state.
const lineTextToRender = currentLine.text;
let lineIsActive = false;
// Determine if line is active (simplistic: if any part of caption is active, or based on time)
// This fallback needs to be considered carefully if caption object has start/end but line doesn't
if (time >= caption.start && time <= caption.end) {
// Default to caption's overall activity
lineIsActive = true;
}
// A more refined approach might try to estimate line start/end if words were totally missing.
// For now, this is a basic fallback.
if (hideUnspoken && !lineIsActive && time < caption.start) {
// Assuming caption.start if line-specific timing is unknown
ctx.save();
ctx.globalAlpha = UNSPOKEN_OPACITY;
}
ctx.fillStyle = lineIsActive ? ACTIVE_COLOR : INACTIVE_COLOR;
ctx.font = `bold ${FONT_SIZE}px Metropolis`;
ctx.textAlign = "center";
if (lineIsActive) {
ctx.shadowColor = SHADOW_COLOR;
ctx.shadowBlur = ACTIVE_SHADOW_BLUR;
ctx.shadowOffsetX = ACTIVE_SHADOW_OFFSET_X;
ctx.shadowOffsetY = ACTIVE_SHADOW_OFFSET_Y;
} else {
ctx.shadowColor = SHADOW_COLOR;
ctx.shadowBlur = INACTIVE_SHADOW_BLUR;
ctx.shadowOffsetX = INACTIVE_SHADOW_OFFSET_X;
ctx.shadowOffsetY = INACTIVE_SHADOW_OFFSET_Y;
}
ctx.fillText(lineTextToRender, bgX + bgWidth / 2, y);
if (hideUnspoken && !lineIsActive && time < caption.start) {
ctx.restore();
}
ctx.shadowColor = "transparent";
ctx.shadowBlur = 0;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
}
}
}
// Function to get a signature representing the frame content
function getFrameSignature(caption, time) {
if (!caption) return "empty";
let signature = `caption-${caption.index}-`;
// Add active words to signature
if (caption.words && caption.words.length > 0) {
const activeWords = caption.words
.filter((word) => time >= word.start && time <= word.end)
.map((word) => `${word.word.trim()}-${word.start}-${word.end}`)
.join("|");
signature += activeWords || "no-active-words";
// Add hide-unspoken state to signature if enabled
if (hideUnspoken) {
signature += `-hide-unspoken-${caption.words
.filter((word) => time >= word.start)
.map((word) => word.word.trim())
.join(".")}`;
}
} else {
// For captions without word-level timing, check if whole caption is active
signature +=
time >= caption.start && time <= caption.end ? "active" : "inactive";
}
return signature;
}
// Compute MD5 hash of a caption for caching comparisons
function getCaptionHash(caption) {
return crypto.createHash("md5").update(JSON.stringify(caption)).digest("hex");
}
// Process each frame
console.log("Generating frames...");
// Create a canvas to draw on
const canvas = createCanvas(WIDTH, HEIGHT);
const ctx = canvas.getContext("2d");
// Frame optimization variables
let lastFrameSignature = null;
let lastFramePath = null;
let duplicateFrames = 0;
for (let frame = 0; frame < totalFrames; frame++) {
const currentTime = startTime + frame / FPS;
// Get active caption for this frame
const activeCaption = getActiveCaptionAt(currentTime);
// Get a signature for the current frame
const currentSignature = getFrameSignature(activeCaption, currentTime);
// Determine output path for this frame
const outputPath = path.join(
outputDir,
`frame_${String(frame).padStart(6, "0")}.png`
);
// Cross-run cache: skip rendering if frame unchanged
const captionHash = activeCaption ? getCaptionHash(activeCaption) : "empty";
const combinedSignature = `${captionHash}-${currentSignature}`;
newCache.mapping[frame] = combinedSignature;
if (
oldCache.mapping &&
oldCache.mapping[frame] === combinedSignature &&
fs.existsSync(outputPath)
) {
console.log(
`Skipping unchanged frame ${frame + 1}/${totalFrames} (${(
(frame / totalFrames) *
100
).toFixed(1)}%) - Time: ${currentTime.toFixed(2)}s`
);
continue;
}
// Check if this frame is identical to the previous one
if (currentSignature === lastFrameSignature && lastFramePath) {
// Copy the previous frame instead of re-rendering
fs.copyFileSync(lastFramePath, outputPath);
duplicateFrames++;
// We still want to show progress
if (frame % 30 === 0) {
console.log(
`Copying identical frame ${frame + 1}/${totalFrames} (${(
(frame / totalFrames) *
100
).toFixed(1)}%) - Time: ${currentTime.toFixed(2)}s`
);
}
} else {
// This is a new unique frame, render it
console.log(
`Rendering frame ${frame + 1}/${totalFrames} (${(
(frame / totalFrames) *
100
).toFixed(1)}%) - Time: ${currentTime.toFixed(2)}s`
);
// Clear the canvas
ctx.fillStyle = "rgba(0, 0, 0, 0)";
ctx.clearRect(0, 0, WIDTH, HEIGHT);
// Draw the caption
drawCaption(ctx, activeCaption, currentTime);
// Save the frame as PNG
const buffer = canvas.toBuffer("image/png");
fs.writeFileSync(outputPath, buffer);
// Update last frame information
lastFrameSignature = currentSignature;
lastFramePath = outputPath;
}
}
// Calculate optimization statistics
const uniqueFrames = totalFrames - duplicateFrames;
const optimizationPercent = ((duplicateFrames / totalFrames) * 100).toFixed(1);
console.log(`\nDone! Generated ${totalFrames} frames in ${outputDir}`);
console.log(
`Optimization: ${duplicateFrames} duplicate frames skipped (${optimizationPercent}% of total)`
);
console.log(`Only ${uniqueFrames} unique frames were actually rendered`);
console.log(
`\nYou can convert these to video with ffmpeg using one of these commands:`
);
console.log(`\nFor transparent MOV with ProRes 4444 (supports alpha channel):`);
console.log(
`ffmpeg -framerate ${FPS} -i ${outputDir}/frame_%06d.png -c:v prores_ks -profile:v 4444 -alpha_bits 16 -pix_fmt yuva444p10le output.mov`
);
console.log(
`\nFor transparent MOV with PNG compression (lossless with alpha):`
);
console.log(
`ffmpeg -framerate ${FPS} -i ${outputDir}/frame_%06d.png -c:v png -pix_fmt rgba output.mov`
);
console.log(`\nFor regular MP4 (no transparency, smaller file):`);
console.log(
`ffmpeg -framerate ${FPS} -i ${outputDir}/frame_%06d.png -c:v libx264 -pix_fmt yuv420p output.mp4`
);
// After processing frames, update cache file
try {
fs.writeFileSync(cacheFile, JSON.stringify(newCache, null, 2));
console.log(`Cache updated at ${cacheFile}`);
} catch (err) {
console.warn(`Warning: Could not write cache file: ${err.message}`);
}