diff --git a/docs/DATADOG.md b/docs/DATADOG.md index 13b4e4acd..358f9e7a0 100644 --- a/docs/DATADOG.md +++ b/docs/DATADOG.md @@ -153,11 +153,11 @@ format, stall reason. **Feature usage** (`feature_used`, `src/lib/featureTelemetry.ts`). One event per editing tool an export uses (`action: exported`): trim, rotate, speed, -mute, volume, normalize_audio, text_overlay, image_overlay, background_music, +mute, volume, normalize_audio, text_overlay, timed_text, image_overlay, background_music, color_adjustments, sharpen, denoise, stabilization, fill_framing, custom_size, crop. Interactive features: `history` (undo, redo), `project_file` (save, open), `preview_tool` (compare, grid, framing_guide, save_frame), -`safe_area`, `export_profile`, `trim_timeline` (seek, drag_handle), `crop_tool` (aspect, drag, reset), `batch_export` (start, done, done_with_failures, cancel, save_folder). Only these names are ever sent; never values, +`safe_area`, `export_profile`, `trim_timeline` (seek, drag_handle), `crop_tool` (aspect, drag, reset), `batch_export` (start, done, done_with_failures, cancel, save_folder), `text_tool` (import_captions, set_timing, caption_box). Only these names are ever sent; never values, names or text. **Synthetic check.** A Datadog Synthetic browser test opens production every diff --git a/docs/USAGE.md b/docs/USAGE.md index b00b3b0a5..6d5720ede 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -42,6 +42,23 @@ the trim are dimmed. Click the strip to move the preview there, and drag the handles (or use the arrow keys on them) to set the start and end. While an export runs, making frames pauses and carries on afterwards. +## Text and captions + +**Add Text** in the Text section puts a line of text on the video. Drag it +in the preview to place it; the preview shows it where, and at the size, +the export will draw it. By default text stays on for the whole video. To +show it for part of it, set **From** and **Until** in seconds of the video, +or play to a moment and press **Start at playhead** or **End at playhead**. +**Whole video** clears the times. Times follow the source video, so they +stay right when you trim or change the speed, and text outside the trim is +left out. **Dark box behind the text** gives it a caption-style background. + +**Import captions** reads an `.srt` or `.vtt` subtitle file and adds each +cue as a timed caption near the bottom of the frame, sized for the output. +An edit holds up to 500 text items; a longer file adds its first 500 cues. +**Remove all** clears them. Exported text uses the bundled Geist font +whatever font the preview shows. + ## Batch export **Batch export** in the Edit panel applies this edit to other videos. Add diff --git a/src/components/DraggableTextOverlays.tsx b/src/components/DraggableTextOverlays.tsx index 9a612ee2f..47c49663b 100644 --- a/src/components/DraggableTextOverlays.tsx +++ b/src/components/DraggableTextOverlays.tsx @@ -1,14 +1,18 @@ "use client"; import { TextOverlay, EditRecipe } from "@/lib/types"; -import { useRef, useState, useCallback, useEffect, useMemo } from "react"; -import { getTextPixelPosition, getTextPercentPosition } from "@/lib/text-overlay"; +import { useRef, useState, useCallback, useEffect, useMemo, type RefObject } from "react"; +import { getTextPixelPosition, getTextPercentPosition, isTextVisibleAt } from "@/lib/text-overlay"; import { getFontFamily, ensureFontLoaded } from "@/utils/fontLoader"; interface DraggableTextOverlaysProps { recipe?: EditRecipe; containerWidth: number; containerHeight: number; + /** Preview pixels per output pixel, so text is the size it will be in the export. */ + scale?: number; + /** The preview video, to show timed text only while it is on. */ + videoRef?: RefObject; selectedTextId: string | null; onUpdateText: (id: string, updates: Partial) => void; onSelectText: (id: string | null) => void; @@ -22,6 +26,8 @@ export default function DraggableTextOverlays({ recipe, containerWidth, containerHeight, + scale = 1, + videoRef, selectedTextId, onUpdateText, onSelectText, @@ -43,6 +49,50 @@ export default function DraggableTextOverlays({ return Array.isArray(overlays) ? overlays : []; }, [recipe?.textOverlays]); + // The preview's playhead, followed only while some text is timed. + const [currentTime, setCurrentTime] = useState(0); + const hasTimedText = textOverlays.some((o) => o.start !== undefined || o.end !== undefined); + useEffect(() => { + const video = videoRef?.current; + if (!video || !hasTimedText) return; + let frame = 0; + // Re-render only when which text is on changes, not on every frame. + let shown = ""; + const update = () => { + const t = video.currentTime; + const next = textOverlays.map((o) => (isTextVisibleAt(o, t) ? "1" : "0")).join(""); + if (next === shown) return; + shown = next; + setCurrentTime(t); + }; + // timeupdate fires only about 4 times a second; follow frames while playing. + const tick = () => { + update(); + frame = requestAnimationFrame(tick); + }; + const play = () => { + cancelAnimationFrame(frame); + frame = requestAnimationFrame(tick); + }; + const stop = () => { + cancelAnimationFrame(frame); + update(); + }; + update(); + if (!video.paused) play(); + video.addEventListener("play", play); + video.addEventListener("pause", stop); + video.addEventListener("seeked", update); + video.addEventListener("timeupdate", update); + return () => { + cancelAnimationFrame(frame); + video.removeEventListener("play", play); + video.removeEventListener("pause", stop); + video.removeEventListener("seeked", update); + video.removeEventListener("timeupdate", update); + }; + }, [videoRef, hasTimedText, textOverlays]); + /** * Handles the start of a drag operation. */ @@ -229,6 +279,10 @@ export default function DraggableTextOverlays({ const isSelected = selectedTextId === overlay.id; const isDragging = draggingId === overlay.id; + // Text outside its time is hidden, except the one being edited, which stays faint. + const visible = !hasTimedText || isTextVisibleAt(overlay, currentTime); + if (!visible && !isSelected) return null; + const fontSize = overlay.fontSize * scale; return (
@@ -283,7 +344,7 @@ export default function DraggableTextOverlays({ className="outline-none bg-black/30 px-1 py-0.5 rounded" style={{ color: overlay.color, - fontSize: `${overlay.fontSize}px`, + fontSize: `${fontSize}px`, fontFamily: getFontFamily(overlay.fontFamily), fontWeight: overlay.fontWeight === "900" diff --git a/src/components/TextControls.tsx b/src/components/TextControls.tsx index 8218dfb85..6b3746bee 100644 --- a/src/components/TextControls.tsx +++ b/src/components/TextControls.tsx @@ -2,8 +2,11 @@ import { EditRecipe, TextOverlay } from "@/lib/types"; import { createDefaultTextOverlay } from "@/lib/text-overlay"; -import { Trash2, Plus } from "lucide-react"; -import { useMemo } from "react"; +import { captionOverlays, MAX_CAPTION_FILE_BYTES, parseCaptions } from "@/lib/captions"; +import { MAX_TEXT_OVERLAYS } from "@/lib/project"; +import { trackFeature } from "@/lib/featureTelemetry"; +import { Trash2, Plus, Captions } from "lucide-react"; +import { useMemo, useRef, useState, type RefObject } from "react"; import FontSelector from "./FontSelector"; import ColorPicker from "./ColorPicker" import { useFontManager } from "@/hooks/useFontManager"; @@ -13,6 +16,87 @@ interface TextControlsProps { onChange: (patch: Partial) => void; selectedTextId: string | null; onSelectText: (id: string | null) => void; + /** Source length in seconds (0 when unknown), for the timing fields. */ + duration?: number; + /** The preview, for "Use playhead". */ + videoRef?: RefObject; + /** Output height in pixels, to size imported captions. */ + outputHeight?: number; +} + +const timeInputClass = + "w-full px-2 py-1.5 text-xs rounded border border-[var(--border)] bg-[var(--bg)] text-[var(--text)] placeholder-[var(--muted)] focus:outline-none focus:ring-2 focus:ring-film-500 aria-[invalid=true]:border-[var(--error)]"; + +/** "12.5" for 12.5 s; "" for none. */ +const showSeconds = (value: number | undefined) => (value === undefined ? "" : String(Number(value.toFixed(2)))); + +/** 0:12.5 */ +export function formatCueTime(seconds: number): string { + const m = Math.floor(seconds / 60); + const s = seconds - m * 60; + return `${m}:${s < 10 ? "0" : ""}${Number(s.toFixed(1))}`; +} + +/** + * A seconds field that only reports values that pass `validate`, so the edit + * never holds a start after its end. While focused it keeps what is typed. + */ +function TimeField({ + label, + shortLabel, + value, + placeholder, + validate, + onCommit, +}: { + label: string; + shortLabel: string; + value: number | undefined; + placeholder: string; + validate: (value: number | undefined) => string | null; + onCommit: (value: number | undefined) => void; +}) { + const [draft, setDraft] = useState(null); + const [error, setError] = useState(null); + const id = `text-${label.toLowerCase().replace(/\W+/g, "-")}`; + return ( +
+ + setDraft(showSeconds(value))} + onBlur={() => { + setDraft(null); + setError(null); + }} + onChange={(e) => { + const text = e.target.value; + setDraft(text); + const next = text.trim() === "" ? undefined : Number(text); + const problem = next !== undefined && (!Number.isFinite(next) || next < 0) ? "Enter a time in seconds." : validate(next); + setError(problem); + if (!problem) onCommit(next); + }} + className={timeInputClass} + /> + {error && ( +

+ {error} +

+ )} +
+ ); } /** @@ -24,8 +108,13 @@ export default function TextControls({ onChange, selectedTextId, onSelectText, + duration = 0, + videoRef, + outputHeight = 1080, }: TextControlsProps) { const { customFonts, addFonts, removeFont, getErrors } = useFontManager(); + const captionInputRef = useRef(null); + const [captionNotice, setCaptionNotice] = useState<{ tone: "info" | "error"; text: string } | null>(null); /** * Always ensures textOverlays is an array, even if recipe is malformed. @@ -63,12 +152,50 @@ export default function TextControls({ * Updates a text overlay property. */ const handleUpdateText = (id: string, updates: Partial) => { - const updatedOverlays = textOverlays.map((overlay) => - overlay.id === id ? { ...overlay, ...updates } : overlay - ); + const updatedOverlays = textOverlays.map((overlay) => { + if (overlay.id !== id) return overlay; + const next = { ...overlay, ...updates }; + // Cleared timing and box are left out, not stored as undefined. + for (const key of ["start", "end", "box"] as const) if (next[key] === undefined) delete next[key]; + return next; + }); onChange({ textOverlays: updatedOverlays }); }; + /** Adds one overlay per cue of an SRT or WebVTT file. */ + const handleImportCaptions = async (file: File) => { + if (file.size > MAX_CAPTION_FILE_BYTES) { + setCaptionNotice({ tone: "error", text: "That file is too large to be a caption file." }); + return; + } + const cues = parseCaptions(await file.text()); + if (cues.length === 0) { + setCaptionNotice({ tone: "error", text: "No captions found. Use an .srt or .vtt file." }); + return; + } + const room = MAX_TEXT_OVERLAYS - textOverlays.length; + if (room <= 0) { + setCaptionNotice({ tone: "error", text: `The edit already has ${MAX_TEXT_OVERLAYS} text items, the most it can hold.` }); + return; + } + const added = captionOverlays(cues, outputHeight, room); + onChange({ textOverlays: [...textOverlays, ...added] }); + onSelectText(null); + trackFeature("text_tool", "import_captions"); + setCaptionNotice({ + tone: "info", + text: + added.length < cues.length + ? `Added the first ${added.length} of ${cues.length} captions (an edit holds at most ${MAX_TEXT_OVERLAYS} text items).` + : `Added ${added.length} caption${added.length === 1 ? "" : "s"}.`, + }); + }; + + const playhead = () => { + const t = videoRef?.current?.currentTime; + return typeof t === "number" && Number.isFinite(t) ? Number(t.toFixed(2)) : 0; + }; + /** * Get the currently selected overlay. */ @@ -80,17 +207,61 @@ export default function TextControls({ return (
- {/* Add Text Button */} - +
+ + +
+ { + const file = e.target.files?.[0]; + e.target.value = ""; + if (file) void handleImportCaptions(file); + }} + /> + {captionNotice && ( +

+ {captionNotice.text} +

+ )} {/* Text Overlay List */} + {textOverlays.length > 1 && ( +
+ {textOverlays.length} text items + +
+ )} {textOverlays.length > 0 && (
{textOverlays.map((overlay, idx) => ( @@ -105,9 +276,14 @@ export default function TextControls({
+ + {/* When the text shows */} +
+ Shows (seconds of the video) +
+ + start !== undefined && selectedOverlay.end !== undefined && start >= selectedOverlay.end + ? "Start before the end time." + : start !== undefined && duration > 0 && start >= duration + ? "Start before the video ends." + : null + } + onCommit={(start) => { + handleUpdateText(selectedOverlay.id, { start }); + trackFeature("text_tool", "set_timing"); + }} + /> + + end !== undefined && end <= (selectedOverlay.start ?? 0) ? "End after the start time." : null + } + onCommit={(end) => { + handleUpdateText(selectedOverlay.id, { end }); + trackFeature("text_tool", "set_timing"); + }} + /> +
+
+ + + {(selectedOverlay.start !== undefined || selectedOverlay.end !== undefined) && ( + + )} +
+
+ +
)}
); } - -// help \ No newline at end of file diff --git a/src/components/VideoEditor.tsx b/src/components/VideoEditor.tsx index b719d9c37..1acad40d8 100644 --- a/src/components/VideoEditor.tsx +++ b/src/components/VideoEditor.tsx @@ -641,6 +641,9 @@ export default function VideoEditor() { onChange={updateRecipe} selectedTextId={selectedTextId} onSelectText={setSelectedTextId} + duration={duration} + videoRef={videoRef} + outputHeight={resolveOutputSize(recipe).height} /> diff --git a/src/components/VideoPreview.tsx b/src/components/VideoPreview.tsx index 7640bf850..0649c20a0 100644 --- a/src/components/VideoPreview.tsx +++ b/src/components/VideoPreview.tsx @@ -7,6 +7,7 @@ import CropOverlay from "./CropOverlay"; import type { CropRect } from "@/lib/crop"; import { outputFrame, SAFE_AREAS } from "@/lib/framing"; import { cn } from "@/lib/utils"; +import { resolveOutputSize } from "@/lib/ffmpegArgs"; import { Camera, Columns2, Grid3x3, Frame, SquareDashed } from "lucide-react"; import ComparisonPreview from "./ComparisonPreview"; import DraggableTextOverlays from "./DraggableTextOverlays"; @@ -393,17 +394,29 @@ export default function VideoPreview({ )} - {/* Draggable Text Overlays */} - {recipe && !isLoading && containerDimensions.width > 0 && ( - {})} - onUpdateText={onUpdateText || (() => {})} - /> - )} + {/* Draggable Text Overlays, placed and sized within the output frame as the export draws them */} + {recipe && frame && !isLoading && containerDimensions.width > 0 && (() => { + const inset = (v: string) => parseFloat(v) / 100; + const width = containerDimensions.width * (1 - inset(frame.left) - inset(frame.right)); + const height = containerDimensions.height * (1 - inset(frame.top) - inset(frame.bottom)); + return ( +
+ {})} + onUpdateText={onUpdateText || (() => {})} + /> +
+ ); + })()} {/* Viewer toolbar: below the picture so controls never cover the video. */} diff --git a/src/lib/captions.ts b/src/lib/captions.ts new file mode 100644 index 000000000..ef75c5104 --- /dev/null +++ b/src/lib/captions.ts @@ -0,0 +1,68 @@ +import type { TextOverlay } from "./types"; +import { generateTextOverlayId } from "./text-overlay"; +import { MAX_OVERLAY_TEXT_LENGTH, MAX_TEXT_OVERLAYS } from "./project"; + +/** One subtitle cue, in seconds of the source video. */ +export interface CaptionCue { + start: number; + end: number; + text: string; +} + +/** Caption files are small text; anything bigger is not one. */ +export const MAX_CAPTION_FILE_BYTES = 1024 * 1024; + +// 00:01:02,345 (SRT) or 00:01:02.345 / 01:02.345 (WebVTT). +const TIME = String.raw`(?:(\d{1,2}):)?(\d{1,2}):(\d{2})[,.](\d{1,3})`; +const TIMING_LINE = new RegExp(`^\\s*${TIME}\\s*-->\\s*${TIME}`); + +function seconds(h: string | undefined, m: string, s: string, ms: string): number { + return Number(h ?? 0) * 3600 + Number(m) * 60 + Number(s) + Number(ms.padEnd(3, "0")) / 1000; +} + +/** + * Reads the cues of an SRT or WebVTT file. Cue numbers, WebVTT headers, NOTE + * and STYLE blocks, cue settings and formatting tags (, {\an8}) are + * dropped; cues without text or with an end before their start are skipped. + */ +export function parseCaptions(source: string): CaptionCue[] { + const blocks = source.replace(/^/, "").replace(/\r\n?/g, "\n").split(/\n{2,}/); + const cues: CaptionCue[] = []; + for (const block of blocks) { + const lines = block.split("\n"); + const at = lines.findIndex((line) => TIMING_LINE.test(line)); + if (at === -1) continue; + const m = TIMING_LINE.exec(lines[at]!)!; + const start = seconds(m[1], m[2]!, m[3]!, m[4]!); + const end = seconds(m[5], m[6]!, m[7]!, m[8]!); + const text = lines + .slice(at + 1) + .map((line) => line.replace(/<[^>]*>/g, "").replace(/\{\\[^}]*\}/g, "").trim()) + .filter(Boolean) + .join("\n"); + if (!text || !(end > start)) continue; + cues.push({ start, end, text: text.slice(0, MAX_OVERLAY_TEXT_LENGTH) }); + } + return cues.sort((a, b) => a.start - b.start); +} + +/** + * Text overlays for caption cues: white text in a dark box, centred near the + * bottom of the frame, sized for the output height. `room` is how many more + * overlays the edit can hold; cues past it are dropped. + */ +export function captionOverlays(cues: CaptionCue[], outputHeight: number, room: number = MAX_TEXT_OVERLAYS): TextOverlay[] { + const fontSize = Math.min(120, Math.max(12, Math.round(outputHeight * 0.045))); + return cues.slice(0, Math.max(0, room)).map((cue) => ({ + id: generateTextOverlayId(), + text: cue.text, + x: 50, + y: 88, + fontSize, + color: "#ffffff", + fontWeight: "normal", + start: cue.start, + end: cue.end, + box: true, + })); +} diff --git a/src/lib/featureTelemetry.ts b/src/lib/featureTelemetry.ts index fda905bb1..6e9d1e37f 100644 --- a/src/lib/featureTelemetry.ts +++ b/src/lib/featureTelemetry.ts @@ -19,6 +19,7 @@ export const FEATURE_ACTIONS = { crop_tool: ["aspect", "drag", "reset"], batch_export: ["start", "done", "done_with_failures", "cancel", "save_folder"], trim_timeline: ["seek", "drag_handle"], + text_tool: ["import_captions", "set_timing", "caption_box"], // One event per editing tool an export used (see toolsUsed). trim: ["exported"], rotate: ["exported"], @@ -27,6 +28,7 @@ export const FEATURE_ACTIONS = { volume: ["exported"], normalize_audio: ["exported"], text_overlay: ["exported"], + timed_text: ["exported"], image_overlay: ["exported"], background_music: ["exported"], color_adjustments: ["exported"], @@ -79,6 +81,7 @@ export function toolsUsed(recipe: EditRecipe, extras: { music?: boolean; imageOv if (recipe.volume !== d.volume) tools.push("volume"); if (recipe.normalizeAudio) tools.push("normalize_audio"); if ((recipe.textOverlays?.length ?? 0) > 0) tools.push("text_overlay"); + if (recipe.textOverlays?.some((o) => o.start !== undefined || o.end !== undefined)) tools.push("timed_text"); if (extras.imageOverlay) tools.push("image_overlay"); if (extras.music) tools.push("background_music"); if (recipe.brightness !== d.brightness || recipe.contrast !== d.contrast || recipe.saturation !== d.saturation) { diff --git a/src/lib/ffmpegArgs.ts b/src/lib/ffmpegArgs.ts index a7bdcbd45..9ec67cb08 100644 --- a/src/lib/ffmpegArgs.ts +++ b/src/lib/ffmpegArgs.ts @@ -203,8 +203,10 @@ export function buildVideoFilter(input: EditRecipe, targetW: number, targetH: nu } const textOverlays = recipe.textOverlays || []; + const timing = { trimStart: recipe.trimStart, trimEnd: recipe.trimEnd, speed: recipe.speed }; textOverlays.forEach((overlay) => { - filters.push(buildTextFilter(overlay, targetW, targetH)); + const text = buildTextFilter(overlay, targetW, targetH, timing); + if (text) filters.push(text); }); return filters.join(","); diff --git a/src/lib/project.ts b/src/lib/project.ts index 6e14f7129..61330e7c9 100644 --- a/src/lib/project.ts +++ b/src/lib/project.ts @@ -21,7 +21,8 @@ export const PROJECT_SCHEMA_VERSION = 1; export const PROJECT_STORAGE_KEY = "reframe:project"; /** Projects are a few KB; anything this large is not one of ours. */ export const MAX_PROJECT_FILE_BYTES = 512 * 1024; -export const MAX_TEXT_OVERLAYS = 50; +/** Enough for an imported caption file; each overlay is one drawtext filter. */ +export const MAX_TEXT_OVERLAYS = 500; export const MAX_OVERLAY_TEXT_LENGTH = 500; export const DEFAULT_IMAGE_OVERLAY: ImageOverlaySettings = { @@ -110,6 +111,12 @@ function parseTextOverlay(raw: unknown, index: number): TextOverlay { if (raw.fontFamily !== undefined && (typeof raw.fontFamily !== "string" || !SAFE_FONT_NAME.test(raw.fontFamily))) { fail(`The ${label} font name is not allowed.`); } + const timing: { start?: number; end?: number } = {}; + if (raw.start !== undefined) timing.start = num(raw, "start", 0, Number.MAX_SAFE_INTEGER, `${label} start`); + if (raw.end !== undefined) { + timing.end = num(raw, "end", 0, Number.MAX_SAFE_INTEGER, `${label} end`); + if (timing.end <= (timing.start ?? 0)) fail(`The ${label} must end after it starts.`); + } // `fontPath` is deliberately never read: it is passed to FFmpeg as a file // path, so a project file must not be able to supply one. return { @@ -121,6 +128,8 @@ function parseTextOverlay(raw: unknown, index: number): TextOverlay { color: raw.color, fontWeight: oneOf(raw, "fontWeight", ["normal", "bold", "900"] as const), ...(typeof raw.fontFamily === "string" ? { fontFamily: raw.fontFamily } : {}), + ...timing, + ...(raw.box !== undefined ? { box: bool(raw, "box") } : {}), }; } diff --git a/src/lib/tests/captions.test.ts b/src/lib/tests/captions.test.ts new file mode 100644 index 000000000..db7dc99b6 --- /dev/null +++ b/src/lib/tests/captions.test.ts @@ -0,0 +1,75 @@ +import { describe, it, expect } from "vitest"; +import { captionOverlays, parseCaptions } from "../captions"; +import { isValidRecipe } from "../types"; +import { DEFAULT_RECIPE } from "../constants"; + +const SRT = `1\r +00:00:01,000 --> 00:00:02,500\r +Hello there\r +\r +2\r +00:00:03,250 --> 00:00:05,000\r +{\\an8}Two\r +lines\r +\r +3\r +00:00:06,000 --> 00:00:06,000\r +zero length\r +`; + +const VTT = `WEBVTT + +NOTE a comment + +intro +00:01.000 --> 00:02.000 align:start position:10% +First + +01:00:00.5 --> 01:00:01.000 +Late +`; + +describe("parseCaptions", () => { + it("reads SRT cues, dropping numbers, tags, BOM and CRLF", () => { + expect(parseCaptions(SRT)).toEqual([ + { start: 1, end: 2.5, text: "Hello there" }, + { start: 3.25, end: 5, text: "Two\nlines" }, + ]); + }); + + it("reads WebVTT cues with settings, ids and short times", () => { + expect(parseCaptions(VTT)).toEqual([ + { start: 1, end: 2, text: "First" }, + { start: 3600.5, end: 3601, text: "Late" }, + ]); + }); + + it("finds nothing in a file that isn't captions", () => { + expect(parseCaptions("just some text\nno timings")).toEqual([]); + expect(parseCaptions("")).toEqual([]); + }); + + it("caps each cue's text at the overlay length limit", () => { + const long = "x".repeat(800); + expect(parseCaptions(`00:00:01,000 --> 00:00:02,000\n${long}`)[0]!.text).toHaveLength(500); + }); +}); + +describe("captionOverlays", () => { + const cues = parseCaptions(SRT); + + it("makes timed, boxed text near the bottom, sized for the output", () => { + const [first] = captionOverlays(cues, 1920); + expect(first).toMatchObject({ text: "Hello there", start: 1, end: 2.5, box: true, x: 50, y: 88, fontSize: 86 }); + expect(captionOverlays(cues, 100)[0]!.fontSize).toBe(12); + }); + + it("stops at the room left in the edit", () => { + expect(captionOverlays(cues, 1080, 1)).toHaveLength(1); + expect(captionOverlays(cues, 1080, 0)).toHaveLength(0); + }); + + it("produces overlays the editor accepts", () => { + expect(isValidRecipe({ ...DEFAULT_RECIPE, textOverlays: captionOverlays(cues, 1080) })).toBe(true); + }); +}); diff --git a/src/lib/tests/project.test.ts b/src/lib/tests/project.test.ts index 0a00c47dc..5799d6bf5 100644 --- a/src/lib/tests/project.test.ts +++ b/src/lib/tests/project.test.ts @@ -117,6 +117,9 @@ describe("project documents", () => { ["an unsafe overlay id", sampleJson((d) => (d.edit.recipe.textOverlays[0].id = "")), "invalid id"], ["overlay text too long", sampleJson((d) => (d.edit.recipe.textOverlays[0].text = "x".repeat(501))), "at most 500"], ["duplicate overlay ids", sampleJson((d) => d.edit.recipe.textOverlays.push(d.edit.recipe.textOverlays[0])), "same id"], + ["text that ends before it starts", sampleJson((d) => Object.assign(d.edit.recipe.textOverlays[0], { start: 4, end: 2 })), "must end after it starts"], + ["a negative text start", sampleJson((d) => (d.edit.recipe.textOverlays[0].start = -1)), "start"], + ["a non-boolean caption box", sampleJson((d) => (d.edit.recipe.textOverlays[0].box = "yes")), "box"], ["a bad overlay position", sampleJson((d) => (d.edit.imageOverlay.position = "middle")), "position"], ["a bad source", sampleJson((d) => (d.source = { name: "" })), "source video name"], ])("rejects %s", (_label, input, message) => { @@ -125,6 +128,12 @@ describe("project documents", () => { if (!parsed.ok) expect(parsed.error).toContain(message); }); + it("keeps text timing and the caption box", () => { + const parsed = parseProject(sampleJson((d) => Object.assign(d.edit.recipe.textOverlays[0], { start: 1.5, end: 4, box: true }))); + expect(parsed.ok).toBe(true); + if (parsed.ok) expect(parsed.project.edit.recipe.textOverlays[0]).toMatchObject({ start: 1.5, end: 4, box: true }); + }); + it("rejects too many text overlays", () => { const parsed = parseProject( sampleJson((d) => { diff --git a/src/lib/tests/textOverlay.test.ts b/src/lib/tests/textOverlay.test.ts index da0feda7b..063b871f3 100644 --- a/src/lib/tests/textOverlay.test.ts +++ b/src/lib/tests/textOverlay.test.ts @@ -1,5 +1,7 @@ import { describe, it, expect } from "vitest"; -import { buildTextFilter, createDefaultTextOverlay, TEXT_FONT_FILE } from "../text-overlay"; +import { buildTextFilter, createDefaultTextOverlay, isTextVisibleAt, textEnableExpression, TEXT_FONT_FILE } from "../text-overlay"; +import { buildVideoFilter } from "../ffmpegArgs"; +import { DEFAULT_RECIPE } from "../constants"; const overlay = (o: Partial> = {}) => ({ ...createDefaultTextOverlay(), ...o }); @@ -23,9 +25,73 @@ describe("buildTextFilter", () => { expect(bold).toMatch(/borderw=2:bordercolor=#ff0000/); }); - it("positions by percentage and escapes drawtext's special characters", () => { + it("centres the text on its position, as the preview does, and escapes drawtext's special characters", () => { const f = buildTextFilter(overlay({ text: "50% off: it's 'here'", x: 25, y: 10 }), 1000, 500); - expect(f).toContain("x=250:y=50"); + expect(f).toContain("x=250-text_w/2:y=50-text_h/2"); expect(f).toContain("text='50%% off\\: it\\'s \\'here\\''"); }); }); + +describe("timed text", () => { + const timing = (o: Partial<{ trimStart: number; trimEnd: number | null; speed: number }> = {}) => ({ + trimStart: 0, + trimEnd: null, + speed: 1, + ...o, + }); + + it("is on for the whole export when it has no start or end", () => { + expect(textEnableExpression({}, timing())).toBe(""); + expect(buildTextFilter(overlay(), 1920, 1080)).not.toContain("enable="); + }); + + it("turns on and off at its start and end", () => { + expect(textEnableExpression({ start: 1.5, end: 3 }, timing())).toBe("between(t,1.5,3)"); + expect(textEnableExpression({ start: 2 }, timing())).toBe("gte(t,2)"); + expect(textEnableExpression({ end: 4 }, timing())).toBe("lt(t,4)"); + expect(buildTextFilter(overlay({ start: 1, end: 2 }), 1920, 1080)).toMatch(/:enable='between\(t,1,2\)'$/); + }); + + it("follows the trim and speed, since drawtext sees the exported clip's time", () => { + // Source 5–9 s, trimmed from 4 s, played at 2×: 0.5–2.5 s of the export. + expect(textEnableExpression({ start: 5, end: 9 }, timing({ trimStart: 4, speed: 2 }))).toBe("between(t,0.5,2.5)"); + // Starts before the trim: on from the export's first frame. + expect(textEnableExpression({ start: 1, end: 6 }, timing({ trimStart: 4 }))).toBe("lt(t,2)"); + // Ends after the trim end: on until the export's last frame. + expect(textEnableExpression({ start: 5, end: 20 }, timing({ trimStart: 4, trimEnd: 10 }))).toBe("gte(t,1)"); + }); + + it("is left out when it falls outside the kept part", () => { + expect(textEnableExpression({ start: 1, end: 3 }, timing({ trimStart: 3 }))).toBeNull(); + expect(textEnableExpression({ start: 10 }, timing({ trimStart: 0, trimEnd: 10 }))).toBeNull(); + const filter = buildVideoFilter( + { ...DEFAULT_RECIPE, trimStart: 5, trimEnd: 8, textOverlays: [overlay({ text: "early", start: 0, end: 2 }), overlay({ text: "kept" })] }, + 1920, + 1080 + ); + expect(filter).not.toContain("early"); + expect(filter).toContain("text='kept'"); + }); + + it("uses the recipe's trim and speed in the export filter", () => { + const filter = buildVideoFilter( + { ...DEFAULT_RECIPE, trimStart: 2, trimEnd: null, speed: 2, textOverlays: [overlay({ start: 4, end: 6 })] }, + 1920, + 1080 + ); + expect(filter).toContain("enable='between(t,1,2)'"); + }); + + it("draws a caption box when asked", () => { + expect(buildTextFilter(overlay(), 1920, 1080)).not.toContain("box=1"); + expect(buildTextFilter(overlay({ box: true, fontSize: 40 }), 1920, 1080)).toContain("box=1:boxcolor=black@0.55:boxborderw=12"); + }); + + it("shows in the preview from its start up to, not including, its end", () => { + const o = { start: 1, end: 2 }; + expect(isTextVisibleAt(o, 0.99)).toBe(false); + expect(isTextVisibleAt(o, 1)).toBe(true); + expect(isTextVisibleAt(o, 2)).toBe(false); + expect(isTextVisibleAt({}, 1e6)).toBe(true); + }); +}); diff --git a/src/lib/text-overlay.ts b/src/lib/text-overlay.ts index e13abaf05..e8d1fcb54 100644 --- a/src/lib/text-overlay.ts +++ b/src/lib/text-overlay.ts @@ -63,16 +63,53 @@ export function getTextPercentPosition( }; } +/** Whether the text is on screen at `time` seconds of the source video. */ +export function isTextVisibleAt(overlay: Pick, time: number): boolean { + return time >= (overlay.start ?? 0) && (overlay.end === undefined || time < overlay.end); +} + +/** The part of the source video that the export keeps, and how fast it plays. */ +export interface TextTiming { + trimStart: number; + trimEnd: number | null; + speed: number; +} + +/** + * The drawtext `enable` expression for an overlay's start and end, which are + * in source seconds. drawtext runs after trim and speed, so its `t` is the + * exported clip's time. Returns "" when the text is on for the whole export, + * and null when it falls outside the kept part and so never shows. + */ +export function textEnableExpression(overlay: Pick, timing: TextTiming): string | null { + const { trimStart, trimEnd, speed } = timing; + const start = overlay.start ?? 0; + const end = overlay.end; + if (end !== undefined && end <= trimStart) return null; + if (trimEnd !== null && start >= trimEnd) return null; + const from = start > trimStart ? (start - trimStart) / speed : 0; + const until = end !== undefined && (trimEnd === null || end < trimEnd) ? (end - trimStart) / speed : null; + const s = (n: number) => String(Number(n.toFixed(3))); + if (from === 0 && until === null) return ""; + if (until === null) return `gte(t,${s(from)})`; + if (from === 0) return `lt(t,${s(until)})`; + return `between(t,${s(from)},${s(until)})`; +} + /** - * Generates a drawText FFmpeg filter for a single text overlay. - * Escapes special characters and positions text on the output video. - * Includes font family and custom font file support. + * Generates a drawText FFmpeg filter for a single text overlay, or null when + * its start and end put it outside the exported part of the video. + * The text is centred on its position, as in the preview. */ export function buildTextFilter( overlay: TextOverlay, targetWidth: number, - targetHeight: number -): string { + targetHeight: number, + timing: TextTiming = { trimStart: 0, trimEnd: null, speed: 1 } +): string | null { + const enable = textEnableExpression(overlay, timing); + if (enable === null) return null; + // Escape special characters for FFmpeg drawtext filter const escapedText = overlay.text .replace(/\\/g, "\\\\") @@ -88,10 +125,14 @@ export function buildTextFilter( // resolve and drawtext needs a font file: the worker writes the bundled one // (public/fonts) into FFmpeg's filesystem as TEXT_FONT_FILE. drawtext has // no weight option either; bold is drawn as a thin outline in the text colour. - let filter = `drawtext=fontfile=${TEXT_FONT_FILE}:text='${escapedText}':x=${pixelX}:y=${pixelY}:fontsize=${overlay.fontSize}:fontcolor=${overlay.color}`; + let filter = `drawtext=fontfile=${TEXT_FONT_FILE}:text='${escapedText}':x=${pixelX}-text_w/2:y=${pixelY}-text_h/2:fontsize=${overlay.fontSize}:fontcolor=${overlay.color}`; if (overlay.fontWeight === "bold" || overlay.fontWeight === "900") { const width = Math.max(1, Math.round(overlay.fontSize / (overlay.fontWeight === "900" ? 18 : 28))); filter += `:borderw=${width}:bordercolor=${overlay.color}`; } + if (overlay.box) { + filter += `:box=1:boxcolor=black@0.55:boxborderw=${Math.max(2, Math.round(overlay.fontSize * 0.3))}`; + } + if (enable) filter += `:enable='${enable}'`; return filter; } diff --git a/src/lib/types.ts b/src/lib/types.ts index 2cf5da148..89208179d 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -15,6 +15,12 @@ export interface TextOverlay { fontWeight: "normal" | "bold" | "900"; fontFamily?: string; // Font family name (e.g., "Arial", "Inter", "CustomFont") fontPath?: string; // Path/URL to custom font file for export + /** When the text appears, in seconds of the source video. Absent: from the start. */ + start?: number; + /** When the text disappears, in seconds of the source video. Absent: until the end. */ + end?: number; + /** Draw a translucent box behind the text, for captions. */ + box?: boolean; } export interface EditRecipe { @@ -162,6 +168,9 @@ export function isValidRecipe(value: unknown): value is EditRecipe { if (typeof overlay.fontSize !== "number" || !isFinite(overlay.fontSize) || overlay.fontSize < 12 || overlay.fontSize > 120) return false; if (typeof overlay.color !== "string") return false; if (!["normal", "bold", "900"].includes(overlay.fontWeight)) return false; + if (overlay.start !== undefined && (typeof overlay.start !== "number" || !isFinite(overlay.start) || overlay.start < 0)) return false; + if (overlay.end !== undefined && (typeof overlay.end !== "number" || !isFinite(overlay.end) || overlay.end <= (overlay.start ?? 0))) return false; + if (overlay.box !== undefined && typeof overlay.box !== "boolean") return false; } return true; diff --git a/test/e2e/captions.spec.ts b/test/e2e/captions.spec.ts new file mode 100644 index 000000000..62bcdda70 --- /dev/null +++ b/test/e2e/captions.spec.ts @@ -0,0 +1,103 @@ +import { test, expect, type Page } from "@playwright/test"; +import { execFileSync } from "node:child_process"; +import { join } from "node:path"; + +// Timed text through the real UI: an SRT file becomes caption items that the +// preview shows only during their cues, and the export draws each one only +// for its time. +const FIXTURES = join(__dirname, "..", "fixtures"); + +const SRT = `1 +00:00:00,000 --> 00:00:01,500 +CAPTION ONE + +2 +00:00:02,200 --> 00:00:02,900 +TWO +`; + +async function openSection(page: Page, name: RegExp) { + const toggle = page.getByRole("button", { name }).first(); + if ((await toggle.getAttribute("aria-expanded")) === "false") await toggle.click(); +} + +async function loadTrimmed(page: Page) { + await page.addInitScript(() => localStorage.setItem("reframe_onboarding_complete", "1")); + await page.goto("/"); + await page.locator('input[type=file][accept="video/*"]').setInputFiles(join(FIXTURES, "normal.mp4")); + await expect(page.getByRole("button", { name: "Export video" }).first()).toBeVisible(); + await openSection(page, /^Trim\b/i); + await page.getByLabel("Trim end time in seconds").fill("3"); +} + +async function exportAndDownload(page: Page, savePath: string) { + await page.getByRole("button", { name: "Export video" }).first().click(); + const download = page.getByRole("link", { name: /^Download (MP4|WEBM|MKV|GIF)$/ }); + const failure = page.getByText(/^Export failed|stopped (responding|making progress)/).first(); + await expect(download.or(failure)).toBeVisible({ timeout: 180_000 }); + await expect(failure, "the export reported an error").toHaveCount(0); + const [file] = await Promise.all([page.waitForEvent("download"), download.click()]); + await file.saveAs(savePath); +} + +/** The caption band (bottom centre) of the frame at `at` seconds, as 32×8 grey pixels. */ +function captionBand(file: string, at: number): Buffer { + return execFileSync("ffmpeg", [ + "-v", "error", "-ss", String(at), "-i", file, "-frames:v", "1", + "-vf", "crop=iw*0.3:ih*0.1:iw*0.35:ih*0.83,scale=32:8,format=gray", "-f", "rawvideo", "-", + ]); +} + +function meanDiff(a: Buffer, b: Buffer): number { + let diff = 0; + for (let i = 0; i < a.length; i++) diff += Math.abs(a[i]! - b[i]!); + return diff / a.length; +} + +async function seekPreview(page: Page, time: number) { + await page.evaluate(async (t) => { + const video = document.querySelector("video")!; + video.pause(); + await new Promise((resolve) => { + video.addEventListener("seeked", () => resolve(), { once: true }); + video.currentTime = t; + }); + }, time); +} + +test("imported captions show only during their cues, in the preview and the export", async ({ page }, testInfo) => { + test.slow(); + await loadTrimmed(page); + const plain = testInfo.outputPath("plain.mp4"); + await exportAndDownload(page, plain); + + await loadTrimmed(page); + await openSection(page, /^Text\b/i); + await page.getByTestId("caption-input").setInputFiles({ name: "talk.srt", mimeType: "application/x-subrip", buffer: Buffer.from(SRT) }); + await expect(page.getByText("Added 2 captions.")).toBeVisible(); + await expect(page.getByRole("button", { name: /CAPTION ONE\s*0:00–0:01\.5/ })).toBeVisible(); + + // The preview shows each caption only during its cue. + const shown = page.getByTestId("text-overlay"); + await seekPreview(page, 0.5); + await expect(shown).toHaveCount(1); + await expect(shown).toHaveText("CAPTION ONE"); + await seekPreview(page, 1.8); + await expect(shown).toHaveCount(0); + await seekPreview(page, 2.5); + await expect(shown).toHaveText("TWO"); + + // An end before the start is refused, so the edit stays valid. + await page.getByRole("button", { name: /^TWO\b/ }).click(); + await page.getByLabel("Text shows until").fill("1"); + await expect(page.getByText("End after the start time.")).toBeVisible(); + await page.getByLabel("Text shows until").blur(); + await expect(page.getByRole("button", { name: /TWO\s*0:02\.2–0:02\.9/ })).toBeVisible(); + + const captioned = testInfo.outputPath("captioned.mp4"); + await exportAndDownload(page, captioned); + + expect(meanDiff(captionBand(plain, 0.5), captionBand(captioned, 0.5)), "caption one drawn at 0.5 s").toBeGreaterThan(5); + expect(meanDiff(captionBand(plain, 1.8), captionBand(captioned, 1.8)), "nothing drawn between cues").toBeLessThan(2); + expect(meanDiff(captionBand(plain, 2.5), captionBand(captioned, 2.5)), "caption two drawn at 2.5 s").toBeGreaterThan(5); +});