diff --git a/src/components/ai-edition/ImportSrtDialog.test.tsx b/src/components/ai-edition/ImportSrtDialog.test.tsx new file mode 100644 index 0000000000..d457ff4952 --- /dev/null +++ b/src/components/ai-edition/ImportSrtDialog.test.tsx @@ -0,0 +1,351 @@ +// @vitest-environment jsdom +import "@testing-library/jest-dom"; +import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { I18nProvider } from "@/contexts/I18nContext"; +import { withTranscript } from "@/lib/ai-edition/document/transcript"; +import { documentSchema } from "@/lib/ai-edition/schema"; +import * as projectWrites from "@/lib/ai-edition/store/projectStore"; +import { useProjectStore } from "@/lib/ai-edition/store/projectStore"; +import { transcriptImportPending } from "@/lib/ai-edition/store/transcriptImport"; +import { useTranscriptionStore } from "@/lib/ai-edition/store/transcriptionStore"; +import { redo, undo } from "@/lib/ai-edition/store/undo"; +import { clearHistory, past } from "@/lib/ai-edition/store/undoStack"; +import { transcriptFromSrt } from "@/lib/ai-edition/transcription/fromSrt"; +import { ImportSrtDialog } from "./ImportSrtDialog"; + +const mocks = vi.hoisted(() => ({ save: vi.fn() })); +vi.mock("@/native/client", () => ({ nativeBridgeClient: { aiEdition: { save: mocks.save } } })); +vi.mock("sonner", () => ({ toast: { error: vi.fn() } })); +const text = "1\n00:00:00,000 --> 00:00:01,000\nHello world"; +function doc() { + return documentSchema.parse({ + schemaVersion: 9, + project: { + id: "p", + title: "P", + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + primaryAssetId: "a", + }, + assets: [ + { id: "a", label: "Recording", originalPath: "/a.mp4", durationSec: 4, kind: "video" }, + { id: "b", label: "Voiceover", originalPath: "/b.wav", durationSec: 4, kind: "audio" }, + ], + timeline: { clips: [] }, + transcripts: [], + audioTracks: [{ id: "v", assetId: "b", kind: "voiceover", startMs: 0, endMs: 4000 }], + }); +} +function show() { + return render( + + + , + ); +} +function file(content = text) { + fireEvent.change(screen.getByLabelText("SRT file"), { + target: { files: [{ name: "example.srt", text: () => Promise.resolve(content) }] }, + }); +} +beforeEach(() => { + clearHistory(); + useProjectStore.setState({ projectId: "p", document: doc() }); + useTranscriptionStore.setState({ projectId: "p", jobs: {} }); + mocks.save.mockImplementation(async (document) => ({ success: true, document })); +}); +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); +it("keeps the import dialog focused on media and file selection without timestamp hints", () => { + show(); + expect(screen.getByLabelText("Target media")).toBeVisible(); + expect(screen.getByLabelText("SRT file")).toBeVisible(); + expect(screen.queryByText(/Subtitle timestamps refer/)).not.toBeInTheDocument(); + expect(screen.queryByText(/Imported subtitle word timings/)).not.toBeInTheDocument(); +}); +it("offers recordings and real voiceovers, excluding generated insertions and music", () => { + const d = doc(); + d.assets.push( + { ...d.assets[0], id: "ext:synth_1", label: "Generated insertion" }, + { ...d.assets[1], id: "music", label: "Background music" }, + ); + d.audioTracks.push({ ...d.audioTracks[0], id: "m", assetId: "music", kind: "music" }); + useProjectStore.setState({ document: d }); + show(); + expect(screen.getByRole("option", { name: "Recording" })).toBeVisible(); + expect(screen.getByRole("option", { name: "Voiceover" })).toBeVisible(); + expect(screen.queryByRole("option", { name: "Generated insertion" })).not.toBeInTheDocument(); + expect(screen.queryByRole("option", { name: "Background music" })).not.toBeInTheDocument(); +}); +it("refuses a voiceover target that becomes music before replacement is confirmed", async () => { + const d = doc(); + d.transcripts = [transcriptFromSrt("b", text, 4, "old.srt")]; + useProjectStore.setState({ document: d }); + show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "b" } }); + file(); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + const replace = await screen.findByRole("button", { name: "Replace transcript" }); + act(() => { + useProjectStore.setState({ + document: { ...d, audioTracks: d.audioTracks.map((track) => ({ ...track, kind: "music" })) }, + }); + }); + fireEvent.click(replace); + await screen.findByRole("alert"); + expect(mocks.save).not.toHaveBeenCalled(); +}); +it("recovers the dialog after a save deadline while reserving the asset until the late write settles", async () => { + let finish!: () => void; + mocks.save.mockImplementationOnce(async (document) => { + await new Promise((resolve) => { + finish = resolve; + }); + return { success: true, document }; + }); + vi.useFakeTimers(); + try { + show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + file(); + await act(async () => { + fireEvent.click(screen.getByRole("button", { name: "Import" })); + }); + expect(mocks.save).toHaveBeenCalledTimes(1); + await act(async () => { + await vi.advanceTimersByTimeAsync(projectWrites.DOCUMENT_SAVES_WAIT_TIMEOUT_MS); + }); + expect(screen.getByRole("alert")).toHaveTextContent(/Saving is taking longer/); + expect(screen.getByRole("button", { name: "Cancel" })).toBeEnabled(); + expect(transcriptImportPending("p", "a")).toBe(true); + await act(async () => { + finish(); + }); + expect(transcriptImportPending("p", "a")).toBe(false); + expect(useProjectStore.getState().document?.transcripts[0].assetId).toBe("a"); + expect(past).toHaveLength(1); + } finally { + if (finish) + await act(async () => { + finish(); + }); + vi.useRealTimers(); + } +}); +it("requires an explicit asset and saves only that transcript with history and provenance", async () => { + show(); + expect(screen.getByRole("button", { name: "Import" })).toBeDisabled(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "b" } }); + file(); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + await waitFor(() => expect(mocks.save).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(useProjectStore.getState().document?.transcripts).toHaveLength(1)); + expect(useProjectStore.getState().document?.transcripts[0].assetId).toBe("b"); + expect(useProjectStore.getState().document?.transcript).toBeNull(); + expect(past).toHaveLength(1); + expect(undo()).toBe(true); + expect(useProjectStore.getState().document?.transcripts).toHaveLength(0); + expect(redo()).toBe(true); + expect(useProjectStore.getState().document?.transcripts[0].importSource?.fileName).toBe( + "example.srt", + ); + expect(useProjectStore.getState().document?.timeline).toEqual(doc().timeline); +}); +it("validates the entire file before replacing existing text", async () => { + const d = doc(); + d.transcripts = [transcriptFromSrt("a", text, 4, "old.srt")]; + useProjectStore.setState({ document: d }); + show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + file("bad"); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + await screen.findByRole("alert"); + expect(mocks.save).not.toHaveBeenCalled(); + expect(useProjectStore.getState().document?.transcripts).toEqual(d.transcripts); +}); +it("asks to replace and rejects transcript changes while awaiting confirmation", async () => { + const d = doc(); + d.transcripts = [transcriptFromSrt("a", text, 4, "old.srt")]; + useProjectStore.setState({ document: d }); + show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + file(); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + const replace = await screen.findByRole("button", { name: "Replace transcript" }); + useProjectStore.setState({ + document: { ...d, transcripts: [transcriptFromSrt("a", text, 4, "new.srt")] }, + }); + fireEvent.click(replace); + await screen.findByRole("alert"); + expect(mocks.save).not.toHaveBeenCalled(); +}); +it("disables a queued transcription target", () => { + useTranscriptionStore.setState({ + jobs: { a: { status: "queued", language: "auto", manual: false } }, + }); + show(); + expect(screen.getByRole("option", { name: /Recording/ })).toBeDisabled(); +}); + +it("abandons a file read when the dialog unmounts", async () => { + let resolve!: (text: string) => void; + const view = show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + fireEvent.change(screen.getByLabelText("SRT file"), { + target: { + files: [ + { + name: "example.srt", + text: () => + new Promise((r) => { + resolve = r; + }), + }, + ], + }, + }); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + view.unmount(); + resolve(text); + await new Promise((r) => setTimeout(r, 0)); + expect(mocks.save).not.toHaveBeenCalled(); +}); +it.each(["project", "removed", "busy"])("refuses a stale %s after reading", async (change) => { + let resolve!: (text: string) => void; + show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + fireEvent.change(screen.getByLabelText("SRT file"), { + target: { + files: [ + { + name: "example.srt", + text: () => + new Promise((r) => { + resolve = r; + }), + }, + ], + }, + }); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + const d = useProjectStore.getState().document!; + if (change === "project") + useProjectStore.setState({ + projectId: "other", + document: { ...d, project: { ...d.project, id: "other" } }, + }); + if (change === "removed") + useProjectStore.setState({ document: { ...d, assets: d.assets.filter((a) => a.id !== "a") } }); + if (change === "busy") + useTranscriptionStore.setState({ + jobs: { a: { status: "running", language: "auto", manual: false } }, + }); + resolve(text); + await screen.findByRole("alert"); + expect(mocks.save).not.toHaveBeenCalled(); +}); +it("reports failed saves without adding history or replacing text", async () => { + mocks.save.mockResolvedValue({ success: false, error: "disk full" }); + const before = useProjectStore.getState().document; + show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + file(); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + expect(await screen.findByRole("alert")).toHaveTextContent("Could not save"); + expect(past).toHaveLength(0); + expect(useProjectStore.getState().document).toBe(before); +}); +it("imports the primary transcript only after explicit replacement confirmation", async () => { + const d = doc(); + const old = transcriptFromSrt("a", text, 4, "old.srt"); + d.transcript = old; + d.transcripts = [old]; + useProjectStore.setState({ document: d }); + show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + file(); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + const replace = await screen.findByRole("button", { name: "Replace transcript" }); + expect(mocks.save).not.toHaveBeenCalled(); + fireEvent.click(replace); + await waitFor(() => expect(past).toHaveLength(1)); + const saved = useProjectStore.getState().document!; + expect(saved.transcript).toEqual(saved.transcripts[0]); + expect(saved.transcript?.importSource?.fileName).toBe("example.srt"); + expect(saved.assets).toEqual(d.assets); + expect(saved.audioTracks).toEqual(d.audioTracks); +}); + +it("waits for an existing B save then merges A into the latest saved document", async () => { + let finish!: () => void; + mocks.save.mockImplementationOnce(async (document) => { + await new Promise((resolve) => { + finish = resolve; + }); + return { success: true, document }; + }); + const old = useProjectStore.getState().document!; + const b = useProjectStore + .getState() + .saveDocument(withTranscript(old, transcriptFromSrt("b", text, 4, "b.srt")), { + history: false, + }); + show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + file(); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + await new Promise((resolve) => setTimeout(resolve, 0)); + const count = mocks.save.mock.calls.length; + finish(); + await b; + await waitFor(() => expect(useProjectStore.getState().document?.transcripts).toHaveLength(2)); + expect(count).toBe(1); + expect( + mocks.save.mock.calls + .at(-1)?.[0] + .transcripts.map((t: { assetId: string }) => t.assetId) + .sort(), + ).toEqual(["a", "b"]); +}); + +it("abandons import when existing document saves time out", async () => { + const wait = vi.spyOn(projectWrites, "waitForDocumentSaves").mockResolvedValueOnce("timeout"); + show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + file(); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + await waitFor(() => expect(wait).toHaveBeenCalled()); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(mocks.save).not.toHaveBeenCalled(); + wait.mockRestore(); +}); +it.each([ + "close", + "unmount", +])("cancels before dispatching import on %s while another save is pending", async (mode) => { + let finish!: () => void; + mocks.save.mockImplementationOnce(async (document) => { + await new Promise((resolve) => { + finish = resolve; + }); + return { success: true, document }; + }); + const b = useProjectStore + .getState() + .saveDocument(useProjectStore.getState().document!, { history: false }); + const view = show(); + fireEvent.change(screen.getByLabelText("Target media"), { target: { value: "a" } }); + file(); + fireEvent.click(screen.getByRole("button", { name: "Import" })); + await new Promise((resolve) => setTimeout(resolve, 0)); + if (mode === "unmount") view.unmount(); + else fireEvent.click(screen.getByRole("button", { name: "Close" })); + finish(); + await b; + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(mocks.save).toHaveBeenCalledTimes(1); + expect(useProjectStore.getState().document?.transcripts).toHaveLength(0); +}); diff --git a/src/components/ai-edition/ImportSrtDialog.tsx b/src/components/ai-edition/ImportSrtDialog.tsx new file mode 100644 index 0000000000..6c4310872c --- /dev/null +++ b/src/components/ai-edition/ImportSrtDialog.tsx @@ -0,0 +1,231 @@ +import { useEffect, useRef, useState } from "react"; +import { createPortal } from "react-dom"; +import { useScopedT } from "@/contexts/I18nContext"; +import { withTranscript } from "@/lib/ai-edition/document/transcript"; +import type { AxcutAsset, AxcutDocument, AxcutTranscript } from "@/lib/ai-edition/schema"; +import { + saveWithDeadline, + useProjectStore, + waitForDocumentSaves, +} from "@/lib/ai-edition/store/projectStore"; +import { runTranscriptImport } from "@/lib/ai-edition/store/transcriptImport"; +import { useTranscriptionStore } from "@/lib/ai-edition/store/transcriptionStore"; +import { isGeneratedAssetId } from "@/lib/ai-edition/timeline/clip-parts"; +import { SrtImportError, transcriptFromSrt } from "@/lib/ai-edition/transcription/fromSrt"; +import { findAssetTranscript } from "@/lib/ai-edition/transcription/status"; +import { ModalShell } from "./Modals"; +import styles from "./NewEditorShell.module.css"; + +interface PendingImport { + transcript: AxcutTranscript; + previous: AxcutTranscript | null; + asset: AxcutAsset; + projectId: string; +} + +function importTargets(document: AxcutDocument | null): AxcutAsset[] { + if (!document) return []; + const voiceovers = new Set( + document.audioTracks + .filter((track) => track.kind === "voiceover") + .map((track) => track.assetId), + ); + return document.assets.filter( + (asset) => + !isGeneratedAssetId(asset.id) && (asset.kind === "video" || voiceovers.has(asset.id)), + ); +} + +/** File input is user-granted text access; no filesystem IPC or HTML rendering. */ +export function ImportSrtDialog({ onClose }: { onClose: () => void }) { + const ts = useScopedT("settings"); + const tc = useScopedT("common"); + const document = useProjectStore((s) => s.document); + const jobs = useTranscriptionStore((s) => s.jobs); + const initialProject = useRef(document?.project.id); + const assets = importTargets(document); + const [assetId, setAssetId] = useState(assets.length === 1 ? assets[0].id : ""); + const [file, setFile] = useState(null); + const [pending, setPending] = useState(null); + const [error, setError] = useState(""); + const [working, setWorking] = useState(false); + const generation = useRef(0); + useEffect( + () => () => { + generation.current++; + }, + [], + ); + const busy = (id: string) => { + const job = useTranscriptionStore.getState().jobs[id]; + return job?.status === "running" || job?.status === "queued"; + }; + const close = () => { + generation.current++; + onClose(); + }; + const valid = (p: PendingImport) => { + const current = useProjectStore.getState().document; + return ( + current?.project.id === p.projectId && + current.project.id === initialProject.current && + importTargets(current).some((asset) => asset.id === p.asset.id) && + JSON.stringify(current.assets.find((a) => a.id === p.asset.id)) === JSON.stringify(p.asset) && + findAssetTranscript(current, p.asset.id) === p.previous && + !busy(p.asset.id) + ); + }; + const commit = async (p: PendingImport) => { + const token = generation.current; + if (!valid(p)) { + setPending(null); + setError(ts("transcript.srt.stale")); + return; + } + setWorking(true); + try { + const operation = runTranscriptImport(p.projectId, p.asset.id, async () => { + if ((await waitForDocumentSaves()) !== "idle") return false; + if (token !== generation.current) return "cancelled" as const; + if (!valid(p)) { + setPending(null); + setError(ts("transcript.srt.stale")); + return "stale" as const; + } + const current = useProjectStore.getState().document!; + return useProjectStore + .getState() + .saveDocument(withTranscript(current, p.transcript), { history: true }); + }); + // A deadline releases the dialog, not the reservation: a late disk write + // must still settle before transcription or a probe reads its document. + const saved = await saveWithDeadline(operation); + if (token !== generation.current) return; + if (saved === true) close(); + else if (saved === false) setError(ts("transcript.srt.saveFailed")); + else if (saved === "timeout") setError(ts("transcript.srt.savePending")); + } catch { + setError(ts("transcript.srt.saveFailed")); + } finally { + setWorking(false); + } + }; + const read = async () => { + const current = useProjectStore.getState().document; + const asset = importTargets(current).find((a) => a.id === assetId); + if ( + !file || + !asset || + !current || + current.project.id !== initialProject.current || + busy(assetId) + ) { + setError(ts("transcript.srt.stale")); + return; + } + const p = { + asset, + projectId: current.project.id, + previous: findAssetTranscript(current, assetId), + }; + const token = ++generation.current; + setWorking(true); + setError(""); + try { + const text = await file.text(); + if (token !== generation.current) return; + const result = { + ...p, + transcript: transcriptFromSrt(assetId, text, asset.durationSec ?? 0, file.name), + }; + if (!valid(result)) { + setError(ts("transcript.srt.stale")); + return; + } + if (p.previous) setPending(result); + else await commit(result); + } catch (e) { + if (token !== generation.current) return; + setError( + e instanceof SrtImportError + ? ts("transcript.srt.validation", { + cue: e.cue, + line: e.line, + reason: ts(`transcript.srt.errors.${e.code}`), + }) + : ts("transcript.srt.readFailed"), + ); + } finally { + setWorking(false); + } + }; + // The floating inspector is transformed and clips its children. Mount the + // modal at the viewport so its backdrop and controls are not cut off by the pane. + return createPortal( + + + + + } + > + + + {pending ?

