fablecut 1.17.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
@@ -554,6 +554,8 @@ const state = {
554
554
  selIds: new Set(), // full multi-selection (includes selId)
555
555
  silence: null, // silences found (Inspector → Silence): {ids, spans, sig}, shown on the timeline until cut or cleared
556
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
557
559
  trackSize: "l", // s | m | l — timeline track density preset
558
560
  connected: false, exporting: false,
559
561
  rendering: false, // fast (server/ffmpeg) export in progress
@@ -1760,13 +1762,22 @@ async function syncFromServer(force) {
1760
1762
  return true;
1761
1763
  }
1762
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;
1763
1770
  if (runtime.saveTimer) { // unsaved local edit vs. external write: external wins, tell the user
1764
1771
  clearTimeout(runtime.saveTimer); runtime.saveTimer = null;
1765
1772
  // the undo steps describe the discarded edit; replaying one would re-save over the external write
1766
1773
  runtime.undo.length = 0; runtime.redo.length = 0;
1767
- toast("Project was updated externally — your last change may need redoing.");
1774
+ clash = true;
1768
1775
  }
1769
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.");
1770
1781
  syncCompCrumb(); // the top bar shows the project's name
1771
1782
  // "Compare with now" was against the document before this change
1772
1783
  // (always: a comparison still on its way was made against the old document too)
@@ -3848,6 +3859,18 @@ function counterSnapshot(snap) {
3848
3859
  return JSON.stringify({ clips: project.clips, markers: project.markers || [], comps: project.comps || [], media: project.media,
3849
3860
  ...(hasSeqClips(snap) ? { seqClips: otherSequenceClips() } : {}) });
3850
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,');
3851
3874
  function undo() {
3852
3875
  if (!runtime.undo.length) return;
3853
3876
  const snap = runtime.undo.pop();
@@ -3855,6 +3878,7 @@ function undo() {
3855
3878
  restoreSnapshot(snap);
3856
3879
  pruneSelection();
3857
3880
  scheduleSave(); renderInspector();
3881
+ if (isOutsideStep(snap)) toast("Undid a change made outside this tab (an agent or another tab)");
3858
3882
  }
3859
3883
  function redo() {
3860
3884
  if (!runtime.redo.length) return;
@@ -4997,6 +5021,7 @@ function rebuildClips() {
4997
5021
  }
4998
5022
  paintAudioOverlaps();
4999
5023
  paintSilences();
5024
+ paintBeats();
5000
5025
  state.dirtyTimeline = false;
5001
5026
  updateWorkArea();
5002
5027
  }
@@ -5019,6 +5044,38 @@ function paintSilences() {
5019
5044
  }
5020
5045
  }
5021
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
+ }
5022
5079
  /* Hatched bands where two+ audio clips share a track (CSS draw, O(n²) per track). */
5023
5080
  function paintAudioOverlaps() {
5024
5081
  const byTrack = new Map();
@@ -6628,6 +6685,23 @@ function renderInspector(lite) {
6628
6685
  ${check("Flip V", "flipV", p.flipV)}
6629
6686
  </div>`;
6630
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
+ }
6631
6705
  if (c.kind === "video" || c.kind === "image" || c.kind === "svg" || c.kind === "adjust" || c.kind === "comp") {
6632
6706
  html += `<div class="insp-section"><h3>Filter / Color</h3>
6633
6707
  ${sel("Preset", "filterPreset", Object.keys(FILTER_PRESETS), p.filterPreset)}
@@ -6696,6 +6770,24 @@ function renderInspector(lite) {
6696
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>` : ""}
6697
6771
  </div>`;
6698
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
+ }
6699
6791
  if (c.kind === "audio" && typeof FableCutFx !== "undefined") {
6700
6792
  html += `<div class="insp-section" data-fx-section><h3>Audio effects</h3>${fxEditorHtml(c.fx, playheadOverClip(c) ? state.time - c.start : null)}</div>`;
6701
6793
  }
@@ -6922,6 +7014,21 @@ function renderInspector(lite) {
6922
7014
  findSilences(sel.length ? sel : [c]);
6923
7015
  });
6924
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; });
6925
7032
  els.inspector.querySelector("[data-sil-clear]")?.addEventListener("click", clearSilences);
