fablecut 1.16.0 → 1.18.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,10 @@ 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)
557
+ beats: null, // the beat Find beats heard (Inspector → Beats): {clipId, sig, a, grid, bpm, drop}, ticks on the timeline
558
+ beatsBusy: false, // Find beats is listening
553
559
  trackSize: "l", // s | m | l — timeline track density preset
554
560
  connected: false, exporting: false,
555
561
  rendering: false, // fast (server/ffmpeg) export in progress
@@ -793,7 +799,7 @@ const els = {
793
799
  btnInsert: $("btnInsert"), btnReplace: $("btnReplace"),
794
800
  vuMeter: $("vuMeter"),
795
801
  sideTabs: $("sideTabs"),
796
- mixer: $("mixer"), colorPage: $("colorPage"),
802
+ mixer: $("mixer"), colorPage: $("colorPage"), transcriptPage: $("transcriptPage"),
797
803
  exportSetup: $("exportSetup"), engineFast: $("engineFast"), engineRealtime: $("engineRealtime"),
798
804
  exportProfileRow: $("exportProfileRow"),
799
805
  exportProfileSel: $("exportProfileSel"), exportProfileNote: $("exportProfileNote"),
@@ -1677,6 +1683,7 @@ function listenSSE() {
1677
1683
  // Named events: "change" = project/media/library; "profiles" = encoding-profiles.json only
1678
1684
  es.addEventListener("change", () => { noteActivity(); syncFromServer(); scheduleOfflineCheck(); });
1679
1685
  es.addEventListener("proxy", (e) => onProxyEvent(e.data));
1686
+ es.addEventListener("transcript", (e) => onTranscriptEvent(e.data));
1680
1687
  es.addEventListener("versions", (e) => {
1681
1688
  let d = {};
1682
1689
  try { d = JSON.parse(e.data); } catch { }
@@ -1755,13 +1762,22 @@ async function syncFromServer(force) {
1755
1762
  return true;
1756
1763
  }
1757
1764
  if (!force && (data.revision || 0) === (project.revision || 0)) return; // our own save
1765
+ // An edit from outside (an agent, another tab) on the open timeline becomes an undo step of its own,
1766
+ // so Ctrl+Z takes it back first instead of replaying an older step over it.
1767
+ const before = !state.compCtx && SeqLib.activeId(data) === SeqLib.activeId(project) ? undoSnapshot() : null;
1768
+ const mediaBefore = project.media;
1769
+ let clash = false;
1758
1770
  if (runtime.saveTimer) { // unsaved local edit vs. external write: external wins, tell the user
1759
1771
  clearTimeout(runtime.saveTimer); runtime.saveTimer = null;
1760
1772
  // the undo steps describe the discarded edit; replaying one would re-save over the external write
1761
1773
  runtime.undo.length = 0; runtime.redo.length = 0;
1762
- toast("Project was updated externally — your last change may need redoing.");
1774
+ clash = true;
1763
1775
  }
1764
1776
  applyProject(data);
1777
+ const step = before && outsideEditStep(before, undoSnapshot(), mediaBefore, project.media);
1778
+ if (step) pushUndo(step);
1779
+ if (clash) toast(step ? "The project was changed from outside while you were editing. Ctrl+Z puts your version back."
1780
+ : "Project was updated externally — your last change may need redoing.");
1765
1781
  syncCompCrumb(); // the top bar shows the project's name
1766
1782
  // "Compare with now" was against the document before this change
1767
1783
  // (always: a comparison still on its way was made against the old document too)
@@ -3843,6 +3859,18 @@ function counterSnapshot(snap) {
3843
3859
  return JSON.stringify({ clips: project.clips, markers: project.markers || [], comps: project.comps || [], media: project.media,
3844
3860
  ...(hasSeqClips(snap) ? { seqClips: otherSequenceClips() } : {}) });
3845
3861
  }
3862
+ /** The undo step for an edit made outside this tab (an agent, another tab): the timeline as it was
3863
+ * (`before`), marked so undo can say what it took back — or null when the open timeline didn't change.
3864
+ * When the edit removed media, the step carries the media list as it was too, so the clips it puts
3865
+ * back find their files (and redo, whose counter-snapshot then carries media, takes them out again). */
3866
+ function outsideEditStep(before, after, mediaBefore = null, mediaAfter = null) {
3867
+ if (before === after) return null;
3868
+ const now = new Set((mediaAfter || []).map((m) => m.id));
3869
+ const lost = (mediaBefore || []).some((m) => !now.has(m.id));
3870
+ const snap = lost ? before.slice(0, -1) + ',"media":' + JSON.stringify(mediaBefore) + "}" : before;
3871
+ return '{"outside":true,' + snap.slice(1);
3872
+ }
3873
+ const isOutsideStep = (snap) => typeof snap === "string" && snap.startsWith('{"outside":true,');
3846
3874
  function undo() {
3847
3875
  if (!runtime.undo.length) return;
3848
3876
  const snap = runtime.undo.pop();
@@ -3850,6 +3878,7 @@ function undo() {
3850
3878
  restoreSnapshot(snap);
3851
3879
  pruneSelection();
3852
3880
  scheduleSave(); renderInspector();
3881
+ if (isOutsideStep(snap)) toast("Undid a change made outside this tab (an agent or another tab)");
3853
3882
  }
3854
3883
  function redo() {
3855
3884
  if (!runtime.redo.length) return;
@@ -4991,9 +5020,62 @@ function rebuildClips() {
4991
5020
  if (hasWave) drawClipWave(div.querySelector(".wave"), c, tr.h);
4992
5021
  }
4993
5022
  paintAudioOverlaps();
5023
+ paintSilences();
5024
+ paintBeats();
4994
5025
  state.dirtyTimeline = false;
4995
5026
  updateWorkArea();
4996
5027
  }
5028
+ /* The silences Find marked: a band on each lane of the clips that were listened to. */
5029
+ function paintSilences() {
5030
+ const s = state.silence;
5031
+ if (!s) return;
5032
+ if (s.sig !== silenceSig()) { state.silence = null; return; } // the timeline moved on: they no longer line up
5033
+ const lanes = new Set(withLinked(project.clips.filter((c) => s.ids.includes(c.id))).map((c) => c.track));
5034
+ for (const id of lanes) {
5035
+ const row = els.tracks.querySelector(`[data-track="${id}"]`);
5036
+ if (!row) continue;
5037
+ for (const sp of s.spans) {
5038
+ const el = document.createElement("div");
5039
+ el.className = "silence-span";
5040
+ el.style.left = (sp.from * state.pps) + "px";
5041
+ el.style.width = Math.max(2, (sp.to - sp.from) * state.pps) + "px";
5042
+ el.title = `Silence ${fmt(sp.from)} → ${fmt(sp.to)} (${(sp.to - sp.from).toFixed(2)} s) · Inspector → Silence → Cut`;
5043
+ row.appendChild(el);
5044
+ }
5045
+ }
5046
+ }
5047
+ /* The beat Find beats heard: a tick on the music's lane and every video lane. */
5048
+ function paintBeats() {
5049
+ const s = state.beats;
5050
+ if (!s) return;
5051
+ if (s.sig !== beatsSig(getClip(s.clipId))) { state.beats = null; return; }
5052
+ const lanes = new Set([getClip(s.clipId).track, ...TRACKS.filter((t) => t.kind === "video").map((t) => t.id)]);
5053
+ const g = s.grid, n = g.length;
5054
+ if (!n) return;
5055
+ // a steady grid is one striped band per lane, however long the song; onsets without a tempo are ticks
5056
+ const per = n > 1 ? (g[n - 1] - g[0]) / (n - 1) : 0;
5057
+ const steady = n > 2 && per > 0 && g.every((t, i) => !i || Math.abs(t - g[i - 1] - per) < 0.004);
5058
+ for (const id of lanes) {
5059
+ const row = els.tracks.querySelector(`[data-track="${id}"]`);
5060
+ if (!row) continue;
5061
+ if (steady) {
5062
+ const el = document.createElement("div");
5063
+ el.className = "beat-band";
5064
+ const step = per * state.pps;
5065
+ el.style.left = (g[0] * state.pps - 0.5) + "px";
5066
+ el.style.width = ((g[n - 1] - g[0]) * state.pps + 1) + "px";
5067
+ el.style.backgroundImage = `repeating-linear-gradient(to right, var(--beat-tick) 0 1px, transparent 1px ${step}px)`;
5068
+ row.appendChild(el);
5069
+ continue;
5070
+ }
5071
+ for (const t of g.slice(0, 600)) {
5072
+ const el = document.createElement("div");
5073
+ el.className = "beat-tick";
5074
+ el.style.left = (t * state.pps) + "px";
5075
+ row.appendChild(el);
5076
+ }
5077
+ }
5078
+ }
4997
5079
  /* Hatched bands where two+ audio clips share a track (CSS draw, O(n²) per track). */
4998
5080
  function paintAudioOverlaps() {
4999
5081
  const byTrack = new Map();
@@ -6603,6 +6685,23 @@ function renderInspector(lite) {
6603
6685
  ${check("Flip V", "flipV", p.flipV)}
6604
6686
  </div>`;
6605
6687
  }
6688
+ if ((c.kind === "video" || c.kind === "image") && typeof Reframe !== "undefined") {
6689
+ const m = getMedia(c.mediaId);
6690
+ const shape = m && m.width > 0 && m.height > 0 && Math.abs(m.width / m.height - project.width / project.height) > 0.01;
6691
+ if (shape || p.reframe) {
6692
+ const note = p.reframe === "follow" ? `Follows the subject${c.keyframes?.x?.length || c.keyframes?.y?.length ? ` (${(c.keyframes.x || c.keyframes.y).length} keys)` : " (one steady position)"}`
6693
+ : p.reframe === "centre" ? "Fitted and centred" : "This picture is another shape than the canvas.";
6694
+ html += `<div class="insp-section"><h3>Reframe</h3>
6695
+ <div class="insp-note">${note}</div>
6696
+ ${reframeRun.busy
6697
+ ? row("", `<span class="insp-ctrls"><span style="opacity:.75">Looking at the footage… ${reframeRun.done + 1}/${reframeRun.of}${reframeRun.frac ? ` · ${Math.round(reframeRun.frac * 100)}%` : ""}</span>
6698
+ <button type="button" class="btn tiny" data-rf-cancel>Cancel</button></span>`)
6699
+ : row("", `<span class="insp-ctrls"><button type="button" class="btn tiny" data-rf-follow title="Fit it to cover the canvas and key its position to keep the subject in view (the selected clips; one undo step)">Follow subject</button>
6700
+ <button type="button" class="btn tiny" data-rf-centre title="Fit it to cover the canvas, centred">Centre</button>
6701
+ <select data-rf-smooth title="How the virtual camera moves" style="width:auto;min-width:6.5em"><option value="0.2">Lively</option><option value="0.5" selected>Balanced</option><option value="0.85">Steady</option></select></span>`)}
6702
+ </div>`;
6703
+ }
6704
+ }
6606
6705
  if (c.kind === "video" || c.kind === "image" || c.kind === "svg" || c.kind === "adjust" || c.kind === "comp") {
6607
6706
  html += `<div class="insp-section"><h3>Filter / Color</h3>
6608
6707
  ${sel("Preset", "filterPreset", Object.keys(FILTER_PRESETS), p.filterPreset)}
@@ -6655,6 +6754,40 @@ function renderInspector(lite) {
6655
6754
  ${slider("speed", 0.25, 4, 0.05, p.speed, "×")}
6656
6755
  </div>`;
6657
6756
  }
6757
+ if ((c.kind === "video" || c.kind === "audio") && typeof FableCutSilence !== "undefined") {
6758
+ const so = silenceOptions(), found = state.silence;
6759
+ 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>`;
6760
+ html += `<div class="insp-section"><h3>Silence</h3>
6761
+ ${row("Below", num("threshold", -80, -10, 1, "dB", "Quieter than this counts as silence (dBFS). Raise it toward −30 in a noisy room"))}
6762
+ ${row("At least", num("minSilence", 0.1, 10, 0.1, "s", "Shorter pauses are left alone"))}
6763
+ ${row("Keep", num("padding", 0, 2, 0.05, "s beside speech", "Quiet kept before and after each phrase, so words aren't clipped"))}
6764
+ ${row("", state.silenceBusy
6765
+ ? `<span class="insp-ctrls"><span style="opacity:.75">Listening…</span>
6766
+ <button type="button" class="btn tiny" data-sil-clear title="Stop listening">Cancel</button></span>`
6767
+ : `<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>
6768
+ ${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>
6769
+ <button type="button" class="btn tiny" data-sil-clear title="Remove the marks">Clear</button>` : ""}</span>`)}
6770
+ ${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>` : ""}
6771
+ </div>`;
6772
+ }
6773
+ if ((c.kind === "video" || c.kind === "audio") && typeof FableCutBeats !== "undefined") {
6774
+ const bt = state.beats && state.beats.clipId === c.id ? state.beats : null, bs = beatsSettings();
6775
+ const lanes = TRACKS.filter((t) => t.kind === "video" && project.clips.some((x) => x.track === t.id)).map((t) => t.id)
6776
+ .sort((x, y) => (+x.slice(1) || 0) - (+y.slice(1) || 0));
6777
+ html += `<div class="insp-section"><h3>Beats</h3>
6778
+ ${row("", state.beatsBusy
6779
+ ? `<span class="insp-ctrls"><span style="opacity:.75">Listening…</span>
6780
+ <button type="button" class="btn tiny" data-beat-clear title="Stop listening">Cancel</button></span>`
6781
+ : `<span class="insp-ctrls"><button type="button" class="btn tiny" data-beat-find title="Listen to this clip's music and show its beat on the timeline">Find beats</button>
6782
+ ${bt ? `<button type="button" class="btn tiny" data-beat-clear title="Hide the beat">Clear</button>` : ""}</span>`)}
6783
+ ${bt ? `<div class="insp-note">${bt.bpm != null ? bt.bpm + " BPM · " : ""}${bt.grid.length} beats, ${fmt(bt.grid[0])} → ${fmt(bt.grid[bt.grid.length - 1])}${bt.drop != null ? ` · the drop at ${fmt(bt.drop)}` : ""}</div>
6784
+ ${row("", `<span class="insp-ctrls"><button type="button" class="btn tiny" data-beat-mark title="A cyan marker on every beat (other markers stay)">Mark</button>
6785
+ <button type="button" class="btn tiny" data-beat-snap title="Roll each cut on the targeted video tracks to the nearest beat — nothing else moves">Snap cuts</button></span>`)}
6786
+ ${lanes.length ? row("Re-cut", `<span class="insp-ctrls"><select data-beat-track title="The track whose clips go on the beat" style="width:auto;min-width:4.2em">${lanes.map((id) => `<option>${id}</option>`).join("")}</select>
6787
+ every <select data-beat-every title="Beats per shot" style="width:auto;min-width:3.6em">${FableCutBeats.EVERY.map((n) => `<option value="${n}" ${n === bs.every ? "selected" : ""}>${n}</option>`).join("")}</select> beats</span>`) +
6788
+ row("", `<span class="insp-ctrls"><button type="button" class="btn tiny" data-beat-retime title="Lay that track's clips back to back on the beat, from the music's start (one undo step)">Re-cut</button></span>`) : ""}` : ""}
6789
+ </div>`;
6790
+ }
6658
6791
  if (c.kind === "audio" && typeof FableCutFx !== "undefined") {
6659
6792
  html += `<div class="insp-section" data-fx-section><h3>Audio effects</h3>${fxEditorHtml(c.fx, playheadOverClip(c) ? state.time - c.start : null)}</div>`;
6660
6793
  }
@@ -6740,7 +6873,11 @@ function renderInspector(lite) {
6740
6873
  ${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
6874
  <button class="btn tiny" data-action="title-shuffle" title="Random style">Shuffle</button>`)}
6742
6875
  ${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")}
6876
+ ${p.textAnim === "highlight" ? row("Highlight", `<input type="color" data-k="highlightColor" value="${p.highlightColor || "#ffd166"}" title="The colour of the word being said">`, "", "highlightColor") : ""}
6877
+ ${Array.isArray(p.wordTimes) && p.wordTimes.length ? `<div class="insp-note">${p.caption ? "Caption: its" : "Its"} ${p.wordTimes.length} words follow the speech${
6878
+ String(p.text || "").split(/\s+/).filter(Boolean).length === p.wordTimes.length ? ", so Word rate doesn't apply"
6879
+ : " — the text now has another number of words, so they are spread over the clip; Add captions again to re-time them"}.</div>`
6880
+ : slider("wordRate", 0.05, 0.6, 0.01, p.wordRate, "s")}
6744
6881
  </div>`;
6745
6882
  }
6746
6883
  els.inspector.innerHTML = html;
@@ -6866,6 +7003,33 @@ function renderInspector(lite) {
6866
7003
  const sel = selectedClips();
6867
7004
  clearDuck(sel.length ? sel : [c]);
6868
7005
  });
7006
+ els.inspector.querySelectorAll("[data-sil]").forEach((inp) => inp.addEventListener("change", () => {
7007
+ const o = silenceOptions(), [lo, hi] = FableCutSilence.LIMITS[inp.dataset.sil];
7008
+ o[inp.dataset.sil] = clamp(+inp.value || 0, lo, hi);
7009
+ inp.value = o[inp.dataset.sil];
7010
+ try { localStorage.setItem(SILENCE_KEY, JSON.stringify(o)); } catch { }
7011
+ }));
7012
+ els.inspector.querySelector("[data-sil-find]")?.addEventListener("click", () => {
7013
+ const sel = selectedClips();
7014
+ findSilences(sel.length ? sel : [c]);
7015
+ });
7016
+ els.inspector.querySelector("[data-sil-cut]")?.addEventListener("click", cutSilences);
7017
+ els.inspector.querySelector("[data-beat-find]")?.addEventListener("click", () => findBeats(c));
7018
+ els.inspector.querySelector("[data-beat-clear]")?.addEventListener("click", clearBeats);
7019
+ els.inspector.querySelector("[data-beat-mark]")?.addEventListener("click", () => beatsAction({ markers: true }));
7020
+ els.inspector.querySelector("[data-beat-snap]")?.addEventListener("click", () => beatsAction({ snap: true }));
7021
+ els.inspector.querySelector("[data-beat-every]")?.addEventListener("change", (e) => {
7022
+ try { localStorage.setItem(BEATS_KEY, JSON.stringify({ every: +e.target.value })); } catch { }
7023
+ });
7024
+ els.inspector.querySelector("[data-beat-retime]")?.addEventListener("click", () => beatsAction({ retime: {
7025
+ track: els.inspector.querySelector("[data-beat-track]")?.value,
7026
+ every: +(els.inspector.querySelector("[data-beat-every]")?.value || 2) } }));
7027
+ const rfTargets = () => { const sel = selectedClips().filter((x) => x.kind === "video" || x.kind === "image"); return sel.length ? sel : [c]; };
7028
+ els.inspector.querySelector("[data-rf-follow]")?.addEventListener("click", () =>
7029
+ reframeClips(rfTargets(), { follow: true, smooth: +(els.inspector.querySelector("[data-rf-smooth]")?.value || 0.5) }));
7030
+ els.inspector.querySelector("[data-rf-centre]")?.addEventListener("click", () => reframeClips(rfTargets(), { follow: false }));
7031
+ els.inspector.querySelector("[data-rf-cancel]")?.addEventListener("click", () => { reframeRun.cancel = true; });
7032
+ els.inspector.querySelector("[data-sil-clear]")?.addEventListener("click", clearSilences);
6869
7033
  els.inspector.querySelector("[data-norm-target]")?.addEventListener("change", (e) => {
6870
7034
  try { localStorage.setItem(NORMALIZE_KEY, e.target.value); } catch { }
6871
7035
  });
@@ -8599,13 +8763,14 @@ function setDuckKeys(c, keys) {
8599
8763
  }
8600
8764
  /** Timeline spans with sound on the voice clips (each measured after its
8601
8765
  * channel routing, scaled by its clip gain and static volume). */
8602
- async function voiceRegions(voices, threshold) {
8766
+ async function voiceRegions(voices, threshold, minLen, heard) {
8603
8767
  const lists = [];
8604
8768
  for (const v of voices) {
8605
8769
  const m = getMedia(v.mediaId);
8606
8770
  if (!m) continue;
8607
8771
  let buf;
8608
8772
  try { buf = await getAudioBuffer(m); } catch { continue; }
8773
+ heard?.add(v.id); // read and measured: its quiet is real quiet, not a file that failed to decode
8609
8774
  const a = clamp(Math.floor(v.in * buf.sampleRate), 0, buf.length);
8610
8775
  const b = clamp(Math.ceil(mediaTimeAt(v, clipEnd(v)) * buf.sampleRate), a, buf.length);
8611
8776
  const src = [];
@@ -8614,9 +8779,765 @@ async function voiceRegions(voices, threshold) {
8614
8779
  lists.push(FableCutDucking.activeRegions(env, {
8615
8780
  t0: v.start, speed: clipSpeed(v), threshold,
8616
8781
  gain: dbToGain(clipGainDb(v)) * clamp(+(v.props?.volume ?? 1), 0, VOL_MAX),
8782
+ ...(minLen != null ? { minLen } : {}),
8617
8783
  }));
8618
8784
  }
8619
- return FableCutDucking.mergeRegions(lists);
8785
+ // silence wants every pause, so nothing is bridged there; ducking bridges short gaps
8786
+ return FableCutDucking.mergeRegions(lists, minLen != null ? 0 : undefined);
8787
+ }
8788
+
8789
+ /* ── Silence (silence.js): find the pauses in speech, mark them on the
8790
+ timeline, cut them out with Extract — the same spans and ops as
8791
+ fablecut_silence. ── */
8792
+ const SILENCE_KEY = "fablecut-silence";
8793
+ function silenceOptions() {
8794
+ try { return FableCutSilence.options(JSON.parse(localStorage.getItem(SILENCE_KEY) || "{}")); }
8795
+ catch { return { ...FableCutSilence.DEFAULTS }; }
8796
+ }
8797
+ /** Each linked group's audio stems, else the clip itself (audio, or a video without stems). */
8798
+ function speechGroups(clips) {
8799
+ const groups = new Map();
8800
+ for (const c of clips) {
8801
+ if (c.kind !== "audio" && c.kind !== "video") continue;
8802
+ const key = c.linkGroup || c.id;
8803
+ if (groups.has(key)) continue;
8804
+ const stems = withLinked([c]).filter((x) => x.kind === "audio");
8805
+ groups.set(key, stems.length ? stems : [c]);
8806
+ }
8807
+ return [...groups.values()];
8808
+ }
8809
+ /** Everything the marks were found from — where each clip sits, its file, speed, level and switches, the
8810
+ * frame rate: marked silences only stand while this is unchanged. */
8811
+ function silenceSig() {
8812
+ return project.fps + "#" + project.clips.map((c) => JSON.stringify([c.id, c.track, c.start, c.in, c.duration, c.mediaId,
8813
+ getMedia(c.mediaId)?.src ?? null, c.linkGroup ?? null, c.props?.speed ?? 1, c.keyframes?.speed ?? null,
8814
+ c.props?.gain ?? 0, c.props?.volume ?? 1, c.props?.audioChannel ?? null, c.props?.channelMode ?? null,
8815
+ clipRenders(c) ? 1 : 0])).join("|");
8816
+ }
8817
+ let silenceGen = 0; // the newest Find: an older one still decoding never replaces its result
8818
+ async function findSilences(clips, opts = silenceOptions()) {
8819
+ if (typeof FableCutSilence === "undefined") { toast("Silence module missing — reload the editor"); return; }
8820
+ // a new Find replaces the old marks whatever it finds, so Cut never acts on another clip's result
8821
+ const gen = ++silenceGen;
8822
+ if (state.silence) { state.silence = null; state.dirtyTimeline = true; renderInspector(); }
8823
+ const all = speechGroups(clips).map((g) => g.filter(clipRenders)).filter((g) => g.length);
8824
+ if (!all.length) { toast("Select a clip with sound to find its silences"); return; }
8825
+ // a speed ramp moves the sound along the timeline unevenly: those clips are left alone
8826
+ const groups = all.filter((g) => !g.some(FableCutSilence.ramped));
8827
+ if (!groups.length) { toast("These clips have a speed ramp — silence removal works on clips at a steady speed"); return; }
8828
+ toast("Listening for silences…");
8829
+ const sig = silenceSig(), heard = new Set();
8830
+ state.silenceBusy = true; // the Inspector shows Listening… with Cancel meanwhile
8831
+ renderInspector();
8832
+ let sound;
8833
+ try { sound = await voiceRegions(groups.flat(), opts.threshold, FableCutSilence.MIN_SOUND, heard); }
8834
+ finally { if (gen === silenceGen) state.silenceBusy = false; }
8835
+ if (gen !== silenceGen) return; // a newer Find took over, or Cancel
8836
+ renderInspector(); // Listening… → Find again, whatever comes next
8837
+ // the timeline moved while it listened: these spans belong to the old one
8838
+ if (silenceSig() !== sig) { toast("The timeline changed while listening — find the silences again"); return; }
8839
+ // a clip whose audio couldn't be read is not silent: leave its time alone
8840
+ const usable = groups.filter((g) => g.every((x) => heard.has(x.id)));
8841
+ if (!usable.length) { toast("Couldn't read the audio of these clips — nothing marked"); return; }
8842
+ const ranges = usable.map((g) => [Math.min(...g.map((x) => x.start)), Math.max(...g.map(clipEnd))]);
8843
+ const spans = FableCutSilence.silentSpans(sound, ranges, { ...opts, fps: project.fps });
8844
+ state.silence = spans.length ? { ids: usable.flat().map((x) => x.id), spans, sig } : null;
8845
+ state.dirtyTimeline = true;
8846
+ renderInspector();
8847
+ toast((spans.length
8848
+ ? `${spans.length} silence${spans.length === 1 ? "" : "s"}, ${FableCutSilence.total(spans).toFixed(1)} s — marked on the timeline`
8849
+ : "No silences that long — try a higher threshold or a shorter minimum") +
8850
+ (usable.length < groups.length ? " · some clips' audio couldn't be read, so their time is left alone" : "") +
8851
+ (groups.length < all.length ? " · clips with a speed ramp are left alone" : ""));
8852
+ }
8853
+ /** Extract every marked silence on the targeted tracks, last first: one undo step. */
8854
+ function cutSilences() {
8855
+ const s = state.silence;
8856
+ // the marks dropped when the timeline changed (the button can outlive them until the Inspector redraws)
8857
+ if (!s) { renderInspector(); toast("The timeline changed — find the silences again"); return; }
8858
+ if (s.sig !== silenceSig()) { state.silence = null; renderInspector(); toast("The timeline changed — find the silences again"); return; }
8859
+ const snap = undoSnapshot();
8860
+ let cut = 0, secs = 0;
8861
+ for (const sp of s.spans.slice().sort((a, b) => b.from - a.from)) {
8862
+ if (!EDIT.liftRange(sp.from, sp.to, true)) { cut++; secs += sp.to - sp.from; }
8863
+ }
8864
+ state.silence = null;
8865
+ if (!cut) { state.dirtyTimeline = true; renderInspector(); toast("Nothing was cut — target the clip's tracks first"); return; }
8866
+ pushUndo(snap);
8867
+ pruneSelection();
8868
+ state.dirtyTimeline = true;
8869
+ scheduleSave();
8870
+ renderInspector();
8871
+ toast(`Cut ${cut} silence${cut === 1 ? "" : "s"} · ${secs.toFixed(1)} s shorter`);
8872
+ }
8873
+
8874
+ /* ── Transcripts (transcribe.js, transcribe-worker.js): speech → words in this
8875
+ browser with Whisper, kept per file by the server (analysis/transcripts/).
8876
+ The Transcript tab shows the timeline's words: click one to go there, select
8877
+ some and press Delete (or Cut) to extract them, find a phrase and cut every
8878
+ time it is said — the same spans and extract ops as fablecut_transcribe. ── */
8879
+ const TRANSCRIBE_KEY = "fablecut-transcribe";
8880
+ const trState = { open: false, built: false, busy: null, sig: "", words: [], sel: null, anchor: null, drag: false, query: "", hits: [], now: -1 };
8881
+ const transcriptCache = new Map(); // src → validated transcript | false (none) | Promise while asking the server
8882
+ let transcriptGen = 0; // bumps whenever a transcript arrives or changes: the tab redraws
8883
+ function transcribeSettings() {
8884
+ let o = {};
8885
+ try { o = JSON.parse(localStorage.getItem(TRANSCRIBE_KEY) || "{}"); } catch { }
8886
+ let model = FableCutTranscribe.DEFAULT_MODEL, language = null, captionStyle = null;
8887
+ try { model = FableCutTranscribe.model(o.model); } catch { }
8888
+ try { language = FableCutTranscribe.language(o.language); } catch { }
8889
+ try { captionStyle = typeof FableCutCaptions !== "undefined" && o.captionStyle ? FableCutCaptions.style(o.captionStyle) : null; } catch { }
8890
+ return { model, language, captionStyle };
8891
+ }
8892
+ function saveTranscribeSettings(patch) {
8893
+ try { localStorage.setItem(TRANSCRIBE_KEY, JSON.stringify({ ...transcribeSettings(), ...patch })); } catch { }
8894
+ }
8895
+ /** The transcript of a file, if it is here already. */
8896
+ function transcriptOf(src) {
8897
+ const d = transcriptCache.get(src);
8898
+ return d && !(d instanceof Promise) ? d : null;
8899
+ }
8900
+ /** Ask the server for a file's transcript (once; `force` asks again). Resolves to it, or false. */
8901
+ function loadTranscript(src, force = false) {
8902
+ const have = transcriptCache.get(src);
8903
+ if (!force && have !== undefined) return have instanceof Promise ? have : Promise.resolve(have);
8904
+ const p = fetch("/api/transcript?src=" + encodeURIComponent(src)).then((r) => (r.ok ? r.json() : null))
8905
+ .then((j) => {
8906
+ let d = false;
8907
+ try { d = j && j.transcript ? FableCutTranscribe.validate(j.transcript) : false; } catch { }
8908
+ if (transcriptCache.get(src) === p) { transcriptCache.set(src, d); transcriptGen++; }
8909
+ return d;
8910
+ })
8911
+ .catch(() => { if (transcriptCache.get(src) === p) transcriptCache.set(src, false); return false; });
8912
+ transcriptCache.set(src, p);
8913
+ return p;
8914
+ }
8915
+ function onTranscriptEvent(data) {
8916
+ let src = null;
8917
+ try { src = JSON.parse(data).src; } catch { }
8918
+ if (!src) return;
8919
+ loadTranscript(src, true).then(() => renderTranscript(true));
8920
+ }
8921
+
8922
+ /* The worker: one at a time, each piece of audio answered in turn. */
8923
+ let trWorker = null, trSeq = 0, trIdleTimer = 0;
8924
+ const trPending = new Map();
8925
+ function transcribeWorker() {
8926
+ if (trWorker) return trWorker;
8927
+ trWorker = new Worker("transcribe-worker.js", { type: "module" });
8928
+ trWorker.onmessage = (e) => {
8929
+ const m = e.data || {};
8930
+ if (m.type === "progress") { onModelProgress(m); return; }
8931
+ const p = trPending.get(m.id);
8932
+ if (!p) return;
8933
+ trPending.delete(m.id);
8934
+ if (m.type === "done") p.resolve(m.chunks || []);
8935
+ else p.reject(new Error(/dynamically imported module|Failed to fetch|NetworkError|Load failed/i.test(m.error || "")
8936
+ ? "couldn't download the speech model — check the internet connection (it is needed the first time)"
8937
+ : m.error || "transcription failed"));
8938
+ };
8939
+ trWorker.onerror = (e) => {
8940
+ for (const p of trPending.values()) p.reject(new Error(e.message || "the speech worker failed to start"));
8941
+ trPending.clear();
8942
+ trWorker = null;
8943
+ };
8944
+ return trWorker;
8945
+ }
8946
+ function stopTranscribeWorker() {
8947
+ if (trWorker) { trWorker.terminate(); trWorker = null; }
8948
+ for (const p of trPending.values()) p.reject(new Error("cancelled"));
8949
+ trPending.clear();
8950
+ }
8951
+ function whisperPiece(pcm, model, language) {
8952
+ return new Promise((resolve, reject) => {
8953
+ const id = ++trSeq;
8954
+ trPending.set(id, { resolve, reject });
8955
+ transcribeWorker().postMessage({ type: "run", id, lib: FableCutTranscribe.LIBRARY, model: FableCutTranscribe.MODELS[model].id, pcm, language }, [pcm.buffer]);
8956
+ });
8957
+ }
8958
+ function onModelProgress(m) {
8959
+ const b = trState.busy;
8960
+ if (!b || !m.file) return;
8961
+ if (m.status === "done") { const f = b.dl.get(m.file); if (f) f.loaded = f.total; }
8962
+ else if (m.total > 0) b.dl.set(m.file, { loaded: m.loaded, total: m.total });
8963
+ b.beat?.();
8964
+ paintTranscribeBusy();
8965
+ }
8966
+ /** A file's sound as Whisper hears it: mono, 16 kHz. */
8967
+ async function speechPcm(m) {
8968
+ const buf = await getAudioBuffer(m);
8969
+ const R = FableCutTranscribe.RATE;
8970
+ const oc = new OfflineAudioContext(1, Math.max(1, Math.ceil(buf.duration * R)), R);
8971
+ const node = oc.createBufferSource();
8972
+ node.buffer = buf;
8973
+ node.connect(oc.destination);
8974
+ node.start();
8975
+ return { pcm: (await oc.startRendering()).getChannelData(0), duration: buf.duration };
8976
+ }
8977
+ /** Transcribe one file and save it on the server. Resolves to {doc, saved}. */
8978
+ async function transcribeFile(src, { model, language, onProgress, cancelled }) {
8979
+ const T = FableCutTranscribe, R = T.RATE;
8980
+ const m = project.media.find((x) => x.src === src) || { src };
8981
+ const { pcm, duration } = await speechPcm(m);
8982
+ const pieces = T.plan(pcm, R), words = [];
8983
+ for (let k = 0; k < pieces.length; k++) {
8984
+ if (cancelled()) throw new Error("cancelled");
8985
+ const [a, b] = pieces[k];
8986
+ if (!T.quiet(pcm, a, b)) words.push(...T.joinChunks(await whisperPiece(pcm.slice(a, b), model, language), a / R, b / R));
8987
+ onProgress((k + 1) / pieces.length);
8988
+ }
8989
+ const doc = T.validate({ src, model, language: language || "auto", duration, created: new Date().toISOString(), words });
8990
+ let saved = false;
8991
+ try { saved = (await fetch("/api/transcript?src=" + encodeURIComponent(src), { method: "POST", body: JSON.stringify(doc) })).ok; } catch { }
8992
+ transcriptCache.set(src, doc);
8993
+ transcriptGen++;
8994
+ return { doc, saved };
8995
+ }
8996
+ /** Transcribe files one after another. `beat(fraction)` hears about progress (an agent's job). */
8997
+ async function transcribeSrcs(srcs, opts = transcribeSettings(), beat = null) {
8998
+ if (trState.busy) throw new Error("this tab is already transcribing — wait for it, or cancel it");
8999
+ const busy = trState.busy = { srcs, i: 0, frac: 0, cancel: false, dl: new Map(), beat: () => beat?.((busy.i + busy.frac) / srcs.length) };
9000
+ const out = { done: [], failed: [], cancelled: false };
9001
+ renderTranscript(true);
9002
+ try {
9003
+ for (let i = 0; i < srcs.length; i++) {
9004
+ busy.i = i; busy.frac = 0;
9005
+ paintTranscribeBusy();
9006
+ busy.beat();
9007
+ try {
9008
+ const r = await transcribeFile(srcs[i], {
9009
+ ...opts, cancelled: () => busy.cancel,
9010
+ onProgress: (f) => { busy.frac = f; paintTranscribeBusy(); busy.beat(); },
9011
+ });
9012
+ out.done.push({ src: srcs[i], words: r.doc.words.length, language: r.doc.language, saved: r.saved });
9013
+ } catch (e) {
9014
+ if (busy.cancel) { out.cancelled = true; break; }
9015
+ out.failed.push({ src: srcs[i], error: String((e && e.message) || e) });
9016
+ }
9017
+ }
9018
+ } finally {
9019
+ trState.busy = null;
9020
+ renderTranscript(true);
9021
+ // the model holds a few hundred MB: let it go after a quiet minute (the browser keeps the download)
9022
+ clearTimeout(trIdleTimer);
9023
+ trIdleTimer = setTimeout(() => { if (!trState.busy) stopTranscribeWorker(); }, 60000);
9024
+ }
9025
+ return out;
9026
+ }
9027
+ function cancelTranscribe() {
9028
+ if (!trState.busy) return;
9029
+ trState.busy.cancel = true;
9030
+ stopTranscribeWorker();
9031
+ }
9032
+
9033
+ /** Each linked group that sounds (its audio stems, else the clip), as on the timeline. */
9034
+ function transcriptGroups() {
9035
+ return speechGroups(project.clips).map((g) => g.filter(clipRenders)).filter((g) => {
9036
+ const m = g.length && getMedia(g[0].mediaId);
9037
+ // a picture with its sound turned off, or a file with no audio stream, has nothing to say
9038
+ return m && m.audioChannels !== 0 && !(g.length === 1 && g[0].kind === "video" && +(g[0].props?.volume ?? 1) === 0);
9039
+ });
9040
+ }
9041
+ /** The timeline's words, every transcribed clip, in time order (transcribe.js layout). */
9042
+ function transcriptWords() {
9043
+ const entries = [];
9044
+ for (const g of transcriptGroups()) {
9045
+ const d = transcriptOf(getMedia(g[0].mediaId).src);
9046
+ if (d) entries.push({ clip: g[0], words: d.words });
9047
+ }
9048
+ return FableCutTranscribe.layout(entries);
9049
+ }
9050
+ /** What Transcribe works on: the selected clips' files, else every file on the timeline without a transcript. */
9051
+ function transcribeTargets() {
9052
+ const groups = transcriptGroups();
9053
+ const picked = new Set();
9054
+ for (const id of state.selIds) {
9055
+ const c = getClip(id);
9056
+ if (c && (c.kind === "video" || c.kind === "audio")) { const m = getMedia(c.mediaId); if (m) picked.add(m.src); }
9057
+ }
9058
+ const srcs = [...new Set(groups.map((g) => getMedia(g[0].mediaId).src))];
9059
+ const sel = srcs.filter((s) => picked.has(s));
9060
+ return sel.length ? { srcs: sel, selected: true } : { srcs: srcs.filter((s) => transcriptCache.get(s) === false), selected: false };
9061
+ }
9062
+ /** What the words' places depend on: the timeline and the transcripts. */
9063
+ function transcriptWordsSig() {
9064
+ return silenceSig() + "|" + transcriptGen;
9065
+ }
9066
+ /** What the tab shows: that, and the clip selection (the Transcribe button follows it). */
9067
+ function transcriptSig() {
9068
+ return transcriptWordsSig() + "|" + [...state.selIds].join(",");
9069
+ }
9070
+
9071
+ function buildTranscriptPage() {
9072
+ const T = FableCutTranscribe, root = els.transcriptPage, set = transcribeSettings();
9073
+ root.innerHTML = `<div class="tr-head">
9074
+ <div class="tr-row">
9075
+ <button type="button" class="btn primary" data-tr-go></button>
9076
+ <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]) =>
9077
+ `<option value="${k}" ${k === set.model ? "selected" : ""}>${m.label} · ${m.mb} MB</option>`).join("")}</select>
9078
+ <select data-tr-lang title="The language spoken. Auto-detect works for most; pick it when a clip is short or mixes languages">
9079
+ <option value="auto">Auto-detect</option>${Object.entries(T.LANGUAGES).sort((a, b) => a[1].localeCompare(b[1])).map(([k, n]) =>
9080
+ `<option value="${k}" ${k === set.language ? "selected" : ""}>${n}</option>`).join("")}</select>
9081
+ </div>
9082
+ <div class="tr-busy hidden" data-tr-busy><span data-tr-busy-text></span><span class="tr-bar"><i data-tr-bar></i></span>
9083
+ <button type="button" class="btn tiny" data-tr-cancel title="Stop transcribing (what is done is kept)">Cancel</button></div>
9084
+ <div class="tr-row">
9085
+ <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">
9086
+ <span class="tr-count" data-tr-count></span>
9087
+ <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>
9088
+ <button type="button" class="btn tiny" data-tr-copy title="Copy the transcript as text, with timecodes">Copy</button>
9089
+ </div>
9090
+ <div class="tr-row">
9091
+ <span class="tr-lbl">Captions</span>
9092
+ <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]) =>
9093
+ `<option value="${k}" ${k === (set.captionStyle || FableCutCaptions.DEFAULT_STYLE) ? "selected" : ""}>${st.label}</option>`).join("")}</select>
9094
+ <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>
9095
+ <button type="button" class="btn tiny" data-tr-cap-file="srt" title="Download the timeline's captions as a SubRip file">SRT</button>
9096
+ <button type="button" class="btn tiny" data-tr-cap-file="vtt" title="Download the timeline's captions as a WebVTT file">VTT</button>
9097
+ <button type="button" class="btn tiny" data-tr-cap-import title="Place the captions of an SRT or WebVTT file">Import…</button>
9098
+ <input type="file" accept=".srt,.vtt,text/vtt,application/x-subrip" data-tr-cap-input hidden>
9099
+ </div>
9100
+ <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>
9101
+ </div>
9102
+ <div class="tr-body" data-tr-body tabindex="0"></div>
9103
+ <div class="tr-foot hidden" data-tr-foot><span data-tr-sel></span>
9104
+ <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>`;
9105
+ const q = (s) => root.querySelector(s);
9106
+ trState.el = { go: q("[data-tr-go]"), busy: q("[data-tr-busy]"), busyText: q("[data-tr-busy-text]"), bar: q("[data-tr-bar]"),
9107
+ find: q("[data-tr-find]"), count: q("[data-tr-count]"), cutFound: q("[data-tr-cut-found]"), body: q("[data-tr-body]"),
9108
+ foot: q("[data-tr-foot]"), selText: q("[data-tr-sel]") };
9109
+ const E = trState.el;
9110
+ E.go.addEventListener("click", transcribeFromTab);
9111
+ q("[data-tr-cancel]").addEventListener("click", cancelTranscribe);
9112
+ q("[data-tr-model]").addEventListener("change", (e) => saveTranscribeSettings({ model: e.target.value }));
9113
+ q("[data-tr-lang]").addEventListener("change", (e) => saveTranscribeSettings({ language: e.target.value === "auto" ? null : e.target.value }));
9114
+ E.find.addEventListener("input", () => { trState.query = E.find.value; findTranscript(); });
9115
+ E.find.addEventListener("keydown", (e) => {
9116
+ if (e.key === "Enter") { e.preventDefault(); nextTranscriptHit(e.shiftKey ? -1 : 1); }
9117
+ if (e.key === "Escape" && E.find.value) { e.stopPropagation(); E.find.value = ""; trState.query = ""; findTranscript(); }
9118
+ });
9119
+ E.cutFound.addEventListener("click", () => {
9120
+ const n = trState.hits.length;
9121
+ if (n) cutTranscriptRuns(trState.hits, `${n} × "${trState.query.trim()}"`);
9122
+ });
9123
+ q("[data-tr-copy]").addEventListener("click", copyTranscript);
9124
+ q("[data-tr-cap-style]").addEventListener("change", (e) => saveTranscribeSettings({ captionStyle: e.target.value }));
9125
+ q("[data-tr-cap-add]").addEventListener("click", () => addCaptionsFromTranscript(q("[data-tr-cap-style]").value));
9126
+ root.querySelectorAll("[data-tr-cap-file]").forEach((b) => b.addEventListener("click", () => downloadCaptions(b.dataset.trCapFile)));
9127
+ const capInput = q("[data-tr-cap-input]");
9128
+ q("[data-tr-cap-import]").addEventListener("click", () => capInput.click());
9129
+ capInput.addEventListener("change", async () => {
9130
+ const f = capInput.files && capInput.files[0];
9131
+ capInput.value = "";
9132
+ if (!f) return;
9133
+ let list;
9134
+ const st = q("[data-tr-cap-style]").value;
9135
+ try { list = FableCutCaptions.parse(await f.text()); } catch (e) { toast(e.message); return; }
9136
+ const m = FableCutCaptions.metrics(st, project.width, project.height);
9137
+ placeCaptions(FableCutCaptions.fit(list, m.chars, m.lines), st, `from ${f.name}`);
9138
+ });
9139
+ q("[data-tr-cut-sel]").addEventListener("click", cutTranscriptSelection);
9140
+ E.body.addEventListener("mousedown", (e) => {
9141
+ const tc = e.target.closest(".tr-tc");
9142
+ if (tc) { goToTranscriptTime(+tc.dataset.t); return; }
9143
+ const w = e.target.closest(".tw");
9144
+ if (!w || e.button !== 0) return;
9145
+ e.preventDefault();
9146
+ E.body.focus({ preventScroll: true });
9147
+ const k = +w.dataset.k;
9148
+ if (e.shiftKey && trState.anchor != null) trState.sel = { i: Math.min(trState.anchor, k), j: Math.max(trState.anchor, k) };
9149
+ else { trState.anchor = k; trState.sel = { i: k, j: k }; goToTranscriptTime(trState.words[k].s); }
9150
+ trState.drag = true;
9151
+ paintTranscriptMarks();
9152
+ });
9153
+ E.body.addEventListener("mouseover", (e) => {
9154
+ if (!trState.drag) return;
9155
+ const w = e.target.closest(".tw");
9156
+ if (!w || trState.anchor == null) return;
9157
+ const k = +w.dataset.k;
9158
+ trState.sel = { i: Math.min(trState.anchor, k), j: Math.max(trState.anchor, k) };
9159
+ paintTranscriptMarks();
9160
+ });
9161
+ window.addEventListener("mouseup", () => { trState.drag = false; });
9162
+ // Delete anywhere in this tab means the words, never the timeline's clips: with none selected it does
9163
+ // nothing; in the Find box it edits the text
9164
+ root.addEventListener("keydown", (e) => {
9165
+ if ((e.key === "Delete" || e.key === "Backspace") && !e.ctrlKey && !e.metaKey && !e.altKey) {
9166
+ e.stopPropagation();
9167
+ if (isTypingTarget(e.target)) return;
9168
+ e.preventDefault();
9169
+ if (trState.sel) cutTranscriptSelection();
9170
+ } else if (e.key === "Escape" && trState.sel && !isTypingTarget(e.target)) {
9171
+ e.preventDefault(); e.stopPropagation();
9172
+ trState.sel = null; trState.anchor = null;
9173
+ paintTranscriptMarks();
9174
+ }
9175
+ });
9176
+ trState.built = true;
9177
+ }
9178
+ function renderTranscript(force = false) {
9179
+ if (!trState.open || !els.transcriptPage) return;
9180
+ if (typeof FableCutTranscribe === "undefined") { els.transcriptPage.innerHTML = `<div class="tr-empty">Transcript module missing — reload the editor.</div>`; return; }
9181
+ if (!trState.built) buildTranscriptPage();
9182
+ const groups = transcriptGroups();
9183
+ for (const g of groups) {
9184
+ const src = getMedia(g[0].mediaId).src;
9185
+ if (!transcriptCache.has(src)) loadTranscript(src).then(() => renderTranscript(true));
9186
+ }
9187
+ paintTranscribeBusy();
9188
+ const sig = transcriptSig();
9189
+ if (!force && sig === trState.sig) return;
9190
+ trState.sig = sig;
9191
+ const T = FableCutTranscribe, E = trState.el;
9192
+ const words = trState.words = transcriptWords();
9193
+ trState.wsig = transcriptWordsSig();
9194
+ const tgt = transcribeTargets();
9195
+ E.go.textContent = tgt.selected ? `Transcribe selected (${tgt.srcs.length})` : tgt.srcs.length ? `Transcribe ${tgt.srcs.length} file${tgt.srcs.length === 1 ? "" : "s"}` : "Transcribe";
9196
+ E.go.disabled = !!trState.busy || !tgt.srcs.length;
9197
+ 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"
9198
+ : groups.length ? "Every file on the timeline has a transcript — select clips to transcribe them again" : "Put clips with speech on the timeline first";
9199
+ const missing = [...new Set(groups.map((g) => getMedia(g[0].mediaId)).filter((m) => transcriptCache.get(m.src) === false).map((m) => m.name || m.src))];
9200
+ let html = "";
9201
+ 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>`;
9202
+ else {
9203
+ 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>`;
9204
+ if (!words.length && !missing.length) html += `<div class="tr-empty">${[...transcriptCache.values()].some((v) => v instanceof Promise) ? "Loading…" : "No words in these clips."}</div>`;
9205
+ for (const s of T.segments(words)) {
9206
+ let p = "";
9207
+ for (let k = s.i; k <= s.j; k++) p += (k > s.i ? " " : "") + `<span class="tw" data-k="${k}">${escapeHtml(words[k].w)}</span>`;
9208
+ 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>`;
9209
+ }
9210
+ }
9211
+ E.body.innerHTML = html;
9212
+ trState.now = -1;
9213
+ // the selection stands only while the words are the same ones
9214
+ const key = words.map((x) => x.s + x.w).join("|");
9215
+ if (key !== trState.wordsKey) { trState.sel = null; trState.anchor = null; }
9216
+ trState.wordsKey = key;
9217
+ findTranscript(true);
9218
+ }
9219
+ /** Go to a time from the transcript: the Program monitor shows it, as markers and placements do. */
9220
+ function goToTranscriptTime(t) {
9221
+ if (isSourceMode()) setMonitorMode("program");
9222
+ setTime(t);
9223
+ }
9224
+ function paintTranscribeBusy() {
9225
+ const E = trState.el, b = trState.busy;
9226
+ if (!E) return;
9227
+ E.busy.classList.toggle("hidden", !b);
9228
+ if (!b) return;
9229
+ let loaded = 0, total = 0, downloading = false;
9230
+ for (const f of b.dl.values()) { loaded += f.loaded; total += f.total; if (f.loaded < f.total) downloading = true; }
9231
+ const name = (project.media.find((m) => m.src === b.srcs[b.i])?.name) || b.srcs[b.i].split("/").pop();
9232
+ const frac = downloading && total ? loaded / total : (b.i + b.frac) / b.srcs.length;
9233
+ E.busyText.textContent = downloading
9234
+ ? `Downloading the speech model (once)… ${Math.round(100 * loaded / total)}%`
9235
+ : `Transcribing ${name}${b.srcs.length > 1 ? ` (${b.i + 1} of ${b.srcs.length})` : ""}… ${Math.round(100 * b.frac)}%`;
9236
+ E.bar.style.width = `${Math.round(100 * frac)}%`;
9237
+ }
9238
+ function findTranscript(keepSel = false) {
9239
+ const E = trState.el;
9240
+ if (!E) return;
9241
+ const q = trState.query.trim();
9242
+ trState.hits = q ? FableCutTranscribe.find(trState.words, q) : [];
9243
+ E.count.textContent = q ? `${trState.hits.length} found` : "";
9244
+ E.cutFound.disabled = !trState.hits.length;
9245
+ E.cutFound.textContent = trState.hits.length ? `Cut ${trState.hits.length}` : "Cut all";
9246
+ if (!keepSel) trState.hitAt = -1;
9247
+ paintTranscriptMarks();
9248
+ }
9249
+ function nextTranscriptHit(dir) {
9250
+ const h = trState.hits;
9251
+ if (!h.length) return;
9252
+ trState.hitAt = ((trState.hitAt ?? -1) + dir + h.length) % h.length;
9253
+ const run = h[trState.hitAt];
9254
+ trState.sel = { i: run.i, j: run.j };
9255
+ trState.anchor = run.i;
9256
+ goToTranscriptTime(trState.words[run.i].s);
9257
+ paintTranscriptMarks();
9258
+ trState.el.body.querySelector(`.tw[data-k="${run.i}"]`)?.scrollIntoView({ block: "center" });
9259
+ }
9260
+ function paintTranscriptMarks() {
9261
+ const E = trState.el;
9262
+ if (!E) return;
9263
+ const hit = new Set();
9264
+ for (const r of trState.hits) for (let k = r.i; k <= r.j; k++) hit.add(k);
9265
+ const s = trState.sel;
9266
+ for (const el of E.body.querySelectorAll(".tw")) {
9267
+ const k = +el.dataset.k;
9268
+ el.classList.toggle("hit", hit.has(k));
9269
+ el.classList.toggle("sel", !!s && k >= s.i && k <= s.j);
9270
+ }
9271
+ E.foot.classList.toggle("hidden", !s);
9272
+ if (s) {
9273
+ const w = trState.words;
9274
+ const txt = FableCutTranscribe.text(w, s.i, s.j);
9275
+ 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}”`;
9276
+ }
9277
+ }
9278
+ function cutTranscriptSelection() {
9279
+ const s = trState.sel;
9280
+ if (!s) return;
9281
+ cutTranscriptRuns([s], `${s.j - s.i + 1} word${s.j === s.i ? "" : "s"}`);
9282
+ }
9283
+ /** Extract the words of each run (and the pause after them) on the targeted tracks: one undo step. */
9284
+ function cutTranscriptRuns(runs, label) {
9285
+ // the words were placed on the timeline as it was at the last redraw: it may have moved since
9286
+ if (transcriptWordsSig() !== trState.wsig) { renderTranscript(true); toast("The timeline changed — find or select the words again"); return; }
9287
+ const spans = FableCutTranscribe.cutSpans(trState.words, runs, { fps: projectFps() });
9288
+ if (!spans.length) { toast("Too short to cut"); return; }
9289
+ const snap = undoSnapshot();
9290
+ let cut = 0, secs = 0;
9291
+ for (const sp of spans.slice().sort((a, b) => b.from - a.from)) {
9292
+ if (!EDIT.liftRange(sp.from, sp.to, true)) { cut++; secs += sp.to - sp.from; }
9293
+ }
9294
+ if (!cut) { state.dirtyTimeline = true; toast("Nothing was cut — target the clip's tracks first (or unlock them)"); return; }
9295
+ pushUndo(snap);
9296
+ pruneSelection();
9297
+ state.dirtyTimeline = true;
9298
+ scheduleSave();
9299
+ trState.sel = null; trState.anchor = null;
9300
+ renderTranscript(true);
9301
+ toast(`Cut ${label} · ${secs.toFixed(1)} s shorter`);
9302
+ }
9303
+ function copyTranscript() {
9304
+ const lines = FableCutTranscribe.segments(trState.words).map((s) => `[${fmt(s.from)}] ${s.text}`);
9305
+ if (!lines.length) { toast("Nothing to copy yet"); return; }
9306
+ navigator.clipboard.writeText(lines.join("\n")).then(() => toast(`Copied ${lines.length} line${lines.length === 1 ? "" : "s"}`), () => toast("Couldn't copy — the browser refused"));
9307
+ }
9308
+ async function transcribeFromTab() {
9309
+ const { srcs } = transcribeTargets();
9310
+ if (!srcs.length) { toast("Put a clip with speech on the timeline first"); return; }
9311
+ let out;
9312
+ try { out = await transcribeSrcs(srcs); } catch (e) { toast(e.message); return; }
9313
+ const unsaved = out.done.filter((d) => !d.saved).length;
9314
+ const words = out.done.reduce((n, d) => n + d.words, 0);
9315
+ toast(out.cancelled ? `Stopped — ${out.done.length} file${out.done.length === 1 ? "" : "s"} transcribed`
9316
+ : out.failed.length && !out.done.length ? `Couldn't transcribe: ${out.failed[0].error}`
9317
+ : `Transcribed ${out.done.length} file${out.done.length === 1 ? "" : "s"}, ${words} words` +
9318
+ (out.failed.length ? ` · ${out.failed.length} failed (${out.failed[0].error})` : "") +
9319
+ (unsaved ? " · kept for this session only (the server didn't save it)" : ""));
9320
+ }
9321
+ /** The word under the playhead, lit (and kept in view while playing); a redraw when the timeline changes. */
9322
+ let trTickAt = 0;
9323
+ function transcriptTick() {
9324
+ const now = performance.now();
9325
+ if (now - trTickAt > 300) { trTickAt = now; renderTranscript(); }
9326
+ const w = trState.words;
9327
+ let lo = 0, hi = w.length - 1, k = -1;
9328
+ 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; }
9329
+ if (k >= 0 && state.time > w[k].e + 0.25) k = -1;
9330
+ if (k === trState.now || !trState.el) return;
9331
+ trState.el.body.querySelector(".tw.now")?.classList.remove("now");
9332
+ const el = k >= 0 ? trState.el.body.querySelector(`.tw[data-k="${k}"]`) : null;
9333
+ el?.classList.add("now");
9334
+ if (el && state.playing) el.scrollIntoView({ block: "nearest" });
9335
+ trState.now = k;
9336
+ }
9337
+
9338
+ /* ── Captions (captions.js): the transcript's words become caption clips — text
9339
+ clips with wordTimes, so karaoke / highlight / word pop follow the speech —
9340
+ on a video lane above the edit; subtitle files out and in. The same clips as
9341
+ fablecut_captions. ── */
9342
+ function addCaptionsFromTranscript(styleKey) {
9343
+ const C = FableCutCaptions;
9344
+ if (transcriptWordsSig() !== trState.wsig) renderTranscript(true);
9345
+ const words = trState.words;
9346
+ if (!words.length) { toast("Transcribe the clips first — captions are made from their words"); return; }
9347
+ const m = C.metrics(styleKey, project.width, project.height);
9348
+ placeCaptions(C.cues(words, { chars: m.chars, lines: m.lines, words: m.words, maxDur: m.maxDur, fps: projectFps() }), styleKey, "");
9349
+ }
9350
+ /** Put caption cues on the timeline (replacing the captions there), as one undo step. */
9351
+ function placeCaptions(list, styleKey, from) {
9352
+ const C = FableCutCaptions;
9353
+ if (!list.length) { toast("No captions to add"); return; }
9354
+ const old = project.clips.filter(C.isCaption);
9355
+ if (old.some(isGroupLocked)) { toastLocked(); return; }
9356
+ const span = [list[0].start, list[list.length - 1].end];
9357
+ const lane = C.trackFor(old.length ? project : { ...project, clips: project.clips.filter((c) => !C.isCaption(c)), tracks: serializeTracks() }, span[0], span[1]);
9358
+ if (state.lockedTracks?.has?.(lane.track) || (project.lockedTracks || []).includes(lane.track)) { toast(`${lane.track} is locked — unlock it for the captions`); return; }
9359
+ const snap = undoSnapshot();
9360
+ let track = lane.track;
9361
+ if (lane.add) {
9362
+ const t = addTimelineTrack("video");
9363
+ if (!t) return;
9364
+ track = t.id;
9365
+ }
9366
+ const oldIds = new Set(old.map((c) => c.id));
9367
+ project.clips = project.clips.filter((c) => !oldIds.has(c.id));
9368
+ for (const id of oldIds) state.selIds.delete(id);
9369
+ if (oldIds.has(state.selId)) state.selId = null;
9370
+ for (const cue of list) project.clips.push({ ...C.clip(cue, { style: styleKey, width: project.width, height: project.height, track }), id: "c_" + uid() });
9371
+ pushUndo(snap);
9372
+ pruneSelection();
9373
+ state.dirtyTimeline = true;
9374
+ scheduleSave();
9375
+ renderInspector();
9376
+ toast(`${list.length} caption${list.length === 1 ? "" : "s"} on ${track}${from ? " " + from : ""}${old.length ? ` · replaced ${old.length}` : ""}`);
9377
+ }
9378
+ /** A cut, split or trim that shortens a caption leaves its words timed to the old cut: say so, for a moment. */
9379
+ const capWatch = { durs: null, at: 0, said: 0 };
9380
+ function watchCaptions(now) {
9381
+ if (now - capWatch.at < 500 || typeof FableCutCaptions === "undefined") return;
9382
+ capWatch.at = now;
9383
+ const durs = new Map();
9384
+ for (const c of project.clips) if (FableCutCaptions.isCaption(c)) durs.set(c.id, c.duration);
9385
+ const prev = capWatch.durs;
9386
+ capWatch.durs = durs;
9387
+ if (!prev || now - capWatch.said < 5000) return;
9388
+ for (const [id, d] of durs) {
9389
+ if (prev.has(id) && d < prev.get(id) - 1e-4) {
9390
+ capWatch.said = now;
9391
+ toast("Captions don't re-time when cut — add them again in the Transcript tab once the edit is done");
9392
+ return;
9393
+ }
9394
+ }
9395
+ }
9396
+ function downloadCaptions(kind) {
9397
+ const C = FableCutCaptions, list = C.fromClips(project.clips, [...state.disabledTracks]);
9398
+ if (!list.length) { toast("No captions on the timeline yet — Add captions first"); return; }
9399
+ const blob = new Blob([kind === "vtt" ? C.toVTT(list) : C.toSRT(list)], { type: kind === "vtt" ? "text/vtt" : "application/x-subrip" });
9400
+ const a = document.createElement("a");
9401
+ a.href = URL.createObjectURL(blob);
9402
+ a.download = `${String(project.name || "captions").replace(/[^\w\- ]+/g, "_").trim() || "captions"}.${kind}`;
9403
+ document.body.appendChild(a);
9404
+ a.click();
9405
+ a.remove();
9406
+ setTimeout(() => URL.revokeObjectURL(a.href), 2000);
9407
+ toast(`Saved ${list.length} caption${list.length === 1 ? "" : "s"} as ${a.download}`);
9408
+ }
9409
+ /* fablecut_transcribe: transcribe the job's files in this tab, save them, report. */
9410
+ async function runTranscribeJob(ticket, fail) {
9411
+ const spec = ticket.transcribe || {};
9412
+ if (typeof FableCutTranscribe === "undefined") return fail("the transcript module is missing — reload the editor");
9413
+ if (trState.busy) return fail("this editor tab is already transcribing — wait for it, or cancel it there");
9414
+ const srcs = [], skipped = [];
9415
+ for (const src of spec.srcs || []) {
9416
+ if (!spec.again && await loadTranscript(src, true)) { skipped.push(src); continue; }
9417
+ srcs.push(src);
9418
+ }
9419
+ const report = (body, force) => fetch("/api/export/job/report?id=" + encodeURIComponent(ticket.id), { method: "POST", body: JSON.stringify(body) })
9420
+ .then((r) => r.json()).then((r) => { if (r?.cancel) cancelTranscribe(); }).catch(() => { });
9421
+ if (!srcs.length) return report({ status: "done", result: { done: [], skipped, failed: [] } });
9422
+ let last = 0;
9423
+ const out = await transcribeSrcs(srcs, { model: FableCutTranscribe.model(spec.model), language: spec.language || null }, (f) => {
9424
+ const t = performance.now();
9425
+ if (t - last > 1000) { last = t; report({ progress: f }); }
9426
+ }).catch((e) => ({ done: [], failed: srcs.map((src) => ({ src, error: e.message })) }));
9427
+ for (const d of out.done) if (!d.saved) out.failed.push({ src: d.src, error: "transcribed, but the server didn't save it" });
9428
+ out.done = out.done.filter((d) => d.saved);
9429
+ if (out.cancelled) return report({ status: "failed", error: "cancelled" });
9430
+ if (!out.done.length && out.failed.length) return fail(out.failed.map((f) => `${f.src}: ${f.error}`).join(" · "));
9431
+ return report({ status: "done", result: { done: out.done, skipped, failed: out.failed } });
9432
+ }
9433
+ function clearSilences() {
9434
+ silenceGen++; // a Find still listening doesn't bring the marks back
9435
+ state.silence = null;
9436
+ state.silenceBusy = false;
9437
+ state.dirtyTimeline = true;
9438
+ renderInspector();
9439
+ }
9440
+
9441
+ /* ── Beats (beats.js): the music's tempo and beat grid, ticks on the timeline, and
9442
+ edits on it — mark, snap the cuts, re-cut a track. The same plan and ops as
9443
+ fablecut_beats; here each action is one undo step. ── */
9444
+ const BEATS_KEY = "fablecut-beats";
9445
+ function beatsSettings() {
9446
+ let o = {};
9447
+ try { o = JSON.parse(localStorage.getItem(BEATS_KEY) || "{}"); } catch { }
9448
+ return { every: FableCutBeats.EVERY.includes(+o.every) ? +o.every : 2 };
9449
+ }
9450
+ /** What a found beat stands on: the clip's place, window, file and speed, and the frame rate. */
9451
+ function beatsSig(c) {
9452
+ if (!c) return "";
9453
+ // the open project and sequence too: a duplicate with the same clip ids must not inherit this beat
9454
+ return JSON.stringify([runtime.projectId ?? null, SeqLib.activeId(seqRoot()), !!state.compCtx, project.fps, c.id, c.start, c.in, c.duration,
9455
+ getMedia(c.mediaId)?.src ?? null, c.props?.speed ?? 1, c.keyframes?.speed ?? null]);
9456
+ }
9457
+ /** The project as beats.js reads it: the timeline plus the track switches. */
9458
+ function beatsDoc() {
9459
+ return { ...project, tracks: TRACKS, lockedTracks: [...state.lockedTracks], untargetedTracks: [...state.untargetedTracks] };
9460
+ }
9461
+ let beatsGen = 0;
9462
+ async function findBeats(c) {
9463
+ if (typeof FableCutBeats === "undefined") { toast("Beats module missing — reload the editor"); return; }
9464
+ if (!c || (c.kind !== "audio" && c.kind !== "video")) { toast("Select the music clip to find its beat"); return; }
9465
+ if (FableCutBeats.ramped(c)) { toast("This clip has a speed ramp — beats follow music playing at a steady speed"); return; }
9466
+ const m = getMedia(c.mediaId);
9467
+ if (!m) return;
9468
+ const gen = ++beatsGen, sig = beatsSig(c);
9469
+ state.beats = null; state.beatsBusy = true; state.dirtyTimeline = true;
9470
+ renderInspector();
9471
+ toast("Listening for the beat…");
9472
+ try {
9473
+ const buf = await getAudioBuffer(m);
9474
+ await new Promise((res) => setTimeout(res, 0)); // let "Listening…" paint and Cancel land before the analysis runs
9475
+ if (gen !== beatsGen) return;
9476
+ const a0 = clamp(Math.floor((c.in || 0) * buf.sampleRate), 0, buf.length);
9477
+ const a1 = clamp(Math.ceil(mediaTimeAt(c, clipEnd(c)) * buf.sampleRate), a0, buf.length);
9478
+ const chs = [];
9479
+ for (let ch = 0; ch < buf.numberOfChannels; ch++) chs.push(buf.getChannelData(ch).subarray(a0, a1));
9480
+ const a = FableCutBeats.analyze(FableCutBeats.resample(FableCutBeats.mono(chs), buf.sampleRate));
9481
+ const abs = { beats: a.beats.map((t) => t + (c.in || 0)), bpm: a.bpm, drop: a.drop != null ? a.drop + (c.in || 0) : null };
9482
+ if (beatsSig(getClip(c.id)) !== sig) { toast("The clip changed while listening — find the beat again"); return; }
9483
+ const r = FableCutBeats.plan(beatsDoc(), getClip(c.id), abs, {});
9484
+ state.beats = r.grid.length ? { clipId: c.id, sig, a: abs, grid: r.grid, bpm: r.bpm, drop: r.drop } : null;
9485
+ toast(r.grid.length ? `${r.bpm} BPM · ${r.grid.length} beats marked on the timeline` + (r.drop != null ? ` · the drop at ${fmt(r.drop)}` : "")
9486
+ : "No steady beat found in this clip");
9487
+ } catch (e) {
9488
+ toast("Couldn't read this clip's audio: " + (e?.message || e));
9489
+ } finally {
9490
+ if (gen === beatsGen) { state.beatsBusy = false; state.dirtyTimeline = true; renderInspector(); }
9491
+ }
9492
+ }
9493
+ function clearBeats() {
9494
+ beatsGen++;
9495
+ state.beats = null; state.beatsBusy = false; state.dirtyTimeline = true;
9496
+ renderInspector();
9497
+ }
9498
+ /** markers / snap / retime on the found beat: beats.js plans, the editor's own edits apply it. One undo step. */
9499
+ function beatsAction(acts) {
9500
+ const s = state.beats, c = s && getClip(s.clipId);
9501
+ if (!s || !c || s.sig !== beatsSig(c)) { state.beats = null; renderInspector(); toast("The music clip changed — find the beat again"); return; }
9502
+ let r;
9503
+ try { r = FableCutBeats.plan(beatsDoc(), c, s.a, acts); }
9504
+ catch (e) { toast(e.message); return; }
9505
+ if (!r.ops.length) { toast(r.done.join(" · ") || "Nothing to change"); return; }
9506
+ const snap = undoSnapshot();
9507
+ let rolls = 0, rolled = 0;
9508
+ for (const op of r.ops) {
9509
+ if (op.op === "setProject") project.markers = normalizeMarkers(op.set.markers);
9510
+ else if (op.op === "roll") {
9511
+ const x = getClip(op.id);
9512
+ rolls++;
9513
+ // what the roll really moved (a refusal is a string, a clamp a smaller number)
9514
+ if (!x) continue;
9515
+ // what this roll can touch: the clips on either side of the cut and their linked partners
9516
+ const end = x.start + x.duration;
9517
+ const next = project.clips.find((c) => c !== x && c.track === x.track && Math.abs(c.start - end) < 1e-3);
9518
+ const touched = withLinked(next ? [x, next] : [x]);
9519
+ const before = new Map(touched.map((c) => [c.id, JSON.stringify(c)]));
9520
+ const d = EDIT.rollEdit(x, op.side, op.delta);
9521
+ if (typeof d === "number" && Math.abs(d - op.delta) < 1e-3) rolled++;
9522
+ // a roll that couldn't reach the beat (clamped, refused) is undone exactly: the cut stays where it was
9523
+ else project.clips = project.clips.map((c) => (before.has(c.id) ? JSON.parse(before.get(c.id)) : c));
9524
+ } else if (op.op === "updateClip") {
9525
+ const x = getClip(op.id);
9526
+ if (x) for (const [k, v] of Object.entries(op.set)) { if (v === null) delete x[k]; else x[k] = v; }
9527
+ }
9528
+ }
9529
+ if (undoSnapshot() === snap) {
9530
+ state.dirtyTimeline = true; renderInspector();
9531
+ toast(acts.markers ? "No new beats to mark: every beat already has a marker" : "Nothing could move: those cuts have no spare footage to reach the beat");
9532
+ return;
9533
+ }
9534
+ pushUndo(snap);
9535
+ pruneSelection();
9536
+ state.dirtyTimeline = true;
9537
+ scheduleSave();
9538
+ renderInspector();
9539
+ const done = r.done.map((d) => (rolls && rolled < rolls && /^snapped /.test(d) ? d.replace(/^snapped \d+/, "snapped " + rolled) : d));
9540
+ toast(done.map((d) => d[0].toUpperCase() + d.slice(1)).join(" · "));
8620
9541
  }
