Skip to content

Open source CapCut alternative.

TypeScript

feat(site): write captions as an SRT file

David Lef3aa5020a054
diff --git a/site/src/cut/lib/download.ts b/site/src/cut/lib/download.ts
index 1c8d9c29..f2d5d711 100644
--- a/site/src/cut/lib/download.ts
+++ b/site/src/cut/lib/download.ts
@@ -18,3 +18,17 @@ export function downloadFromUrl(url: string, name: string) {
a.click();
a.remove();
}
+
+/** Save text made in this tab — a captions file — to the user's Downloads
+ * folder. The blob is same-origin, so the anchor's own name is honored. */
+export function downloadText(text: string, name: string, type = "text/plain") {
+ const url = URL.createObjectURL(new Blob([text], { type }));
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = name;
+ a.rel = "noopener";
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 10_000);
+}
diff --git a/site/src/cut/lib/subtitleFile.test.ts b/site/src/cut/lib/subtitleFile.test.ts
new file mode 100644
index 00000000..3378c89c
--- /dev/null
+++ b/site/src/cut/lib/subtitleFile.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, test } from "bun:test";
+import { srtOf, subtitleFiles } from "./subtitleFile";
+import type { SubtitleCue, SubtitlesBlock } from "./types";
+
+const cue = (id: string, start: number, end: number, text: string, lane?: number): SubtitleCue => ({
+ id,
+ start,
+ end,
+ text,
+ ...(lane !== undefined ? { lane } : {}),
+});
+
+const block = (cues: SubtitleCue[], over: Partial<SubtitlesBlock> = {}): SubtitlesBlock =>
+ ({ cues, showOnVideo: true, showOnTimeline: true, ...over }) as SubtitlesBlock;
+
+describe("srtOf", () => {
+ test("numbers cues in time order with comma milliseconds", () => {
+ const srt = srtOf([cue("b", 61.5, 63.25, "second"), cue("a", 0, 1.2, "first")]);
+ expect(srt).toBe(
+ ["1", "00:00:00,000 --> 00:00:01,200", "first", "", "2", "00:01:01,500 --> 00:01:03,250", "second", ""].join("\n")
+ );
+ });
+
+ test("a range keeps the cues inside it, timed from its start, cut at its edges", () => {
+ const srt = srtOf(
+ [cue("a", 0, 2, "before"), cue("b", 4, 7, "across"), cue("c", 8, 9, "inside"), cue("d", 12, 13, "after")],
+ { start: 5, end: 10 }
+ );
+ expect(srt).toBe(
+ ["1", "00:00:00,000 --> 00:00:02,000", "across", "", "2", "00:00:03,000 --> 00:00:04,000", "inside", ""].join("\n")
+ );
+ });
+
+ test("skips empty text", () => {
+ expect(srtOf([cue("a", 0, 1, " ")])).toBe("");
+ });
+});
+
+describe("subtitleFiles", () => {
+ test("one file per visible track, named by language when there are several", () => {
+ const subs = block(
+ [cue("a", 0, 1, "hi", 0), cue("b", 0, 1, "안녕", 1), cue("c", 0, 1, "hola", 2)],
+ { tracks: [{ locale: "en-US" }, { locale: "ko-KR" }, { locale: "es-ES", hidden: true }] }
+ );
+ expect(subtitleFiles(subs, "Cut").map((f) => f.name)).toEqual(["Cut.en-US.srt", "Cut.ko-KR.srt"]);
+ });
+
+ test("a single track takes the plain name", () => {
+ expect(subtitleFiles(block([cue("a", 0, 1, "hi")]), "Cut").map((f) => f.name)).toEqual(["Cut.srt"]);
+ });
+
+ test("nothing to write is no file", () => {
+ expect(subtitleFiles(block([cue("a", 0, 1, "hi")]), "Cut", { start: 5, end: 6 })).toEqual([]);
+ });
+});
diff --git a/site/src/cut/lib/subtitleFile.ts b/site/src/cut/lib/subtitleFile.ts
new file mode 100644
index 00000000..365a7c3c
--- /dev/null
+++ b/site/src/cut/lib/subtitleFile.ts
@@ -0,0 +1,59 @@
+import type { ExportRange } from "./exportDelivery";
+import { laneCues, laneHidden, subtitleLaneCount, trackLocale } from "./subtitles";
+import type { SubtitleCue, SubtitlesBlock } from "./types";
+
+// Captions as a file of their own, for the platforms that take one beside
+// the video. SRT is the one they all read: numbered cues, a time span with a
+// comma before the milliseconds, the text, a blank line.
+
+/** `01:02:03,450` for 3723.45 seconds. */
+function srtTime(t: number): string {
+ const ms = Math.max(0, Math.round(t * 1000));
+ const h = Math.floor(ms / 3_600_000);
+ const m = Math.floor((ms % 3_600_000) / 60_000);
+ const s = Math.floor((ms % 60_000) / 1000);
+ const frac = ms % 1000;
+ const two = (n: number) => String(n).padStart(2, "0");
+ return `${two(h)}:${two(m)}:${two(s)},${String(frac).padStart(3, "0")}`;
+}
+
+/**
+ * One track's cues as SRT text. With a range, only the cues inside it, timed
+ * from the range's start, so the file lines up with a range export. A cue
+ * that crosses an edge is cut at it.
+ */
+export function srtOf(cues: SubtitleCue[], range?: ExportRange): string {
+ const from = range ? Math.max(0, range.start) : 0;
+ const to = range ? range.end : Infinity;
+ const lines: string[] = [];
+ let n = 0;
+ for (const c of [...cues].sort((a, b) => a.start - b.start)) {
+ const start = Math.max(c.start, from);
+ const end = Math.min(c.end, to);
+ const text = c.text.trim();
+ if (!(end > start) || !text) continue;
+ n++;
+ lines.push(String(n), `${srtTime(start - from)} --> ${srtTime(end - from)}`, text, "");
+ }
+ return lines.join("\n");
+}
+
+/** A caption file for each track the export burns in: its name carries the
+ * track's language when the project has more than one. Empty when nothing
+ * would be written. */
+export function subtitleFiles(
+ subs: SubtitlesBlock,
+ baseName: string,
+ range?: ExportRange
+): { name: string; text: string }[] {
+ const files: { name: string; text: string }[] = [];
+ const lanes = subtitleLaneCount(subs);
+ for (let lane = 0; lane < lanes; lane++) {
+ if (laneHidden(subs, lane)) continue;
+ const text = srtOf(laneCues(subs, lane), range);
+ if (!text) continue;
+ const suffix = lanes > 1 ? `.${trackLocale(subs, lane)}` : "";
+ files.push({ name: `${baseName}${suffix}.srt`, text });
+ }
+ return files;
+}