6926
7033
  els.inspector.querySelector("[data-norm-target]")?.addEventListener("change", (e) => {
6927
7034
  try { localStorage.setItem(NORMALIZE_KEY, e.target.value); } catch { }
@@ -9330,6 +9437,108 @@ function clearSilences() {
9330
9437
  state.dirtyTimeline = true;
9331
9438
  renderInspector();
9332
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(" · "));
9541
+ }
9333
9542
  async function autoDuckClips(clips, { under = null, amount = duckAmount(), threshold = -40 } = {}) {
9334
9543
  if (typeof FableCutDucking === "undefined") { toast("Ducking module missing — reload the editor"); return; }
9335
9544
  const music = withLinked(clips).filter((x) => x.kind === "audio" && !isGroupLocked(x));
@@ -11716,15 +11925,17 @@ function openSequence(id) {
11716
11925
  return true;
11717
11926
  }
11718
11927
  /** Add a sequence ({name?, from?, width?, height?}) and open it. */
11719
- function newSequence(opts) {
11928
+ function newSequence(opts, clips = null) {
11720
11929
  if (state.exporting) { toast("Wait for the export to finish"); return; }
11721
11930
  if (state.compCtx) exitComp(state.compCtx.path.length);
11722
11931
  const doc = projectJSONHere();
11723
11932
  let s;
11724
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)
11725
11935
  project.sequences = doc.sequences; project.sequence = doc.sequence;
11726
- if (openSequence(s.id)) toast(`New sequence “${s.name}” · ${s.width}×${s.height}`);
11727
- 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;
11728
11939
  }
11729
11940
  function renameSequence(id, name) {
11730
11941
  const r = seqRoot();
@@ -11801,6 +12012,8 @@ function showSequenceMenu(x, y) {
11801
12012
  }
11802
12013
  sep();
11803
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);
11804
12017
  item(`<span>Duplicate “${escapeHtml(open.name)}”</span>`, () => newSequence({ from: "open" }));
11805
12018
  item(`<span>Rename “${escapeHtml(open.name)}”…</span>`, () => promptBinText(x, y, "Sequence name", open.name, (v) => renameSequence(openId, v), { max: 120, ok: "Rename" }));
11806
12019
  item(`<span>Delete “${escapeHtml(open.name)}”…</span>`, (b) => {
@@ -11815,21 +12028,35 @@ function promptNewSequence(x, y) {
11815
12028
  const pop = document.createElement("div");
11816
12029
  pop.className = "ctx-menu bin-pop seq-new";
11817
12030
  const n = SeqLib.entries(seqRoot()).length + 1;
11818
- 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];
11819
12032
  pop.innerHTML = `<label class="bin-pop-label" for="seqNewName">New sequence</label>
11820
12033
  <input type="text" class="bin-pop-input" id="seqNewName" maxlength="120" spellcheck="false">
11821
12034
  <label class="bin-pop-label" for="seqNewSize">Canvas</label>
11822
12035
  <select id="seqNewSize" class="bin-pop-input">${sizes.map((s, i) => `<option value="${i}">${escapeHtml(s.label)}</option>`).join("")}</select>
11823
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>
11824
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>
11825
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>`;
11826
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();
11827
12050
  const ok = () => {
11828
12051
  const name = pop.querySelector("#seqNewName").value.trim();
11829
12052
  const size = sizes[+pop.querySelector("#seqNewSize").value] || sizes[0];
11830
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;
11831
12057
  hideTrackCtxMenu();
11832
- 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 });
11833
12060
  };
11834
12061
  pop.querySelector("[data-ok]").addEventListener("click", ok);
11835
12062
  pop.querySelector("[data-cancel]").addEventListener("click", () => hideTrackCtxMenu());
@@ -11842,6 +12069,49 @@ function promptNewSequence(x, y) {
11842
12069
  const input = pop.querySelector("#seqNewName");
11843
12070
  input.focus(); input.select();
11844
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
+ }
11845
12115
  function initSequencesUi() {
11846
12116
  const b = $("btnSequences");
11847
12117
  if (!b || b.dataset.wired) return;
@@ -12965,6 +13235,216 @@ function seekFrame(el, t) {
12965
13235
  el.currentTime = t;
12966
13236
  });
12967
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
+ }
12968
13448
  /**
12969
13449
  * Follow `box` (picture fractions {x, y, w, h}) through clip c from clip-local
12970
13450
  * `from` towards `to` (dir ±1), one sample per project frame. Returns