fablecut 1.16.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/app.js CHANGED
@@ -73,7 +73,7 @@ const DEFAULT_PROPS = {
73
73
  bold: true, italic: false, weight: 0, align: "center",
74
74
  letterSpacing: 0, lineHeight: 1.2, uppercase: false, textShadow: 12,
75
75
  glow: 0, glowColor: "", // neon glow (glowColor defaults to fill)
76
- textAnim: "none", wordRate: 0.15, direction: "auto",
76
+ textAnim: "none", wordRate: 0.15, direction: "auto", highlightColor: "#ffd166",
77
77
  strokeWidth: 0, strokeColor: "#000000", bgColor: "#000000", bgOpacity: 0,
78
78
  boxW: 0, boxH: 0, // text box (px); 0 = hug content. Resize handles edit these.
79
79
  boxFit: false, // false = wrap at fixed fontSize; true = scale font to fit box
@@ -86,7 +86,7 @@ const ANIMATABLE = ["x", "y", "scale", "rotation", "opacity", "volume", "pan", "
86
86
  const TRANSITIONS = ["none", "fade", "slide-left", "slide-right", "slide-up", "slide-down",
87
87
  "zoom", "wipe", "wipe-right", "wipe-up", "wipe-down", "iris", "spin", "blur", "whip",
88
88
  "glitch", "pop"];
89
- const TEXT_ANIMS = ["none", "typewriter", "word-pop", "word-slide", "karaoke",
89
+ const TEXT_ANIMS = ["none", "typewriter", "word-pop", "word-slide", "karaoke", "highlight",
90
90
  "letter-pop", "wave", "bounce", "shake",
91
91
  "clip-reveal", "zoom-in", "font-cut", "rise-mask"];
92
92
  const BLEND_MODES = self.FableCutMask.BLENDS; // the canvas composite set, shared with the agent (mask.js)
@@ -434,6 +434,8 @@ function showClipCtxMenu(clientX, clientY, c) {
434
434
  item("Crossfade with neighbours", "Shift+D", () => crossfadeSelected(), locked ? "Locked — unlock to change" : null);
435
435
  item("Auto-duck under other tracks", "", () => autoDuckClips(selectedClips()), locked ? "Locked — unlock to change" : null);
436
436
  }
437
+ if (group.some((x) => x.kind === "audio" || x.kind === "video"))
438
+ item("Find silences", "", () => findSilences(selectedClips()));
437
439
  if (selectedClips().some((x) => isVisualClip(x) && x.kind !== "null"))
438
440
  item("Parent to a new null", "", parentSelectionToNull, locked ? "Locked — unlock to change" : null);
439
441
  item("Precompose", "", precomposeSelection, locked ? "Locked — unlock to change" : null);
@@ -550,6 +552,8 @@ const state = {
550
552
  previewRate: 1, // playback speed for PREVIEW only — never affects export
551
553
  selId: null, // primary selection (drives the inspector)
552
554
  selIds: new Set(), // full multi-selection (includes selId)
555
+ silence: null, // silences found (Inspector → Silence): {ids, spans, sig}, shown on the timeline until cut or cleared
556
+ silenceBusy: false, // a Find is listening (the Inspector offers Cancel)
553
557
  trackSize: "l", // s | m | l — timeline track density preset
554
558
  connected: false, exporting: false,
555
559
  rendering: false, // fast (server/ffmpeg) export in progress
@@ -793,7 +797,7 @@ const els = {
793
797
  btnInsert: $("btnInsert"), btnReplace: $("btnReplace"),
794
798
  vuMeter: $("vuMeter"),
795
799
  sideTabs: $("sideTabs"),
796
- mixer: $("mixer"), colorPage: $("colorPage"),
800
+ mixer: $("mixer"), colorPage: $("colorPage"), transcriptPage: $("transcriptPage"),
797
801
  exportSetup: $("exportSetup"), engineFast: $("engineFast"), engineRealtime: $("engineRealtime"),
798
802
  exportProfileRow: $("exportProfileRow"),
799
803
  exportProfileSel: $("exportProfileSel"), exportProfileNote: $("exportProfileNote"),
@@ -1677,6 +1681,7 @@ function listenSSE() {
1677
1681
  // Named events: "change" = project/media/library; "profiles" = encoding-profiles.json only
1678
1682
  es.addEventListener("change", () => { noteActivity(); syncFromServer(); scheduleOfflineCheck(); });
1679
1683
  es.addEventListener("proxy", (e) => onProxyEvent(e.data));
1684
+ es.addEventListener("transcript", (e) => onTranscriptEvent(e.data));
1680
1685
  es.addEventListener("versions", (e) => {
1681
1686
  let d = {};
1682
1687
  try { d = JSON.parse(e.data); } catch { }
@@ -4991,9 +4996,29 @@ function rebuildClips() {
4991
4996
  if (hasWave) drawClipWave(div.querySelector(".wave"), c, tr.h);
4992
4997
  }
4993
4998
  paintAudioOverlaps();
4999
+ paintSilences();
4994
5000
  state.dirtyTimeline = false;
4995
5001
  updateWorkArea();
4996
5002
  }
5003
+ /* The silences Find marked: a band on each lane of the clips that were listened to. */
5004
+ function paintSilences() {
5005
+ const s = state.silence;
5006
+ if (!s) return;
5007
+ if (s.sig !== silenceSig()) { state.silence = null; return; } // the timeline moved on: they no longer line up
5008
+ const lanes = new Set(withLinked(project.clips.filter((c) => s.ids.includes(c.id))).map((c) => c.track));
5009
+ for (const id of lanes) {
5010
+ const row = els.tracks.querySelector(`[data-track="${id}"]`);
5011
+ if (!row) continue;
5012
+ for (const sp of s.spans) {
5013
+ const el = document.createElement("div");
5014
+ el.className = "silence-span";
5015
+ el.style.left = (sp.from * state.pps) + "px";
5016
+ el.style.width = Math.max(2, (sp.to - sp.from) * state.pps) + "px";
5017
+ el.title = `Silence ${fmt(sp.from)} → ${fmt(sp.to)} (${(sp.to - sp.from).toFixed(2)} s) · Inspector → Silence → Cut`;
5018
+ row.appendChild(el);
5019
+ }
5020
+ }
5021
+ }
4997
5022
  /* Hatched bands where two+ audio clips share a track (CSS draw, O(n²) per track). */
4998
5023
  function paintAudioOverlaps() {
4999
5024
  const byTrack = new Map();
@@ -6655,6 +6680,22 @@ function renderInspector(lite) {
6655
6680
  ${slider("speed", 0.25, 4, 0.05, p.speed, "×")}
6656
6681
  </div>`;
6657
6682
  }
6683
+ if ((c.kind === "video" || c.kind === "audio") && typeof FableCutSilence !== "undefined") {
6684
+ const so = silenceOptions(), found = state.silence;
6685
+ const num = (k, lo, hi, step, unit, title) => `<span class="insp-ctrls"><input type="number" data-sil="${k}" min="${lo}" max="${hi}" step="${step}" value="${so[k]}" title="${title}" style="max-width:64px"> ${unit}</span>`;
6686
+ html += `<div class="insp-section"><h3>Silence</h3>
6687
+ ${row("Below", num("threshold", -80, -10, 1, "dB", "Quieter than this counts as silence (dBFS). Raise it toward −30 in a noisy room"))}
6688
+ ${row("At least", num("minSilence", 0.1, 10, 0.1, "s", "Shorter pauses are left alone"))}
6689
+ ${row("Keep", num("padding", 0, 2, 0.05, "s beside speech", "Quiet kept before and after each phrase, so words aren't clipped"))}
6690
+ ${row("", state.silenceBusy
6691
+ ? `<span class="insp-ctrls"><span style="opacity:.75">Listening…</span>
6692
+ <button type="button" class="btn tiny" data-sil-clear title="Stop listening">Cancel</button></span>`
6693
+ : `<span class="insp-ctrls"><button type="button" class="btn tiny" data-sil-find title="Listen to the selected clips and mark their silences on the timeline">Find</button>
6694
+ ${found ? `<button type="button" class="btn tiny" data-sil-cut title="Extract every marked silence on the targeted tracks (one undo step)">Cut ${found.spans.length}</button>
6695
+ <button type="button" class="btn tiny" data-sil-clear title="Remove the marks">Clear</button>` : ""}</span>`)}
6696
+ ${found ? `<div class="insp-note">${found.spans.length} silence${found.spans.length === 1 ? "" : "s"}, ${FableCutSilence.total(found.spans).toFixed(1)} s, marked on the timeline. Cut extracts them on the targeted tracks — lock the music bed first to keep it running.</div>` : ""}
6697
+ </div>`;
6698
+ }
6658
6699
  if (c.kind === "audio" && typeof FableCutFx !== "undefined") {
6659
6700
  html += `<div class="insp-section" data-fx-section><h3>Audio effects</h3>${fxEditorHtml(c.fx, playheadOverClip(c) ? state.time - c.start : null)}</div>`;
6660
6701
  }
@@ -6740,7 +6781,11 @@ function renderInspector(lite) {
6740
6781
  ${row("Title style", `<button type="button" class="btn tiny style-picker-btn" data-style-open title="Pick a style — hover to preview it live">${(TITLE_STYLES[c.styleName] || {}).label || "Choose…"} ▾</button>
6741
6782
  <button class="btn tiny" data-action="title-shuffle" title="Random style">Shuffle</button>`)}
6742
6783
  ${row("Animation", `<select data-k="textAnim">${TEXT_ANIMS.map((a) => `<option ${a === p.textAnim ? "selected" : ""}>${a}</option>`).join("")}</select>`, "", "textAnim")}
6743
- ${slider("wordRate", 0.05, 0.6, 0.01, p.wordRate, "s")}
6784
+ ${p.textAnim === "highlight" ? row("Highlight", `<input type="color" data-k="highlightColor" value="${p.highlightColor || "#ffd166"}" title="The colour of the word being said">`, "", "highlightColor") : ""}
6785
+ ${Array.isArray(p.wordTimes) && p.wordTimes.length ? `<div class="insp-note">${p.caption ? "Caption: its" : "Its"} ${p.wordTimes.length} words follow the speech${
6786
+ String(p.text || "").split(/\s+/).filter(Boolean).length === p.wordTimes.length ? ", so Word rate doesn't apply"
6787
+ : " — the text now has another number of words, so they are spread over the clip; Add captions again to re-time them"}.</div>`
6788
+ : slider("wordRate", 0.05, 0.6, 0.01, p.wordRate, "s")}
6744
6789
  </div>`;
6745
6790
  }
6746
6791
  els.inspector.innerHTML = html;
@@ -6866,6 +6911,18 @@ function renderInspector(lite) {
6866
6911
  const sel = selectedClips();
6867
6912
  clearDuck(sel.length ? sel : [c]);
6868
6913
  });
6914
+ els.inspector.querySelectorAll("[data-sil]").forEach((inp) => inp.addEventListener("change", () => {
6915
+ const o = silenceOptions(), [lo, hi] = FableCutSilence.LIMITS[inp.dataset.sil];
6916
+ o[inp.dataset.sil] = clamp(+inp.value || 0, lo, hi);
6917
+ inp.value = o[inp.dataset.sil];
6918
+ try { localStorage.setItem(SILENCE_KEY, JSON.stringify(o)); } catch { }
6919
+ }));
6920
+ els.inspector.querySelector("[data-sil-find]")?.addEventListener("click", () => {
6921
+ const sel = selectedClips();
6922
+ findSilences(sel.length ? sel : [c]);
6923
+ });
6924
+ els.inspector.querySelector("[data-sil-cut]")?.addEventListener("click", cutSilences);
6925
+ els.inspector.querySelector("[data-sil-clear]")?.addEventListener("click", clearSilences);
6869
6926
  els.inspector.querySelector("[data-norm-target]")?.addEventListener("change", (e) => {
6870
6927
  try { localStorage.setItem(NORMALIZE_KEY, e.target.value); } catch { }
6871
6928
  });
@@ -8599,13 +8656,14 @@ function setDuckKeys(c, keys) {
8599
8656
  }
8600
8657
  /** Timeline spans with sound on the voice clips (each measured after its
8601
8658
  * channel routing, scaled by its clip gain and static volume). */
8602
- async function voiceRegions(voices, threshold) {
8659
+ async function voiceRegions(voices, threshold, minLen, heard) {
8603
8660
  const lists = [];
8604
8661
  for (const v of voices) {
8605
8662
  const m = getMedia(v.mediaId);
8606
8663
  if (!m) continue;
8607
8664
  let buf;
8608
8665
  try { buf = await getAudioBuffer(m); } catch { continue; }
8666
+ heard?.add(v.id); // read and measured: its quiet is real quiet, not a file that failed to decode
8609
8667
  const a = clamp(Math.floor(v.in * buf.sampleRate), 0, buf.length);
8610
8668
  const b = clamp(Math.ceil(mediaTimeAt(v, clipEnd(v)) * buf.sampleRate), a, buf.length);
8611
8669
  const src = [];
@@ -8614,9 +8672,663 @@ async function voiceRegions(voices, threshold) {
8614
8672
  lists.push(FableCutDucking.activeRegions(env, {
8615
8673
  t0: v.start, speed: clipSpeed(v), threshold,
8616
8674
  gain: dbToGain(clipGainDb(v)) * clamp(+(v.props?.volume ?? 1), 0, VOL_MAX),
8675
+ ...(minLen != null ? { minLen } : {}),
8617
8676
  }));
8618
8677
  }
8619
- return FableCutDucking.mergeRegions(lists);
8678
+ // silence wants every pause, so nothing is bridged there; ducking bridges short gaps
8679
+ return FableCutDucking.mergeRegions(lists, minLen != null ? 0 : undefined);
8680
+ }
8681
+
8682
+ /* ── Silence (silence.js): find the pauses in speech, mark them on the
8683
+ timeline, cut them out with Extract — the same spans and ops as
8684
+ fablecut_silence. ── */
8685
+ const SILENCE_KEY = "fablecut-silence";
8686
+ function silenceOptions() {
8687
+ try { return FableCutSilence.options(JSON.parse(localStorage.getItem(SILENCE_KEY) || "{}")); }
8688
+ catch { return { ...FableCutSilence.DEFAULTS }; }
8689
+ }
8690
+ /** Each linked group's audio stems, else the clip itself (audio, or a video without stems). */
8691
+ function speechGroups(clips) {
8692
+ const groups = new Map();
8693
+ for (const c of clips) {
8694
+ if (c.kind !== "audio" && c.kind !== "video") continue;
8695
+ const key = c.linkGroup || c.id;
8696
+ if (groups.has(key)) continue;
8697
+ const stems = withLinked([c]).filter((x) => x.kind === "audio");
8698
+ groups.set(key, stems.length ? stems : [c]);
8699
+ }
8700
+ return [...groups.values()];
8701
+ }
8702
+ /** Everything the marks were found from — where each clip sits, its file, speed, level and switches, the
8703
+ * frame rate: marked silences only stand while this is unchanged. */
8704
+ function silenceSig() {
8705
+ return project.fps + "#" + project.clips.map((c) => JSON.stringify([c.id, c.track, c.start, c.in, c.duration, c.mediaId,
8706
+ getMedia(c.mediaId)?.src ?? null, c.linkGroup ?? null, c.props?.speed ?? 1, c.keyframes?.speed ?? null,
8707
+ c.props?.gain ?? 0, c.props?.volume ?? 1, c.props?.audioChannel ?? null, c.props?.channelMode ?? null,
8708
+ clipRenders(c) ? 1 : 0])).join("|");
8709
+ }
8710
+ let silenceGen = 0; // the newest Find: an older one still decoding never replaces its result
8711
+ async function findSilences(clips, opts = silenceOptions()) {
8712
+ if (typeof FableCutSilence === "undefined") { toast("Silence module missing — reload the editor"); return; }
8713
+ // a new Find replaces the old marks whatever it finds, so Cut never acts on another clip's result
8714
+ const gen = ++silenceGen;
8715
+ if (state.silence) { state.silence = null; state.dirtyTimeline = true; renderInspector(); }
8716
+ const all = speechGroups(clips).map((g) => g.filter(clipRenders)).filter((g) => g.length);
8717
+ if (!all.length) { toast("Select a clip with sound to find its silences"); return; }
8718
+ // a speed ramp moves the sound along the timeline unevenly: those clips are left alone
8719
+ const groups = all.filter((g) => !g.some(FableCutSilence.ramped));
8720
+ if (!groups.length) { toast("These clips have a speed ramp — silence removal works on clips at a steady speed"); return; }
8721
+ toast("Listening for silences…");
8722
+ const sig = silenceSig(), heard = new Set();
8723
+ state.silenceBusy = true; // the Inspector shows Listening… with Cancel meanwhile
8724
+ renderInspector();
8725
+ let sound;
8726
+ try { sound = await voiceRegions(groups.flat(), opts.threshold, FableCutSilence.MIN_SOUND, heard); }
8727
+ finally { if (gen === silenceGen) state.silenceBusy = false; }
8728
+ if (gen !== silenceGen) return; // a newer Find took over, or Cancel
8729
+ renderInspector(); // Listening… → Find again, whatever comes next
8730
+ // the timeline moved while it listened: these spans belong to the old one
8731
+ if (silenceSig() !== sig) { toast("The timeline changed while listening — find the silences again"); return; }
8732
+ // a clip whose audio couldn't be read is not silent: leave its time alone
8733
+ const usable = groups.filter((g) => g.every((x) => heard.has(x.id)));
8734
+ if (!usable.length) { toast("Couldn't read the audio of these clips — nothing marked"); return; }
8735
+ const ranges = usable.map((g) => [Math.min(...g.map((x) => x.start)), Math.max(...g.map(clipEnd))]);
8736
+ const spans = FableCutSilence.silentSpans(sound, ranges, { ...opts, fps: project.fps });
8737
+ state.silence = spans.length ? { ids: usable.flat().map((x) => x.id), spans, sig } : null;
8738
+ state.dirtyTimeline = true;
8739
+ renderInspector();
8740
+ toast((spans.length
8741
+ ? `${spans.length} silence${spans.length === 1 ? "" : "s"}, ${FableCutSilence.total(spans).toFixed(1)} s — marked on the timeline`
8742
+ : "No silences that long — try a higher threshold or a shorter minimum") +
8743
+ (usable.length < groups.length ? " · some clips' audio couldn't be read, so their time is left alone" : "") +
8744
+ (groups.length < all.length ? " · clips with a speed ramp are left alone" : ""));
8745
+ }
8746
+ /** Extract every marked silence on the targeted tracks, last first: one undo step. */
8747
+ function cutSilences() {
8748
+ const s = state.silence;
8749
+ // the marks dropped when the timeline changed (the button can outlive them until the Inspector redraws)
8750
+ if (!s) { renderInspector(); toast("The timeline changed — find the silences again"); return; }
8751
+ if (s.sig !== silenceSig()) { state.silence = null; renderInspector(); toast("The timeline changed — find the silences again"); return; }
8752
+ const snap = undoSnapshot();
8753
+ let cut = 0, secs = 0;
8754
+ for (const sp of s.spans.slice().sort((a, b) => b.from - a.from)) {
8755
+ if (!EDIT.liftRange(sp.from, sp.to, true)) { cut++; secs += sp.to - sp.from; }
8756
+ }
8757
+ state.silence = null;
8758
+ if (!cut) { state.dirtyTimeline = true; renderInspector(); toast("Nothing was cut — target the clip's tracks first"); return; }
8759
+ pushUndo(snap);
8760
+ pruneSelection();
8761
+ state.dirtyTimeline = true;
8762
+ scheduleSave();
8763
+ renderInspector();
8764
+ toast(`Cut ${cut} silence${cut === 1 ? "" : "s"} · ${secs.toFixed(1)} s shorter`);
8765
+ }
8766
+
8767
+ /* ── Transcripts (transcribe.js, transcribe-worker.js): speech → words in this
8768
+ browser with Whisper, kept per file by the server (analysis/transcripts/).
8769
+ The Transcript tab shows the timeline's words: click one to go there, select
8770
+ some and press Delete (or Cut) to extract them, find a phrase and cut every
8771
+ time it is said — the same spans and extract ops as fablecut_transcribe. ── */
8772
+ const TRANSCRIBE_KEY = "fablecut-transcribe";
8773
+ const trState = { open: false, built: false, busy: null, sig: "", words: [], sel: null, anchor: null, drag: false, query: "", hits: [], now: -1 };
8774
+ const transcriptCache = new Map(); // src → validated transcript | false (none) | Promise while asking the server
8775
+ let transcriptGen = 0; // bumps whenever a transcript arrives or changes: the tab redraws
8776
+ function transcribeSettings() {
8777
+ let o = {};
8778
+ try { o = JSON.parse(localStorage.getItem(TRANSCRIBE_KEY) || "{}"); } catch { }
8779
+ let model = FableCutTranscribe.DEFAULT_MODEL, language = null, captionStyle = null;
8780
+ try { model = FableCutTranscribe.model(o.model); } catch { }
8781
+ try { language = FableCutTranscribe.language(o.language); } catch { }
8782
+ try { captionStyle = typeof FableCutCaptions !== "undefined" && o.captionStyle ? FableCutCaptions.style(o.captionStyle) : null; } catch { }
8783
+ return { model, language, captionStyle };
8784
+ }
8785
+ function saveTranscribeSettings(patch) {
8786
+ try { localStorage.setItem(TRANSCRIBE_KEY, JSON.stringify({ ...transcribeSettings(), ...patch })); } catch { }
8787
+ }
8788
+ /** The transcript of a file, if it is here already. */
8789
+ function transcriptOf(src) {
8790
+ const d = transcriptCache.get(src);
8791
+ return d && !(d instanceof Promise) ? d : null;
8792
+ }
8793
+ /** Ask the server for a file's transcript (once; `force` asks again). Resolves to it, or false. */
8794
+ function loadTranscript(src, force = false) {
8795
+ const have = transcriptCache.get(src);
8796
+ if (!force && have !== undefined) return have instanceof Promise ? have : Promise.resolve(have);
8797
+ const p = fetch("/api/transcript?src=" + encodeURIComponent(src)).then((r) => (r.ok ? r.json() : null))
8798
+ .then((j) => {
8799
+ let d = false;
8800
+ try { d = j && j.transcript ? FableCutTranscribe.validate(j.transcript) : false; } catch { }
8801
+ if (transcriptCache.get(src) === p) { transcriptCache.set(src, d); transcriptGen++; }
8802
+ return d;
8803
+ })
8804
+ .catch(() => { if (transcriptCache.get(src) === p) transcriptCache.set(src, false); return false; });
8805
+ transcriptCache.set(src, p);
8806
+ return p;
8807
+ }
8808
+ function onTranscriptEvent(data) {
8809
+ let src = null;
8810
+ try { src = JSON.parse(data).src; } catch { }
8811
+ if (!src) return;
8812
+ loadTranscript(src, true).then(() => renderTranscript(true));
8813
+ }
8814
+
8815
+ /* The worker: one at a time, each piece of audio answered in turn. */
8816
+ let trWorker = null, trSeq = 0, trIdleTimer = 0;
8817
+ const trPending = new Map();
8818
+ function transcribeWorker() {
8819
+ if (trWorker) return trWorker;
8820
+ trWorker = new Worker("transcribe-worker.js", { type: "module" });
8821
+ trWorker.onmessage = (e) => {
8822
+ const m = e.data || {};
8823
+ if (m.type === "progress") { onModelProgress(m); return; }
8824
+ const p = trPending.get(m.id);
8825
+ if (!p) return;
8826
+ trPending.delete(m.id);
8827
+ if (m.type === "done") p.resolve(m.chunks || []);
8828
+ else p.reject(new Error(/dynamically imported module|Failed to fetch|NetworkError|Load failed/i.test(m.error || "")
8829
+ ? "couldn't download the speech model — check the internet connection (it is needed the first time)"
8830
+ : m.error || "transcription failed"));
8831
+ };
8832
+ trWorker.onerror = (e) => {
8833
+ for (const p of trPending.values()) p.reject(new Error(e.message || "the speech worker failed to start"));
8834
+ trPending.clear();
8835
+ trWorker = null;
8836
+ };
8837
+ return trWorker;
8838
+ }
8839
+ function stopTranscribeWorker() {
8840
+ if (trWorker) { trWorker.terminate(); trWorker = null; }
8841
+ for (const p of trPending.values()) p.reject(new Error("cancelled"));
8842
+ trPending.clear();
8843
+ }
8844
+ function whisperPiece(pcm, model, language) {
8845
+ return new Promise((resolve, reject) => {
8846
+ const id = ++trSeq;
8847
+ trPending.set(id, { resolve, reject });
8848
+ transcribeWorker().postMessage({ type: "run", id, lib: FableCutTranscribe.LIBRARY, model: FableCutTranscribe.MODELS[model].id, pcm, language }, [pcm.buffer]);
8849
+ });
8850
+ }
8851
+ function onModelProgress(m) {
8852
+ const b = trState.busy;
8853
+ if (!b || !m.file) return;
8854
+ if (m.status === "done") { const f = b.dl.get(m.file); if (f) f.loaded = f.total; }
8855
+ else if (m.total > 0) b.dl.set(m.file, { loaded: m.loaded, total: m.total });
8856
+ b.beat?.();
8857
+ paintTranscribeBusy();
8858
+ }
8859
+ /** A file's sound as Whisper hears it: mono, 16 kHz. */
8860
+ async function speechPcm(m) {
8861
+ const buf = await getAudioBuffer(m);
8862
+ const R = FableCutTranscribe.RATE;
8863
+ const oc = new OfflineAudioContext(1, Math.max(1, Math.ceil(buf.duration * R)), R);
8864
+ const node = oc.createBufferSource();
8865
+ node.buffer = buf;
8866
+ node.connect(oc.destination);
8867
+ node.start();
8868
+ return { pcm: (await oc.startRendering()).getChannelData(0), duration: buf.duration };
8869
+ }
8870
+ /** Transcribe one file and save it on the server. Resolves to {doc, saved}. */
8871
+ async function transcribeFile(src, { model, language, onProgress, cancelled }) {
8872
+ const T = FableCutTranscribe, R = T.RATE;
8873
+ const m = project.media.find((x) => x.src === src) || { src };
8874
+ const { pcm, duration } = await speechPcm(m);
8875
+ const pieces = T.plan(pcm, R), words = [];
8876
+ for (let k = 0; k < pieces.length; k++) {
8877
+ if (cancelled()) throw new Error("cancelled");
8878
+ const [a, b] = pieces[k];
8879
+ if (!T.quiet(pcm, a, b)) words.push(...T.joinChunks(await whisperPiece(pcm.slice(a, b), model, language), a / R, b / R));
8880
+ onProgress((k + 1) / pieces.length);
8881
+ }
8882
+ const doc = T.validate({ src, model, language: language || "auto", duration, created: new Date().toISOString(), words });
8883
+ let saved = false;
8884
+ try { saved = (await fetch("/api/transcript?src=" + encodeURIComponent(src), { method: "POST", body: JSON.stringify(doc) })).ok; } catch { }
8885
+ transcriptCache.set(src, doc);
8886
+ transcriptGen++;
8887
+ return { doc, saved };
8888
+ }
8889
+ /** Transcribe files one after another. `beat(fraction)` hears about progress (an agent's job). */
8890
+ async function transcribeSrcs(srcs, opts = transcribeSettings(), beat = null) {
8891
+ if (trState.busy) throw new Error("this tab is already transcribing — wait for it, or cancel it");
8892
+ const busy = trState.busy = { srcs, i: 0, frac: 0, cancel: false, dl: new Map(), beat: () => beat?.((busy.i + busy.frac) / srcs.length) };
8893
+ const out = { done: [], failed: [], cancelled: false };
8894
+ renderTranscript(true);
8895
+ try {
8896
+ for (let i = 0; i < srcs.length; i++) {
8897
+ busy.i = i; busy.frac = 0;
8898
+ paintTranscribeBusy();
8899
+ busy.beat();
8900
+ try {
8901
+ const r = await transcribeFile(srcs[i], {
8902
+ ...opts, cancelled: () => busy.cancel,
8903
+ onProgress: (f) => { busy.frac = f; paintTranscribeBusy(); busy.beat(); },
8904
+ });
8905
+ out.done.push({ src: srcs[i], words: r.doc.words.length, language: r.doc.language, saved: r.saved });
8906
+ } catch (e) {
8907
+ if (busy.cancel) { out.cancelled = true; break; }
8908
+ out.failed.push({ src: srcs[i], error: String((e && e.message) || e) });
8909
+ }
8910
+ }
8911
+ } finally {
8912
+ trState.busy = null;
8913
+ renderTranscript(true);
8914
+ // the model holds a few hundred MB: let it go after a quiet minute (the browser keeps the download)
8915
+ clearTimeout(trIdleTimer);
8916
+ trIdleTimer = setTimeout(() => { if (!trState.busy) stopTranscribeWorker(); }, 60000);
8917
+ }
8918
+ return out;
8919
+ }
8920
+ function cancelTranscribe() {
8921
+ if (!trState.busy) return;
8922
+ trState.busy.cancel = true;
8923
+ stopTranscribeWorker();
8924
+ }
8925
+
8926
+ /** Each linked group that sounds (its audio stems, else the clip), as on the timeline. */
8927
+ function transcriptGroups() {
8928
+ return speechGroups(project.clips).map((g) => g.filter(clipRenders)).filter((g) => {
8929
+ const m = g.length && getMedia(g[0].mediaId);
8930
+ // a picture with its sound turned off, or a file with no audio stream, has nothing to say
8931
+ return m && m.audioChannels !== 0 && !(g.length === 1 && g[0].kind === "video" && +(g[0].props?.volume ?? 1) === 0);
8932
+ });
8933
+ }
8934
+ /** The timeline's words, every transcribed clip, in time order (transcribe.js layout). */
8935
+ function transcriptWords() {
8936
+ const entries = [];
8937
+ for (const g of transcriptGroups()) {
8938
+ const d = transcriptOf(getMedia(g[0].mediaId).src);
8939
+ if (d) entries.push({ clip: g[0], words: d.words });
8940
+ }
8941
+ return FableCutTranscribe.layout(entries);
8942
+ }
8943
+ /** What Transcribe works on: the selected clips' files, else every file on the timeline without a transcript. */
8944
+ function transcribeTargets() {
8945
+ const groups = transcriptGroups();
8946
+ const picked = new Set();
8947
+ for (const id of state.selIds) {
8948
+ const c = getClip(id);
8949
+ if (c && (c.kind === "video" || c.kind === "audio")) { const m = getMedia(c.mediaId); if (m) picked.add(m.src); }
8950
+ }
8951
+ const srcs = [...new Set(groups.map((g) => getMedia(g[0].mediaId).src))];
8952
+ const sel = srcs.filter((s) => picked.has(s));
8953
+ return sel.length ? { srcs: sel, selected: true } : { srcs: srcs.filter((s) => transcriptCache.get(s) === false), selected: false };
8954
+ }
8955
+ /** What the words' places depend on: the timeline and the transcripts. */
8956
+ function transcriptWordsSig() {
8957
+ return silenceSig() + "|" + transcriptGen;
8958
+ }
8959
+ /** What the tab shows: that, and the clip selection (the Transcribe button follows it). */
8960
+ function transcriptSig() {
8961
+ return transcriptWordsSig() + "|" + [...state.selIds].join(",");
8962
+ }
8963
+
8964
+ function buildTranscriptPage() {
8965
+ const T = FableCutTranscribe, root = els.transcriptPage, set = transcribeSettings();
8966
+ root.innerHTML = `<div class="tr-head">
8967
+ <div class="tr-row">
8968
+ <button type="button" class="btn primary" data-tr-go></button>
8969
+ <select data-tr-model title="Speech model. Base is quick; Small is more accurate and slower. Each downloads once, then stays in this browser">${Object.entries(T.MODELS).map(([k, m]) =>
8970
+ `<option value="${k}" ${k === set.model ? "selected" : ""}>${m.label} · ${m.mb} MB</option>`).join("")}</select>
8971
+ <select data-tr-lang title="The language spoken. Auto-detect works for most; pick it when a clip is short or mixes languages">
8972
+ <option value="auto">Auto-detect</option>${Object.entries(T.LANGUAGES).sort((a, b) => a[1].localeCompare(b[1])).map(([k, n]) =>
8973
+ `<option value="${k}" ${k === set.language ? "selected" : ""}>${n}</option>`).join("")}</select>
8974
+ </div>
8975
+ <div class="tr-busy hidden" data-tr-busy><span data-tr-busy-text></span><span class="tr-bar"><i data-tr-bar></i></span>
8976
+ <button type="button" class="btn tiny" data-tr-cancel title="Stop transcribing (what is done is kept)">Cancel</button></div>
8977
+ <div class="tr-row">
8978
+ <input type="search" data-tr-find placeholder="Find words…" spellcheck="false" title="A word or phrase; case and punctuation don't matter. Enter goes to the next one">
8979
+ <span class="tr-count" data-tr-count></span>
8980
+ <button type="button" class="btn tiny" data-tr-cut-found disabled title="Extract every place it is said, on the targeted tracks (one undo step)">Cut all</button>
8981
+ <button type="button" class="btn tiny" data-tr-copy title="Copy the transcript as text, with timecodes">Copy</button>
8982
+ </div>
8983
+ <div class="tr-row">
8984
+ <span class="tr-lbl">Captions</span>
8985
+ <select data-tr-cap-style title="The look: subtitle on a dark bar, karaoke (words light up as said), highlight (the word being said in colour), word pop (a few big words at a time)">${Object.entries(FableCutCaptions.STYLES).map(([k, st]) =>
8986
+ `<option value="${k}" ${k === (set.captionStyle || FableCutCaptions.DEFAULT_STYLE) ? "selected" : ""}>${st.label}</option>`).join("")}</select>
8987
+ <button type="button" class="btn tiny" data-tr-cap-add title="Make captions from these words, timed word by word, on a video lane above the edit (replaces the captions there; one undo step)">Add captions</button>
8988
+ <button type="button" class="btn tiny" data-tr-cap-file="srt" title="Download the timeline's captions as a SubRip file">SRT</button>
8989
+ <button type="button" class="btn tiny" data-tr-cap-file="vtt" title="Download the timeline's captions as a WebVTT file">VTT</button>
8990
+ <button type="button" class="btn tiny" data-tr-cap-import title="Place the captions of an SRT or WebVTT file">Import…</button>
8991
+ <input type="file" accept=".srt,.vtt,text/vtt,application/x-subrip" data-tr-cap-input hidden>
8992
+ </div>
8993
+ <div class="tr-note">Caption last: a cut through a caption doesn't re-time its words, so add captions again after changing the edit.</div>
8994
+ </div>
8995
+ <div class="tr-body" data-tr-body tabindex="0"></div>
8996
+ <div class="tr-foot hidden" data-tr-foot><span data-tr-sel></span>
8997
+ <button type="button" class="btn tiny" data-tr-cut-sel title="Extract the selected words and the pause after them, on the targeted tracks (Delete)">Cut</button></div>`;
8998
+ const q = (s) => root.querySelector(s);
8999
+ trState.el = { go: q("[data-tr-go]"), busy: q("[data-tr-busy]"), busyText: q("[data-tr-busy-text]"), bar: q("[data-tr-bar]"),
9000
+ find: q("[data-tr-find]"), count: q("[data-tr-count]"), cutFound: q("[data-tr-cut-found]"), body: q("[data-tr-body]"),
9001
+ foot: q("[data-tr-foot]"), selText: q("[data-tr-sel]") };
9002
+ const E = trState.el;
9003
+ E.go.addEventListener("click", transcribeFromTab);
9004
+ q("[data-tr-cancel]").addEventListener("click", cancelTranscribe);
9005
+ q("[data-tr-model]").addEventListener("change", (e) => saveTranscribeSettings({ model: e.target.value }));
9006
+ q("[data-tr-lang]").addEventListener("change", (e) => saveTranscribeSettings({ language: e.target.value === "auto" ? null : e.target.value }));
9007
+ E.find.addEventListener("input", () => { trState.query = E.find.value; findTranscript(); });
9008
+ E.find.addEventListener("keydown", (e) => {
9009
+ if (e.key === "Enter") { e.preventDefault(); nextTranscriptHit(e.shiftKey ? -1 : 1); }
9010
+ if (e.key === "Escape" && E.find.value) { e.stopPropagation(); E.find.value = ""; trState.query = ""; findTranscript(); }
9011
+ });
9012
+ E.cutFound.addEventListener("click", () => {
9013
+ const n = trState.hits.length;
9014
+ if (n) cutTranscriptRuns(trState.hits, `${n} × "${trState.query.trim()}"`);
9015
+ });
9016
+ q("[data-tr-copy]").addEventListener("click", copyTranscript);
9017
+ q("[data-tr-cap-style]").addEventListener("change", (e) => saveTranscribeSettings({ captionStyle: e.target.value }));
9018
+ q("[data-tr-cap-add]").addEventListener("click", () => addCaptionsFromTranscript(q("[data-tr-cap-style]").value));
9019
+ root.querySelectorAll("[data-tr-cap-file]").forEach((b) => b.addEventListener("click", () => downloadCaptions(b.dataset.trCapFile)));
9020
+ const capInput = q("[data-tr-cap-input]");
9021
+ q("[data-tr-cap-import]").addEventListener("click", () => capInput.click());
9022
+ capInput.addEventListener("change", async () => {
9023
+ const f = capInput.files && capInput.files[0];
9024
+ capInput.value = "";
9025
+ if (!f) return;
9026
+ let list;
9027
+ const st = q("[data-tr-cap-style]").value;
9028
+ try { list = FableCutCaptions.parse(await f.text()); } catch (e) { toast(e.message); return; }
9029
+ const m = FableCutCaptions.metrics(st, project.width, project.height);
9030
+ placeCaptions(FableCutCaptions.fit(list, m.chars, m.lines), st, `from ${f.name}`);
9031
+ });
9032
+ q("[data-tr-cut-sel]").addEventListener("click", cutTranscriptSelection);
9033
+ E.body.addEventListener("mousedown", (e) => {
9034
+ const tc = e.target.closest(".tr-tc");
9035
+ if (tc) { goToTranscriptTime(+tc.dataset.t); return; }
9036
+ const w = e.target.closest(".tw");
9037
+ if (!w || e.button !== 0) return;
9038
+ e.preventDefault();
9039
+ E.body.focus({ preventScroll: true });
9040
+ const k = +w.dataset.k;
9041
+ if (e.shiftKey && trState.anchor != null) trState.sel = { i: Math.min(trState.anchor, k), j: Math.max(trState.anchor, k) };
9042
+ else { trState.anchor = k; trState.sel = { i: k, j: k }; goToTranscriptTime(trState.words[k].s); }
9043
+ trState.drag = true;
9044
+ paintTranscriptMarks();
9045
+ });
9046
+ E.body.addEventListener("mouseover", (e) => {
9047
+ if (!trState.drag) return;
9048
+ const w = e.target.closest(".tw");
9049
+ if (!w || trState.anchor == null) return;
9050
+ const k = +w.dataset.k;
9051
+ trState.sel = { i: Math.min(trState.anchor, k), j: Math.max(trState.anchor, k) };
9052
+ paintTranscriptMarks();
9053
+ });
9054
+ window.addEventListener("mouseup", () => { trState.drag = false; });
9055
+ // Delete anywhere in this tab means the words, never the timeline's clips: with none selected it does
9056
+ // nothing; in the Find box it edits the text
9057
+ root.addEventListener("keydown", (e) => {
9058
+ if ((e.key === "Delete" || e.key === "Backspace") && !e.ctrlKey && !e.metaKey && !e.altKey) {
9059
+ e.stopPropagation();
9060
+ if (isTypingTarget(e.target)) return;
9061
+ e.preventDefault();
9062
+ if (trState.sel) cutTranscriptSelection();
9063
+ } else if (e.key === "Escape" && trState.sel && !isTypingTarget(e.target)) {
9064
+ e.preventDefault(); e.stopPropagation();
9065
+ trState.sel = null; trState.anchor = null;
9066
+ paintTranscriptMarks();
9067
+ }
9068
+ });
9069
+ trState.built = true;
9070
+ }
9071
+ function renderTranscript(force = false) {
9072
+ if (!trState.open || !els.transcriptPage) return;
9073
+ if (typeof FableCutTranscribe === "undefined") { els.transcriptPage.innerHTML = `<div class="tr-empty">Transcript module missing — reload the editor.</div>`; return; }
9074
+ if (!trState.built) buildTranscriptPage();
9075
+ const groups = transcriptGroups();
9076
+ for (const g of groups) {
9077
+ const src = getMedia(g[0].mediaId).src;
9078
+ if (!transcriptCache.has(src)) loadTranscript(src).then(() => renderTranscript(true));
9079
+ }
9080
+ paintTranscribeBusy();
9081
+ const sig = transcriptSig();
9082
+ if (!force && sig === trState.sig) return;
9083
+ trState.sig = sig;
9084
+ const T = FableCutTranscribe, E = trState.el;
9085
+ const words = trState.words = transcriptWords();
9086
+ trState.wsig = transcriptWordsSig();
9087
+ const tgt = transcribeTargets();
9088
+ E.go.textContent = tgt.selected ? `Transcribe selected (${tgt.srcs.length})` : tgt.srcs.length ? `Transcribe ${tgt.srcs.length} file${tgt.srcs.length === 1 ? "" : "s"}` : "Transcribe";
9089
+ E.go.disabled = !!trState.busy || !tgt.srcs.length;
9090
+ E.go.title = tgt.srcs.length ? "Turn the speech into words, in this browser (the model downloads once). Select clips to transcribe just those, or again"
9091
+ : groups.length ? "Every file on the timeline has a transcript — select clips to transcribe them again" : "Put clips with speech on the timeline first";
9092
+ const missing = [...new Set(groups.map((g) => getMedia(g[0].mediaId)).filter((m) => transcriptCache.get(m.src) === false).map((m) => m.name || m.src))];
9093
+ let html = "";
9094
+ if (!groups.length) html = `<div class="tr-empty">Put clips with speech on the timeline, then transcribe them here. Speech becomes words in this browser; your audio never leaves it.</div>`;
9095
+ else {
9096
+ if (missing.length) html += `<div class="tr-note">No transcript yet: ${missing.slice(0, 6).map(escapeHtml).join(", ")}${missing.length > 6 ? ` +${missing.length - 6} more` : ""}</div>`;
9097
+ if (!words.length && !missing.length) html += `<div class="tr-empty">${[...transcriptCache.values()].some((v) => v instanceof Promise) ? "Loading…" : "No words in these clips."}</div>`;
9098
+ for (const s of T.segments(words)) {
9099
+ let p = "";
9100
+ for (let k = s.i; k <= s.j; k++) p += (k > s.i ? " " : "") + `<span class="tw" data-k="${k}">${escapeHtml(words[k].w)}</span>`;
9101
+ html += `<p class="tr-seg"><span class="tr-tc" data-t="${s.from}" title="Go to ${fmt(s.from)}">${fmt(s.from)}</span>${p}</p>`;
9102
+ }
9103
+ }
9104
+ E.body.innerHTML = html;
9105
+ trState.now = -1;
9106
+ // the selection stands only while the words are the same ones
9107
+ const key = words.map((x) => x.s + x.w).join("|");
9108
+ if (key !== trState.wordsKey) { trState.sel = null; trState.anchor = null; }
9109
+ trState.wordsKey = key;
9110
+ findTranscript(true);
9111
+ }
9112
+ /** Go to a time from the transcript: the Program monitor shows it, as markers and placements do. */
9113
+ function goToTranscriptTime(t) {
9114
+ if (isSourceMode()) setMonitorMode("program");
9115
+ setTime(t);
9116
+ }
9117
+ function paintTranscribeBusy() {
9118
+ const E = trState.el, b = trState.busy;
9119
+ if (!E) return;
9120
+ E.busy.classList.toggle("hidden", !b);
9121
+ if (!b) return;
9122
+ let loaded = 0, total = 0, downloading = false;
9123
+ for (const f of b.dl.values()) { loaded += f.loaded; total += f.total; if (f.loaded < f.total) downloading = true; }
9124
+ const name = (project.media.find((m) => m.src === b.srcs[b.i])?.name) || b.srcs[b.i].split("/").pop();
9125
+ const frac = downloading && total ? loaded / total : (b.i + b.frac) / b.srcs.length;
9126
+ E.busyText.textContent = downloading
9127
+ ? `Downloading the speech model (once)… ${Math.round(100 * loaded / total)}%`
9128
+ : `Transcribing ${name}${b.srcs.length > 1 ? ` (${b.i + 1} of ${b.srcs.length})` : ""}… ${Math.round(100 * b.frac)}%`;
9129
+ E.bar.style.width = `${Math.round(100 * frac)}%`;
9130
+ }
9131
+ function findTranscript(keepSel = false) {
9132
+ const E = trState.el;
9133
+ if (!E) return;
9134
+ const q = trState.query.trim();
9135
+ trState.hits = q ? FableCutTranscribe.find(trState.words, q) : [];
9136
+ E.count.textContent = q ? `${trState.hits.length} found` : "";
9137
+ E.cutFound.disabled = !trState.hits.length;
9138
+ E.cutFound.textContent = trState.hits.length ? `Cut ${trState.hits.length}` : "Cut all";
9139
+ if (!keepSel) trState.hitAt = -1;
9140
+ paintTranscriptMarks();
9141
+ }
9142
+ function nextTranscriptHit(dir) {
9143
+ const h = trState.hits;
9144
+ if (!h.length) return;
9145
+ trState.hitAt = ((trState.hitAt ?? -1) + dir + h.length) % h.length;
9146
+ const run = h[trState.hitAt];
9147
+ trState.sel = { i: run.i, j: run.j };
9148
+ trState.anchor = run.i;
9149
+ goToTranscriptTime(trState.words[run.i].s);
9150
+ paintTranscriptMarks();
9151
+ trState.el.body.querySelector(`.tw[data-k="${run.i}"]`)?.scrollIntoView({ block: "center" });
9152
+ }
9153
+ function paintTranscriptMarks() {
9154
+ const E = trState.el;
9155
+ if (!E) return;
9156
+ const hit = new Set();
9157
+ for (const r of trState.hits) for (let k = r.i; k <= r.j; k++) hit.add(k);
9158
+ const s = trState.sel;
9159
+ for (const el of E.body.querySelectorAll(".tw")) {
9160
+ const k = +el.dataset.k;
9161
+ el.classList.toggle("hit", hit.has(k));
9162
+ el.classList.toggle("sel", !!s && k >= s.i && k <= s.j);
9163
+ }
9164
+ E.foot.classList.toggle("hidden", !s);
9165
+ if (s) {
9166
+ const w = trState.words;
9167
+ const txt = FableCutTranscribe.text(w, s.i, s.j);
9168
+ E.selText.textContent = `${s.j - s.i + 1} word${s.j === s.i ? "" : "s"} · ${(w[s.j].e - w[s.i].s).toFixed(1)} s · “${txt.length > 60 ? txt.slice(0, 57) + "…" : txt}”`;
9169
+ }
9170
+ }
9171
+ function cutTranscriptSelection() {
9172
+ const s = trState.sel;
9173
+ if (!s) return;
9174
+ cutTranscriptRuns([s], `${s.j - s.i + 1} word${s.j === s.i ? "" : "s"}`);
9175
+ }
9176
+ /** Extract the words of each run (and the pause after them) on the targeted tracks: one undo step. */
9177
+ function cutTranscriptRuns(runs, label) {
9178
+ // the words were placed on the timeline as it was at the last redraw: it may have moved since
9179
+ if (transcriptWordsSig() !== trState.wsig) { renderTranscript(true); toast("The timeline changed — find or select the words again"); return; }
9180
+ const spans = FableCutTranscribe.cutSpans(trState.words, runs, { fps: projectFps() });
9181
+ if (!spans.length) { toast("Too short to cut"); return; }
9182
+ const snap = undoSnapshot();
9183
+ let cut = 0, secs = 0;
9184
+ for (const sp of spans.slice().sort((a, b) => b.from - a.from)) {
9185
+ if (!EDIT.liftRange(sp.from, sp.to, true)) { cut++; secs += sp.to - sp.from; }
9186
+ }
9187
+ if (!cut) { state.dirtyTimeline = true; toast("Nothing was cut — target the clip's tracks first (or unlock them)"); return; }
9188
+ pushUndo(snap);
9189
+ pruneSelection();
9190
+ state.dirtyTimeline = true;
9191
+ scheduleSave();
9192
+ trState.sel = null; trState.anchor = null;
9193
+ renderTranscript(true);
9194
+ toast(`Cut ${label} · ${secs.toFixed(1)} s shorter`);
9195
+ }
9196
+ function copyTranscript() {
9197
+ const lines = FableCutTranscribe.segments(trState.words).map((s) => `[${fmt(s.from)}] ${s.text}`);
9198
+ if (!lines.length) { toast("Nothing to copy yet"); return; }
9199
+ navigator.clipboard.writeText(lines.join("\n")).then(() => toast(`Copied ${lines.length} line${lines.length === 1 ? "" : "s"}`), () => toast("Couldn't copy — the browser refused"));
9200
+ }
9201
+ async function transcribeFromTab() {
9202
+ const { srcs } = transcribeTargets();
9203
+ if (!srcs.length) { toast("Put a clip with speech on the timeline first"); return; }
9204
+ let out;
9205
+ try { out = await transcribeSrcs(srcs); } catch (e) { toast(e.message); return; }
9206
+ const unsaved = out.done.filter((d) => !d.saved).length;
9207
+ const words = out.done.reduce((n, d) => n + d.words, 0);
9208
+ toast(out.cancelled ? `Stopped — ${out.done.length} file${out.done.length === 1 ? "" : "s"} transcribed`
9209
+ : out.failed.length && !out.done.length ? `Couldn't transcribe: ${out.failed[0].error}`
9210
+ : `Transcribed ${out.done.length} file${out.done.length === 1 ? "" : "s"}, ${words} words` +
9211
+ (out.failed.length ? ` · ${out.failed.length} failed (${out.failed[0].error})` : "") +
9212
+ (unsaved ? " · kept for this session only (the server didn't save it)" : ""));
9213
+ }
9214
+ /** The word under the playhead, lit (and kept in view while playing); a redraw when the timeline changes. */
9215
+ let trTickAt = 0;
9216
+ function transcriptTick() {
9217
+ const now = performance.now();
9218
+ if (now - trTickAt > 300) { trTickAt = now; renderTranscript(); }
9219
+ const w = trState.words;
9220
+ let lo = 0, hi = w.length - 1, k = -1;
9221
+ while (lo <= hi) { const m = (lo + hi) >> 1; if (w[m].s <= state.time + 1e-4) { k = m; lo = m + 1; } else hi = m - 1; }
9222
+ if (k >= 0 && state.time > w[k].e + 0.25) k = -1;
9223
+ if (k === trState.now || !trState.el) return;
9224
+ trState.el.body.querySelector(".tw.now")?.classList.remove("now");
9225
+ const el = k >= 0 ? trState.el.body.querySelector(`.tw[data-k="${k}"]`) : null;
9226
+ el?.classList.add("now");
9227
+ if (el && state.playing) el.scrollIntoView({ block: "nearest" });
9228
+ trState.now = k;
9229
+ }
9230
+
9231
+ /* ── Captions (captions.js): the transcript's words become caption clips — text
9232
+ clips with wordTimes, so karaoke / highlight / word pop follow the speech —
9233
+ on a video lane above the edit; subtitle files out and in. The same clips as
9234
+ fablecut_captions. ── */
9235
+ function addCaptionsFromTranscript(styleKey) {
9236
+ const C = FableCutCaptions;
9237
+ if (transcriptWordsSig() !== trState.wsig) renderTranscript(true);
9238
+ const words = trState.words;
9239
+ if (!words.length) { toast("Transcribe the clips first — captions are made from their words"); return; }
9240
+ const m = C.metrics(styleKey, project.width, project.height);
9241
+ placeCaptions(C.cues(words, { chars: m.chars, lines: m.lines, words: m.words, maxDur: m.maxDur, fps: projectFps() }), styleKey, "");
9242
+ }
9243
+ /** Put caption cues on the timeline (replacing the captions there), as one undo step. */
9244
+ function placeCaptions(list, styleKey, from) {
9245
+ const C = FableCutCaptions;
9246
+ if (!list.length) { toast("No captions to add"); return; }
9247
+ const old = project.clips.filter(C.isCaption);
9248
+ if (old.some(isGroupLocked)) { toastLocked(); return; }
9249
+ const span = [list[0].start, list[list.length - 1].end];
9250
+ const lane = C.trackFor(old.length ? project : { ...project, clips: project.clips.filter((c) => !C.isCaption(c)), tracks: serializeTracks() }, span[0], span[1]);
9251
+ if (state.lockedTracks?.has?.(lane.track) || (project.lockedTracks || []).includes(lane.track)) { toast(`${lane.track} is locked — unlock it for the captions`); return; }
9252
+ const snap = undoSnapshot();
9253
+ let track = lane.track;
9254
+ if (lane.add) {
9255
+ const t = addTimelineTrack("video");
9256
+ if (!t) return;
9257
+ track = t.id;
9258
+ }
9259
+ const oldIds = new Set(old.map((c) => c.id));
9260
+ project.clips = project.clips.filter((c) => !oldIds.has(c.id));
9261
+ for (const id of oldIds) state.selIds.delete(id);
9262
+ if (oldIds.has(state.selId)) state.selId = null;
9263
+ for (const cue of list) project.clips.push({ ...C.clip(cue, { style: styleKey, width: project.width, height: project.height, track }), id: "c_" + uid() });
9264
+ pushUndo(snap);
9265
+ pruneSelection();
9266
+ state.dirtyTimeline = true;
9267
+ scheduleSave();
9268
+ renderInspector();
9269
+ toast(`${list.length} caption${list.length === 1 ? "" : "s"} on ${track}${from ? " " + from : ""}${old.length ? ` · replaced ${old.length}` : ""}`);
9270
+ }
9271
+ /** A cut, split or trim that shortens a caption leaves its words timed to the old cut: say so, for a moment. */
9272
+ const capWatch = { durs: null, at: 0, said: 0 };
9273
+ function watchCaptions(now) {
9274
+ if (now - capWatch.at < 500 || typeof FableCutCaptions === "undefined") return;
9275
+ capWatch.at = now;
9276
+ const durs = new Map();
9277
+ for (const c of project.clips) if (FableCutCaptions.isCaption(c)) durs.set(c.id, c.duration);
9278
+ const prev = capWatch.durs;
9279
+ capWatch.durs = durs;
9280
+ if (!prev || now - capWatch.said < 5000) return;
9281
+ for (const [id, d] of durs) {
9282
+ if (prev.has(id) && d < prev.get(id) - 1e-4) {
9283
+ capWatch.said = now;
9284
+ toast("Captions don't re-time when cut — add them again in the Transcript tab once the edit is done");
9285
+ return;
9286
+ }
9287
+ }
9288
+ }
9289
+ function downloadCaptions(kind) {
9290
+ const C = FableCutCaptions, list = C.fromClips(project.clips, [...state.disabledTracks]);
9291
+ if (!list.length) { toast("No captions on the timeline yet — Add captions first"); return; }
9292
+ const blob = new Blob([kind === "vtt" ? C.toVTT(list) : C.toSRT(list)], { type: kind === "vtt" ? "text/vtt" : "application/x-subrip" });
9293
+ const a = document.createElement("a");
9294
+ a.href = URL.createObjectURL(blob);
9295
+ a.download = `${String(project.name || "captions").replace(/[^\w\- ]+/g, "_").trim() || "captions"}.${kind}`;
9296
+ document.body.appendChild(a);
9297
+ a.click();
9298
+ a.remove();
9299
+ setTimeout(() => URL.revokeObjectURL(a.href), 2000);
9300
+ toast(`Saved ${list.length} caption${list.length === 1 ? "" : "s"} as ${a.download}`);
9301
+ }
9302
+ /* fablecut_transcribe: transcribe the job's files in this tab, save them, report. */
9303
+ async function runTranscribeJob(ticket, fail) {
9304
+ const spec = ticket.transcribe || {};
9305
+ if (typeof FableCutTranscribe === "undefined") return fail("the transcript module is missing — reload the editor");
9306
+ if (trState.busy) return fail("this editor tab is already transcribing — wait for it, or cancel it there");
9307
+ const srcs = [], skipped = [];
9308
+ for (const src of spec.srcs || []) {
9309
+ if (!spec.again && await loadTranscript(src, true)) { skipped.push(src); continue; }
9310
+ srcs.push(src);
9311
+ }
9312
+ const report = (body, force) => fetch("/api/export/job/report?id=" + encodeURIComponent(ticket.id), { method: "POST", body: JSON.stringify(body) })
9313
+ .then((r) => r.json()).then((r) => { if (r?.cancel) cancelTranscribe(); }).catch(() => { });
9314
+ if (!srcs.length) return report({ status: "done", result: { done: [], skipped, failed: [] } });
9315
+ let last = 0;
9316
+ const out = await transcribeSrcs(srcs, { model: FableCutTranscribe.model(spec.model), language: spec.language || null }, (f) => {
9317
+ const t = performance.now();
9318
+ if (t - last > 1000) { last = t; report({ progress: f }); }
9319
+ }).catch((e) => ({ done: [], failed: srcs.map((src) => ({ src, error: e.message })) }));
9320
+ for (const d of out.done) if (!d.saved) out.failed.push({ src: d.src, error: "transcribed, but the server didn't save it" });
9321
+ out.done = out.done.filter((d) => d.saved);
9322
+ if (out.cancelled) return report({ status: "failed", error: "cancelled" });
9323
+ if (!out.done.length && out.failed.length) return fail(out.failed.map((f) => `${f.src}: ${f.error}`).join(" · "));
9324
+ return report({ status: "done", result: { done: out.done, skipped, failed: out.failed } });
9325
+ }
9326
+ function clearSilences() {
9327
+ silenceGen++; // a Find still listening doesn't bring the marks back
9328
+ state.silence = null;
9329
+ state.silenceBusy = false;
9330
+ state.dirtyTimeline = true;
9331
+ renderInspector();
8620
9332
  }
8621
9333
  async function autoDuckClips(clips, { under = null, amount = duckAmount(), threshold = -40 } = {}) {
8622
9334
  if (typeof FableCutDucking === "undefined") { toast("Ducking module missing — reload the editor"); return; }
@@ -8703,17 +9415,20 @@ function parseDbInput(s) {
8703
9415
  return Number.isFinite(v) ? clampFaderDb(v) : null;
8704
9416
  }
8705
9417
  function setSideTab(tab) {
8706
- const mixer = tab === "mixer", color = tab === "color";
9418
+ const mixer = tab === "mixer", color = tab === "color", transcript = tab === "transcript";
8707
9419
  mixerState.open = mixer;
8708
9420
  colorState.open = color;
9421
+ trState.open = transcript;
8709
9422
  for (const b of els.sideTabs.querySelectorAll("[data-side]"))
8710
9423
  b.classList.toggle("on", b.dataset.side === tab);
8711
- els.inspector.classList.toggle("hidden", mixer || color);
9424
+ els.inspector.classList.toggle("hidden", mixer || color || transcript);
8712
9425
  els.mixer.classList.toggle("hidden", !mixer);
8713
9426
  els.colorPage.classList.toggle("hidden", !color);
9427
+ els.transcriptPage.classList.toggle("hidden", !transcript);
8714
9428
  try { localStorage.setItem(SIDE_TAB_KEY, tab); } catch { }
8715
9429
  if (mixer) renderMixer();
8716
9430
  else if (color) renderColorPage(true);
9431
+ else if (transcript) renderTranscript(true);
8717
9432
  else renderInspector();
8718
9433
  }
8719
9434
  /** Write a track's fader / pan, push it into the live graph, persist. */
@@ -12987,6 +13702,7 @@ window.addEventListener("keydown", (e) => {
12987
13702
  return;
12988
13703
  }
12989
13704
  if (!maskUi.clip || (maskUi.sel < 0 && !maskUi.tool)) return;
13705
+ if (els.transcriptPage?.contains(e.target)) return; // keys typed in the Transcript tab are its own
12990
13706
  const tg = e.target;
12991
13707
  if (tg && (tg.tagName === "INPUT" || tg.tagName === "TEXTAREA" || tg.tagName === "SELECT" || tg.isContentEditable)) return;
12992
13708
  const c = getClip(state.selId);
@@ -13659,6 +14375,7 @@ els.preview.addEventListener("dblclick", (e) => {
13659
14375
  shapeUi.pt = -1; scheduleSave(); renderInspector();
13660
14376
  }, true);
13661
14377
  window.addEventListener("keydown", (e) => {
14378
+ if (els.transcriptPage?.contains(e.target)) return; // keys typed in the Transcript tab are its own
13662
14379
  if (e.key === "Escape" && runtime.anchorTool && !shapeUi.sel && !shapeUi.tool) {
13663
14380
  const tg0 = e.target;
13664
14381
  if (!(tg0 && (tg0.tagName === "INPUT" || tg0.tagName === "TEXTAREA" || tg0.tagName === "SELECT"))) {
@@ -13792,12 +14509,13 @@ function drawTextOnPath(c, p, local) {
13792
14509
  return out;
13793
14510
  };
13794
14511
  const words = anim === "word-pop" ? centre("word") : null, lineBox = anim === "zoom-in" ? centre("line") : null;
14512
+ const clk = wordClock(c, p, wi, rate);
13795
14513
  const shown = anim === "typewriter" ? Math.floor(local / (rate / 4)) : Infinity;
13796
14514
  const ease = EASE["ease-out"];
13797
14515
  for (const q of glyphs) {
13798
14516
  if (q.space || q.gi >= shown) continue;
13799
- let d = q.d, scale = 1, alpha = 1, dx = 0, dy = 0, clipL = null, clipR = null, rise = null;
13800
- const uw = clamp((local - q.word * rate) / 0.25, 0, 1); // per word
14517
+ let d = q.d, scale = 1, alpha = 1, dx = 0, dy = 0, clipL = null, clipR = null, rise = null, lit = false;
14518
+ const uw = clamp((local - clk(q.word)[0]) / 0.25, 0, 1); // per word
13801
14519
  const ul = (dur) => clamp((local - q.line * rate) / dur, 0, 1); // per line
13802
14520
  if (anim === "letter-pop") {
13803
14521
  const u = clamp((local - q.ci * rate / 3) / 0.18, 0, 1);
@@ -13815,6 +14533,7 @@ function drawTextOnPath(c, p, local) {
13815
14533
  } else if (anim === "bounce") dy -= Math.abs(Math.sin(local * 3.2 + q.word * 0.9)) * size * 0.18;
13816
14534
  else if (anim === "shake") { dx += Math.sin(local * 31 + q.word * 7.3) * size * 0.035; dy += Math.cos(local * 27 + q.word * 3.1) * size * 0.035; }
13817
14535
  else if (anim === "karaoke") alpha = uw >= 1 ? 1 : 0.3 + uw * 0.7;
14536
+ else if (anim === "highlight") lit = wordIsCurrent(clk, q.word, wi, local);
13818
14537
  else if (anim === "clip-reveal") { // a wipe runs along each line in reading order
13819
14538
  const u = ul(0.5);
13820
14539
  if (u <= 0) continue;
@@ -13853,7 +14572,7 @@ function drawTextOnPath(c, p, local) {
13853
14572
  }
13854
14573
  if (p.glow > 0) { ctx2d.shadowColor = p.glowColor || p.color || "#fff"; ctx2d.shadowBlur = (+p.glow) * size / 40; }
13855
14574
  else if (shadowBlur > 0) { ctx2d.shadowColor = "rgba(0,0,0,.7)"; ctx2d.shadowBlur = shadowBlur; ctx2d.shadowOffsetY = shadowBlur / 3; }
13856
- ctx2d.fillStyle = fill();
14575
+ ctx2d.fillStyle = lit ? p.highlightColor || "#ffd166" : fill();
13857
14576
  ctx2d.fillText(q.g, 0, 0);
13858
14577
  if (p.glow > 0) ctx2d.fillText(q.g, 0, 0);
13859
14578
  ctx2d.globalAlpha = keep;
@@ -14158,7 +14877,24 @@ function letterAnimSegments(line) {
14158
14877
 
14159
14878
  /* ── Text rendering: styling (stroke / background pill) + kinetic animations.
14160
14879
  `local` is clip-local time in seconds. Word timing: word i enters at
14161
- i * wordRate; each entrance animation lasts ~0.25 s. ── */
14880
+ i * wordRate — or, on a caption timed to speech, at its wordTimes start;
14881
+ each entrance animation lasts ~0.25 s. ── */
14882
+ /** Word i's [start, end], seconds from the clip's start: props.wordTimes (a caption timed to speech)
14883
+ * when it has one pair per word; if the text was edited to another word count, spread over the clip;
14884
+ * else one every wordRate seconds. */
14885
+ function wordClock(c, p, n, rate) {
14886
+ const wt = p.wordTimes;
14887
+ if (Array.isArray(wt) && wt.length === n && n) return (i) => [+wt[i]?.[0] || 0, +wt[i]?.[1] || 0];
14888
+ if (Array.isArray(wt) && n) { const step = Math.max(0.05, (+c?.duration || n * rate) / n); return (i) => [i * step, (i + 1) * step]; }
14889
+ return (i) => [i * rate, (i + 1) * rate];
14890
+ }
14891
+ /** Is word i the one being said? From its start to its end (a tenth of a second more, so the
14892
+ * highlight doesn't flicker between words), and never past the next word's start. */
14893
+ function wordIsCurrent(clk, i, n, local) {
14894
+ const [a, b] = clk(i);
14895
+ const until = Math.max(b, a + 0.05) + 0.1;
14896
+ return local >= a && local < (i + 1 < n ? Math.min(clk(i + 1)[0], until) : until);
14897
+ }
14162
14898
  const backOut = (u) => { const c1 = 1.70158, c3 = c1 + 1; const v = u - 1; return 1 + c3 * v * v * v + c1 * v * v; };
14163
14899
  function hexToRgba(hex, a) {
14164
14900
  const n = parseInt(String(hex).replace("#", ""), 16) || 0;
@@ -14352,7 +15088,7 @@ function drawText(c, p, local) {
14352
15088
  g.addColorStop(1, p.color2);
14353
15089
  return g;
14354
15090
  };
14355
- const paint = (str, x, y, alpha = 1, rtl = false) => {
15091
+ const paint = (str, x, y, alpha = 1, rtl = false, fill = null) => {
14356
15092
  if (alpha <= 0) return;
14357
15093
  const keep = ctx2d.globalAlpha;
14358
15094
  const prevDir = ctx2d.direction;
@@ -14369,15 +15105,15 @@ function drawText(c, p, local) {
14369
15105
  if (p.glow > 0) { // neon: colored halo, double-fill for intensity
14370
15106
  ctx2d.shadowColor = p.glowColor || p.color || "#fff";
14371
15107
  ctx2d.shadowBlur = (+p.glow) * size / 40;
14372
- ctx2d.fillStyle = fillFor(y);
15108
+ ctx2d.fillStyle = fill || fillFor(y);
14373
15109
  ctx2d.fillText(str, x, y);
14374
15110
  ctx2d.fillText(str, x, y);
14375
15111
  } else if (shadowBlur > 0) {
14376
15112
  ctx2d.shadowColor = "rgba(0,0,0,.7)"; ctx2d.shadowBlur = shadowBlur; ctx2d.shadowOffsetY = shadowBlur / 3;
14377
- ctx2d.fillStyle = fillFor(y);
15113
+ ctx2d.fillStyle = fill || fillFor(y);
14378
15114
  ctx2d.fillText(str, x, y);
14379
15115
  } else {
14380
- ctx2d.fillStyle = fillFor(y);
15116
+ ctx2d.fillStyle = fill || fillFor(y);
14381
15117
  ctx2d.fillText(str, x, y);
14382
15118
  }
14383
15119
  ctx2d.shadowColor = "transparent"; ctx2d.shadowBlur = 0; ctx2d.shadowOffsetY = 0;
@@ -14506,6 +15242,8 @@ function drawText(c, p, local) {
14506
15242
  }
14507
15243
  // word-based animations: lay words out manually, per-line, honoring alignment + direction
14508
15244
  const spaceW = ctx2d.measureText(" ").width;
15245
+ const nWords = rawLines.reduce((n, ln) => n + ln.split(/\s+/).filter(Boolean).length, 0);
15246
+ const clk = wordClock(c, p, nWords, rate);
14509
15247
  let wi = 0;
14510
15248
  rawLines.forEach((ln, i) => {
14511
15249
  const y = y0 + i * lh;
@@ -14523,8 +15261,16 @@ function drawText(c, p, local) {
14523
15261
  words.forEach((word, j) => {
14524
15262
  const w = widths[j];
14525
15263
  const cx = rtl ? x - w / 2 : x + w / 2;
14526
- const u = clamp((local - wi * rate) / 0.25, 0, 1);
14527
- if (anim === "word-pop") {
15264
+ const u = clamp((local - clk(wi)[0]) / 0.25, 0, 1);
15265
+ if (anim === "highlight") { // every word shown; the one being said lit and lifted a little
15266
+ const on = wordIsCurrent(clk, wi, nWords, local);
15267
+ const s = on ? 1 + 0.03 * backOut(clamp((local - clk(wi)[0]) / 0.15, 0, 1)) : 1;
15268
+ ctx2d.save();
15269
+ ctx2d.translate(cx, y);
15270
+ if (s !== 1) ctx2d.scale(s, s);
15271
+ paint(word, 0, 0, 1, rtl, on ? p.highlightColor || "#ffd166" : null);
15272
+ ctx2d.restore();
15273
+ } else if (anim === "word-pop") {
14528
15274
  if (u > 0) {
14529
15275
  ctx2d.save();
14530
15276
  ctx2d.translate(cx, y);
@@ -14791,6 +15537,8 @@ function loop(ts) {
14791
15537
  }
14792
15538
  }
14793
15539
  if (state.dirtyTimeline) rebuildClips();
15540
+ if (trState.open) transcriptTick();
15541
+ watchCaptions(ts);
14794
15542
  const phX = Math.round(state.time * state.pps);
14795
15543
  if (phX !== playheadPx) {
14796
15544
  playheadPx = phX;
@@ -16622,6 +17370,7 @@ async function runExportJob(ticket) {
16622
17370
  if (ticket.revision != null && (project.revision || 0) < ticket.revision) await syncFromServer();
16623
17371
  if (ticket.kind === "scopes") return runScopesJob(ticket, fail);
16624
17372
  if (ticket.kind === "track") return runTrackJob(ticket, fail);
17373
+ if (ticket.kind === "transcribe") return runTranscribeJob(ticket, fail);
16625
17374
  if (!state.ffmpeg) {
16626
17375
  const j = await fetch("/api/export/ffmpeg").then((r) => r.json()).catch(() => ({}));
16627
17376
  state.ffmpeg = !!j.available;
@@ -19326,7 +20075,7 @@ for (const b of els.sideTabs.querySelectorAll("[data-side]"))
19326
20075
  b.addEventListener("click", () => setSideTab(b.dataset.side));
19327
20076
  try {
19328
20077
  const side = localStorage.getItem(SIDE_TAB_KEY);
19329
- if (side === "mixer" || side === "color") setSideTab(side);
20078
+ if (side === "mixer" || side === "color" || side === "transcript") setSideTab(side);
19330
20079
  if (localStorage.getItem(WS_KEY) === "color") setWorkspace("color");
19331
20080
  } catch { }
19332
20081
  connectServer().then(() => { loadLibraryFonts(); runExportJobFromUrl(); });