8621
9542
  async function autoDuckClips(clips, { under = null, amount = duckAmount(), threshold = -40 } = {}) {
8622
9543
  if (typeof FableCutDucking === "undefined") { toast("Ducking module missing — reload the editor"); return; }
@@ -8703,17 +9624,20 @@ function parseDbInput(s) {
8703
9624
  return Number.isFinite(v) ? clampFaderDb(v) : null;
8704
9625
  }
8705
9626
  function setSideTab(tab) {
8706
- const mixer = tab === "mixer", color = tab === "color";
9627
+ const mixer = tab === "mixer", color = tab === "color", transcript = tab === "transcript";
8707
9628
  mixerState.open = mixer;
8708
9629
  colorState.open = color;
9630
+ trState.open = transcript;
8709
9631
  for (const b of els.sideTabs.querySelectorAll("[data-side]"))
8710
9632
  b.classList.toggle("on", b.dataset.side === tab);
8711
- els.inspector.classList.toggle("hidden", mixer || color);
9633
+ els.inspector.classList.toggle("hidden", mixer || color || transcript);
8712
9634
  els.mixer.classList.toggle("hidden", !mixer);
8713
9635
  els.colorPage.classList.toggle("hidden", !color);
9636
+ els.transcriptPage.classList.toggle("hidden", !transcript);
8714
9637
  try { localStorage.setItem(SIDE_TAB_KEY, tab); } catch { }
8715
9638
  if (mixer) renderMixer();
8716
9639
  else if (color) renderColorPage(true);
9640
+ else if (transcript) renderTranscript(true);
8717
9641
  else renderInspector();
8718
9642
  }
8719
9643
  /** Write a track's fader / pan, push it into the live graph, persist. */
@@ -11001,15 +11925,17 @@ function openSequence(id) {
11001
11925
  return true;
11002
11926
  }
11003
11927
  /** Add a sequence ({name?, from?, width?, height?}) and open it. */
11004
- function newSequence(opts) {
11928
+ function newSequence(opts, clips = null) {
11005
11929
  if (state.exporting) { toast("Wait for the export to finish"); return; }
11006
11930
  if (state.compCtx) exitComp(state.compCtx.path.length);
11007
11931
  const doc = projectJSONHere();
11008
11932
  let s;
11009
11933
  try { s = SeqLib.add(doc, opts); } catch (e) { toast(e.message); return; }
11934
+ if (clips) s.clips = clips; // an empty sequence that starts with these (Highlights)
11010
11935
  project.sequences = doc.sequences; project.sequence = doc.sequence;
11011
- if (openSequence(s.id)) toast(`New sequence “${s.name}” · ${s.width}×${s.height}`);
11012
- else { scheduleSave(); syncCompCrumb(); toast(`New sequence “${s.name}” added — open it from the sequence menu`); }
11936
+ if (openSequence(s.id)) { toast(`New sequence “${s.name}” · ${s.width}×${s.height}`); return true; }
11937
+ scheduleSave(); syncCompCrumb(); toast(`New sequence “${s.name}” added — open it from the sequence menu`);
11938
+ return false;
11013
11939
  }
11014
11940
  function renameSequence(id, name) {
11015
11941
  const r = seqRoot();
@@ -11086,6 +12012,8 @@ function showSequenceMenu(x, y) {
11086
12012
  }
11087
12013
  sep();
11088
12014
  item(`<span>New sequence…</span>`, () => promptNewSequence(x, y));
12015
+ item(`<span>Highlights…</span>`, () => promptHighlights(x, y),
12016
+ state.compCtx ? "Close the composition first" : !project.clips.some((c) => c.kind === "video") ? "Put video on the timeline first" : null);
11089
12017
  item(`<span>Duplicate “${escapeHtml(open.name)}”</span>`, () => newSequence({ from: "open" }));
11090
12018
  item(`<span>Rename “${escapeHtml(open.name)}”…</span>`, () => promptBinText(x, y, "Sequence name", open.name, (v) => renameSequence(openId, v), { max: 120, ok: "Rename" }));
11091
12019
  item(`<span>Delete “${escapeHtml(open.name)}”…</span>`, (b) => {
@@ -11100,21 +12028,35 @@ function promptNewSequence(x, y) {
11100
12028
  const pop = document.createElement("div");
11101
12029
  pop.className = "ctx-menu bin-pop seq-new";
11102
12030
  const n = SeqLib.entries(seqRoot()).length + 1;
11103
- const sizes = [{ label: `Same as “${openSequenceName()}” · ${project.width}×${project.height}`, w: 0, h: 0 }, ...ASPECT_PRESETS];
12031
+ const sizes = [{ label: `Same as “${openSequenceName()}” · ${seqRoot().width}×${seqRoot().height}`, w: 0, h: 0 }, ...ASPECT_PRESETS];
11104
12032
  pop.innerHTML = `<label class="bin-pop-label" for="seqNewName">New sequence</label>
11105
12033
  <input type="text" class="bin-pop-input" id="seqNewName" maxlength="120" spellcheck="false">
11106
12034
  <label class="bin-pop-label" for="seqNewSize">Canvas</label>
11107
12035
  <select id="seqNewSize" class="bin-pop-input">${sizes.map((s, i) => `<option value="${i}">${escapeHtml(s.label)}</option>`).join("")}</select>
11108
12036
  <label class="seq-new-copy"><input type="checkbox" id="seqNewCopy"> Start from a copy of “${escapeHtml(openSequenceName())}”</label>
12037
+ <label class="seq-new-copy" title="Each full-frame shot is fitted to the new shape and keyed to keep what matters in it in view (Inspector → Reframe)"><input type="checkbox" id="seqNewFollow" checked> Follow the subject in each shot</label>
11109
12038
  <div class="bin-pop-hint">Media and compositions are shared by every sequence. Each has its own timeline, canvas, frame rate, mix and delivery settings.</div>
11110
12039
  <div class="bin-pop-btns"><button type="button" class="btn tiny" data-cancel>Cancel</button><button type="button" class="btn tiny accent" data-ok>Create</button></div>`;
11111
12040
  pop.querySelector("#seqNewName").value = `Sequence ${n}`;
12041
+ const syncFollow = () => {
12042
+ const size = sizes[+pop.querySelector("#seqNewSize").value] || sizes[0];
12043
+ const root = seqRoot(); // a composition may be open: the copy is of the sequence around it
12044
+ const on = pop.querySelector("#seqNewCopy").checked && size.w && size.w * root.height !== size.h * root.width;
12045
+ pop.querySelector("#seqNewFollow").closest("label").hidden = !on;
12046
+ };
12047
+ pop.querySelector("#seqNewSize").addEventListener("change", syncFollow);
12048
+ pop.querySelector("#seqNewCopy").addEventListener("change", syncFollow);
12049
+ syncFollow();
11112
12050
  const ok = () => {
11113
12051
  const name = pop.querySelector("#seqNewName").value.trim();
11114
12052
  const size = sizes[+pop.querySelector("#seqNewSize").value] || sizes[0];
11115
12053
  const copy = pop.querySelector("#seqNewCopy").checked;
12054
+ const follow = pop.querySelector("#seqNewFollow").checked;
12055
+ const root = seqRoot();
12056
+ const reshaped = size.w && size.w * root.height !== size.h * root.width;
11116
12057
  hideTrackCtxMenu();
11117
- newSequence({ name: name || undefined, from: copy ? "open" : "empty", ...(size.w ? { width: size.w, height: size.h } : {}) });
12058
+ const opened = newSequence({ name: name || undefined, from: copy ? "open" : "empty", ...(size.w ? { width: size.w, height: size.h } : {}) });
12059
+ if (opened && copy && reshaped && follow) reframeClips(null, { follow: true });
11118
12060
  };
11119
12061
  pop.querySelector("[data-ok]").addEventListener("click", ok);
11120
12062
  pop.querySelector("[data-cancel]").addEventListener("click", () => hideTrackCtxMenu());
@@ -11127,6 +12069,49 @@ function promptNewSequence(x, y) {
11127
12069
  const input = pop.querySelector("#seqNewName");
11128
12070
  input.focus(); input.select();
11129
12071
  }
12072
+ /** Highlights: the best moments of this timeline's video (or the selected clips), cut into a new sequence. */
12073
+ function promptHighlights(x, y) {
12074
+ const sel = selectedClips().filter((c) => c.kind === "video");
12075
+ const from = sel.length ? sel : null;
12076
+ const n = Highlights.sourcesOf({ clips: project.clips, disabledTracks: [...state.disabledTracks] }, from && from.map((c) => c.id)).take.length;
12077
+ const sizes = [{ label: `Same as “${openSequenceName()}” · ${project.width}×${project.height}`, w: 0, h: 0 }, ...ASPECT_PRESETS];
12078
+ const pop = document.createElement("div");
12079
+ pop.className = "ctx-menu bin-pop seq-new";
12080
+ pop.innerHTML = `<label class="bin-pop-label" for="hlLen">Highlights</label>
12081
+ <select id="hlLen" class="bin-pop-input">${[15, 30, 60, 90].map((s) => `<option value="${s}" ${s === 30 ? "selected" : ""}>${s} s</option>`).join("")}</select>
12082
+ <label class="bin-pop-label" for="hlSize">Canvas</label>
12083
+ <select id="hlSize" class="bin-pop-input">${sizes.map((s, i) => `<option value="${i}">${escapeHtml(s.label)}</option>`).join("")}</select>
12084
+ <label class="seq-new-copy" title="Each shot is fitted to the new shape and keyed to keep what matters in it in view (Inspector → Reframe)"><input type="checkbox" id="hlFollow" checked> Follow the subject in each shot</label>
12085
+ <div class="bin-pop-hint" data-hl-status>From ${from ? `the ${n} selected video clip${n === 1 ? "" : "s"}` : `every video clip on this timeline (${n})`}: the moments with the most movement and sound, in story order, never across a cut. They go into a new sequence; this one stays as it is.</div>
12086
+ <div class="bin-pop-btns"><button type="button" class="btn tiny" data-cancel>Cancel</button><button type="button" class="btn tiny accent" data-ok ${n ? "" : "disabled"}>Make</button></div>`;
12087
+ const size = () => sizes[+pop.querySelector("#hlSize").value] || sizes[0];
12088
+ const reshaped = () => { const s = size(); return !!(s.w && s.w * project.height !== s.h * project.width); };
12089
+ const syncFollow = () => { pop.querySelector("#hlFollow").closest("label").hidden = !reshaped(); };
12090
+ pop.querySelector("#hlSize").addEventListener("change", syncFollow);
12091
+ syncFollow();
12092
+ const status = pop.querySelector("[data-hl-status]");
12093
+ const ok = async () => {
12094
+ if (highlightRun.busy) return;
12095
+ const okBtn = pop.querySelector("[data-ok]");
12096
+ okBtn.disabled = true;
12097
+ pop.querySelectorAll("select, input").forEach((el) => { el.disabled = true; });
12098
+ const duration = +pop.querySelector("#hlLen").value, s = size();
12099
+ const made = await makeHighlights(from, { duration, size: s.w ? { width: s.w, height: s.h } : null, follow: reshaped() && pop.querySelector("#hlFollow").checked,
12100
+ progress: (f) => { status.textContent = `Looking at the footage… ${Math.round(f * 100)}%`; }, cancelled: () => !pop.isConnected });
12101
+ if (pop.isConnected) hideTrackCtxMenu();
12102
+ return made;
12103
+ };
12104
+ pop.querySelector("[data-ok]").addEventListener("click", ok);
12105
+ // closing the dialog stops a run that has started
12106
+ pop.querySelector("[data-cancel]").addEventListener("click", () => { highlightRun.cancel = true; hideTrackCtxMenu(); });
12107
+ pop.addEventListener("keydown", (e) => {
12108
+ if (e.key === "Enter" && e.target.tagName !== "SELECT") { e.preventDefault(); ok(); }
12109
+ else if (e.key === "Escape") { e.preventDefault(); highlightRun.cancel = true; hideTrackCtxMenu(); }
12110
+ e.stopPropagation();
12111
+ });
12112
+ showPopover(pop, x, y);
12113
+ pop.querySelector("#hlLen").focus();
12114
+ }
11130
12115
  function initSequencesUi() {
11131
12116
  const b = $("btnSequences");
11132
12117
  if (!b || b.dataset.wired) return;
@@ -12250,6 +13235,216 @@ function seekFrame(el, t) {
12250
13235
  el.currentTime = t;
12251
13236
  });
12252
13237
  }
13238
+ /* ── Reframe (reframe.js): fit each full-frame shot to the canvas and key its position to keep
13239
+ the subject in view. The frames come from a private <video>, small, 5 a second — the same
13240
+ samples, plan and keys as fablecut_reframe. One undo step. ── */
13241
+ const Reframe = self.FableCutReframe;
13242
+ const reframeRun = { busy: false, cancel: false, done: 0, of: 0 };
13243
+ /** RGB frames of clip c (SAMPLE_FPS across its window; one for a still), w×h each. With `onRgb`,
13244
+ * each frame goes to it as it is read and nothing is kept (a long shot needn't sit in memory). */
13245
+ async function sampleClipFrames(c, w, h, onFrame, onRgb, { fps = Reframe.SAMPLE_FPS, cancelled = () => reframeRun.cancel } = {}) {
13246
+ const m = getMedia(c.mediaId);
13247
+ const cv = document.createElement("canvas"); cv.width = w; cv.height = h;
13248
+ const x = cv.getContext("2d", { willReadFrequently: true });
13249
+ const rgb = () => {
13250
+ const d = x.getImageData(0, 0, w, h).data, out = new Uint8Array(w * h * 3);
13251
+ for (let i = 0, j = 0; i < d.length; i += 4, j += 3) { out[j] = d[i]; out[j + 1] = d[i + 1]; out[j + 2] = d[i + 2]; }
13252
+ return out;
13253
+ };
13254
+ if (c.kind === "image") {
13255
+ const img = new Image();
13256
+ if (isCrossOriginSrc(m.src)) img.crossOrigin = "anonymous"; // else the canvas can't be read back
13257
+ await new Promise((res, rej) => { img.onload = res; img.onerror = () => rej(new Error("the picture could not be read")); img.src = m.src; });
13258
+ x.drawImage(img, 0, 0, w, h);
13259
+ if (onRgb) { onRgb(rgb()); return []; }
13260
+ return [rgb()];
13261
+ }
13262
+ const el = document.createElement("video");
13263
+ if (isCrossOriginSrc(m.src)) el.crossOrigin = "anonymous";
13264
+ el.muted = true; el.preload = "auto"; el.playsInline = true; el.src = m.src;
13265
+ try {
13266
+ await new Promise((res, rej) => {
13267
+ const tm = setTimeout(() => rej(new Error("the video did not load")), 15000);
13268
+ el.addEventListener("loadeddata", () => { clearTimeout(tm); res(); }, { once: true });
13269
+ el.addEventListener("error", () => { clearTimeout(tm); rej(new Error("the video could not be read")); }, { once: true });
13270
+ });
13271
+ const n = Math.max(1, Math.floor(c.duration * clipSpeed(c) * fps + 1e-6));
13272
+ const frames = [];
13273
+ for (let i = 0; i < n; i++) {
13274
+ if (cancelled()) break;
13275
+ await seekFrame(el, Math.max(0, (c.in || 0) + i / fps) + 0.001);
13276
+ x.drawImage(el, 0, 0, w, h);
13277
+ if (onRgb) onRgb(rgb()); else frames.push(rgb());
13278
+ if (onFrame) onFrame(i + 1, n);
13279
+ }
13280
+ return frames;
13281
+ } finally { el.removeAttribute("src"); el.load(); }
13282
+ }
13283
+ /** The picture size of clip c's media (probed, else read from the file). */
13284
+ async function pictureSize(c) {
13285
+ const m = getMedia(c.mediaId);
13286
+ if (m && m.width > 0 && m.height > 0) return { width: m.width, height: m.height };
13287
+ // a file that never answers mustn't hold Reframe busy for good
13288
+ const wait = (el, ok, what) => new Promise((res, rej) => {
13289
+ const tm = setTimeout(() => rej(new Error(`the ${what} did not load`)), 15000);
13290
+ el.addEventListener(ok, () => { clearTimeout(tm); res(); }, { once: true });
13291
+ el.addEventListener("error", () => { clearTimeout(tm); rej(new Error(`the ${what} could not be read`)); }, { once: true });
13292
+ });
13293
+ if (c.kind === "image") {
13294
+ const img = new Image();
13295
+ if (isCrossOriginSrc(m.src)) img.crossOrigin = "anonymous";
13296
+ const p = wait(img, "load", "picture"); img.src = m.src; await p;
13297
+ return { width: img.naturalWidth, height: img.naturalHeight };
13298
+ }
13299
+ const el = document.createElement("video");
13300
+ el.preload = "metadata";
13301
+ try {
13302
+ const p = wait(el, "loadedmetadata", "video"); el.src = m.src; await p;
13303
+ return { width: el.videoWidth, height: el.videoHeight };
13304
+ } finally { el.removeAttribute("src"); el.load(); }
13305
+ }
13306
+ /** Reframe `clips` (default: every full-frame shot on the timeline) for this canvas. Returns the plan lines. */
13307
+ async function reframeClips(clips, { follow = true, smooth = 0.5 } = {}) {
13308
+ if (!Reframe) { toast("Reframe module missing — reload the editor"); return null; }
13309
+ if (reframeRun.busy) { toast("Already reframing — wait for it, or Cancel"); return null; }
13310
+ // every clip, so a linked partner's lock counts; `clips` (the selection) picks which ones
13311
+ const doc = { clips: project.clips, lockedTracks: [...state.lockedTracks] };
13312
+ const { take, skip } = Reframe.targets(doc, { ids: clips ? clips.map((c) => c.id) : null });
13313
+ if (!take.length) { toast(skip.length ? `Nothing to reframe: ${skip[0].id} is ${skip[0].why}` : "Select a video or picture clip to reframe"); return null; }
13314
+ Object.assign(reframeRun, { busy: true, cancel: false, done: 0, of: take.length, frac: 0 });
13315
+ renderInspector();
13316
+ const canvas = { width: project.width, height: project.height }, fps = projectFps() || 30;
13317
+ // what the plans were made for: if any of it changes while the footage is read, nothing is applied
13318
+ const gen = runtime.projectGen, seqId = SeqLib.activeId(seqRoot()), lanes = JSON.stringify([...state.lockedTracks]);
13319
+ const stamp = (c) => { const m = getMedia(c.mediaId) || {}; return JSON.stringify([c.mediaId, m.src, m.width, m.height, c.track, c.start, c.in, c.duration, !!c.locked, c.props || {}, c.keyframes || {}]); };
13320
+ const stamps = new Map(take.map((c) => [c.id, stamp(c)]));
13321
+ const plans = [];
13322
+ try {
13323
+ for (const c of take) {
13324
+ if (reframeRun.cancel) break;
13325
+ reframeRun.frac = 0;
13326
+ const src = await pictureSize(c);
13327
+ let samples = null;
13328
+ const cover = Reframe.coverRect(src.width, src.height, canvas.width, canvas.height, 1);
13329
+ if (follow && Math.max(cover.maxX, cover.maxY) > 0.5) { // no room to pan: nothing to look at
13330
+ const w = Reframe.SAMPLE_W, h = Math.max(8, Math.round(w * src.height / src.width / 2) * 2);
13331
+ // each frame is looked at as it is read, between seeks, so Cancel answers and nothing piles up
13332
+ const tr = Reframe.tracker(w, h);
13333
+ await sampleClipFrames(c, w, h, (i, n) => { reframeRun.frac = i / n; if (i % 10 === 0) renderInspector(); }, (f) => tr.push(f));
13334
+ if (reframeRun.cancel) break;
13335
+ samples = tr.samples;
13336
+ }
13337
+ plans.push({ id: c.id, ...Reframe.clipPlan(c, samples, src, canvas, { smooth, fps, follow }) });
13338
+ reframeRun.done++;
13339
+ renderInspector();
13340
+ }
13341
+ } catch (e) {
13342
+ plans.length = 0; // all or nothing, as with Cancel
13343
+ toast("Couldn't look at the footage: " + (e?.message || e) + " — nothing changed");
13344
+ } finally {
13345
+ reframeRun.busy = false;
13346
+ }
13347
+ if (reframeRun.cancel || !plans.length) { reframeRun.cancel = false; renderInspector(); if (plans.length) toast("Reframe stopped — nothing changed"); return null; }
13348
+ if (gen !== runtime.projectGen || seqId !== SeqLib.activeId(seqRoot()) || project.width !== canvas.width || project.height !== canvas.height ||
13349
+ (projectFps() || 30) !== fps || JSON.stringify([...state.lockedTracks]) !== lanes ||
13350
+ plans.some((p) => { const c = getClip(p.id); return !c || stamp(c) !== stamps.get(p.id); })) {
13351
+ renderInspector();
13352
+ toast("The project changed while reframing — nothing was applied; run it again");
13353
+ return null;
13354
+ }
13355
+ pushUndo();
13356
+ for (const p of plans) {
13357
+ const c = getClip(p.id);
13358
+ if (!c) continue;
13359
+ for (const [k, v] of Object.entries(p.set.props || {})) {
13360
+ if (v !== null) c.props[k] = v;
13361
+ else if (Object.hasOwn(DEFAULT_PROPS, k)) c.props[k] = DEFAULT_PROPS[k];
13362
+ else delete c.props[k];
13363
+ }
13364
+ if ("keyframes" in p.set) { if (p.set.keyframes === null) delete c.keyframes; else c.keyframes = p.set.keyframes; }
13365
+ }
13366
+ state.dirtyTimeline = true;
13367
+ scheduleSave();
13368
+ renderInspector();
13369
+ const moving = plans.filter((p) => p.keys).length;
13370
+ toast(`Reframed ${plans.length} shot${plans.length === 1 ? "" : "s"} for ${canvas.width}×${canvas.height}` +
13371
+ (follow ? ` · ${moving} follow${moving === 1 ? "s" : ""} the subject` : "") + (skip.length ? ` · ${skip.length} left as placed` : ""));
13372
+ return plans;
13373
+ }
13374
+ /* ── Highlights: the best moments of the timeline's video, cut into a new sequence. The frames
13375
+ come from a private <video> (2 a second, small), the sound from the decoded file — the same
13376
+ reading, scores and picks as fablecut_highlights. ── */
13377
+ const Highlights = self.FableCutHighlights;
13378
+ const highlightRun = { busy: false, cancel: false };
13379
+ const HL_AUDIO_MAX_SECS = 30 * 60;
13380
+ async function readHighlightSource(c, cancelled, onFrame) {
13381
+ const src = await pictureSize(c);
13382
+ const w = Highlights.SAMPLE_W, h = Math.max(8, Math.round(w * src.height / src.width / 2) * 2);
13383
+ const pic = Highlights.picture(w, h), sp = clipSpeed(c);
13384
+ await sampleClipFrames(c, w, h, onFrame, (f) => pic.push(f), { fps: Highlights.PIC_FPS, cancelled });
13385
+ let aud = null;
13386
+ const media = getMedia(c.mediaId);
13387
+ // stopped: the caller drops it; no audio stream: nothing to decode (a failed decode would fetch the file again next time);
13388
+ // a file longer than HL_AUDIO_MAX_SECS isn't decoded whole in a browser tab: its picture decides
13389
+ const done = () => ({ id: c.id, len: c.duration * sp, pic, aud, speed: sp });
13390
+ if (cancelled() || !media || media.audioChannels === 0 || +media.duration > HL_AUDIO_MAX_SECS) return done();
13391
+ try {
13392
+ const buf = await getAudioBuffer(media);
13393
+ const a0 = Math.max(0, Math.floor((c.in || 0) * buf.sampleRate));
13394
+ const a1 = Math.min(buf.length, Math.ceil(((c.in || 0) + c.duration * sp) * buf.sampleRate));
13395
+ if (a1 > a0) {
13396
+ const chs = [];
13397
+ for (let k = 0; k < buf.numberOfChannels; k++) chs.push(buf.getChannelData(k).subarray(a0, a1));
13398
+ aud = Highlights.sound(buf.sampleRate);
13399
+ aud.push(FableCutBeats.mono(chs));
13400
+ }
13401
+ } catch { aud = null; } // no sound to read: the picture alone decides
13402
+ return done();
13403
+ }
13404
+ /** Read `clips` (default: every video clip on this timeline), pick the moments, and open them as a
13405
+ * new sequence. Nothing changes if it is cancelled or the timeline changes meanwhile. */
13406
+ async function makeHighlights(clips, { duration = 30, shot, size = null, follow = false, progress, cancelled: stop } = {}) {
13407
+ if (!Highlights) { toast("Highlights module missing — reload the editor"); return null; }
13408
+ if (highlightRun.busy) { toast("Already making highlights — wait for it, or Cancel"); return null; }
13409
+ if (state.exporting) { toast("Wait for the export to finish"); return null; }
13410
+ const { take, skip } = Highlights.sourcesOf({ clips: project.clips, disabledTracks: [...state.disabledTracks] }, clips && clips.map((c) => c.id));
13411
+ if (!take.length) { toast(skip.length ? `Nothing to look at: ${skip[0].id} is ${skip[0].why}` : "Put video on the timeline first"); return null; }
13412
+ Object.assign(highlightRun, { busy: true, cancel: false });
13413
+ const gen = runtime.projectGen, seqId = SeqLib.activeId(seqRoot());
13414
+ const cancelled = () => highlightRun.cancel || gen !== runtime.projectGen || (stop && stop());
13415
+ const stamp = (c) => { const m = getMedia(c.mediaId) || {}; return JSON.stringify([c.mediaId, m.src, c.track, c.start, c.in, c.duration, c.props?.speed ?? 1, c.linkGroup || null]); };
13416
+ const stamps = new Map(take.map((c) => [c.id, stamp(c)]));
13417
+ const sources = [];
13418
+ let failed = 0;
13419
+ try {
13420
+ for (let i = 0; i < take.length && !cancelled(); i++) {
13421
+ try { sources.push(await readHighlightSource(take[i], cancelled, (k, n) => progress && progress((i + k / n) / take.length))); }
13422
+ catch { failed++; }
13423
+ }
13424
+ } finally { highlightRun.busy = false; }
13425
+ if (cancelled()) { highlightRun.cancel = false; toast("Highlights stopped — nothing changed"); return null; }
13426
+ if (!sources.length) { toast("Couldn't read the footage"); return null; }
13427
+ let picks;
13428
+ try { picks = Highlights.pick(sources, { duration, shot }); } catch (e) { toast(e.message); return null; }
13429
+ if (!picks.length) { toast("No moments long enough to use"); return null; }
13430
+ // the picks name clips by id and read their in points: the timeline must be as it was read
13431
+ // (and no video was added or taken away: the clips it would read now are the ones it read)
13432
+ const now = Highlights.sourcesOf({ clips: project.clips, disabledTracks: [...state.disabledTracks] }, clips && clips.map((c) => c.id)).take;
13433
+ if (seqId !== SeqLib.activeId(seqRoot()) || JSON.stringify(now.map((c) => c.id)) !== JSON.stringify(take.map((c) => c.id)) ||
13434
+ take.some((c) => { const cur = getClip(c.id); return !cur || stamp(cur) !== stamps.get(c.id); })) {
13435
+ toast("The timeline changed while reading — nothing was made; run it again");
13436
+ return null;
13437
+ }
13438
+ const name = `Highlights ${duration} s`;
13439
+ const ops = Highlights.ops(projectJSONHere(), picks, { name, ...(size || {}) });
13440
+ const opened = newSequence({ name, from: "empty", ...(size || {}) }, ops.slice(1).map((o) => o.clip));
13441
+ if (opened === undefined) return null; // nothing was made: newSequence said why
13442
+ if (opened && follow) reframeClips(null, { follow: true });
13443
+ const total = picks.reduce((n, p) => n + p.len, 0);
13444
+ toast(`Highlights: ${picks.length} moments, ${total.toFixed(1)} s` + (failed ? ` · ${failed} clip${failed === 1 ? "" : "s"} couldn't be read` : "") +
13445
+ (total < duration - 0.5 ? " — the footage has no more distinct moments" : ""));
13446
+ return picks;
13447
+ }
12253
13448
  /**
12254
13449
  * Follow `box` (picture fractions {x, y, w, h}) through clip c from clip-local
12255
13450
  * `from` towards `to` (dir ±1), one sample per project frame. Returns
@@ -12987,6 +14182,7 @@ window.addEventListener("keydown", (e) => {
12987
14182
  return;
12988
14183
  }
12989
14184
  if (!maskUi.clip || (maskUi.sel < 0 && !maskUi.tool)) return;
14185
+ if (els.transcriptPage?.contains(e.target)) return; // keys typed in the Transcript tab are its own
12990
14186
  const tg = e.target;
12991
14187
  if (tg && (tg.tagName === "INPUT" || tg.tagName === "TEXTAREA" || tg.tagName === "SELECT" || tg.isContentEditable)) return;
12992
14188
  const c = getClip(state.selId);
@@ -13659,6 +14855,7 @@ els.preview.addEventListener("dblclick", (e) => {
13659
14855
  shapeUi.pt = -1; scheduleSave(); renderInspector();
13660
14856
  }, true);
13661
14857
  window.addEventListener("keydown", (e) => {
14858
+ if (els.transcriptPage?.contains(e.target)) return; // keys typed in the Transcript tab are its own
13662
14859
  if (e.key === "Escape" && runtime.anchorTool && !shapeUi.sel && !shapeUi.tool) {
13663
14860
  const tg0 = e.target;
13664
14861
  if (!(tg0 && (tg0.tagName === "INPUT" || tg0.tagName === "TEXTAREA" || tg0.tagName === "SELECT"))) {
@@ -13792,12 +14989,13 @@ function drawTextOnPath(c, p, local) {
13792
14989
  return out;
13793
14990
  };
13794
14991
  const words = anim === "word-pop" ? centre("word") : null, lineBox = anim === "zoom-in" ? centre("line") : null;
14992
+ const clk = wordClock(c, p, wi, rate);
13795
14993
  const shown = anim === "typewriter" ? Math.floor(local / (rate / 4)) : Infinity;
13796
14994
  const ease = EASE["ease-out"];
13797
14995
  for (const q of glyphs) {
13798
14996
  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
14997
+ let d = q.d, scale = 1, alpha = 1, dx = 0, dy = 0, clipL = null, clipR = null, rise = null, lit = false;
14998
+ const uw = clamp((local - clk(q.word)[0]) / 0.25, 0, 1); // per word
13801
14999
  const ul = (dur) => clamp((local - q.line * rate) / dur, 0, 1); // per line
13802
15000
  if (anim === "letter-pop") {
13803
15001
  const u = clamp((local - q.ci * rate / 3) / 0.18, 0, 1);
@@ -13815,6 +15013,7 @@ function drawTextOnPath(c, p, local) {
13815
15013
  } else if (anim === "bounce") dy -= Math.abs(Math.sin(local * 3.2 + q.word * 0.9)) * size * 0.18;
13816
15014
  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
15015
  else if (anim === "karaoke") alpha = uw >= 1 ? 1 : 0.3 + uw * 0.7;
15016
+ else if (anim === "highlight") lit = wordIsCurrent(clk, q.word, wi, local);
13818
15017
  else if (anim === "clip-reveal") { // a wipe runs along each line in reading order
13819
15018
  const u = ul(0.5);
13820
15019
  if (u <= 0) continue;
@@ -13853,7 +15052,7 @@ function drawTextOnPath(c, p, local) {
13853
15052
  }
13854
15053
  if (p.glow > 0) { ctx2d.shadowColor = p.glowColor || p.color || "#fff"; ctx2d.shadowBlur = (+p.glow) * size / 40; }
13855
15054
  else if (shadowBlur > 0) { ctx2d.shadowColor = "rgba(0,0,0,.7)"; ctx2d.shadowBlur = shadowBlur; ctx2d.shadowOffsetY = shadowBlur / 3; }
13856
- ctx2d.fillStyle = fill();
15055
+ ctx2d.fillStyle = lit ? p.highlightColor || "#ffd166" : fill();
13857
15056
  ctx2d.fillText(q.g, 0, 0);
13858
15057
  if (p.glow > 0) ctx2d.fillText(q.g, 0, 0);
13859
15058
  ctx2d.globalAlpha = keep;
@@ -14158,7 +15357,24 @@ function letterAnimSegments(line) {
14158
15357
 
14159
15358
  /* ── Text rendering: styling (stroke / background pill) + kinetic animations.
14160
15359
  `local` is clip-local time in seconds. Word timing: word i enters at
14161
- i * wordRate; each entrance animation lasts ~0.25 s. ── */
15360
+ i * wordRate — or, on a caption timed to speech, at its wordTimes start;
15361
+ each entrance animation lasts ~0.25 s. ── */
15362
+ /** Word i's [start, end], seconds from the clip's start: props.wordTimes (a caption timed to speech)
15363
+ * when it has one pair per word; if the text was edited to another word count, spread over the clip;
15364
+ * else one every wordRate seconds. */
15365
+ function wordClock(c, p, n, rate) {
15366
+ const wt = p.wordTimes;
15367
+ if (Array.isArray(wt) && wt.length === n && n) return (i) => [+wt[i]?.[0] || 0, +wt[i]?.[1] || 0];
15368
+ if (Array.isArray(wt) && n) { const step = Math.max(0.05, (+c?.duration || n * rate) / n); return (i) => [i * step, (i + 1) * step]; }
15369
+ return (i) => [i * rate, (i + 1) * rate];
15370
+ }
15371
+ /** Is word i the one being said? From its start to its end (a tenth of a second more, so the
15372
+ * highlight doesn't flicker between words), and never past the next word's start. */
15373
+ function wordIsCurrent(clk, i, n, local) {
15374
+ const [a, b] = clk(i);
15375
+ const until = Math.max(b, a + 0.05) + 0.1;
15376
+ return local >= a && local < (i + 1 < n ? Math.min(clk(i + 1)[0], until) : until);
15377
+ }
14162
15378
  const backOut = (u) => { const c1 = 1.70158, c3 = c1 + 1; const v = u - 1; return 1 + c3 * v * v * v + c1 * v * v; };
14163
15379
  function hexToRgba(hex, a) {
14164
15380
  const n = parseInt(String(hex).replace("#", ""), 16) || 0;
@@ -14352,7 +15568,7 @@ function drawText(c, p, local) {
14352
15568
  g.addColorStop(1, p.color2);
14353
15569
  return g;
14354
15570
  };
14355
- const paint = (str, x, y, alpha = 1, rtl = false) => {
15571
+ const paint = (str, x, y, alpha = 1, rtl = false, fill = null) => {
14356
15572
  if (alpha <= 0) return;
14357
15573
  const keep = ctx2d.globalAlpha;
14358
15574
  const prevDir = ctx2d.direction;
@@ -14369,15 +15585,15 @@ function drawText(c, p, local) {
14369
15585
  if (p.glow > 0) { // neon: colored halo, double-fill for intensity
14370
15586
  ctx2d.shadowColor = p.glowColor || p.color || "#fff";
14371
15587
  ctx2d.shadowBlur = (+p.glow) * size / 40;
14372
- ctx2d.fillStyle = fillFor(y);
15588
+ ctx2d.fillStyle = fill || fillFor(y);
14373
15589
  ctx2d.fillText(str, x, y);
14374
15590
  ctx2d.fillText(str, x, y);
14375
15591
  } else if (shadowBlur > 0) {
14376
15592
  ctx2d.shadowColor = "rgba(0,0,0,.7)"; ctx2d.shadowBlur = shadowBlur; ctx2d.shadowOffsetY = shadowBlur / 3;
14377
- ctx2d.fillStyle = fillFor(y);
15593
+ ctx2d.fillStyle = fill || fillFor(y);
14378
15594
  ctx2d.fillText(str, x, y);
14379
15595
  } else {
14380
- ctx2d.fillStyle = fillFor(y);
15596
+ ctx2d.fillStyle = fill || fillFor(y);
14381
15597
  ctx2d.fillText(str, x, y);
14382
15598
  }
14383
15599
  ctx2d.shadowColor = "transparent"; ctx2d.shadowBlur = 0; ctx2d.shadowOffsetY = 0;
@@ -14506,6 +15722,8 @@ function drawText(c, p, local) {
14506
15722
  }
14507
15723
  // word-based animations: lay words out manually, per-line, honoring alignment + direction
14508
15724
  const spaceW = ctx2d.measureText(" ").width;
15725
+ const nWords = rawLines.reduce((n, ln) => n + ln.split(/\s+/).filter(Boolean).length, 0);
15726
+ const clk = wordClock(c, p, nWords, rate);
14509
15727
  let wi = 0;
14510
15728
  rawLines.forEach((ln, i) => {
14511
15729
  const y = y0 + i * lh;
@@ -14523,8 +15741,16 @@ function drawText(c, p, local) {
14523
15741
  words.forEach((word, j) => {
14524
15742
  const w = widths[j];
14525
15743
  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") {
15744
+ const u = clamp((local - clk(wi)[0]) / 0.25, 0, 1);
15745
+ if (anim === "highlight") { // every word shown; the one being said lit and lifted a little
15746
+ const on = wordIsCurrent(clk, wi, nWords, local);
15747
+ const s = on ? 1 + 0.03 * backOut(clamp((local - clk(wi)[0]) / 0.15, 0, 1)) : 1;
15748
+ ctx2d.save();
15749
+ ctx2d.translate(cx, y);
15750
+ if (s !== 1) ctx2d.scale(s, s);
15751
+ paint(word, 0, 0, 1, rtl, on ? p.highlightColor || "#ffd166" : null);
15752
+ ctx2d.restore();
15753
+ } else if (anim === "word-pop") {
14528
15754
  if (u > 0) {
14529
15755
  ctx2d.save();
14530
15756
  ctx2d.translate(cx, y);
@@ -14791,6 +16017,8 @@ function loop(ts) {
14791
16017
  }
14792
16018
  }
14793
16019
  if (state.dirtyTimeline) rebuildClips();
16020
+ if (trState.open) transcriptTick();
16021
+ watchCaptions(ts);
14794
16022
  const phX = Math.round(state.time * state.pps);
14795
16023
  if (phX !== playheadPx) {
14796
16024
  playheadPx = phX;
@@ -16622,6 +17850,7 @@ async function runExportJob(ticket) {
16622
17850
  if (ticket.revision != null && (project.revision || 0) < ticket.revision) await syncFromServer();
16623
17851
  if (ticket.kind === "scopes") return runScopesJob(ticket, fail);
16624
17852
  if (ticket.kind === "track") return runTrackJob(ticket, fail);
17853
+ if (ticket.kind === "transcribe") return runTranscribeJob(ticket, fail);
16625
17854
  if (!state.ffmpeg) {
16626
17855
  const j = await fetch("/api/export/ffmpeg").then((r) => r.json()).catch(() => ({}));
16627
17856
  state.ffmpeg = !!j.available;
@@ -19326,7 +20555,7 @@ for (const b of els.sideTabs.querySelectorAll("[data-side]"))
19326
20555
  b.addEventListener("click", () => setSideTab(b.dataset.side));
19327
20556
  try {
19328
20557
  const side = localStorage.getItem(SIDE_TAB_KEY);
19329
- if (side === "mixer" || side === "color") setSideTab(side);
20558
+ if (side === "mixer" || side === "color" || side === "transcript") setSideTab(side);
19330
20559
  if (localStorage.getItem(WS_KEY) === "color") setWorkspace("color");
19331
20560
  } catch { }
19332
20561
  connectServer().then(() => { loadLibraryFonts(); runExportJobFromUrl(); });