diff --git a/README.md b/README.md index 2773b369..61c21cce 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,7 @@ Two caveats worth stating plainly, since "everything is local" is the headline c - **Screen Recorder**: Record your screen, window, or tab directly in the browser using the Screen Capture API. - **GIF Maker**: Turn a series of images into an animated GIF. Reorder frames, set speed, loop, and resize. - **Subtitle Studio**: Transcribe a video into word-timed subtitles with an on-device Whisper model, style the captions, and burn them into your video. +- **Subtitle Cinema Player**: Watch local videos with precisely timed SRT subtitles, a searchable transcript, cinema mode, and playback controls. - **Video to Audio**: Extract audio from videos in your browser — MP3, M4A, OGG, or WAV out, with batch conversion, bitrate control, and optional trimming. - **Video Converter**: Convert videos between MP4, WebM, MKV, AVI, MOV, and GIF in your browser — choose resolution, quality, and audio, trim a range, and watch live progress with cancel. diff --git a/messages/en.json b/messages/en.json index 760bb715..7069ae6c 100644 --- a/messages/en.json +++ b/messages/en.json @@ -819,6 +819,10 @@ "word-to-pdf": { "name": "Word to PDF", "description": "Convert a Word (.docx) document into a PDF using your browser's print dialog — text stays selectable and searchable, entirely in your browser. Styling is normalized, not pixel-exact." + }, + "subtitle-cinema-player": { + "name": "Subtitle Cinema Player", + "description": "Watch local videos with perfectly timed SRT subtitles, a searchable transcript, cinema mode, and precise playback controls. Nothing is uploaded." } }, "categoriesShort": { diff --git a/src/__tests__/components/SubtitleCinemaPlayer.test.tsx b/src/__tests__/components/SubtitleCinemaPlayer.test.tsx new file mode 100644 index 00000000..f379a3fe --- /dev/null +++ b/src/__tests__/components/SubtitleCinemaPlayer.test.tsx @@ -0,0 +1,47 @@ +import { describe, expect, it } from "vitest"; +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import SubtitleCinemaPlayer from "@/components/SubtitleCinemaPlayer"; + +describe("SubtitleCinemaPlayer", () => { + it("loads and presents an SRT without requiring a video", async () => { + const user = userEvent.setup(); + render(); + const file = new File(["1\n00:00:00,000 --> 00:00:02,000\nHello cinema\n"], "captions.srt", { type: "text/plain" }); + await user.upload(screen.getByLabelText("Choose SRT subtitle file"), file); + expect(await screen.findByText("1 cues loaded")).toBeInTheDocument(); + expect(screen.getByText("SRT-only cinema mode — use play to step through your transcript.")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Play" })).toBeInTheDocument(); + }); + + it("exposes subtitle styling controls and highlights the active transcript cue", async () => { + const user = userEvent.setup(); + render(); + const file = new File(["1\n00:00:00,000 --> 00:02:00,000\nActive cue\n"], "captions.srt", { type: "text/plain" }); + await user.upload(screen.getByLabelText("Choose SRT subtitle file"), file); + expect(screen.getByLabelText("Subtitle text size")).toBeInTheDocument(); + expect(screen.getByLabelText("Subtitle text color")).toBeInTheDocument(); + expect(screen.getByLabelText("Subtitle background color")).toBeInTheDocument(); + expect(screen.getByLabelText("Subtitle background opacity")).toBeInTheDocument(); + expect(screen.getByLabelText("Subtitle position")).toBeInTheDocument(); + expect(screen.getByLabelText("Subtitle font family")).toBeInTheDocument(); + await user.click(screen.getByRole("button", { name: /Active cue/ })); + expect(screen.getAllByText("Active cue")[1].closest("button")).toHaveClass("text-primary"); + }); + + it("supports dedicated SRT seek buttons and keyboard shortcuts", async () => { + const user = userEvent.setup(); + render(); + const file = new File(["1\n00:00:00,000 --> 00:00:20,000\nLong cue\n"], "captions.srt", { type: "text/plain" }); + await user.upload(screen.getByLabelText("Choose SRT subtitle file"), file); + + await user.click(screen.getByRole("button", { name: "Seek forward 5 seconds" })); + expect(screen.getByLabelText("Video progress")).toHaveValue("5"); + await user.keyboard("{ArrowLeft}"); + expect(screen.getByLabelText("Video progress")).toHaveValue("4"); + await user.keyboard("{Shift>}{ArrowRight}{/Shift}"); + expect(screen.getByLabelText("Video progress")).toHaveValue("9"); + await user.click(screen.getByRole("button", { name: "Seek backward 1 second" })); + expect(screen.getByLabelText("Video progress")).toHaveValue("8"); + }); +}); diff --git a/src/__tests__/lib/srt.test.ts b/src/__tests__/lib/srt.test.ts new file mode 100644 index 00000000..9221443e --- /dev/null +++ b/src/__tests__/lib/srt.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from "vitest"; +import { activeCue, parseSrt, parseSrtTimestamp } from "@/lib/subtitles/srt"; + +describe("SRT timing", () => { + it("parses millisecond timestamps exactly", () => expect(parseSrtTimestamp("01:02:03,450")).toBe(3723.45)); + it("parses multiline cues and ignores malformed blocks", () => { + const cues = parseSrt("1\n00:00:01,000 --> 00:00:02,500\nHello\nworld\n\nbad\nno timing"); + expect(cues).toEqual([{ id: "1", start: 1, end: 2.5, text: "Hello\nworld" }]); + }); + it("applies offset while choosing the active cue", () => { + const cues = parseSrt("1\n00:00:01,000 --> 00:00:02,000\nHello"); + expect(activeCue(cues, 0.6, 0.5)?.text).toBe("Hello"); + expect(activeCue(cues, 2, 0.5)).toBeUndefined(); + }); +}); diff --git a/src/app/tools/subtitle-cinema-player/opengraph-image.tsx b/src/app/tools/subtitle-cinema-player/opengraph-image.tsx new file mode 100644 index 00000000..5f16e7a3 --- /dev/null +++ b/src/app/tools/subtitle-cinema-player/opengraph-image.tsx @@ -0,0 +1,9 @@ +import { generateToolOgImage, ogSize, ogContentType } from "@/lib/og-image"; + +export const alt = "subtitle-cinema-player | BrowseryTools"; +export const size = ogSize; +export const contentType = ogContentType; + +export default function Image() { + return generateToolOgImage("subtitle-cinema-player"); +} diff --git a/src/app/tools/subtitle-cinema-player/page.tsx b/src/app/tools/subtitle-cinema-player/page.tsx new file mode 100644 index 00000000..ac98f94c --- /dev/null +++ b/src/app/tools/subtitle-cinema-player/page.tsx @@ -0,0 +1,5 @@ +import SubtitleCinemaPlayer from "@/components/SubtitleCinemaPlayer"; +import { generateToolMetadata } from "@/lib/metadata"; + +export const metadata = generateToolMetadata("/tools/subtitle-cinema-player"); +export default function SubtitleCinemaPlayerPage() { return ; } diff --git a/src/app/tools/subtitle-cinema-player/twitter-image.tsx b/src/app/tools/subtitle-cinema-player/twitter-image.tsx new file mode 100644 index 00000000..5f16e7a3 --- /dev/null +++ b/src/app/tools/subtitle-cinema-player/twitter-image.tsx @@ -0,0 +1,9 @@ +import { generateToolOgImage, ogSize, ogContentType } from "@/lib/og-image"; + +export const alt = "subtitle-cinema-player | BrowseryTools"; +export const size = ogSize; +export const contentType = ogContentType; + +export default function Image() { + return generateToolOgImage("subtitle-cinema-player"); +} diff --git a/src/components/SubtitleCinemaPlayer.tsx b/src/components/SubtitleCinemaPlayer.tsx new file mode 100644 index 00000000..7dd746a4 --- /dev/null +++ b/src/components/SubtitleCinemaPlayer.tsx @@ -0,0 +1,117 @@ +"use client"; + +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { ToolShell } from "@/components/template/tool-shell"; +import { FileDropzone } from "@/components/shared/FileDropzone"; +import { OptionRow, SettingsCard } from "@/components/shared/SettingsCard"; +import { StatStrip } from "@/components/shared/StatStrip"; +import { TwoPane } from "@/components/shared/TwoPane"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { parseSrt, activeCue, type SubtitleCue } from "@/lib/subtitles/srt"; +import { FastForward, Maximize, Minimize, Pause, Play, Rewind, Search, Upload } from "lucide-react"; + +const formatTime = (time: number) => `${Math.floor(time / 60)}:${String(Math.floor(time % 60)).padStart(2, "0")}`; +const ACCEPT_VIDEO = { "video/*": [] }; +const ACCEPT_SRT = { "text/plain": [".srt"], "application/x-subrip": [".srt"] }; +const fonts = ["system-ui", "Arial", "Verdana", "Georgia", "monospace"]; + +type SubtitleStyle = { size: number; color: string; background: string; opacity: number; outline: boolean; shadow: boolean; position: "top" | "center" | "bottom"; font: string }; +const defaultStyle: SubtitleStyle = { size: 1.25, color: "#ffffff", background: "#000000", opacity: 75, outline: true, shadow: true, position: "bottom", font: "system-ui" }; + +export default function SubtitleCinemaPlayer() { + const videoRef = useRef(null); + const stageRef = useRef(null); + const [videoUrl, setVideoUrl] = useState(""); + const [videoName, setVideoName] = useState(""); + const [cues, setCues] = useState([]); + const [currentTime, setCurrentTime] = useState(0); + const [duration, setDuration] = useState(0); + const [playing, setPlaying] = useState(false); + const [offset, setOffset] = useState(0); + const [speed, setSpeed] = useState("1"); + const [query, setQuery] = useState(""); + const [style, setStyle] = useState(defaultStyle); + const [cinema, setCinema] = useState(false); + const [status, setStatus] = useState("Choose an SRT file to begin. Video is optional."); + + useEffect(() => () => { if (videoUrl) URL.revokeObjectURL(videoUrl); }, [videoUrl]); + useEffect(() => { + if (!playing || videoUrl) return; + const timer = window.setInterval(() => setCurrentTime((time) => { + const end = duration || cues.at(-1)?.end || 0; + if (end && time >= end) { setPlaying(false); return 0; } + return time + 0.1 * Number(speed); + }), 100); + return () => window.clearInterval(timer); + }, [playing, videoUrl, duration, cues, speed]); + + const current = activeCue(cues, currentTime, offset); + const filtered = useMemo(() => cues.filter((cue) => cue.text.toLowerCase().includes(query.toLowerCase())), [cues, query]); + const subtitleStyle = { + color: style.color, + fontFamily: style.font, + fontSize: `${style.size}em`, + backgroundColor: `${style.background}${Math.round(style.opacity * 2.55).toString(16).padStart(2, "0")}`, + textShadow: [style.outline ? "-1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000" : "", style.shadow ? "0 2px 4px rgb(0 0 0 / 90%)" : ""].filter(Boolean).join(", "), + }; + const positionClass = style.position === "top" ? "top-8" : style.position === "center" ? "top-1/2 -translate-y-1/2" : "bottom-16"; + const updateStyle = (key: K, value: SubtitleStyle[K]) => setStyle((old) => ({ ...old, [key]: value })); + + const loadVideo = (files: File[]) => { const file = files[0]; if (!file) return; setVideoUrl((old) => { if (old) URL.revokeObjectURL(old); return URL.createObjectURL(file); }); setVideoName(file.name); setCurrentTime(0); setDuration(0); setStatus(`${file.name} loaded locally. SRT playback remains available without it.`); }; + const loadSrt = async (files: File[]) => { const file = files[0]; if (!file) return; const parsed = parseSrt(await file.text()); setCues(parsed); setCurrentTime(0); setDuration(videoUrl ? 0 : parsed.at(-1)?.end || 0); setPlaying(false); setStatus(`${parsed.length} subtitle cues loaded locally. Ready for SRT-only playback.`); }; + const togglePlay = useCallback(() => { const video = videoRef.current; if (video) { if (video.paused) void video.play(); else video.pause(); } else if (cues.length) setPlaying((value) => !value); }, [cues.length]); + const seek = useCallback((time: number) => { const end = duration || cues.at(-1)?.end || 0; const next = Math.min(end || Number.POSITIVE_INFINITY, Math.max(0, time)); if (videoRef.current) videoRef.current.currentTime = next; setCurrentTime(next); }, [cues, duration]); + useEffect(() => { + const handleKeyDown = (event: KeyboardEvent) => { + const target = event.target as HTMLElement | null; + if (target?.isContentEditable || target?.tagName === "INPUT" || target?.tagName === "TEXTAREA" || target?.tagName === "SELECT") return; + if (event.key === "ArrowLeft" || event.key === "ArrowRight") { + event.preventDefault(); + const amount = event.shiftKey ? 5 : 1; + seek(currentTime + (event.key === "ArrowLeft" ? -amount : amount)); + } else if (event.key === " ") { + event.preventDefault(); + togglePlay(); + } + }; + window.addEventListener("keydown", handleKeyDown); + return () => window.removeEventListener("keydown", handleKeyDown); + }, [currentTime, seek, togglePlay]); + const toggleFullscreen = async () => { if (!stageRef.current) return; if (document.fullscreenElement) await document.exitFullscreen(); else await stageRef.current.requestFullscreen?.(); }; + + return + + + + {cues.length ? `${cues.length} cues loaded` : "Choose subtitles"}SRT format + + Optional: add a local video{videoName || "Choose optional video"} + {status} + + + + {videoUrl ? setDuration(e.currentTarget.duration)} onTimeUpdate={(e) => setCurrentTime(e.currentTarget.currentTime)} onPlay={() => setPlaying(true)} onPause={() => setPlaying(false)} onEnded={() => setPlaying(false)} aria-label="Local video preview" /> : {cues.length ? "SRT-only cinema mode — use play to step through your transcript." : "Choose an SRT file above to begin."}} + {current && {current.text}} + seek(currentTime - 5)} aria-label="Seek backward 5 seconds">-5s seek(currentTime - 1)} aria-label="Seek backward 1 second">-1s{playing ? : } seek(currentTime + 1)} aria-label="Seek forward 1 second">+1s seek(currentTime + 5)} aria-label="Seek forward 5 seconds">+5s seek(Number(e.target.value))} disabled={!cues.length} />{formatTime(currentTime)} / {formatTime(duration || cues.at(-1)?.end || 0)}{cinema ? : } + + + + setOffset(Number(e.target.value) || 0)} /> + { setSpeed(value); if (videoRef.current) videoRef.current.playbackRate = Number(value); }}>{["0.5", "0.75", "1", "1.25", "1.5", "2"].map((value) => {value}×)} + updateStyle("size", Number(e.target.value))} /> + updateStyle("color", e.target.value)} className="h-9 w-full rounded border" /> + updateStyle("background", e.target.value)} className="h-9 w-full rounded border" /> + updateStyle("opacity", Number(e.target.value))} /> + updateStyle("position", value)}>{["top", "center", "bottom"].map((value) => {value})} + updateStyle("font", value)}>{fonts.map((font) => {font})} + updateStyle("outline", !style.outline)}>Outline updateStyle("shadow", !style.shadow)}>Shadow + setCinema((value) => !value)}>{cinema ? : } {cinema ? "Exit cinema" : "Cinema mode"} + } end={} /> + + TranscriptAbout setQuery(e.target.value)} />{filtered.map((cue) => seek(Math.max(0, cue.start - offset))}>{formatTime(cue.start)}{cue.text})}{!filtered.length && Load an SRT file to see clickable cues.}SRT and optional video are processed locally in your browser. Nothing is uploaded. + + ; +} diff --git a/src/components/layout/tool-title.tsx b/src/components/layout/tool-title.tsx index 9bf96c79..69451237 100644 --- a/src/components/layout/tool-title.tsx +++ b/src/components/layout/tool-title.tsx @@ -247,6 +247,7 @@ const HAS_OWN_H1 = new Set([ "anagram-solver", // Wave 5 (W5) Task 7: Subtitle Studio ships directly on ToolShell. "subtitle-studio", + "subtitle-cinema-player", // Wave 7 (W7) Task 10: PDF to Word ships directly on ToolShell. "pdf-to-word", // Wave 7 (W7) Task 11: Word to PDF ships directly on ToolShell. diff --git a/src/lib/subtitles/srt.ts b/src/lib/subtitles/srt.ts new file mode 100644 index 00000000..41288573 --- /dev/null +++ b/src/lib/subtitles/srt.ts @@ -0,0 +1,32 @@ +export interface SubtitleCue { + id: string; + start: number; + end: number; + text: string; +} + +export function parseSrtTimestamp(value: string): number { + const match = value.trim().match(/^(\d{2}):(\d{2}):(\d{2})[,.](\d{3})$/); + if (!match) return Number.NaN; + const [, h, m, s, ms] = match; + return Number(h) * 3600 + Number(m) * 60 + Number(s) + Number(ms) / 1000; +} + +export function parseSrt(input: string): SubtitleCue[] { + return input.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n").split(/\n{2,}/).flatMap((block, index) => { + const lines = block.split("\n").map((line) => line.trimEnd()); + const timingIndex = lines.findIndex((line) => line.includes("-->")); + if (timingIndex < 0) return []; + const [startRaw, endRaw] = lines[timingIndex].split("-->").map((v) => v.trim().split(/\s+/)[0]); + const start = parseSrtTimestamp(startRaw); + const end = parseSrtTimestamp(endRaw); + const text = lines.slice(timingIndex + 1).join("\n").trim(); + if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start || !text) return []; + return [{ id: lines.slice(0, timingIndex).join("-") || String(index + 1), start, end, text }]; + }); +} + +export function activeCue(cues: SubtitleCue[], time: number, offset = 0): SubtitleCue | undefined { + const adjusted = time + offset; + return cues.find((cue) => adjusted >= cue.start && adjusted < cue.end); +} diff --git a/src/lib/tools-config.ts b/src/lib/tools-config.ts index b57f50b3..ec0118f9 100644 --- a/src/lib/tools-config.ts +++ b/src/lib/tools-config.ts @@ -766,6 +766,16 @@ export const tools: ToolCategory[] = [ description: "Transcribe a video into word-timed subtitles with an on-device Whisper model, style the captions, and burn them into your video. No uploads — runs entirely on-device.", }, + { + name: "Subtitle Cinema Player", + href: "/tools/subtitle-cinema-player", + icon: CaptionsIcon, + available: true, + order: 7.5, + creationDate: "2026-09-19", + description: + "Watch local videos with perfectly timed SRT subtitles, a searchable transcript, cinema mode, and precise playback controls. Nothing is uploaded.", + }, { name: "Video to Audio", href: "/tools/video-to-audio",
{status}
Load an SRT file to see clickable cues.
SRT and optional video are processed locally in your browser. Nothing is uploaded.