Skip to content

🎥 Make videos programmatically with React

@remotion/captions: Fix parseSrt CRLF and pre-cue handling

copilot-swe-agent[bot]555f8db60c98
diff --git a/packages/captions/src/parse-srt.ts b/packages/captions/src/parse-srt.ts
index b9badf3100..31066b7e67 100644
--- a/packages/captions/src/parse-srt.ts
+++ b/packages/captions/src/parse-srt.ts
@@ -14,7 +14,7 @@ function toSeconds(time: string) {
throw new Error(`Invalid timestamp:${time}`);
}
- const [seconds, millis] = third.split(',');
+ const [seconds, millis] = third.trim().split(/[,.]/);
if (!seconds) {
throw new Error(`Invalid timestamp:${time}`);
}
@@ -40,16 +40,20 @@ export type ParseSrtOutput = {
};
export const parseSrt = ({input}: ParseSrtInput): ParseSrtOutput => {
- const inputLines = input.split('\n');
+ const inputLines = input
+ .replace(/^\uFEFF/, '')
+ .replace(/\r\n/g, '\n')
+ .replace(/\r/g, '\n')
+ .split('\n');
const captions: Caption[] = [];
for (let i = 0; i < inputLines.length; i++) {
const line = inputLines[i];
const nextLine = inputLines[i + 1];
- if (line?.match(/([0-9]+)/) && nextLine?.includes(' --> ')) {
+ if (line?.match(/^\s*\d+\s*$/) && nextLine?.includes(' --> ')) {
const nextLineSplit = nextLine.split(' --> ');
- const start = toSeconds(nextLineSplit[0] as string);
- const end = toSeconds(nextLineSplit[1] as string);
+ const start = toSeconds((nextLineSplit[0] as string).trim());
+ const end = toSeconds((nextLineSplit[1] as string).trim());
captions.push({
text: '',
startMs: start * 1000,
@@ -60,10 +64,12 @@ export const parseSrt = ({input}: ParseSrtInput): ParseSrtOutput => {
} else if (line?.includes(' --> ')) {
continue;
} else if (line?.trim() === '') {
- (captions[captions.length - 1] as Caption).text = (
- captions[captions.length - 1] as Caption
- ).text.trim();
- } else {
+ if (captions.length > 0) {
+ (captions[captions.length - 1] as Caption).text = (
+ captions[captions.length - 1] as Caption
+ ).text.trim();
+ }
+ } else if (captions.length > 0) {
(captions[captions.length - 1] as Caption).text += line + '\n';
}
}
diff --git a/packages/captions/src/test/srt.test.ts b/packages/captions/src/test/srt.test.ts
index ac1db60338..7754a5b844 100644
--- a/packages/captions/src/test/srt.test.ts
+++ b/packages/captions/src/test/srt.test.ts
@@ -74,3 +74,18 @@ test('Should start a new SRT cue after a forced page break', () => {
'1\n00:00:00,000 --> 00:00:00,500\nFirst line\n\n2\n00:00:00,500 --> 00:00:01,000\nSecond line',
);
});
+
+test('Should parse CRLF and dot timestamps with leading blank lines', () => {
+ const srt = '\r\n \r\n1\r\n00:00:00.000 --> 00:00:01.500\r\nHello\r\n';
+ const {captions} = parseSrt({input: srt});
+
+ expect(captions).toEqual([
+ {
+ confidence: 1,
+ endMs: 1500,
+ startMs: 0,
+ text: 'Hello',
+ timestampMs: 750,
+ },
+ ]);
+});