{ts("transcript.srt.replaceWarning", { name: pending.asset.label })}

: null} + {error ?

{error}

: null} +
, + globalThis.document.body, + ); +} diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsx index 8cf35e98aa..12ee6d5788 100644 --- a/src/components/ai-edition/RightPanes.tsx +++ b/src/components/ai-edition/RightPanes.tsx @@ -157,6 +157,7 @@ import { useClickSound } from "../../hooks/useClickSound"; import { useCanSegmentCamera } from "../../native/hooks/useSegmentationSupport"; import { CaptionsPane } from "./CaptionsPane"; import { ColorField } from "./ColorField"; +import { ImportSrtDialog } from "./ImportSrtDialog"; import { insertionsEnabled } from "./insertionsEnabled"; import styles from "./NewEditorShell.module.css"; import { useRecordedCursorTypes } from "./recordedCursorTypes"; @@ -948,6 +949,20 @@ export function TranscriptPane({ const silentMedia = blocked?.reason === "no-audio"; const transcriptionLabel = useTranscriptionLabel(); const [captionsOpen, setCaptionsOpen] = useState(false); + const [srtOpen, setSrtOpen] = useState(false); + const srtActions = ( + <> + + {srtOpen ? setSrtOpen(false)} /> : null} + + ); const paneBusyLabel = transcriptionBusyLabel( busyView ?? (isTranscribing ? { assetId: "", status: "running", phase: "loading-model" } : undefined), @@ -971,7 +986,11 @@ export function TranscriptPane({ helpText={helpText} actions={ setCaptionsOpen(true)} />} > + {srtActions} {laneSwitch} + {transcripts.some((t) => t.importSource?.format === "srt") ? ( +

{ts("transcript.srt.estimated")}

+ ) : null}
setCaptionsOpen(true)} />} > + {srtActions} {laneSwitch} + {transcripts.some((t) => t.importSource?.format === "srt") ? ( +

{ts("transcript.srt.estimated")}

+ ) : null} {/* The gestures are invisible until tried: nothing on a plain word stream says * that double-click corrects and Backspace cuts. One muted line names them; the * ? popover above carries the long version (amber inserts, hover-bin restore). */} diff --git a/src/components/ai-edition/TranscriptPane.gating.test.tsx b/src/components/ai-edition/TranscriptPane.gating.test.tsx index 787549f2e6..940027c39f 100644 --- a/src/components/ai-edition/TranscriptPane.gating.test.tsx +++ b/src/components/ai-edition/TranscriptPane.gating.test.tsx @@ -6,10 +6,12 @@ // there is nothing to press". import "@testing-library/jest-dom"; -import { cleanup, render, screen } from "@testing-library/react"; +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; import { afterEach, describe, expect, it, vi } from "vitest"; import { I18nProvider } from "@/contexts/I18nContext"; import type { AxcutAsset, AxcutClip } from "@/lib/ai-edition/schema"; +import { documentSchema } from "@/lib/ai-edition/schema"; +import { useProjectStore } from "@/lib/ai-edition/store/projectStore"; import type { TranscriptGateReason } from "@/lib/ai-edition/transcription/status"; import { TranscriptPane } from "./RightPanes"; @@ -98,3 +100,24 @@ describe("transcript pane gating", () => { expect(screen.getByText("whisper-server exited")).toBeInTheDocument(); }); }); + +it("offers exactly one import button and dialog in the empty pane", () => { + const doc = documentSchema.parse({ + schemaVersion: 9, + project: { + id: "p", + title: "P", + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }, + assets: [ASSET], + timeline: { clips: CLIPS }, + }); + useProjectStore.setState({ projectId: "p", document: doc }); + renderPane(); + expect(screen.getAllByRole("button", { name: "Import SRT" })).toHaveLength(1); + fireEvent.click(screen.getByRole("button", { name: "Import SRT" })); + expect(screen.getAllByRole("dialog")).toHaveLength(1); + cleanup(); + useProjectStore.setState({ projectId: null, document: null }); +}); diff --git a/src/i18n/locales/ar/settings.json b/src/i18n/locales/ar/settings.json index 2e599890e4..38b7d3e089 100644 --- a/src/i18n/locales/ar/settings.json +++ b/src/i18n/locales/ar/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "لا يوجد نص لهذا المقطع — افتح بطاقة الوسيط وأعد التوليد.", "editingHintDev": "انقر نقرًا مزدوجًا على كلمة لتصحيحها، واضغط Backspace لقطعها من الفيلم، واكتب بين كلمتين لإضافة كلمة.", "noAudio": "لا يحتوي هذا الملف على مسار صوتي", - "blankedWord": "مُفرَّغة" + "blankedWord": "مُفرَّغة", + "srt": { + "title": "استيراد SRT", + "import": "استيراد", + "replace": "استبدال النص", + "target": "الوسائط المستهدفة", + "chooseTarget": "اختر تسجيلاً أو تعليقاً صوتياً", + "file": "ملف SRT", + "busy": "جارٍ التفريغ", + "estimated": "توقيت الكلمات المستوردة تقديري؛ قد يكون التظليل والقص حسب الكلمات غير دقيق.", + "replaceWarning": "هل تريد استبدال نص {{name}}؟ يمكن التراجع عن ذلك.", + "stale": "تغير المشروع أو الوسائط أو النص، أو بدأ التفريغ. أعد فتح نافذة الاستيراد.", + "saveFailed": "تعذر حفظ النص. حاول مجدداً.", + "savePending": "يستغرق الحفظ وقتًا أطول من المتوقع. قد يكتمل لاحقًا. يمكنك إغلاق هذا الحوار.", + "readFailed": "تعذرت قراءة ملف الترجمة.", + "validation": "المقطع {{cue}}، السطر {{line}}: {{reason}}", + "errors": { + "empty": "الملف لا يحتوي على ترجمة.", + "index": "يجب أن يكون رقم المقطع عدداً موجباً.", + "timestamp": "التنسيق المطلوب HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "يجب أن يأتي وقت النهاية بعد البداية.", + "bounds": "تتجاوز الترجمة مدة الوسائط، أو أن المدة غير معروفة.", + "markup": "يدعم النص العادي وعلامات b وi وu فقط.", + "overlap": "يجب ترتيب المقاطع دون تداخل.", + "text": "يجب أن يحتوي المقطع على نص." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/cs/settings.json b/src/i18n/locales/cs/settings.json index bdfc5bd6e3..e5dc43314c 100644 --- a/src/i18n/locales/cs/settings.json +++ b/src/i18n/locales/cs/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Pro tento klip není přepis. Otevřete kartu média a znovu generujte.", "editingHintDev": "Dvojklikem slovo opravte, Backspace ho vystřihne z filmu, psaním mezi dvěma slovy přidáte nové.", "noAudio": "Toto médium nemá zvukovou stopu", - "blankedWord": "vynecháno" + "blankedWord": "vynecháno", + "srt": { + "title": "Importovat SRT", + "import": "Importovat", + "replace": "Nahradit přepis", + "target": "Cílové médium", + "chooseTarget": "Vyberte záznam nebo komentář", + "file": "Soubor SRT", + "busy": "Probíhá přepis", + "estimated": "Časy importovaných slov jsou odhadnuté. Zvýraznění a střih podle slov mohou být nepřesné.", + "replaceWarning": "Nahradit přepis pro {{name}}? Tuto akci lze vrátit.", + "stale": "Projekt, médium nebo přepis se změnil, případně začal přepis. Otevřete import znovu.", + "saveFailed": "Přepis nelze uložit. Zkuste to znovu.", + "savePending": "Ukládání trvá déle, než se očekávalo. Stále může být dokončeno. Toto okno můžete zavřít.", + "readFailed": "Soubor titulků nelze přečíst.", + "validation": "Titulek {{cue}}, řádek {{line}}: {{reason}}", + "errors": { + "empty": "Soubor neobsahuje titulky.", + "index": "Očekává se kladné číselné pořadí titulku.", + "timestamp": "Očekává se HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "Konec musí být později než začátek.", + "bounds": "Titulek překračuje délku média nebo délka není známá.", + "markup": "Podporován je prostý text a značky b, i, u.", + "overlap": "Titulky musí být seřazené a nesmí se překrývat.", + "text": "Titulek musí obsahovat text." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/de/settings.json b/src/i18n/locales/de/settings.json index 61707f28eb..ede33218b8 100644 --- a/src/i18n/locales/de/settings.json +++ b/src/i18n/locales/de/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Kein Transkript für diesen Clip — öffne die Asset-Karte und erzeuge es neu.", "editingHintDev": "Doppelklick auf ein Wort korrigiert es, Backspace schneidet es aus dem Film, Tippen zwischen zwei Wörtern fügt eines hinzu.", "noAudio": "Dieses Medium hat keine Audiospur", - "blankedWord": "geleert" + "blankedWord": "geleert", + "srt": { + "title": "SRT importieren", + "import": "Importieren", + "replace": "Transkript ersetzen", + "target": "Zielmedium", + "chooseTarget": "Aufnahme oder Sprachaufnahme wählen", + "file": "SRT-Datei", + "busy": "Transkription läuft", + "estimated": "Wortzeiten importierter Untertitel sind geschätzt. Worthervorhebung und wortbasierte Schnitte können ungenau sein.", + "replaceWarning": "Transkript für {{name}} ersetzen? Dies kann rückgängig gemacht werden.", + "stale": "Projekt, Medium oder Transkript wurde geändert oder eine Transkription gestartet. Importdialog erneut öffnen.", + "saveFailed": "Transkript konnte nicht gespeichert werden. Erneut versuchen.", + "savePending": "Das Speichern dauert länger als erwartet und kann noch abgeschlossen werden. Du kannst diesen Dialog schließen.", + "readFailed": "Untertiteldatei konnte nicht gelesen werden.", + "validation": "Untertitel {{cue}}, Zeile {{line}}: {{reason}}", + "errors": { + "empty": "Die Datei enthält keine Untertitel.", + "index": "Eine positive numerische Untertitelnummer wird erwartet.", + "timestamp": "Erwartet: HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "Die Endzeit muss nach der Startzeit liegen.", + "bounds": "Der Untertitel überschreitet die Mediendauer oder die Dauer ist unbekannt.", + "markup": "Nur Klartext und die Formatierungstags b, i, u werden unterstützt.", + "overlap": "Untertitel müssen geordnet sein und dürfen sich nicht überschneiden.", + "text": "Der Untertitel muss Text enthalten." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/en/settings.json b/src/i18n/locales/en/settings.json index 122ff48143..1329133c97 100644 --- a/src/i18n/locales/en/settings.json +++ b/src/i18n/locales/en/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "No transcript for this clip — open the asset card and regenerate.", "editingHintDev": "Double-click a word to correct it, Backspace cuts it from the film, type between two words to add one.", "noAudio": "This media has no audio track", - "blankedWord": "blanked" + "blankedWord": "blanked", + "srt": { + "title": "Import SRT", + "import": "Import", + "replace": "Replace transcript", + "target": "Target media", + "chooseTarget": "Choose a recording or voiceover", + "file": "SRT file", + "busy": "Transcribing", + "estimated": "Imported subtitle word timings are estimated. Word highlighting and word-based cuts may be approximate.", + "replaceWarning": "Replace the existing transcript for {{name}}? This can be undone.", + "stale": "The project, media or transcript changed, or transcription started. Close and reopen the import dialog.", + "saveFailed": "Could not save the transcript. Try again.", + "savePending": "Saving is taking longer than expected. It may still finish. You can close this dialog.", + "readFailed": "Could not read the subtitle file.", + "validation": "Cue {{cue}}, line {{line}}: {{reason}}", + "errors": { + "empty": "The file contains no subtitles.", + "index": "Expected a positive numeric cue index.", + "timestamp": "Expected HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "The end time must be after the start time.", + "bounds": "The subtitle exceeds the source media duration, or its duration is unknown.", + "markup": "Only plain text and b, i, u formatting tags are supported.", + "overlap": "Cues must be ordered and must not overlap.", + "text": "The cue must contain text." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/es/settings.json b/src/i18n/locales/es/settings.json index 7f6ae74928..84e9181f2c 100644 --- a/src/i18n/locales/es/settings.json +++ b/src/i18n/locales/es/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Este clip no tiene transcripción: abre la ficha del recurso y vuelve a generarla.", "editingHintDev": "Haz doble clic en una palabra para corregirla, Retroceso la corta del vídeo, escribe entre dos palabras para añadir una.", "noAudio": "Este medio no tiene pista de audio", - "blankedWord": "vaciada" + "blankedWord": "vaciada", + "srt": { + "title": "Importar SRT", + "import": "Importar", + "replace": "Reemplazar transcripción", + "target": "Medio de destino", + "chooseTarget": "Elige una grabación o voz en off", + "file": "Archivo SRT", + "busy": "Transcribiendo", + "estimated": "Los tiempos de palabras importadas son estimados. El resaltado y los cortes por palabras pueden ser imprecisos.", + "replaceWarning": "¿Reemplazar la transcripción de {{name}}? Se puede deshacer.", + "stale": "El proyecto, el medio o la transcripción cambió, o comenzó una transcripción. Vuelve a abrir la importación.", + "saveFailed": "No se pudo guardar. Inténtalo de nuevo.", + "savePending": "El guardado está tardando más de lo esperado. Aún puede completarse. Puedes cerrar este diálogo.", + "readFailed": "No se pudo leer el archivo de subtítulos.", + "validation": "Subtítulo {{cue}}, línea {{line}}: {{reason}}", + "errors": { + "empty": "El archivo no contiene subtítulos.", + "index": "Se esperaba un índice numérico positivo.", + "timestamp": "Se esperaba HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "El final debe ser posterior al inicio.", + "bounds": "El subtítulo supera la duración del medio o su duración es desconocida.", + "markup": "Solo se admiten texto plano y etiquetas b, i, u.", + "overlap": "Los subtítulos deben estar ordenados y no solaparse.", + "text": "El subtítulo debe contener texto." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/fr/settings.json b/src/i18n/locales/fr/settings.json index 8cee3e8460..9fb3b0b920 100644 --- a/src/i18n/locales/fr/settings.json +++ b/src/i18n/locales/fr/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Aucune transcription pour ce clip — ouvrez la fiche du média et relancez la génération.", "editingHintDev": "Double-cliquez sur un mot pour le corriger, Retour arrière le coupe du film, tapez entre deux mots pour en ajouter un.", "noAudio": "Ce média n'a pas de piste audio", - "blankedWord": "vidé" + "blankedWord": "vidé", + "srt": { + "title": "Importer un SRT", + "import": "Importer", + "replace": "Remplacer la transcription", + "target": "Média cible", + "chooseTarget": "Choisir un enregistrement ou une voix off", + "file": "Fichier SRT", + "busy": "Transcription en cours", + "estimated": "Les temps des mots importés sont estimés. Le surlignage et les coupes par mot peuvent être approximatifs.", + "replaceWarning": "Remplacer la transcription de {{name}} ? Cette action peut être annulée.", + "stale": "Le projet, le média ou la transcription a changé, ou une transcription a démarré. Rouvrez la fenêtre d’import.", + "saveFailed": "Impossible d’enregistrer la transcription. Réessayez.", + "savePending": "L’enregistrement prend plus de temps que prévu. Il peut encore se terminer. Vous pouvez fermer cette fenêtre.", + "readFailed": "Impossible de lire le fichier de sous-titres.", + "validation": "Sous-titre {{cue}}, ligne {{line}} : {{reason}}", + "errors": { + "empty": "Le fichier ne contient aucun sous-titre.", + "index": "Un numéro de sous-titre positif est attendu.", + "timestamp": "Format attendu : HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "La fin doit être après le début.", + "bounds": "Le sous-titre dépasse la durée du média, ou sa durée est inconnue.", + "markup": "Seuls le texte brut et les balises b, i, u sont pris en charge.", + "overlap": "Les sous-titres doivent être ordonnés sans chevauchement.", + "text": "Le sous-titre doit contenir du texte." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/it/settings.json b/src/i18n/locales/it/settings.json index 977040db8d..796dec86d4 100644 --- a/src/i18n/locales/it/settings.json +++ b/src/i18n/locales/it/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Nessuna trascrizione per questo clip: apri la scheda della risorsa e rigenerala.", "editingHintDev": "Fai doppio clic su una parola per correggerla, Backspace la taglia dal video, scrivi tra due parole per aggiungerne una.", "noAudio": "Questo contenuto non ha una traccia audio", - "blankedWord": "svuotata" + "blankedWord": "svuotata", + "srt": { + "title": "Importa SRT", + "import": "Importa", + "replace": "Sostituisci trascrizione", + "target": "Media di destinazione", + "chooseTarget": "Scegli una registrazione o voce fuori campo", + "file": "File SRT", + "busy": "Trascrizione in corso", + "estimated": "I tempi delle parole importate sono stimati. Evidenziazione e tagli per parola possono essere approssimativi.", + "replaceWarning": "Sostituire la trascrizione di {{name}}? Puoi annullare questa azione.", + "stale": "Il progetto, il media o la trascrizione è cambiato, oppure è iniziata una trascrizione. Riapri l’importazione.", + "saveFailed": "Impossibile salvare la trascrizione. Riprova.", + "savePending": "Il salvataggio sta richiedendo più tempo del previsto. Potrebbe ancora completarsi. Puoi chiudere questa finestra.", + "readFailed": "Impossibile leggere il file dei sottotitoli.", + "validation": "Sottotitolo {{cue}}, riga {{line}}: {{reason}}", + "errors": { + "empty": "Il file non contiene sottotitoli.", + "index": "È richiesto un indice numerico positivo.", + "timestamp": "Formato richiesto: HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "La fine deve essere successiva all’inizio.", + "bounds": "Il sottotitolo supera la durata del media o la durata è sconosciuta.", + "markup": "Sono supportati solo testo semplice e tag b, i, u.", + "overlap": "I sottotitoli devono essere ordinati e non sovrapporsi.", + "text": "Il sottotitolo deve contenere testo." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/ja-JP/settings.json b/src/i18n/locales/ja-JP/settings.json index ec739e70ee..e929b804ec 100644 --- a/src/i18n/locales/ja-JP/settings.json +++ b/src/i18n/locales/ja-JP/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "このクリップには文字起こしがありません。アセットカードを開いて再生成してください。", "editingHintDev": "ダブルクリックで単語を修正、Backspace で映像からカット、2つの単語の間に入力して新しい単語を追加。", "noAudio": "このメディアには音声トラックがありません", - "blankedWord": "空欄" + "blankedWord": "空欄", + "srt": { + "title": "SRTをインポート", + "import": "インポート", + "replace": "文字起こしを置換", + "target": "対象メディア", + "chooseTarget": "録画またはナレーションを選択", + "file": "SRTファイル", + "busy": "文字起こし中", + "estimated": "インポートした字幕の単語時刻は推定値です。単語の強調表示や単語単位のカットは正確でない場合があります。", + "replaceWarning": "{{name}}の文字起こしを置き換えますか?元に戻せます。", + "stale": "プロジェクト、メディア、文字起こしが変更されたか、文字起こしが開始されました。インポート画面を開き直してください。", + "saveFailed": "文字起こしを保存できませんでした。再試行してください。", + "savePending": "保存に予想以上の時間がかかっています。まだ完了する可能性があります。このダイアログは閉じられます。", + "readFailed": "字幕ファイルを読み込めませんでした。", + "validation": "字幕{{cue}}、行{{line}}:{{reason}}", + "errors": { + "empty": "ファイルに字幕がありません。", + "index": "字幕番号は正の整数で指定してください。", + "timestamp": "HH:MM:SS,mmm --> HH:MM:SS,mmm形式で指定してください。", + "duration": "終了時刻は開始時刻より後にしてください。", + "bounds": "字幕が元メディアの長さを超えているか、長さが不明です。", + "markup": "プレーンテキストとb、i、uタグのみ対応しています。", + "overlap": "字幕は時刻順で、重ならないようにしてください。", + "text": "字幕にテキストが必要です。" + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/ko-KR/settings.json b/src/i18n/locales/ko-KR/settings.json index 12c13cd7f4..6ad672ec23 100644 --- a/src/i18n/locales/ko-KR/settings.json +++ b/src/i18n/locales/ko-KR/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "이 클립에는 전사가 없습니다. 에셋 카드를 열고 다시 생성하세요.", "editingHintDev": "단어를 더블 클릭해 수정하고, Backspace로 영상에서 잘라내고, 두 단어 사이에 입력해 새 단어를 추가하세요.", "noAudio": "이 미디어에는 오디오 트랙이 없습니다", - "blankedWord": "비움" + "blankedWord": "비움", + "srt": { + "title": "SRT 가져오기", + "import": "가져오기", + "replace": "대본 바꾸기", + "target": "대상 미디어", + "chooseTarget": "녹화 또는 음성 해설 선택", + "file": "SRT 파일", + "busy": "대본 생성 중", + "estimated": "가져온 자막의 단어 시간은 추정값입니다. 단어 강조와 단어 단위 자르기가 부정확할 수 있습니다.", + "replaceWarning": "{{name}}의 대본을 바꾸시겠습니까? 실행 취소할 수 있습니다.", + "stale": "프로젝트, 미디어 또는 대본이 변경되었거나 대본 생성이 시작되었습니다. 가져오기 창을 다시 여세요.", + "saveFailed": "대본을 저장할 수 없습니다. 다시 시도하세요.", + "savePending": "저장이 예상보다 오래 걸리고 있습니다. 아직 완료될 수 있습니다. 이 대화 상자를 닫아도 됩니다.", + "readFailed": "자막 파일을 읽을 수 없습니다.", + "validation": "자막 {{cue}}, 줄 {{line}}: {{reason}}", + "errors": { + "empty": "파일에 자막이 없습니다.", + "index": "양의 숫자로 된 자막 번호가 필요합니다.", + "timestamp": "HH:MM:SS,mmm --> HH:MM:SS,mmm 형식이 필요합니다.", + "duration": "종료 시간은 시작 시간보다 뒤여야 합니다.", + "bounds": "자막이 원본 미디어 길이를 초과하거나 길이를 알 수 없습니다.", + "markup": "일반 텍스트와 b, i, u 태그만 지원합니다.", + "overlap": "자막은 시간순이어야 하며 겹치면 안 됩니다.", + "text": "자막에 텍스트가 있어야 합니다." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/nl/settings.json b/src/i18n/locales/nl/settings.json index 9483b1b27d..5133a5e090 100644 --- a/src/i18n/locales/nl/settings.json +++ b/src/i18n/locales/nl/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Geen transcriptie voor deze clip. Open de itemkaart en genereer opnieuw.", "editingHintDev": "Dubbelklik op een woord om het te corrigeren. Backspace knipt het uit de film. Typ tussen twee woorden om er een toe te voegen.", "noAudio": "Deze media heeft geen audiospoor", - "blankedWord": "weggelaten" + "blankedWord": "weggelaten", + "srt": { + "title": "SRT importeren", + "import": "Importeren", + "replace": "Transcriptie vervangen", + "target": "Doelmedia", + "chooseTarget": "Kies een opname of voice-over", + "file": "SRT-bestand", + "busy": "Bezig met transcriberen", + "estimated": "Woordtijden van geïmporteerde ondertitels zijn geschat. Woordmarkering en knippen op woordniveau kunnen onnauwkeurig zijn.", + "replaceWarning": "De bestaande transcriptie voor {{name}} vervangen? Je kunt dit ongedaan maken.", + "stale": "Het project, de media of de transcriptie is gewijzigd, of er is een transcriptie gestart. Sluit dit venster en open het opnieuw.", + "saveFailed": "De transcriptie kon niet worden opgeslagen. Probeer het opnieuw.", + "savePending": "Het opslaan duurt langer dan verwacht. Het kan nog worden voltooid. Je kunt dit venster sluiten.", + "readFailed": "Het ondertitelbestand kon niet worden gelezen.", + "validation": "Ondertitel {{cue}}, regel {{line}}: {{reason}}", + "errors": { + "empty": "Het bestand bevat geen ondertitels.", + "index": "Een positief numeriek ondertitelnummer wordt verwacht.", + "timestamp": "Verwacht HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "De eindtijd moet na de begintijd liggen.", + "bounds": "De ondertitel valt buiten de duur van de bronmedia, of die duur is onbekend.", + "markup": "Alleen platte tekst en de opmaaktags b, i en u worden ondersteund.", + "overlap": "Ondertitels moeten op volgorde staan en mogen niet overlappen.", + "text": "De ondertitel moet tekst bevatten." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/pl/settings.json b/src/i18n/locales/pl/settings.json index 1e00b6bcb1..78a5ec55ee 100644 --- a/src/i18n/locales/pl/settings.json +++ b/src/i18n/locales/pl/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Brak transkrypcji dla tego klipu — otwórz kartę materiału i wygeneruj ją ponownie.", "editingHintDev": "Kliknij dwukrotnie słowo, aby je poprawić; Backspace wycina je z filmu; wpisz tekst między dwoma słowami, aby dodać nowe.", "noAudio": "Ten materiał nie ma ścieżki dźwiękowej", - "blankedWord": "wyciszone" + "blankedWord": "wyciszone", + "srt": { + "title": "Importuj SRT", + "import": "Importuj", + "replace": "Zastąp transkrypcję", + "target": "Materiał docelowy", + "chooseTarget": "Wybierz nagranie lub narrację", + "file": "Plik SRT", + "busy": "Trwa transkrypcja", + "estimated": "Czasy słów w importowanych napisach są szacunkowe. Podświetlanie słów i cięcia według słów mogą być niedokładne.", + "replaceWarning": "Zastąpić istniejącą transkrypcję dla {{name}}? Tę zmianę można cofnąć.", + "stale": "Projekt, materiał lub transkrypcja uległy zmianie albo rozpoczęto transkrypcję. Zamknij i ponownie otwórz okno importu.", + "saveFailed": "Nie udało się zapisać transkrypcji. Spróbuj ponownie.", + "savePending": "Zapisywanie trwa dłużej niż oczekiwano. Nadal może się zakończyć. Możesz zamknąć to okno.", + "readFailed": "Nie udało się odczytać pliku napisów.", + "validation": "Napis {{cue}}, wiersz {{line}}: {{reason}}", + "errors": { + "empty": "Plik nie zawiera napisów.", + "index": "Oczekiwano dodatniego numeru napisu.", + "timestamp": "Oczekiwano HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "Czas końcowy musi być późniejszy niż początkowy.", + "bounds": "Napis wykracza poza czas trwania materiału źródłowego lub czas ten jest nieznany.", + "markup": "Obsługiwane są tylko zwykły tekst i znaczniki formatowania b, i, u.", + "overlap": "Napisy muszą być uporządkowane i nie mogą się nakładać.", + "text": "Napis musi zawierać tekst." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/pt-BR/settings.json b/src/i18n/locales/pt-BR/settings.json index 65f8c2761a..93ebdc8a61 100644 --- a/src/i18n/locales/pt-BR/settings.json +++ b/src/i18n/locales/pt-BR/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Sem transcrição para este clipe — abra o cartão do recurso e gere novamente.", "editingHintDev": "Clique duas vezes em uma palavra para corrigi-la, Backspace a corta do vídeo, digite entre duas palavras para adicionar uma.", "noAudio": "Esta mídia não tem faixa de áudio", - "blankedWord": "apagada" + "blankedWord": "apagada", + "srt": { + "title": "Importar SRT", + "import": "Importar", + "replace": "Substituir transcrição", + "target": "Mídia de destino", + "chooseTarget": "Escolha uma gravação ou narração", + "file": "Arquivo SRT", + "busy": "Transcrevendo", + "estimated": "Os tempos das palavras importadas são estimados. O destaque e os cortes por palavra podem ser imprecisos.", + "replaceWarning": "Substituir a transcrição de {{name}}? Esta ação pode ser desfeita.", + "stale": "O projeto, a mídia ou a transcrição mudou, ou uma transcrição foi iniciada. Reabra a importação.", + "saveFailed": "Não foi possível salvar a transcrição. Tente novamente.", + "savePending": "O salvamento está demorando mais que o esperado. Ele ainda pode ser concluído. Você pode fechar esta janela.", + "readFailed": "Não foi possível ler o arquivo de legendas.", + "validation": "Legenda {{cue}}, linha {{line}}: {{reason}}", + "errors": { + "empty": "O arquivo não contém legendas.", + "index": "Era esperado um índice numérico positivo.", + "timestamp": "Formato esperado: HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "O fim deve ser posterior ao início.", + "bounds": "A legenda excede a duração da mídia ou a duração é desconhecida.", + "markup": "Apenas texto simples e tags b, i, u são aceitos.", + "overlap": "As legendas devem estar ordenadas e não se sobrepor.", + "text": "A legenda deve conter texto." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/ru/settings.json b/src/i18n/locales/ru/settings.json index d548578b61..bd5c280b4a 100644 --- a/src/i18n/locales/ru/settings.json +++ b/src/i18n/locales/ru/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Для этого клипа нет расшифровки — откройте карточку файла и создайте её заново.", "editingHintDev": "Дважды щёлкните слово, чтобы исправить его, Backspace вырезает его из фильма, напечатайте между двумя словами, чтобы добавить одно.", "noAudio": "В этом медиафайле нет аудиодорожки", - "blankedWord": "очищено" + "blankedWord": "очищено", + "srt": { + "title": "Импорт SRT", + "import": "Импортировать", + "replace": "Заменить расшифровку", + "target": "Целевой медиафайл", + "chooseTarget": "Выберите запись или озвучку", + "file": "Файл SRT", + "busy": "Расшифровка", + "estimated": "Время импортированных слов приблизительное. Подсветка и обрезка по словам могут быть неточными.", + "replaceWarning": "Заменить расшифровку для {{name}}? Это действие можно отменить.", + "stale": "Проект, медиафайл или расшифровка изменились либо начата расшифровка. Откройте импорт заново.", + "saveFailed": "Не удалось сохранить расшифровку. Повторите попытку.", + "savePending": "Сохранение занимает больше времени, чем ожидалось. Оно ещё может завершиться. Вы можете закрыть это окно.", + "readFailed": "Не удалось прочитать файл субтитров.", + "validation": "Субтитр {{cue}}, строка {{line}}: {{reason}}", + "errors": { + "empty": "В файле нет субтитров.", + "index": "Ожидается положительный числовой номер субтитра.", + "timestamp": "Ожидается HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "Время окончания должно быть позже начала.", + "bounds": "Субтитр выходит за длительность медиафайла либо длительность неизвестна.", + "markup": "Поддерживаются только обычный текст и теги b, i, u.", + "overlap": "Субтитры должны идти по порядку и не пересекаться.", + "text": "Субтитр должен содержать текст." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/tr/settings.json b/src/i18n/locales/tr/settings.json index 26842ec8a0..3f86ee9d2e 100644 --- a/src/i18n/locales/tr/settings.json +++ b/src/i18n/locales/tr/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Bu klip için döküm yok — medya kartını açıp yeniden oluşturun.", "editingHintDev": "Bir kelimeye çift tıklayarak düzeltin, Backspace onu videodan keser, iki kelimenin arasına yazarak yeni kelime ekleyin.", "noAudio": "Bu medyada ses parçası yok", - "blankedWord": "boşaltıldı" + "blankedWord": "boşaltıldı", + "srt": { + "title": "SRT içe aktar", + "import": "İçe aktar", + "replace": "Dökümü değiştir", + "target": "Hedef medya", + "chooseTarget": "Bir kayıt veya seslendirme seçin", + "file": "SRT dosyası", + "busy": "Döküm hazırlanıyor", + "estimated": "İçe aktarılan sözcük zamanları tahminidir. Sözcük vurguları ve sözcük tabanlı kesimler kesin olmayabilir.", + "replaceWarning": "{{name}} dökümü değiştirilsin mi? Bu işlem geri alınabilir.", + "stale": "Proje, medya veya döküm değişti ya da döküm başladı. İçe aktarma penceresini yeniden açın.", + "saveFailed": "Döküm kaydedilemedi. Yeniden deneyin.", + "savePending": "Kaydetme beklenenden uzun sürüyor. Yine de tamamlanabilir. Bu iletişim kutusunu kapatabilirsiniz.", + "readFailed": "Altyazı dosyası okunamadı.", + "validation": "Altyazı {{cue}}, satır {{line}}: {{reason}}", + "errors": { + "empty": "Dosyada altyazı yok.", + "index": "Pozitif sayısal altyazı numarası bekleniyor.", + "timestamp": "HH:MM:SS,mmm --> HH:MM:SS,mmm biçimi bekleniyor.", + "duration": "Bitiş zamanı başlangıçtan sonra olmalıdır.", + "bounds": "Altyazı medya süresini aşıyor veya süre bilinmiyor.", + "markup": "Yalnızca düz metin ve b, i, u etiketleri desteklenir.", + "overlap": "Altyazılar sıralı olmalı ve çakışmamalıdır.", + "text": "Altyazı metin içermelidir." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/vi/settings.json b/src/i18n/locales/vi/settings.json index ff225df50d..ac0157196b 100644 --- a/src/i18n/locales/vi/settings.json +++ b/src/i18n/locales/vi/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "Clip này chưa có bản chép lời — mở thẻ tài nguyên và tạo lại.", "editingHintDev": "Nhấp đúp vào một từ để sửa nó, Backspace cắt nó khỏi video, gõ giữa hai từ để thêm một từ mới.", "noAudio": "Media này không có bản âm thanh", - "blankedWord": "đã xoá" + "blankedWord": "đã xoá", + "srt": { + "title": "Nhập SRT", + "import": "Nhập", + "replace": "Thay bản chép lời", + "target": "Tệp phương tiện đích", + "chooseTarget": "Chọn bản ghi hoặc lời thuyết minh", + "file": "Tệp SRT", + "busy": "Đang chép lời", + "estimated": "Thời gian của từng từ được nhập là ước tính. Tô sáng và cắt theo từ có thể không chính xác.", + "replaceWarning": "Thay bản chép lời của {{name}}? Có thể hoàn tác thao tác này.", + "stale": "Dự án, phương tiện hoặc bản chép lời đã thay đổi, hoặc quá trình chép lời đã bắt đầu. Hãy mở lại cửa sổ nhập.", + "saveFailed": "Không thể lưu bản chép lời. Hãy thử lại.", + "savePending": "Quá trình lưu mất nhiều thời gian hơn dự kiến và vẫn có thể hoàn tất. Bạn có thể đóng hộp thoại này.", + "readFailed": "Không thể đọc tệp phụ đề.", + "validation": "Phụ đề {{cue}}, dòng {{line}}: {{reason}}", + "errors": { + "empty": "Tệp không chứa phụ đề.", + "index": "Cần số thứ tự phụ đề là số nguyên dương.", + "timestamp": "Cần định dạng HH:MM:SS,mmm --> HH:MM:SS,mmm.", + "duration": "Thời điểm kết thúc phải sau thời điểm bắt đầu.", + "bounds": "Phụ đề vượt quá thời lượng nguồn hoặc chưa biết thời lượng.", + "markup": "Chỉ hỗ trợ văn bản thuần và thẻ b, i, u.", + "overlap": "Phụ đề phải đúng thứ tự và không chồng lấn.", + "text": "Phụ đề phải có nội dung." + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/zh-CN/settings.json b/src/i18n/locales/zh-CN/settings.json index 47a62d2ff3..f642c9efc2 100644 --- a/src/i18n/locales/zh-CN/settings.json +++ b/src/i18n/locales/zh-CN/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "该片段没有转录 — 请打开素材卡片并重新生成。", "editingHintDev": "双击单词即可修正,Backspace 将其从影片中剪掉,在两个单词之间输入即可添加新词。", "noAudio": "此媒体没有音频轨道", - "blankedWord": "已清空" + "blankedWord": "已清空", + "srt": { + "title": "导入 SRT", + "import": "导入", + "replace": "替换转录", + "target": "目标媒体", + "chooseTarget": "选择录制或配音媒体", + "file": "SRT 文件", + "busy": "正在转录", + "estimated": "导入字幕的词级时间为估算值,逐词高亮和按词裁剪可能不精确。", + "replaceWarning": "替换 {{name}} 的现有转录?此操作可以撤销。", + "stale": "项目、媒体或转录已更改,或转录任务已开始。请关闭并重新打开导入窗口。", + "saveFailed": "无法保存转录,请重试。", + "savePending": "保存时间超出预期,仍可能完成。你可以关闭此对话框。", + "readFailed": "无法读取字幕文件。", + "validation": "第 {{cue}} 条字幕,第 {{line}} 行:{{reason}}", + "errors": { + "empty": "文件中没有字幕。", + "index": "字幕序号必须是正整数。", + "timestamp": "时间格式应为 HH:MM:SS,mmm --> HH:MM:SS,mmm。", + "duration": "结束时间必须晚于开始时间。", + "bounds": "字幕超过原始媒体时长,或媒体时长未知。", + "markup": "仅支持纯文本和 b、i、u 格式标签。", + "overlap": "字幕必须按时间排序,且不能重叠。", + "text": "字幕内容不能为空。" + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/i18n/locales/zh-TW/settings.json b/src/i18n/locales/zh-TW/settings.json index 9725a48f69..c365930e2f 100644 --- a/src/i18n/locales/zh-TW/settings.json +++ b/src/i18n/locales/zh-TW/settings.json @@ -193,7 +193,33 @@ "noClipTranscript": "此片段沒有逐字稿 — 請開啟素材卡片並重新產生。", "editingHintDev": "雙擊單字即可修正,Backspace 將其從影片中剪掉,在兩個單字之間輸入即可新增新詞。", "noAudio": "此媒體沒有音訊軌道", - "blankedWord": "已清空" + "blankedWord": "已清空", + "srt": { + "title": "匯入 SRT", + "import": "匯入", + "replace": "取代轉錄", + "target": "目標媒體", + "chooseTarget": "選擇錄製或配音媒體", + "file": "SRT 檔案", + "busy": "正在轉錄", + "estimated": "匯入字幕的逐字時間為估計值,逐字反白和按字裁剪可能不精確。", + "replaceWarning": "取代 {{name}} 的現有轉錄?此操作可以復原。", + "stale": "專案、媒體或轉錄已變更,或轉錄工作已開始。請關閉並重新開啟匯入視窗。", + "saveFailed": "無法儲存轉錄,請重試。", + "savePending": "儲存時間超出預期,仍可能完成。你可以關閉此對話框。", + "readFailed": "無法讀取字幕檔案。", + "validation": "第 {{cue}} 條字幕,第 {{line}} 行:{{reason}}", + "errors": { + "empty": "檔案中沒有字幕。", + "index": "字幕序號必須是正整數。", + "timestamp": "時間格式應為 HH:MM:SS,mmm --> HH:MM:SS,mmm。", + "duration": "結束時間必須晚於開始時間。", + "bounds": "字幕超過原始媒體長度,或媒體長度未知。", + "markup": "僅支援純文字和 b、i、u 格式標籤。", + "overlap": "字幕必須按時間排序,且不能重疊。", + "text": "字幕內容不能為空。" + } + } }, "exportFormat": { "mp4": "MP4", diff --git a/src/lib/ai-edition/captions/cues.ts b/src/lib/ai-edition/captions/cues.ts index bde765a465..31f374494e 100644 --- a/src/lib/ai-edition/captions/cues.ts +++ b/src/lib/ai-edition/captions/cues.ts @@ -103,6 +103,32 @@ export function captionLinesForAsset( settings: CaptionSettings, translations: CaptionTranslations, ): CaptionSegment[] { + // External cues are authored boundaries, including intentional repeated lines. + if (transcript.importSource?.format === "srt") { + return transcript.segments.flatMap((segment) => { + const isolated = { + ...transcript, + importSource: undefined, + segments: [segment], + words: transcript.words.filter((word) => segment.wordIds.includes(word.id)), + }; + const stream = + settings.language === null + ? originalWordStream(isolated) + : translatedWordStream(isolated, translations, settings.language); + return groupTimedCaptionWordsIntoLines( + stream, + settings.minWordsPerLine, + settings.maxWordsPerLine, + ) + .map((line) => ({ + ...line, + startSec: Math.max(segment.startSec, line.startSec), + endSec: Math.min(segment.endSec, line.endSec), + })) + .filter((line) => line.endSec > line.startSec); + }); + } const minWords = settings.minWordsPerLine; const maxWords = settings.maxWordsPerLine; diff --git a/src/lib/ai-edition/captions/translations.ts b/src/lib/ai-edition/captions/translations.ts index 07abd1efbc..c0f8b07448 100644 --- a/src/lib/ai-edition/captions/translations.ts +++ b/src/lib/ai-edition/captions/translations.ts @@ -200,7 +200,10 @@ export function captionTranslationUnits(transcript: AxcutTranscript): CaptionTra continue; } - if (segment.startSec - current.endSec >= UNIT_BREAK_GAP_SEC) { + if ( + transcript.importSource?.format === "srt" || + segment.startSec - current.endSec >= UNIT_BREAK_GAP_SEC + ) { flush(); current = { id: unitKey(segment.id), diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.ts index e9bf15f1f8..6c1a4589e2 100644 --- a/src/lib/ai-edition/schema/index.ts +++ b/src/lib/ai-edition/schema/index.ts @@ -109,6 +109,9 @@ export const transcriptSegmentSchema = z }); export const transcriptSchema = z.object({ + importSource: z + .object({ format: z.literal("srt"), fileName: z.string(), wordTiming: z.literal("estimated") }) + .optional(), assetId: z.string().min(1), language: z.string().min(1), sourceDslPath: z.string().optional(), diff --git a/src/lib/ai-edition/store/documentWriteAudit.test.ts b/src/lib/ai-edition/store/documentWriteAudit.test.ts index a27d74ef17..12dedbb01a 100644 --- a/src/lib/ai-edition/store/documentWriteAudit.test.ts +++ b/src/lib/ai-edition/store/documentWriteAudit.test.ts @@ -111,6 +111,9 @@ const WRITER_NAMES = { // --------------------------------------------------------------------------- const DECLARED: WritePath[] = [ + // A confirmed SRT import replaces one asset transcript in one undoable edit. + w("src/components/ai-edition/ImportSrtDialog.tsx", "operation", "save", "gesture"), + // Dropping the legacy auto-caption annotations is a button in the captions pane. w( "src/components/ai-edition/CaptionsPane.tsx", diff --git a/src/lib/ai-edition/store/projectStore.ts b/src/lib/ai-edition/store/projectStore.ts index e884d473c6..b0370d5c07 100644 --- a/src/lib/ai-edition/store/projectStore.ts +++ b/src/lib/ai-edition/store/projectStore.ts @@ -74,10 +74,10 @@ export function waitForDocumentSaves( * here as there: the write may still land, so treat the document as unknown and * keep whatever state lets a later attempt retry. */ -export async function saveWithDeadline( - save: Promise, +export async function saveWithDeadline( + save: Promise, timeoutMs: number = DOCUMENT_SAVES_WAIT_TIMEOUT_MS, -): Promise { +): Promise { let timer: ReturnType | undefined; const deadline = new Promise<"timeout">((resolve) => { timer = setTimeout(() => resolve("timeout"), timeoutMs); diff --git a/src/lib/ai-edition/store/transcriptImport.test.ts b/src/lib/ai-edition/store/transcriptImport.test.ts new file mode 100644 index 0000000000..2bb12fa3dd --- /dev/null +++ b/src/lib/ai-edition/store/transcriptImport.test.ts @@ -0,0 +1,69 @@ +import { expect, it, vi } from "vitest"; +import { + runTranscriptImport, + transcriptImportPending, + waitForProjectTranscriptImports, + waitForTranscriptImport, +} from "./transcriptImport"; + +it("holds the asset reservation until save settles, releasing failures too", async () => { + let finish!: () => void; + const work = runTranscriptImport( + "p", + "a", + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + expect(transcriptImportPending("p", "a")).toBe(true); + expect(transcriptImportPending("other", "a")).toBe(false); + let released = false; + const wait = waitForTranscriptImport("p", "a").then(() => { + released = true; + }); + await Promise.resolve(); + expect(released).toBe(false); + finish(); + await work; + await wait; + expect(released).toBe(true); + expect(transcriptImportPending("p", "a")).toBe(false); + await expect( + runTranscriptImport("p", "a", async () => { + throw new Error("save"); + }), + ).rejects.toThrow("save"); + expect(transcriptImportPending("p", "a")).toBe(false); +}); + +it.each([ + false, + true, +])("cancels a project wait without releasing the import reservation (already aborted: %s)", async (alreadyAborted) => { + let finish!: () => void; + const work = runTranscriptImport( + "cancel_project", + "asset", + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + const controller = new AbortController(); + if (alreadyAborted) controller.abort(); + let waiterSettled = false; + const wait = waitForProjectTranscriptImports("cancel_project", controller.signal).then(() => { + waiterSettled = true; + }); + controller.abort(); + try { + await vi.waitFor(() => expect(waiterSettled).toBe(true), { timeout: 100 }); + expect(transcriptImportPending("cancel_project", "asset")).toBe(true); + } finally { + finish(); + await work; + await wait; + } + expect(transcriptImportPending("cancel_project", "asset")).toBe(false); +}); diff --git a/src/lib/ai-edition/store/transcriptImport.ts b/src/lib/ai-edition/store/transcriptImport.ts new file mode 100644 index 0000000000..8fc4c725bd --- /dev/null +++ b/src/lib/ai-edition/store/transcriptImport.ts @@ -0,0 +1,63 @@ +// Keep the automatic speech queue from starting while an imported transcript is saving. +// Scoped to project + asset so an old project's disk write cannot block a new project. +const pending = new Map>>(); +export function transcriptImportPending(projectId: string, assetId: string): boolean { + return pending.get(projectId)?.has(assetId) ?? false; +} +export async function waitForTranscriptImport(projectId: string, assetId: string): Promise { + await pending.get(projectId)?.get(assetId); +} +export function projectTranscriptImportPending(projectId: string): boolean { + return (pending.get(projectId)?.size ?? 0) > 0; +} + +/** + * Wait before reading a whole-document snapshot, including imports on other assets. + * Aborting releases this waiter only; the import retains its reservation until its save settles. + */ +export async function waitForProjectTranscriptImports( + projectId: string, + signal?: AbortSignal, +): Promise { + while (!signal?.aborted && pending.get(projectId)?.size) { + const imports = Promise.all(pending.get(projectId)?.values() ?? []); + if (!signal) { + await imports; + continue; + } + await new Promise((resolve) => { + const settle = () => { + signal.removeEventListener("abort", settle); + resolve(); + }; + signal.addEventListener("abort", settle, { once: true }); + void imports.then(settle); + }); + } +} +export async function runTranscriptImport( + projectId: string, + assetId: string, + save: () => Promise, +): Promise { + let release!: () => void; + const done = new Promise((resolve) => { + release = resolve; + }); + let assets = pending.get(projectId); + if (!assets) { + assets = new Map(); + pending.set(projectId, assets); + } + if (assets.has(assetId)) throw new Error("Transcript import already saving"); + const predecessors = [...assets.values()]; + assets.set(assetId, done); + try { + if (predecessors.length) await Promise.all(predecessors); + return await save(); + } finally { + assets.delete(assetId); + if (!assets.size) pending.delete(projectId); + release(); + } +} diff --git a/src/lib/ai-edition/store/transcriptionStore.test.ts b/src/lib/ai-edition/store/transcriptionStore.test.ts index eeca60a6e4..e33bc03fb8 100644 --- a/src/lib/ai-edition/store/transcriptionStore.test.ts +++ b/src/lib/ai-edition/store/transcriptionStore.test.ts @@ -1,9 +1,11 @@ // @vitest-environment jsdom import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { toastText } from "@/i18n/toastText"; +import { withTranscript } from "../document/transcript"; import type { AxcutDocument, AxcutTranscript } from "../schema"; import { answerMcpHostRequest } from "./mcpDocumentHost"; import { useProjectStore } from "./projectStore"; +import { runTranscriptImport, transcriptImportPending } from "./transcriptImport"; import { useTranscriptionStore, whenTranscriptionIdle } from "./transcriptionStore"; const bridgeMocks = vi.hoisted(() => ({ @@ -529,4 +531,111 @@ describe("useTranscriptionStore", () => { expect(useProjectStore.getState().document?.transcripts).toHaveLength(1); }); + + it.each([ + "transcript", + "permanent failure", + ] as const)("starts a new project's queue while an old %s waits on a hung import", async (result) => { + loadDocument(makeDoc(["a", "b"])); + const engine = deferred(); + const disk = deferred(); + transcribeMocks.transcribeAsset.mockImplementation( + async (_document: AxcutDocument, assetId: string) => { + if (assetId === "b") { + await engine.promise; + if (result === "permanent failure") + throw new Error("No audio track found in this video."); + } + return transcriptFor(assetId); + }, + ); + bridgeMocks.save.mockImplementationOnce(async (document: AxcutDocument) => { + await disk.promise; + return { success: true, document }; + }); + const imported = runTranscriptImport("proj_1", "a", () => + useProjectStore + .getState() + .saveDocument(withTranscript(useProjectStore.getState().document!, transcriptFor("a")), { + history: true, + }), + ); + try { + useTranscriptionStore.getState().sync(useProjectStore.getState().document); + await vi.waitFor(() => + expect(transcribeMocks.transcribeAsset).toHaveBeenCalledWith( + expect.anything(), + "b", + expect.anything(), + ), + ); + engine.release(); + // Let B finish inference and reach the project import barrier. + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(bridgeMocks.save).toHaveBeenCalledTimes(1); + useProjectStore.getState().clear(); + const other = makeDoc(["c"], "proj_2"); + loadDocument(other); + useTranscriptionStore.getState().sync(other); + await vi.waitFor( + () => + expect(transcribeMocks.transcribeAsset).toHaveBeenCalledWith( + expect.objectContaining({ project: expect.objectContaining({ id: "proj_2" }) }), + "c", + expect.anything(), + ), + { timeout: 200 }, + ); + await whenTranscriptionIdle(); + expect(useProjectStore.getState().document?.transcripts.map((t) => t.assetId)).toEqual(["c"]); + expect(transcriptImportPending("proj_1", "a")).toBe(true); + } finally { + engine.release(); + disk.release(); + await imported; + await whenTranscriptionIdle(); + } + }); + + it("retains imported A when unrelated B finishes during A's deferred save", async () => { + loadDocument(makeDoc(["a", "b"])); + delete (window as unknown as { electronAPI?: unknown }).electronAPI; + const engine = deferred(); + const disk = deferred(); + transcribeMocks.transcribeAsset.mockImplementation(async () => { + await engine.promise; + return transcriptFor("b"); + }); + const b = useTranscriptionStore.getState().request("b"); + bridgeMocks.save.mockImplementationOnce(async (document: AxcutDocument) => { + await disk.promise; + return { success: true, document }; + }); + const imported = runTranscriptImport("proj_1", "a", () => + useProjectStore + .getState() + .saveDocument(withTranscript(useProjectStore.getState().document!, transcriptFor("a")), { + history: true, + }), + ); + engine.release(); + await new Promise((resolve) => setTimeout(resolve, 0)); + const writesBeforeImportSettled = bridgeMocks.save.mock.calls.length; + disk.release(); + await imported; + await b; + expect(writesBeforeImportSettled).toBe(1); + expect( + useProjectStore + .getState() + .document?.transcripts.map((t) => t.assetId) + .sort(), + ).toEqual(["a", "b"]); + expect( + bridgeMocks.save.mock.calls + .at(-1)?.[0] + .transcripts.map((t: AxcutTranscript) => t.assetId) + .sort(), + ).toEqual(["a", "b"]); + }); }); diff --git a/src/lib/ai-edition/store/transcriptionStore.ts b/src/lib/ai-edition/store/transcriptionStore.ts index 341bd72f80..b6abb4a469 100644 --- a/src/lib/ai-edition/store/transcriptionStore.ts +++ b/src/lib/ai-edition/store/transcriptionStore.ts @@ -47,6 +47,12 @@ import { withTranscriptionFailure, } from "../transcription/status"; import { useProjectStore } from "./projectStore"; +import { + projectTranscriptImportPending, + transcriptImportPending, + waitForProjectTranscriptImports, + waitForTranscriptImport, +} from "./transcriptImport"; export interface TranscriptionJob { status: "queued" | "running" | "failed"; @@ -139,7 +145,7 @@ export const useTranscriptionStore = create((set, get) => ({ if (hasLocalSttEngine()) { for (const asset of document.assets) { - if (jobs[asset.id]) continue; + if (jobs[asset.id] || transcriptImportPending(document.project.id, asset.id)) continue; if (findAssetTranscript(document, asset.id)) continue; if (asset.transcriptionFailure) continue; // Music is not speech, and finding that out costs a whole inference pass — @@ -156,7 +162,12 @@ export const useTranscriptionStore = create((set, get) => ({ } }, - request(assetId, language = "auto") { + async request(assetId, language = "auto") { + const importProject = useProjectStore.getState().document?.project.id; + if (importProject && transcriptImportPending(importProject, assetId)) { + await waitForTranscriptImport(importProject, assetId); + if (useProjectStore.getState().document?.project.id !== importProject) return; + } // A manual run can be the first thing that happens in a project (the // auto pass is off without a local engine), so adopt the loaded project // before queueing — `runJob` refuses to write into a document the queue @@ -337,8 +348,13 @@ async function persistPermanentFailure( projectId: string, assetId: string, failure: TranscriptionFailure, + signal: AbortSignal, ): Promise { - if (!isPermanentFailure(failure.kind)) return; + if (!isPermanentFailure(failure.kind) || signal.aborted) return; + // A new import can reserve between waits; recheck synchronously before reading the document. + while (!signal.aborted && projectTranscriptImportPending(projectId)) + await waitForProjectTranscriptImports(projectId, signal); + if (signal.aborted) return; const project = useProjectStore.getState(); const doc = project.document; if (!doc || doc.project.id !== projectId) return; @@ -412,6 +428,10 @@ async function runJob(assetId: string, job: TranscriptionJob): Promise { } // The user may have switched projects while whisper was working — writing // the transcript now would attach it to the document that is loaded today. + // A new import can reserve between waits; recheck synchronously before reading the document. + while (!controller.signal.aborted && projectTranscriptImportPending(projectId)) + await waitForProjectTranscriptImports(projectId, controller.signal); + if (!isCurrentRun(assetId, runId) || controller.signal.aborted) return; const current = useProjectStore.getState().document; if (!current || current.project.id !== projectId) { dropJob(assetId, runId); @@ -446,7 +466,8 @@ async function runJob(assetId: string, job: TranscriptionJob): Promise { console.warn(`[transcription] asset ${assetId} failed:`, error); patchJob(assetId, runId, { status: "failed", phase: undefined, progress: undefined, failure }); flushSettleWaiters(assetId); - await persistPermanentFailure(projectId, assetId, failure); + await persistPermanentFailure(projectId, assetId, failure, controller.signal); + if (controller.signal.aborted || !isCurrentRun(assetId, runId)) return; // A transient failure is about the ENGINE, not about this media: the model // download died, whisper-server didn't come up. Marching the rest of the // queue into the same wall would spend a full retry budget per asset and diff --git a/src/lib/ai-edition/store/useTimeline.test.ts b/src/lib/ai-edition/store/useTimeline.test.ts index 3a8433ce9f..f6541e68ef 100644 --- a/src/lib/ai-edition/store/useTimeline.test.ts +++ b/src/lib/ai-edition/store/useTimeline.test.ts @@ -7,9 +7,10 @@ import { DEFAULT_TEXT_PLATE } from "../annotations/background"; import { layoutRuns } from "../document/layout"; import { type RegionKind, readSpeedRegions } from "../document/timeline"; import type { AxcutDocument } from "../schema"; -import { axcutSchemaVersion, parseDocumentFile } from "../schema"; +import { axcutSchemaVersion, createAudioTrack, parseDocumentFile } from "../schema"; import { coalesceRegionsForRuler } from "../timeline/timelineMap"; -import { useProjectStore } from "./projectStore"; +import { useProjectStore, waitForDocumentSaves } from "./projectStore"; +import { runTranscriptImport } from "./transcriptImport"; import { clearHistory, redo, undo } from "./undo"; import { future, past } from "./undoStack"; import { useTimeline } from "./useTimeline"; @@ -243,6 +244,223 @@ describe("useTimeline.insertClipAt background duration probe", () => { }); }); +describe("useTimeline background probes during transcript imports", () => { + beforeEach(() => { + useProjectStore.getState().clear(); + for (const mock of Object.values(bridgeMocks)) mock.mockReset(); + probeVideoDurationMock.mockReset(); + probeVideoDimensionsMock.mockReset(); + probeVideoDimensionsMock.mockResolvedValue({ width: 1920, height: 1080 }); + probeAudioDurationMock.mockReset(); + probeAudioDurationMock.mockResolvedValue(null); + bridgeMocks.save.mockImplementation(async (document: AxcutDocument) => ({ + success: true, + document, + })); + }); + + afterEach(() => { + act(() => useProjectStore.getState().clear()); + vi.clearAllMocks(); + }); + + function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; + } + + async function startProbe(kind: "audio" | "dimensions" | "clip") { + const probe = deferred(); + let document = sampleDoc; + if (kind === "audio") { + document = { + ...sampleDoc, + assets: [ + ...sampleDoc.assets, + { + id: "audio_1", + kind: "audio", + label: "music.mp3", + originalPath: "/tmp/music.mp3", + cameraTrack: null, + }, + ], + audioTracks: [createAudioTrack({ assetId: "audio_1", durationSec: 0 })], + }; + probeAudioDurationMock.mockReturnValue(probe.promise); + } else if (kind === "dimensions") { + document = { ...sampleDoc, assets: [{ ...sampleDoc.assets[0], video: undefined }] }; + probeVideoDimensionsMock.mockImplementation(async () => { + await probe.promise; + return { width: 1080, height: 1920 }; + }); + } else { + document = { ...sampleDoc, assets: [{ ...sampleDoc.assets[0], durationSec: undefined }] }; + probeVideoDurationMock.mockReturnValue(probe.promise); + } + useProjectStore.setState({ projectId: "proj_test", document, status: "ready" }); + const hook = renderTimeline(); + if (kind === "clip") { + await act(async () => { + await hook.result.current.insertClipAt("asset_1", 1); + }); + } + bridgeMocks.save.mockClear(); + return probe; + } + + const importedTranscript: NonNullable = { + assetId: "asset_1", + language: "en", + words: [], + segments: [ + { + id: "srt_1", + kind: "speech", + startSec: 0, + endSec: 1, + text: "Imported subtitle", + wordIds: [], + }, + ], + importSource: { format: "srt", fileName: "captions.srt", wordTiming: "estimated" }, + }; + + it.each([ + "audio", + "dimensions", + "clip", + ] as const)("keeps the imported transcript when the %s probe resolves during its save", async (kind) => { + const probe = await startProbe(kind); + const write = deferred(); + // Model ordered native writes: a stale probe snapshot is written after the + // imported document, exactly as on the native document service's save queue. + bridgeMocks.save.mockImplementation(async (document: AxcutDocument) => { + await write.promise; + return { success: true, document }; + }); + let imported!: Promise; + await act(async () => { + imported = runTranscriptImport("proj_test", "asset_1", async () => { + await waitForDocumentSaves(); + const current = useProjectStore.getState().document!; + return useProjectStore.getState().saveDocument( + { + ...current, + transcript: importedTranscript, + transcripts: [importedTranscript], + }, + { history: true }, + ); + }); + }); + await waitFor(() => expect(bridgeMocks.save).toHaveBeenCalledTimes(1)); + await act(async () => { + probe.resolve(12.5); + }); + await act(async () => { + write.resolve(); + await imported; + }); + await waitFor(() => expect(bridgeMocks.save).toHaveBeenCalledTimes(2)); + const current = useProjectStore.getState().document; + expect(current?.transcripts).toEqual([importedTranscript]); + if (kind === "audio") expect(current?.audioTracks[0].durationSec).toBe(12.5); + if (kind === "dimensions") expect(current?.assets[0].video?.width).toBe(1080); + if (kind === "clip") expect(current?.timeline.clips[1].sourceEndSec).toBe(12.5); + }); + + it.each([ + "audio", + "dimensions", + "clip", + ] as const)("abandons the %s probe when the same project is reopened during its import wait", async (kind) => { + const probe = await startProbe(kind); + const reservation = deferred(); + const imported = runTranscriptImport("proj_test", "asset_1", () => reservation.promise); + await act(async () => { + probe.resolve(12.5); + }); + act(() => { + const document = useProjectStore.getState().document; + // Reopening the same id invalidates old callbacks even though both the + // project id and reused asset/clip ids still match the current document. + useProjectStore.getState().clear(); + useProjectStore.setState({ projectId: "proj_test", document }); + }); + await act(async () => { + reservation.resolve(); + await imported; + }); + expect(bridgeMocks.save).not.toHaveBeenCalled(); + }); + + it("keeps the audio correction when an import reserves immediately after the probe resolves", async () => { + const probe = await startProbe("audio"); + let imported!: Promise; + await act(async () => { + probe.resolve(12.5); + // The probe continuation runs first. An unconditional await of an idle + // import helper lets this reservation run before the probe snapshot save. + queueMicrotask(() => { + imported = runTranscriptImport("proj_test", "asset_1", async () => { + await waitForDocumentSaves(); + const current = useProjectStore.getState().document!; + return useProjectStore.getState().saveDocument( + { + ...current, + transcript: importedTranscript, + transcripts: [importedTranscript], + }, + { history: true }, + ); + }); + }); + }); + await act(async () => { + await imported; + }); + const current = useProjectStore.getState().document; + expect(current?.transcripts).toEqual([importedTranscript]); + expect(current?.audioTracks[0].durationSec).toBe(12.5); + expect(current?.assets.find((asset) => asset.id === "audio_1")?.durationSec).toBe(12.5); + }); + + it("waits for a reserved import before dimension backfill reads its snapshot", async () => { + const probe = await startProbe("dimensions"); + const beginImport = deferred(); + const imported = runTranscriptImport("proj_test", "asset_1", async () => { + await beginImport.promise; + await waitForDocumentSaves(); + const current = useProjectStore.getState().document!; + return useProjectStore.getState().saveDocument( + { + ...current, + transcript: importedTranscript, + transcripts: [importedTranscript], + }, + { history: true }, + ); + }); + try { + await act(async () => { + probe.resolve(12.5); + }); + expect(bridgeMocks.save).not.toHaveBeenCalled(); + } finally { + await act(async () => { + beginImport.resolve(); + await imported; + }); + } + await waitFor(() => expect(bridgeMocks.save).toHaveBeenCalledTimes(2)); + expect(useProjectStore.getState().document?.transcripts).toEqual([importedTranscript]); + }); +}); + describe("useTimeline.moveClip / duplicateClip (delegates to document/timeline.ts)", () => { const twoClipDoc: AxcutDocument = { ...sampleDoc, diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.ts index 32408cdb37..38607df46e 100644 --- a/src/lib/ai-edition/store/useTimeline.ts +++ b/src/lib/ai-edition/store/useTimeline.ts @@ -79,6 +79,10 @@ import { MAX_ZOOM_SCALE, MIN_ZOOM_SCALE } from "../timeline/zoom-scale"; import type { AutoZoomSuggestion } from "../timeline/zoom-suggestions"; import { getEditorSettings } from "./editorSettings"; import { saveWithDeadline, useProjectStore, waitForDocumentSaves } from "./projectStore"; +import { + projectTranscriptImportPending, + waitForProjectTranscriptImports, +} from "./transcriptImport"; import { currentWriteEpoch } from "./undoStack"; import { useSequentialTimelineOps } from "./useSequentialTimelineOps"; @@ -286,8 +290,9 @@ export function useTimeline() { // measured duration, camera link, auto-zoom). A cancel dropped the result while the // asset was already marked attempted, so nothing ever probed it again that session and // the take was exported with no dims. The write below re-reads the store instead, and - // the project check is the only staleness that matters. + // project and write-epoch checks discard results after navigation or undo. const originatingProjectId = document.project.id; + const originatingEpoch = currentWriteEpoch(); void (async () => { type Dims = { width: number; height: number }; const probed: Record = {}; @@ -315,9 +320,19 @@ export function useTimeline() { for (const id of Object.keys(probed)) probedAssetIdsRef.current.delete(id); return; } + // An SRT import reserves its write before saveDocument starts, so waiting + // for saves alone can still read the pre-import snapshot. Check synchronously + // when idle so an import cannot reserve between the check and snapshot save. + while (projectTranscriptImportPending(originatingProjectId)) + await waitForProjectTranscriptImports(originatingProjectId); // Re-read fresh state so a concurrent edit made while probing isn't stomped. const current = useProjectStore.getState().document; - if (!current || current.project.id !== originatingProjectId) return; + if ( + !current || + current.project.id !== originatingProjectId || + currentWriteEpoch() !== originatingEpoch + ) + return; // `history: false` — see the comment above: a backfill nobody asked for must // not become the thing the next Ctrl+Z reverses. await useProjectStore.getState().saveDocument( @@ -366,16 +381,26 @@ export function useTimeline() { // came meant a document change that re-entered this effect while asset #1 was // still awaiting found #2+ unmarked and probed them a second time. for (const a of missing) probedAudioAssetIdsRef.current.add(a.id); - let cancelled = false; + // Document changes, including the import itself, must not cancel the result. + // Navigation and undo still invalidate it through the captured project and epoch. + const originatingProjectId = document.project.id; + const originatingEpoch = currentWriteEpoch(); void (async () => { const probed: Record = {}; for (const a of missing) { const durationSec = await probeAudioDuration(toFileUrl(a.originalPath)); if (durationSec != null && durationSec > 0) probed[a.id] = durationSec; } - if (cancelled || Object.keys(probed).length === 0) return; + if (Object.keys(probed).length === 0) return; + while (projectTranscriptImportPending(originatingProjectId)) + await waitForProjectTranscriptImports(originatingProjectId); const current = useProjectStore.getState().document; - if (!current) return; + if ( + !current || + current.project.id !== originatingProjectId || + currentWriteEpoch() !== originatingEpoch + ) + return; await useProjectStore.getState().saveDocument( { ...current, @@ -391,9 +416,6 @@ export function useTimeline() { { history: false }, ); })(); - return () => { - cancelled = true; - }; }, [document]); // Every add* below anchors the new region to the clip(s) it covers before storing it. @@ -1479,6 +1501,9 @@ export function useTimeline() { // subsequent inserts use the cached value without re-probing. const probeAndCorrectClip = useCallback( async (assetId: string, clipId: string, originalPath: string) => { + const originatingProjectId = useProjectStore.getState().projectId; + const originatingEpoch = currentWriteEpoch(); + if (!originatingProjectId) return; const fileUrl = toFileUrl(originalPath); // Dims probed alongside duration — otherwise `asset.video` stays permanently unset for // most recordings (nothing else populates it), silently breaking anything that reads @@ -1487,9 +1512,16 @@ export function useTimeline() { probeVideoDuration(fileUrl), probeVideoDimensions(fileUrl), ]); + while (projectTranscriptImportPending(originatingProjectId)) + await waitForProjectTranscriptImports(originatingProjectId); const state = useProjectStore.getState(); const doc = state.document; - if (!doc) return; + if ( + !doc || + state.projectId !== originatingProjectId || + currentWriteEpoch() !== originatingEpoch + ) + return; const asset = doc.assets.find((a) => a.id === assetId); const needsDims = probedDims != null && !asset?.video; if (probedDuration == null && !needsDims) return; diff --git a/src/lib/ai-edition/transcription/fromSrt.test.ts b/src/lib/ai-edition/transcription/fromSrt.test.ts new file mode 100644 index 0000000000..9277d2fb49 --- /dev/null +++ b/src/lib/ai-edition/transcription/fromSrt.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vitest"; +import { transcriptSchema } from "../schema"; +import { SrtImportError, transcriptFromSrt } from "./fromSrt"; + +describe("SRT import", () => { + it("preserves cues and provenance through schema serialization", () => { + const t = transcriptFromSrt( + "a", + "\uFEFF1\r\n00:00:01,000 --> 00:00:02,000\r\nHello 世界\r\nnext line\r\n\r\n2\r\n00:00:02,010 --> 00:00:03,000\r\nAgain", + 4, + "captions.srt", + ); + expect(t.segments.map((s) => s.text)).toEqual(["Hello 世界\nnext line", "Again"]); + expect(t.words).toHaveLength(5); + const serialized = JSON.stringify(t); + expect(transcriptSchema.parse(JSON.parse(serialized)).importSource).toEqual({ + format: "srt", + fileName: "captions.srt", + wordTiming: "estimated", + }); + expect(t.words[0].id).not.toBe("word_1"); + }); + it.each([ + ["", "empty"], + ["1\n00:00:00,000 --> 00:00:04,001\nx", "bounds"], + ["x\n00:00:00,000 --> 00:00:01,000\nx", "index"], + ["1\n00:60:00,000 --> 00:00:01,000\nx", "timestamp"], + ["1\n00:00:00,000 -> 00:00:01,000\nx", "timestamp"], + ["1\n00:00:01,000 --> 00:00:01,000\nx", "duration"], + ["1\n00:00:00,000 --> 00:00:05,000\nx", "bounds"], + ["1\n00:00:00,000 --> 00:00:01,000\n", "markup"], + ["1\n00:00:00,000 --> 00:00:02,000\nx\n\n2\n00:00:01,000 --> 00:00:03,000\ny", "overlap"], + ["1\n00:00:00,000 --> 00:00:01,000", "text"], + ])("rejects invalid file with typed location: %s", (text, code) => { + try { + transcriptFromSrt("a", text, 4, "x.srt"); + throw new Error("accepted"); + } catch (e) { + expect(e).toBeInstanceOf(SrtImportError); + expect(e).toMatchObject({ code }); + expect((e as SrtImportError).line).toBeGreaterThan(0); + } + }); +}); diff --git a/src/lib/ai-edition/transcription/fromSrt.ts b/src/lib/ai-edition/transcription/fromSrt.ts new file mode 100644 index 0000000000..c7e4fbe12c --- /dev/null +++ b/src/lib/ai-edition/transcription/fromSrt.ts @@ -0,0 +1,82 @@ +import type { AxcutTranscript } from "../schema"; +import { transcriptFromSegments } from "./fromStt"; + +export type SrtErrorCode = + | "empty" + | "index" + | "timestamp" + | "duration" + | "bounds" + | "markup" + | "overlap" + | "text"; +export class SrtImportError extends Error { + constructor( + public readonly code: SrtErrorCode, + public readonly cue: number, + public readonly line: number, + ) { + super(`SRT ${code} (cue ${cue}, line ${line})`); + } +} + +/** Validate the whole file before returning a transcript. All times refer to source media. */ +export function transcriptFromSrt( + assetId: string, + input: string, + durationSec: number, + fileName: string, +): AxcutTranscript { + const lines = input + .replace(/^\uFEFF/, "") + .replace(/\r\n?/g, "\n") + .split("\n"); + const segments: { startSec: number; endSec: number; text: string }[] = []; + let i = 0; + const fail = (code: SrtErrorCode, line = i + 1): never => { + throw new SrtImportError(code, segments.length + 1, line); + }; + while (i < lines.length) { + if (!lines[i].trim()) { + i++; + continue; + } + if (!/^\d+$/.test(lines[i].trim()) || Number(lines[i].trim()) < 1) fail("index"); + i++; + const match = + /^(\d{2,}):([0-5]\d):([0-5]\d),(\d{3}) --> (\d{2,}):([0-5]\d):([0-5]\d),(\d{3})$/.exec( + lines[i]?.trim() ?? "", + ); + if (!match) fail("timestamp"); + const m = match!; + const startSec = Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3]) + Number(m[4]) / 1000; + const endSec = Number(m[5]) * 3600 + Number(m[6]) * 60 + Number(m[7]) + Number(m[8]) / 1000; + if (endSec <= startSec) fail("duration"); + if (!Number.isFinite(durationSec) || durationSec <= 0 || endSec > durationSec) fail("bounds"); + if (segments.length && startSec < segments[segments.length - 1].endSec) fail("overlap"); + i++; + const textLine = i + 1; + const textLines: string[] = []; + while (i < lines.length && lines[i].trim()) textLines.push(lines[i++]); + const text = textLines + .join("\n") + .replace(/<\/?(?:b|i|u)>/gi, "") + .trim(); + if (!text) fail("text", textLine); + if (/<[^>]*>|\{\\[^}]*\}/.test(text)) fail("markup", textLine); + segments.push({ startSec, endSec, text }); + } + if (!segments.length) fail("empty", 1); + const result = transcriptFromSegments(assetId, segments, "auto"); + const prefix = `srt_${crypto.randomUUID()}_`; + return { + ...result, + importSource: { format: "srt", fileName, wordTiming: "estimated" }, + segments: result.segments.map((s) => ({ + ...s, + id: prefix + s.id, + wordIds: s.wordIds.map((id) => prefix + id), + })), + words: result.words.map((w) => ({ ...w, id: prefix + w.id, segmentId: prefix + w.segmentId })), + }; +} diff --git a/src/lib/ai-edition/transcription/srtCaptions.test.ts b/src/lib/ai-edition/transcription/srtCaptions.test.ts new file mode 100644 index 0000000000..b0445d0c35 --- /dev/null +++ b/src/lib/ai-edition/transcription/srtCaptions.test.ts @@ -0,0 +1,87 @@ +import { expect, it } from "vitest"; +import { captionLinesForAsset, deriveCaptionCues } from "../captions/cues"; +import { DEFAULT_CAPTION_SETTINGS } from "../captions/settings"; +import { captionTranslationUnits } from "../captions/translations"; +import { documentSchema } from "../schema"; +import { transcriptFromSrt } from "./fromSrt"; + +it("keeps adjacent repeated SRT cues separate in captions and translation", () => { + const transcript = transcriptFromSrt( + "a", + "1\n00:00:00,000 --> 00:00:01,000\nAgain\n\n2\n00:00:01,010 --> 00:00:02,000\nAgain", + 3, + "a.srt", + ); + expect(captionLinesForAsset(transcript, DEFAULT_CAPTION_SETTINGS, {}).map((s) => s.text)).toEqual( + ["Again", "Again"], + ); + expect(captionTranslationUnits(transcript)).toHaveLength(2); +}); +it("does not extend an imported cue past its authored end even for very short cues", () => { + const transcript = transcriptFromSrt("a", "1\n00:00:01,000 --> 00:00:01,001\nHi", 2, "a.srt"); + const lines = captionLinesForAsset(transcript, DEFAULT_CAPTION_SETTINGS, {}); + expect(lines[0].startSec).toBe(1); + expect(lines[0].endSec).toBe(1.001); +}); +it("projects only the imported asset through source-trimmed and repeated clips", () => { + const transcript = transcriptFromSrt("a", "1\n00:00:01,000 --> 00:00:03,000\nHello", 4, "a.srt"); + const document = documentSchema.parse({ + schemaVersion: 9, + project: { + id: "p", + title: "P", + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }, + transcripts: [transcript], + timeline: { + clips: [ + { + id: "c1", + assetId: "a", + origin: "user", + sourceStartSec: 2, + sourceEndSec: 4, + timelineStartSec: 0, + timelineEndSec: 2, + }, + { + id: "c2", + assetId: "a", + origin: "user", + sourceStartSec: 0, + sourceEndSec: 4, + timelineStartSec: 2, + timelineEndSec: 6, + }, + { + id: "other", + assetId: "b", + origin: "user", + sourceStartSec: 0, + sourceEndSec: 4, + timelineStartSec: 6, + timelineEndSec: 10, + }, + ], + }, + }); + expect( + deriveCaptionCues(document, { ...DEFAULT_CAPTION_SETTINGS, enabled: true }, {}).map( + ({ startMs, endMs, text }) => ({ startMs, endMs, text }), + ), + ).toEqual([ + { startMs: 0, endMs: 1000, text: "Hello" }, + { startMs: 3000, endMs: 5000, text: "Hello" }, + ]); +}); +it("preserves intentional repeated words split into separate imported caption lines", () => { + const t = transcriptFromSrt("a", "1\n00:00:00,000 --> 00:00:02,000\nAgain Again", 3, "a.srt"); + expect( + captionLinesForAsset( + t, + { ...DEFAULT_CAPTION_SETTINGS, minWordsPerLine: 1, maxWordsPerLine: 1 }, + {}, + ).map((s) => s.text), + ).toEqual(["Again", "Again"]); +}); diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.ts index 010ba77084..94f5b3247f 100644 --- a/src/native/sceneDescription.test.ts +++ b/src/native/sceneDescription.test.ts @@ -20,6 +20,7 @@ import type { AxcutZoomRegion, } from "@/lib/ai-edition/schema"; import { axcutSchemaVersion } from "@/lib/ai-edition/schema"; +import { transcriptFromSrt } from "@/lib/ai-edition/transcription/fromSrt"; import { CURSOR_KIND_IDS, DEFAULT_CURSOR_THEME_ID } from "@/lib/cursor/cursorThemes"; import { DEVICE_FRAMES } from "@/lib/projectDefaults"; import { getFocusBoundsForScale } from "@/lib/zoomMath/focusUtils"; @@ -2429,6 +2430,42 @@ describe("buildSceneDescription.captions", () => { } as AxcutDocument; } + it("projects imported SRT through a timeline trim and actual speed regions for preview and export", () => { + const doc = docWithCaptions(true); + doc.transcripts = [ + transcriptFromSrt("a1", "1\n00:00:01,000 --> 00:00:05,000\nImported", 30, "captions.srt"), + ]; + doc.timeline.trimRanges = [ + { id: "cut", assetId: "a1", startSec: 2, endSec: 4, origin: "user", reason: "" }, + ]; + // speedRanges carries the document range; the speed multiplier lives in the legacy envelope. + doc.timeline.speedRanges = [{ startSec: 4, endSec: 8, reason: "" }]; + doc.legacyEditor = { + ...(doc.legacyEditor as Record), + speedRegions: [{ id: "fast", startMs: 4000, endMs: 8000, speed: 2 }], + }; + const scene = buildSceneDescription(doc); + expect( + scene.annotations.map(({ startSec, endSec, clipIndex, text }) => ({ + startSec, + endSec, + clipIndex, + text: text?.content, + })), + ).toEqual([ + { startSec: 1, endSec: 2, clipIndex: 0, text: "Imported" }, + { startSec: 4, endSec: 5, clipIndex: 1, text: "Imported" }, + ]); + expect(scene.speedRegions).toEqual([{ startSec: 4, endSec: 8, speed: 2, clipIndex: 1 }]); + // Both consumers receive source times on the same surviving clip; 4..5 plays at 2x. + expect( + scene.clips.map(({ sourceStartSec, sourceEndSec }) => ({ sourceStartSec, sourceEndSec })), + ).toEqual([ + { sourceStartSec: 0, sourceEndSec: 2 }, + { sourceStartSec: 4, sourceEndSec: 30 }, + ]); + }); + it("sends captions to the compositor as text annotations", () => { // Without this the caption would show in the DOM overlay and be missing from the // composited pixels — the preview/render gap the annotation bridge exists to close. diff --git a/technical-documentation/testing/manual-e2e-checklist.md b/technical-documentation/testing/manual-e2e-checklist.md index 6b46ffc4ea..0977babcf5 100644 --- a/technical-documentation/testing/manual-e2e-checklist.md +++ b/technical-documentation/testing/manual-e2e-checklist.md @@ -1128,3 +1128,5 @@ These checks are the human slice: an agent cannot click Apple's picker (see abov | 2026-11-17 | Exact public `v2.3.0-rc.6` @ `a4641a0b7`, AppImage SHA256 `7c79f01496c1d448807f2e24477b4dfb6ce69886edb7ef0ffef591de3acac363` | Vivo Ubuntu24.04/GNOME46 Wayland | **Fail — residual cross-file ruler seek stops playback** | Final scope follows the maintainer's RC5→RC6 diff request; observed unaffected RC5 passes are reused, never-observed unrelated checks remain uncovered. Two distinct synthetic H264/AAC files: same-asset seek keeps playing; native ruler seeks in both cross-file directions stop. Passive trace has pointerup64.2ms after pointerdown on a replacement video still paused/ready0, then metadata63.5ms later with no media error or resume. This exposes a gap in the original seek fix; the earlier Mac counterproof used clips from the same file. Public package/native hashes are unchanged. Follow-up source PR1613 and frozen-branch PR1614 address queued intent and premature play; this row remains the public RC6 verdict. Other essential exact-package capture/export/audio checks remain separately recorded. Unrelated/hardware cases are excluded. Evidence: takeover/linux/seek-one-control-provenance.json, seek-passive-event-trace-normalized.json, seek-two-assets.openscreen and C227. | | 2026-11-17 | Tag `a4641a0b7` plus only PR1613 head `22b5daeee`; private final renderer V2 SHA256 `0be50bc95ce5b5b11ace96d61440c14fe73ea534876cc01a330a8f19fe17fb32`, runtime patch ID `ecc90aba7c7c43d267946492a23cba2169485d4e` | Windows11 x64 and Vivo Linux Wayland; Mac counterproof skipped | **Pass for four targeted controls on Windows and Vivo; Partial overall** | Real OS input with distinct real files/asset IDs passes playing ruler seeks in both directions, rapid cross-file drag and initially paused seek. Windows reproduces the preserved V1 drag failure (jump to programme end in269ms) successfully with V2 in263ms, then time advances; paused seek remains fixed after1s. Vivo's forward/reverse/drag clocks advance and paused seek stays fixed across two reads. All124 renderer hashes match, native sets remain complete/unchanged and public RC6 is untouched; Windows verifies149-file runtimes and24 natives before/after. Two original unit cases and the later three-seek cancellation case fail before their fixes; final104 targeted tests, both TypeScript configurations, lint and build pass. Main PR1613 is merged with green CI and independent review PASS; frozen-branch PR1614 contains only the same four source/test files. Its tracked tree equals the compiled QA source tree. **Skipped:** Mac fixed-renderer execution, because the initial external-renderer QA route stayed on an empty target with no renderer request; no seek ran, no signature/quarantine/security change or alternate route was attempted. A signed future candidate remains needed for Mac. No new capture/benchmark/hardware matrix or whole-file Pass. Evidence: takeover/windows/RC6-CROSS-ASSET-SCRUB.md, takeover/linux/seek-v2-native-counterproof.json, takeover/mac/MAC-CROSS-ASSET-SCRUB-FIX.md and renderer manifests. | | 2026-11-17 | Official signed ARM64 `v2.3.0-rc.7` @ `460ea875510d9b54f0a298047817797f4d038d79`, CI44080825057; DMG SHA256 `a39e46e405d8aa890cc477e03765920abe450a2f7f14ddddd44523e4c046f09a` | macOS27.0.1, Apple M1 | **Partial — targeted cross-file seek 4/4 Pass** | Version7/hash verified; codesign deep/strict valid, Gatekeeper Notarized Developer ID accepted. Intact read-only mounted bundle launched via normal LaunchServices open -n with isolated QA profile, no VITE/addon/ORT/DYLD override; file renderer and bundled compositor/FFmpeg paths confirmed. Real OS inputs on two distinct files/assetIds (10s A + first10s of58.4s B): playing click A→B and B→A, real scrub drag6→14 across10s boundary, initially paused cross-file seek remains paused. Correct file src, readyState4, no video error; both timeline and video clocks advance in all three playing cases, paused values remain unchanged800ms. Native A/B still images inspected with rendered mire/source clocks. No recording/export/camera/install/security or general-checklist work. QA quit normally, original installed app preserved. RC7-MAC-SEEK.md and rc7-cross-asset-scrub/validation.json. Public release published 2026-11-17T12:42:05Z with16assets; tested DMG and updater ZIP match public SHA256/size, all three update feeds name2.3.0-rc.7 and Mac SHA512 matches the CI sidecar. Previously observed unaffected RC5/RC6 controls are reused; no whole-checklist claim or stable promotion. | +| 2026-10-28 | Dev v2.1.2, `codex/srt-import` @ `b7596902` | macOS host; Chromium renderer in browser mode | **Partial — automated subtitle import slice only** | Issue #1365: real browser controls selected an asset and SRT file, imported two cues, undid/redid, cancelled replacement, rejected a reversed cue with a line-specific error while preserving existing text, and retained imported text after reload. Narrow inspector overflow found during visual QA was fixed; pane body now fits its 315 px container. Persistent estimated-word-timing disclosure was visible. Review regressions cover cross-asset transcription/import save ordering, close/unmount before deferred save dispatch, authored repeated words and imported cue projection through real trim and 2× speed regions. Initial full suite: 5,117 passed, 2 skipped; latest affected checks: 216 passed; independent quality review: 205 passed. Both TypeScript configs, lint, i18n and docs passed. **Skipped:** computer-use MCP unavailable; actual Electron file picker/native persistence, physical capture/webcam/tray, compositor-rendered caption preview/export, Windows/Linux runtime and remainder of checklist. Browser-shim checks are not native desktop verification or release-promotion QA. | +| 2026-11-18 | Dev v2.3.0, `codex/srt-import` based on `main` @ `42a776ef` | macOS 26.4 arm64; Electron 41.2.1; Node 22.22.1 / npm 10.9.4 | **Partial — actual Electron SRT import and persistence slice** | Issue #1365: Playwright drove the actual Electron renderer with an isolated profile and a seeded silent two-second fixture. The real file input imported two UTF-8 BOM/CRLF cues through the native document save/get bridge. One Undo/Redo removed/restored the import; cancelling replacement and a reversed cue preserved existing text; the latter reported cue 1, line 2. Confirmed replacement saved, one Undo restored both original cues, and a full process restart restored them with the original timeline. The dialog has no timestamp explanatory hints and its backdrop covers the viewport, escaping inspector clipping. Regression tests reproduce and prevent background-probe/import races, invalid generated targets, stale target changes, hung-save UI lockup and old-project STT queue blockage on cancellation. Full unit suite: **5,820 passed, 2 skipped**, 409 files. Both TypeScript checks, lint (36 existing warnings), i18n (17 locales), docs and renderer/main/preload build passed. Independent review found no remaining important issues. **Skipped:** computer-use MCP unavailable, so OS pointer/keyboard and native file-picker interactions were not tested; file selection used Playwright setInputFiles. Native compositor addon is absent, so caption pixels, playback/export, real recording/webcam/tray and Windows/Linux runtime were not exercised. This is not release-promotion QA. |