fablecut 1.17.0 → 1.19.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/CLAUDE.md +189 -10
- package/README.md +39 -17
- package/analyze.js +3 -96
- package/app.js +1062 -77
- package/beats.js +458 -0
- package/command-search.js +79 -0
- package/export-jobs.js +4 -2
- package/highlights.js +296 -0
- package/index.html +34 -0
- package/mcp-server.js +344 -10
- package/media-files.js +271 -0
- package/package.json +2 -2
- package/reframe.js +297 -0
- package/server.js +210 -4
- package/style.css +76 -0
- package/transcripts.js +10 -0
package/app.js
CHANGED
|
@@ -110,9 +110,19 @@ const FILTER_PRESETS = {
|
|
|
110
110
|
};
|
|
111
111
|
const SYSTEM_FONTS = ["Segoe UI", "Arial", "Georgia", "Impact", "Courier New",
|
|
112
112
|
"Trebuchet MS", "Verdana", "Times New Roman", "Comic Sans MS", "Consolas"];
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
"
|
|
113
|
+
/* Google fonts offered in the font picker, by look. Any other Google Font loads by name too. */
|
|
114
|
+
const GOOGLE_FONT_GROUPS = {
|
|
115
|
+
Display: ["Anton", "Archivo Black", "Bebas Neue", "Bangers", "Bungee", "Oswald", "Teko", "Russo One",
|
|
116
|
+
"Alfa Slab One", "Black Ops One", "Righteous", "Fjalla One", "Unbounded", "Syne"],
|
|
117
|
+
Sans: ["Inter", "Montserrat", "Poppins", "Roboto", "Roboto Condensed", "Barlow", "Lato", "Open Sans", "Raleway",
|
|
118
|
+
"Nunito", "Work Sans", "DM Sans", "Rubik", "Kanit", "Lexend", "Outfit", "Sora", "Space Grotesk", "Josefin Sans", "Fredoka"],
|
|
119
|
+
Serif: ["Playfair Display", "Abril Fatface", "Cinzel", "Cormorant Garamond", "Lora", "Merriweather",
|
|
120
|
+
"DM Serif Display", "Libre Baskerville", "Marcellus"],
|
|
121
|
+
"Script & hand": ["Caveat", "Pacifico", "Lobster", "Permanent Marker", "Dancing Script", "Great Vibes",
|
|
122
|
+
"Satisfy", "Shadows Into Light", "Kalam"],
|
|
123
|
+
"Retro & mono": ["Monoton", "Press Start 2P", "Special Elite", "Space Mono", "VT323", "Courier Prime"],
|
|
124
|
+
};
|
|
125
|
+
const GOOGLE_FONTS = Object.values(GOOGLE_FONT_GROUPS).flat();
|
|
116
126
|
|
|
117
127
|
/* ── Title styles: cohesive one-tap looks. Each bundles a DIFFERENT font,
|
|
118
128
|
placement and animation, so titles vary instead of all looking basic.
|
|
@@ -121,7 +131,7 @@ const FONT_CUT_DEFAULT = ["Anton", "Bebas Neue", "Archivo Black", "Oswald", "Imp
|
|
|
121
131
|
const STYLE_RESET = { // decorative props a style owns; reset before applying
|
|
122
132
|
color2: "", glow: 0, glowColor: "", strokeWidth: 0, bgColor: "#000000", bgOpacity: 0,
|
|
123
133
|
rotation: 0, letterSpacing: 0, uppercase: false, italic: false, textShadow: 12,
|
|
124
|
-
fontCutSet: undefined, align: "center",
|
|
134
|
+
fontCutSet: undefined, align: "center", weight: 0, strokeColor: "#000000", highlightColor: "#ffd166",
|
|
125
135
|
};
|
|
126
136
|
const TITLE_STYLES = {
|
|
127
137
|
plain: { label: "Plain", place: "center", props: { font: "Segoe UI", fontSize: 72, bold: true, color: "#ffffff", textAnim: "none" } },
|
|
@@ -134,8 +144,20 @@ const TITLE_STYLES = {
|
|
|
134
144
|
subtitle: { label: "Subtitle", place: "lower", props: { font: "Roboto", fontSize: 52, bold: false, color: "#ffffff", bgColor: "#000000", bgOpacity: 0.5, textAnim: "karaoke" } },
|
|
135
145
|
boldRise: { label: "Bold rise", place: "lower", props: { font: "Archivo Black", fontSize: 92, bold: false, uppercase: true, color: "#ffffff", textAnim: "rise-mask" } },
|
|
136
146
|
luxury: { label: "Luxury", place: "center", props: { font: "Cinzel", fontSize: 88, bold: false, uppercase: true, color: "#faf0dc", color2: "#c9a227", letterSpacing: 6, textAnim: "clip-reveal" } },
|
|
147
|
+
popOutline: { label: "Pop outline", place: "center", props: { font: "Montserrat", fontSize: 100, bold: false, weight: 900, uppercase: true, color: "#ffd166", strokeWidth: 6, strokeColor: "#111111", textShadow: 0, textAnim: "letter-pop" } },
|
|
148
|
+
boxed: { label: "Boxed", place: "lower", props: { font: "Inter", fontSize: 60, bold: false, weight: 800, color: "#111111", bgColor: "#ffffff", bgOpacity: 0.95, textShadow: 0, textAnim: "word-slide" } },
|
|
149
|
+
headline: { label: "Headline", place: "center", props: { font: "Montserrat", fontSize: 92, bold: false, weight: 900, uppercase: true, color: "#ffffff", highlightColor: "#ff4d6d", strokeWidth: 4, strokeColor: "#000000", textShadow: 0, textAnim: "highlight" } },
|
|
150
|
+
comic: { label: "Comic", place: "center", props: { font: "Bangers", fontSize: 112, bold: false, color: "#ffe14d", strokeWidth: 8, strokeColor: "#1a1a1a", rotation: -3, letterSpacing: 2, textShadow: 0, textAnim: "bounce" } },
|
|
151
|
+
typewriter: { label: "Typewriter", place: "lower-left", props: { font: "Special Elite", fontSize: 64, bold: false, color: "#f5f0e6", textShadow: 6, textAnim: "typewriter" } },
|
|
152
|
+
minimal: { label: "Minimal", place: "center", props: { font: "Inter", fontSize: 60, bold: false, weight: 300, uppercase: true, color: "#ffffff", letterSpacing: 12, textShadow: 0, textAnim: "rise-mask" } },
|
|
153
|
+
script: { label: "Script", place: "center", props: { font: "Great Vibes", fontSize: 120, bold: false, color: "#ffffff", color2: "#f9c5d1", textShadow: 10, textAnim: "clip-reveal" } },
|
|
154
|
+
retro: { label: "Retro", place: "center", props: { font: "Monoton", fontSize: 96, bold: false, uppercase: true, color: "#ff6ec7", glow: 40, glowColor: "#ff6ec7", textAnim: "letter-pop" } },
|
|
155
|
+
sticker: { label: "Sticker", place: "lower", props: { font: "Fredoka", fontSize: 80, bold: false, weight: 700, color: "#ffffff", bgColor: "#7b6cff", bgOpacity: 1, rotation: -2, textShadow: 0, textAnim: "word-pop" } },
|
|
156
|
+
glitch: { label: "Glitch", place: "center", props: { font: "Russo One", fontSize: 100, bold: false, uppercase: true, color: "#e8f9ff", glow: 30, glowColor: "#ff2e63", letterSpacing: 2, textAnim: "shake" } },
|
|
157
|
+
cinematic: { label: "Cinematic", place: "center", props: { font: "Cormorant Garamond", fontSize: 84, bold: false, weight: 500, uppercase: true, color: "#f2efe9", letterSpacing: 14, textShadow: 8, textAnim: "rise-mask" } },
|
|
137
158
|
};
|
|
138
|
-
const STYLE_CYCLE = ["impact", "elegant", "kinetic", "neon", "handwritten", "serifDrop", "boldRise", "luxury"
|
|
159
|
+
const STYLE_CYCLE = ["impact", "elegant", "kinetic", "neon", "handwritten", "serifDrop", "boldRise", "luxury",
|
|
160
|
+
"popOutline", "boxed", "comic", "typewriter", "script", "sticker", "cinematic"];
|
|
139
161
|
const AUDIO_EXT = /\.(mp3|wav|ogg|m4a|aac|flac|mpeg)$/i;
|
|
140
162
|
const VIDEO_EXT = /\.(mp4|webm|mov|mkv|m4v)$/i;
|
|
141
163
|
const IMAGE_EXT = /\.(png|jpe?g|gif|webp|avif)$/i;
|
|
@@ -477,6 +499,9 @@ const DEFAULT_SETTINGS = {
|
|
|
477
499
|
webCodecsBitrateMode: "variable", // "variable" | "constant"
|
|
478
500
|
snapTargets: { clips: true, playhead: true, markers: true, inout: true, keyframes: false, frames: true },
|
|
479
501
|
useProxies: true, // play proxies (when a file has one) while editing; export always reads the original
|
|
502
|
+
exportAsk: true, // Export opens its dialog (name + settings) first; false = render straight away
|
|
503
|
+
exportEngine: null, // "fast" | "second" — what the last export used ("Don't ask again" reuses it)
|
|
504
|
+
exportChoice: null, // the Export dialog's preset / profile last used ("d:<preset>" | "p:<profile>"), reused with it
|
|
480
505
|
};
|
|
481
506
|
let settings = { ...DEFAULT_SETTINGS };
|
|
482
507
|
function loadSettings() {
|
|
@@ -554,6 +579,8 @@ const state = {
|
|
|
554
579
|
selIds: new Set(), // full multi-selection (includes selId)
|
|
555
580
|
silence: null, // silences found (Inspector → Silence): {ids, spans, sig}, shown on the timeline until cut or cleared
|
|
556
581
|
silenceBusy: false, // a Find is listening (the Inspector offers Cancel)
|
|
582
|
+
beats: null, // the beat Find beats heard (Inspector → Beats): {clipId, sig, a, grid, bpm, drop}, ticks on the timeline
|
|
583
|
+
beatsBusy: false, // Find beats is listening
|
|
557
584
|
trackSize: "l", // s | m | l — timeline track density preset
|
|
558
585
|
connected: false, exporting: false,
|
|
559
586
|
rendering: false, // fast (server/ffmpeg) export in progress
|
|
@@ -1744,6 +1771,8 @@ async function syncFromServer(force) {
|
|
|
1744
1771
|
// another project was opened (the dashboard, another tab, an agent)
|
|
1745
1772
|
const pid = res.headers.get("X-FableCut-Project");
|
|
1746
1773
|
const switched = !!(pid && runtime.projectId && pid !== runtime.projectId);
|
|
1774
|
+
if (switched && runtime.jobHold) { runtime.pendingSync = true; return false; } // an agent's job is rendering this project
|
|
1775
|
+
if (pid && pid !== runtime.projectId && cmdk.pid && cmdkOpen()) closeCmdk(false); // its results were for the other project
|
|
1747
1776
|
if (pid) runtime.projectId = pid;
|
|
1748
1777
|
if (switched) {
|
|
1749
1778
|
onProjectSwitched();
|
|
@@ -1760,13 +1789,22 @@ async function syncFromServer(force) {
|
|
|
1760
1789
|
return true;
|
|
1761
1790
|
}
|
|
1762
1791
|
if (!force && (data.revision || 0) === (project.revision || 0)) return; // our own save
|
|
1792
|
+
// An edit from outside (an agent, another tab) on the open timeline becomes an undo step of its own,
|
|
1793
|
+
// so Ctrl+Z takes it back first instead of replaying an older step over it.
|
|
1794
|
+
const before = !state.compCtx && SeqLib.activeId(data) === SeqLib.activeId(project) ? undoSnapshot() : null;
|
|
1795
|
+
const mediaBefore = project.media;
|
|
1796
|
+
let clash = false;
|
|
1763
1797
|
if (runtime.saveTimer) { // unsaved local edit vs. external write: external wins, tell the user
|
|
1764
1798
|
clearTimeout(runtime.saveTimer); runtime.saveTimer = null;
|
|
1765
1799
|
// the undo steps describe the discarded edit; replaying one would re-save over the external write
|
|
1766
1800
|
runtime.undo.length = 0; runtime.redo.length = 0;
|
|
1767
|
-
|
|
1801
|
+
clash = true;
|
|
1768
1802
|
}
|
|
1769
1803
|
applyProject(data);
|
|
1804
|
+
const step = before && outsideEditStep(before, undoSnapshot(), mediaBefore, project.media);
|
|
1805
|
+
if (step) pushUndo(step);
|
|
1806
|
+
if (clash) toast(step ? "The project was changed from outside while you were editing. Ctrl+Z puts your version back."
|
|
1807
|
+
: "Project was updated externally — your last change may need redoing.");
|
|
1770
1808
|
syncCompCrumb(); // the top bar shows the project's name
|
|
1771
1809
|
// "Compare with now" was against the document before this change
|
|
1772
1810
|
// (always: a comparison still on its way was made against the old document too)
|
|
@@ -3408,7 +3446,7 @@ function pjNewHtml() {
|
|
|
3408
3446
|
async function pjOpenProject(id) {
|
|
3409
3447
|
const p = pj.list.find((x) => x.id === id);
|
|
3410
3448
|
if (!p || p.active || pj.busy) return;
|
|
3411
|
-
if (
|
|
3449
|
+
if (exportBusy()) { toast("Wait for the export to finish before switching projects"); return; }
|
|
3412
3450
|
pj.busy = true;
|
|
3413
3451
|
try {
|
|
3414
3452
|
if (!(await flushSaveBeforeSwitch())) return;
|
|
@@ -3430,7 +3468,7 @@ async function pjAction(act, btn) {
|
|
|
3430
3468
|
if (act === "new-cancel") { pj.mode = "detail"; renderProjects(); return; }
|
|
3431
3469
|
if (act === "new-create") {
|
|
3432
3470
|
if (pj.busy) return;
|
|
3433
|
-
if (
|
|
3471
|
+
if (exportBusy()) { toast("Wait for the export to finish before switching projects"); return; }
|
|
3434
3472
|
const name = ($("pjNewName")?.value || "").trim() || "Untitled Project";
|
|
3435
3473
|
const fps = $("pjNewFps")?.value;
|
|
3436
3474
|
pj.busy = true;
|
|
@@ -3607,7 +3645,7 @@ async function pjVersionRun(act, btn) {
|
|
|
3607
3645
|
setTimeout(() => { if (btn.isConnected) { btn.dataset.armed = ""; btn.textContent = "Restore…"; } }, 3000);
|
|
3608
3646
|
return;
|
|
3609
3647
|
}
|
|
3610
|
-
if (p.active &&
|
|
3648
|
+
if (p.active && exportBusy()) { toast("Wait for the export to finish before restoring"); return; }
|
|
3611
3649
|
if (p.active && !(await flushSaveForVersion("nothing was restored"))) return;
|
|
3612
3650
|
const out = await post({ action: "restore", version: v });
|
|
3613
3651
|
if (!out) return;
|
|
@@ -3848,6 +3886,18 @@ function counterSnapshot(snap) {
|
|
|
3848
3886
|
return JSON.stringify({ clips: project.clips, markers: project.markers || [], comps: project.comps || [], media: project.media,
|
|
3849
3887
|
...(hasSeqClips(snap) ? { seqClips: otherSequenceClips() } : {}) });
|
|
3850
3888
|
}
|
|
3889
|
+
/** The undo step for an edit made outside this tab (an agent, another tab): the timeline as it was
|
|
3890
|
+
* (`before`), marked so undo can say what it took back — or null when the open timeline didn't change.
|
|
3891
|
+
* When the edit removed media, the step carries the media list as it was too, so the clips it puts
|
|
3892
|
+
* back find their files (and redo, whose counter-snapshot then carries media, takes them out again). */
|
|
3893
|
+
function outsideEditStep(before, after, mediaBefore = null, mediaAfter = null) {
|
|
3894
|
+
if (before === after) return null;
|
|
3895
|
+
const now = new Set((mediaAfter || []).map((m) => m.id));
|
|
3896
|
+
const lost = (mediaBefore || []).some((m) => !now.has(m.id));
|
|
3897
|
+
const snap = lost ? before.slice(0, -1) + ',"media":' + JSON.stringify(mediaBefore) + "}" : before;
|
|
3898
|
+
return '{"outside":true,' + snap.slice(1);
|
|
3899
|
+
}
|
|
3900
|
+
const isOutsideStep = (snap) => typeof snap === "string" && snap.startsWith('{"outside":true,');
|
|
3851
3901
|
function undo() {
|
|
3852
3902
|
if (!runtime.undo.length) return;
|
|
3853
3903
|
const snap = runtime.undo.pop();
|
|
@@ -3855,6 +3905,7 @@ function undo() {
|
|
|
3855
3905
|
restoreSnapshot(snap);
|
|
3856
3906
|
pruneSelection();
|
|
3857
3907
|
scheduleSave(); renderInspector();
|
|
3908
|
+
if (isOutsideStep(snap)) toast("Undid a change made outside this tab (an agent or another tab)");
|
|
3858
3909
|
}
|
|
3859
3910
|
function redo() {
|
|
3860
3911
|
if (!runtime.redo.length) return;
|
|
@@ -4997,6 +5048,7 @@ function rebuildClips() {
|
|
|
4997
5048
|
}
|
|
4998
5049
|
paintAudioOverlaps();
|
|
4999
5050
|
paintSilences();
|
|
5051
|
+
paintBeats();
|
|
5000
5052
|
state.dirtyTimeline = false;
|
|
5001
5053
|
updateWorkArea();
|
|
5002
5054
|
}
|
|
@@ -5019,6 +5071,38 @@ function paintSilences() {
|
|
|
5019
5071
|
}
|
|
5020
5072
|
}
|
|
5021
5073
|
}
|
|
5074
|
+
/* The beat Find beats heard: a tick on the music's lane and every video lane. */
|
|
5075
|
+
function paintBeats() {
|
|
5076
|
+
const s = state.beats;
|
|
5077
|
+
if (!s) return;
|
|
5078
|
+
if (s.sig !== beatsSig(getClip(s.clipId))) { state.beats = null; return; }
|
|
5079
|
+
const lanes = new Set([getClip(s.clipId).track, ...TRACKS.filter((t) => t.kind === "video").map((t) => t.id)]);
|
|
5080
|
+
const g = s.grid, n = g.length;
|
|
5081
|
+
if (!n) return;
|
|
5082
|
+
// a steady grid is one striped band per lane, however long the song; onsets without a tempo are ticks
|
|
5083
|
+
const per = n > 1 ? (g[n - 1] - g[0]) / (n - 1) : 0;
|
|
5084
|
+
const steady = n > 2 && per > 0 && g.every((t, i) => !i || Math.abs(t - g[i - 1] - per) < 0.004);
|
|
5085
|
+
for (const id of lanes) {
|
|
5086
|
+
const row = els.tracks.querySelector(`[data-track="${id}"]`);
|
|
5087
|
+
if (!row) continue;
|
|
5088
|
+
if (steady) {
|
|
5089
|
+
const el = document.createElement("div");
|
|
5090
|
+
el.className = "beat-band";
|
|
5091
|
+
const step = per * state.pps;
|
|
5092
|
+
el.style.left = (g[0] * state.pps - 0.5) + "px";
|
|
5093
|
+
el.style.width = ((g[n - 1] - g[0]) * state.pps + 1) + "px";
|
|
5094
|
+
el.style.backgroundImage = `repeating-linear-gradient(to right, var(--beat-tick) 0 1px, transparent 1px ${step}px)`;
|
|
5095
|
+
row.appendChild(el);
|
|
5096
|
+
continue;
|
|
5097
|
+
}
|
|
5098
|
+
for (const t of g.slice(0, 600)) {
|
|
5099
|
+
const el = document.createElement("div");
|
|
5100
|
+
el.className = "beat-tick";
|
|
5101
|
+
el.style.left = (t * state.pps) + "px";
|
|
5102
|
+
row.appendChild(el);
|
|
5103
|
+
}
|
|
5104
|
+
}
|
|
5105
|
+
}
|
|
5022
5106
|
/* Hatched bands where two+ audio clips share a track (CSS draw, O(n²) per track). */
|
|
5023
5107
|
function paintAudioOverlaps() {
|
|
5024
5108
|
const byTrack = new Map();
|
|
@@ -6628,6 +6712,23 @@ function renderInspector(lite) {
|
|
|
6628
6712
|
${check("Flip V", "flipV", p.flipV)}
|
|
6629
6713
|
</div>`;
|
|
6630
6714
|
}
|
|
6715
|
+
if ((c.kind === "video" || c.kind === "image") && typeof Reframe !== "undefined") {
|
|
6716
|
+
const m = getMedia(c.mediaId);
|
|
6717
|
+
const shape = m && m.width > 0 && m.height > 0 && Math.abs(m.width / m.height - project.width / project.height) > 0.01;
|
|
6718
|
+
if (shape || p.reframe) {
|
|
6719
|
+
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)"}`
|
|
6720
|
+
: p.reframe === "centre" ? "Fitted and centred" : "This picture is another shape than the canvas.";
|
|
6721
|
+
html += `<div class="insp-section"><h3>Reframe</h3>
|
|
6722
|
+
<div class="insp-note">${note}</div>
|
|
6723
|
+
${reframeRun.busy
|
|
6724
|
+
? 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>
|
|
6725
|
+
<button type="button" class="btn tiny" data-rf-cancel>Cancel</button></span>`)
|
|
6726
|
+
: 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>
|
|
6727
|
+
<button type="button" class="btn tiny" data-rf-centre title="Fit it to cover the canvas, centred">Centre</button>
|
|
6728
|
+
<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>`)}
|
|
6729
|
+
</div>`;
|
|
6730
|
+
}
|
|
6731
|
+
}
|
|
6631
6732
|
if (c.kind === "video" || c.kind === "image" || c.kind === "svg" || c.kind === "adjust" || c.kind === "comp") {
|
|
6632
6733
|
html += `<div class="insp-section"><h3>Filter / Color</h3>
|
|
6633
6734
|
${sel("Preset", "filterPreset", Object.keys(FILTER_PRESETS), p.filterPreset)}
|
|
@@ -6696,6 +6797,24 @@ function renderInspector(lite) {
|
|
|
6696
6797
|
${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
6798
|
</div>`;
|
|
6698
6799
|
}
|
|
6800
|
+
if ((c.kind === "video" || c.kind === "audio") && typeof FableCutBeats !== "undefined") {
|
|
6801
|
+
const bt = state.beats && state.beats.clipId === c.id ? state.beats : null, bs = beatsSettings();
|
|
6802
|
+
const lanes = TRACKS.filter((t) => t.kind === "video" && project.clips.some((x) => x.track === t.id)).map((t) => t.id)
|
|
6803
|
+
.sort((x, y) => (+x.slice(1) || 0) - (+y.slice(1) || 0));
|
|
6804
|
+
html += `<div class="insp-section"><h3>Beats</h3>
|
|
6805
|
+
${row("", state.beatsBusy
|
|
6806
|
+
? `<span class="insp-ctrls"><span style="opacity:.75">Listening…</span>
|
|
6807
|
+
<button type="button" class="btn tiny" data-beat-clear title="Stop listening">Cancel</button></span>`
|
|
6808
|
+
: `<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>
|
|
6809
|
+
${bt ? `<button type="button" class="btn tiny" data-beat-clear title="Hide the beat">Clear</button>` : ""}</span>`)}
|
|
6810
|
+
${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>
|
|
6811
|
+
${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>
|
|
6812
|
+
<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>`)}
|
|
6813
|
+
${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>
|
|
6814
|
+
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>`) +
|
|
6815
|
+
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>`) : ""}` : ""}
|
|
6816
|
+
</div>`;
|
|
6817
|
+
}
|
|
6699
6818
|
if (c.kind === "audio" && typeof FableCutFx !== "undefined") {
|
|
6700
6819
|
html += `<div class="insp-section" data-fx-section><h3>Audio effects</h3>${fxEditorHtml(c.fx, playheadOverClip(c) ? state.time - c.start : null)}</div>`;
|
|
6701
6820
|
}
|
|
@@ -6755,7 +6874,8 @@ function renderInspector(lite) {
|
|
|
6755
6874
|
${row("Family", `<select data-k="font">
|
|
6756
6875
|
${fontGroup("System", SYSTEM_FONTS)}
|
|
6757
6876
|
${fontGroup("Library fonts", runtime.customFonts)}
|
|
6758
|
-
${fontGroup("Google
|
|
6877
|
+
${Object.entries(GOOGLE_FONT_GROUPS).map(([g, list]) => fontGroup("Google · " + g, list)).join("")}
|
|
6878
|
+
${fontGroup("Google · loaded by name", [...runtime.googleLoaded].filter((f) => !GOOGLE_FONTS.includes(f)))}
|
|
6759
6879
|
${known.includes(p.font) ? "" : `<option selected>${p.font}</option>`}
|
|
6760
6880
|
</select>`, "", "font")}
|
|
6761
6881
|
${row("Google font", `<input type="text" data-gfont placeholder="Type any Google Font name…">
|
|
@@ -6922,6 +7042,21 @@ function renderInspector(lite) {
|
|
|
6922
7042
|
findSilences(sel.length ? sel : [c]);
|
|
6923
7043
|
});
|
|
6924
7044
|
els.inspector.querySelector("[data-sil-cut]")?.addEventListener("click", cutSilences);
|
|
7045
|
+
els.inspector.querySelector("[data-beat-find]")?.addEventListener("click", () => findBeats(c));
|
|
7046
|
+
els.inspector.querySelector("[data-beat-clear]")?.addEventListener("click", clearBeats);
|
|
7047
|
+
els.inspector.querySelector("[data-beat-mark]")?.addEventListener("click", () => beatsAction({ markers: true }));
|
|
7048
|
+
els.inspector.querySelector("[data-beat-snap]")?.addEventListener("click", () => beatsAction({ snap: true }));
|
|
7049
|
+
els.inspector.querySelector("[data-beat-every]")?.addEventListener("change", (e) => {
|
|
7050
|
+
try { localStorage.setItem(BEATS_KEY, JSON.stringify({ every: +e.target.value })); } catch { }
|
|
7051
|
+
});
|
|
7052
|
+
els.inspector.querySelector("[data-beat-retime]")?.addEventListener("click", () => beatsAction({ retime: {
|
|
7053
|
+
track: els.inspector.querySelector("[data-beat-track]")?.value,
|
|
7054
|
+
every: +(els.inspector.querySelector("[data-beat-every]")?.value || 2) } }));
|
|
7055
|
+
const rfTargets = () => { const sel = selectedClips().filter((x) => x.kind === "video" || x.kind === "image"); return sel.length ? sel : [c]; };
|
|
7056
|
+
els.inspector.querySelector("[data-rf-follow]")?.addEventListener("click", () =>
|
|
7057
|
+
reframeClips(rfTargets(), { follow: true, smooth: +(els.inspector.querySelector("[data-rf-smooth]")?.value || 0.5) }));
|
|
7058
|
+
els.inspector.querySelector("[data-rf-centre]")?.addEventListener("click", () => reframeClips(rfTargets(), { follow: false }));
|
|
7059
|
+
els.inspector.querySelector("[data-rf-cancel]")?.addEventListener("click", () => { reframeRun.cancel = true; });
|
|
6925
7060
|
els.inspector.querySelector("[data-sil-clear]")?.addEventListener("click", clearSilences);
|
|
6926
7061
|
els.inspector.querySelector("[data-norm-target]")?.addEventListener("change", (e) => {
|
|
6927
7062
|
try { localStorage.setItem(NORMALIZE_KEY, e.target.value); } catch { }
|
|
@@ -8772,6 +8907,8 @@ function cutSilences() {
|
|
|
8772
8907
|
const TRANSCRIBE_KEY = "fablecut-transcribe";
|
|
8773
8908
|
const trState = { open: false, built: false, busy: null, sig: "", words: [], sel: null, anchor: null, drag: false, query: "", hits: [], now: -1 };
|
|
8774
8909
|
const transcriptCache = new Map(); // src → validated transcript | false (none) | Promise while asking the server
|
|
8910
|
+
const transcriptHeld = new Map(); // src → the last transcript (or false) shown, kept while a refresh is pending
|
|
8911
|
+
const transcriptStale = new Set(); // srcs whose shown transcript the server hasn't confirmed (a failed read or save)
|
|
8775
8912
|
let transcriptGen = 0; // bumps whenever a transcript arrives or changes: the tab redraws
|
|
8776
8913
|
function transcribeSettings() {
|
|
8777
8914
|
let o = {};
|
|
@@ -8794,16 +8931,34 @@ function transcriptOf(src) {
|
|
|
8794
8931
|
function loadTranscript(src, force = false) {
|
|
8795
8932
|
const have = transcriptCache.get(src);
|
|
8796
8933
|
if (!force && have !== undefined) return have instanceof Promise ? have : Promise.resolve(have);
|
|
8797
|
-
|
|
8934
|
+
return readTranscript(src).then((r) => r.doc);
|
|
8935
|
+
}
|
|
8936
|
+
/** One read from the server → {doc, ok}: ok only when this read answered (a transcript, or that
|
|
8937
|
+
there is none) and no later read has replaced it. A read that fails (a server error, no network,
|
|
8938
|
+
a document that doesn't validate) keeps what was shown, marked unconfirmed. */
|
|
8939
|
+
function readTranscript(src) {
|
|
8940
|
+
let p = null;
|
|
8941
|
+
const read = fetch("/api/transcript?src=" + encodeURIComponent(src))
|
|
8942
|
+
.then((r) => (r.ok ? r.json() : r.status === 404 ? { transcript: null } : Promise.reject(new Error("HTTP " + r.status))))
|
|
8798
8943
|
.then((j) => {
|
|
8799
|
-
|
|
8800
|
-
|
|
8801
|
-
if (
|
|
8802
|
-
return d;
|
|
8944
|
+
const d = j && j.transcript ? FableCutTranscribe.validate(j.transcript) : false;
|
|
8945
|
+
const latest = transcriptCache.get(src) === p;
|
|
8946
|
+
if (latest) { setTranscript(src, d); transcriptStale.delete(src); }
|
|
8947
|
+
return { doc: d, ok: latest };
|
|
8803
8948
|
})
|
|
8804
|
-
.catch(() => {
|
|
8949
|
+
.catch(() => {
|
|
8950
|
+
const d = transcriptHeld.get(src) || false;
|
|
8951
|
+
if (transcriptCache.get(src) === p) { setTranscript(src, d); transcriptStale.add(src); }
|
|
8952
|
+
return { doc: d, ok: false };
|
|
8953
|
+
});
|
|
8954
|
+
p = read.then((r) => r.doc);
|
|
8805
8955
|
transcriptCache.set(src, p);
|
|
8806
|
-
return
|
|
8956
|
+
return read;
|
|
8957
|
+
}
|
|
8958
|
+
function setTranscript(src, d) {
|
|
8959
|
+
transcriptCache.set(src, d);
|
|
8960
|
+
transcriptHeld.set(src, d);
|
|
8961
|
+
transcriptGen++;
|
|
8807
8962
|
}
|
|
8808
8963
|
function onTranscriptEvent(data) {
|
|
8809
8964
|
let src = null;
|
|
@@ -8882,8 +9037,8 @@ async function transcribeFile(src, { model, language, onProgress, cancelled }) {
|
|
|
8882
9037
|
const doc = T.validate({ src, model, language: language || "auto", duration, created: new Date().toISOString(), words });
|
|
8883
9038
|
let saved = false;
|
|
8884
9039
|
try { saved = (await fetch("/api/transcript?src=" + encodeURIComponent(src), { method: "POST", body: JSON.stringify(doc) })).ok; } catch { }
|
|
8885
|
-
|
|
8886
|
-
|
|
9040
|
+
setTranscript(src, doc);
|
|
9041
|
+
if (saved) transcriptStale.delete(src); else transcriptStale.add(src);
|
|
8887
9042
|
return { doc, saved };
|
|
8888
9043
|
}
|
|
8889
9044
|
/** Transcribe files one after another. `beat(fraction)` hears about progress (an agent's job). */
|
|
@@ -8943,14 +9098,23 @@ function transcriptWords() {
|
|
|
8943
9098
|
/** What Transcribe works on: the selected clips' files, else every file on the timeline without a transcript. */
|
|
8944
9099
|
function transcribeTargets() {
|
|
8945
9100
|
const groups = transcriptGroups();
|
|
9101
|
+
// a selected clip picks the file its speech group is heard from (a picture's sound may come
|
|
9102
|
+
// from denoised stems, another file): the group counts when it or a clip linked to it is selected
|
|
8946
9103
|
const picked = new Set();
|
|
8947
|
-
for (const
|
|
8948
|
-
const
|
|
8949
|
-
if (
|
|
9104
|
+
for (const g of groups) {
|
|
9105
|
+
const ids = new Set(withLinked(g).map((c) => c.id));
|
|
9106
|
+
if ([...ids].some((id) => state.selIds.has(id))) picked.add(getMedia(g[0].mediaId).src);
|
|
8950
9107
|
}
|
|
8951
9108
|
const srcs = [...new Set(groups.map((g) => getMedia(g[0].mediaId).src))];
|
|
8952
9109
|
const sel = srcs.filter((s) => picked.has(s));
|
|
8953
|
-
|
|
9110
|
+
if (sel.length) return { srcs: sel, selected: true };
|
|
9111
|
+
// a selection with no speech in it (a title) never turns into a timeline-wide action
|
|
9112
|
+
if (state.selIds.size) return { srcs: [], selected: false, none: true };
|
|
9113
|
+
const missing = srcs.filter((s) => transcriptCache.get(s) === false);
|
|
9114
|
+
// every file has a transcript already (an agent may have made them): the button offers them all again
|
|
9115
|
+
if (!missing.length && srcs.length && srcs.every((s) => transcriptCache.get(s) && !(transcriptCache.get(s) instanceof Promise)))
|
|
9116
|
+
return { srcs, selected: false, again: true };
|
|
9117
|
+
return { srcs: missing, selected: false };
|
|
8954
9118
|
}
|
|
8955
9119
|
/** What the words' places depend on: the timeline and the transcripts. */
|
|
8956
9120
|
function transcriptWordsSig() {
|
|
@@ -9085,15 +9249,32 @@ function renderTranscript(force = false) {
|
|
|
9085
9249
|
const words = trState.words = transcriptWords();
|
|
9086
9250
|
trState.wsig = transcriptWordsSig();
|
|
9087
9251
|
const tgt = transcribeTargets();
|
|
9088
|
-
E.go.textContent = tgt.selected ? `Transcribe selected (${tgt.srcs.length})` : tgt.
|
|
9252
|
+
E.go.textContent = tgt.selected ? `Transcribe selected (${tgt.srcs.length})` : tgt.again ? `Transcribe again (${tgt.srcs.length})`
|
|
9253
|
+
: tgt.srcs.length ? `Transcribe ${tgt.srcs.length} file${tgt.srcs.length === 1 ? "" : "s"}` : "Transcribe";
|
|
9089
9254
|
E.go.disabled = !!trState.busy || !tgt.srcs.length;
|
|
9090
|
-
E.go.title = tgt.
|
|
9091
|
-
:
|
|
9255
|
+
E.go.title = tgt.again ? "Every file on the timeline has a transcript. Transcribe them all again, with the model and language picked here (or select clips to redo just those)"
|
|
9256
|
+
: tgt.srcs.length ? "Turn the speech into words, in this browser (the model downloads once). Select clips to transcribe just those, or again"
|
|
9257
|
+
: tgt.none ? "The selected clips have no speech. Select clips with speech to transcribe those, or clear the selection to transcribe the timeline's files"
|
|
9258
|
+
: "Put clips with speech on the timeline first";
|
|
9092
9259
|
const missing = [...new Set(groups.map((g) => getMedia(g[0].mediaId)).filter((m) => transcriptCache.get(m.src) === false).map((m) => m.name || m.src))];
|
|
9093
9260
|
let html = "";
|
|
9094
9261
|
if (!groups.length) html = `<div class="tr-empty">Put clips with speech on the timeline, then transcribe them here. Speech becomes words in this browser; your audio never leaves it.</div>`;
|
|
9095
9262
|
else {
|
|
9096
9263
|
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>`;
|
|
9264
|
+
// which model and language made these words, so wrong words point at the fix
|
|
9265
|
+
const docs = groups.map((g) => transcriptCache.get(getMedia(g[0].mediaId).src)).filter((d) => d && d.words);
|
|
9266
|
+
const made = new Map();
|
|
9267
|
+
for (const d of docs) made.set(JSON.stringify([d.model ?? null, d.language ?? null]), d);
|
|
9268
|
+
if (made.size) {
|
|
9269
|
+
const said = [...made.values()].map((d) => {
|
|
9270
|
+
const model = d.model == null ? "an unknown model" : T.MODELS[d.model]?.label || d.model;
|
|
9271
|
+
const lang = d.language == null ? "an unknown language" : d.language === "" || d.language === "auto" ? "auto-detected" : T.LANGUAGES[d.language] || d.language;
|
|
9272
|
+
return `${escapeHtml(model)}, ${escapeHtml(lang)}`;
|
|
9273
|
+
});
|
|
9274
|
+
// with some files still untranscribed the button does those, so redoing others takes a selection
|
|
9275
|
+
const how = tgt.selected ? "then Transcribe selected" : tgt.again ? "then Transcribe again" : "select those clips, then Transcribe selected";
|
|
9276
|
+
html += `<div class="tr-note tr-made">Transcribed with ${said.join("; ")}. Words look wrong? Pick the language spoken and the Small model above, ${how}.</div>`;
|
|
9277
|
+
}
|
|
9097
9278
|
if (!words.length && !missing.length) html += `<div class="tr-empty">${[...transcriptCache.values()].some((v) => v instanceof Promise) ? "Loading…" : "No words in these clips."}</div>`;
|
|
9098
9279
|
for (const s of T.segments(words)) {
|
|
9099
9280
|
let p = "";
|
|
@@ -9199,10 +9380,32 @@ function copyTranscript() {
|
|
|
9199
9380
|
navigator.clipboard.writeText(lines.join("\n")).then(() => toast(`Copied ${lines.length} line${lines.length === 1 ? "" : "s"}`), () => toast("Couldn't copy — the browser refused"));
|
|
9200
9381
|
}
|
|
9201
9382
|
async function transcribeFromTab() {
|
|
9202
|
-
|
|
9203
|
-
|
|
9383
|
+
// what the click meant is taken now (its files, its model and language); a selection already names its files
|
|
9384
|
+
let tgt = transcribeTargets();
|
|
9385
|
+
const opts = transcribeSettings();
|
|
9386
|
+
if (!tgt.selected && !tgt.none) {
|
|
9387
|
+
// transcripts being re-read (another tab saved one) decide which files are left: wait for
|
|
9388
|
+
// those of this timeline's files (a few seconds at most), then take the targets again,
|
|
9389
|
+
// unless the timeline or the selection changed meanwhile
|
|
9390
|
+
const at = silenceSig() + "|" + [...state.selIds].join(",");
|
|
9391
|
+
const srcs = new Set(transcriptGroups().map((g) => getMedia(g[0].mediaId).src));
|
|
9392
|
+
const loading = [...transcriptCache].filter(([s, v]) => srcs.has(s) && v instanceof Promise).map(([, v]) => v);
|
|
9393
|
+
if (loading.length) {
|
|
9394
|
+
await Promise.race([Promise.allSettled(loading), new Promise((r) => setTimeout(r, 5000))]);
|
|
9395
|
+
if (silenceSig() + "|" + [...state.selIds].join(",") !== at) { renderTranscript(true); toast("The timeline changed — check the button and click again"); return; }
|
|
9396
|
+
// the same action as clicked: "Transcribe N files" drops files whose transcript just arrived
|
|
9397
|
+
// (it never turns into a rerun of everything); "Transcribe again" stays a rerun
|
|
9398
|
+
if (!tgt.srcs.length) tgt = transcribeTargets(); // the button hadn't caught up: what it offers now
|
|
9399
|
+
else if (!tgt.again) {
|
|
9400
|
+
tgt = { ...tgt, srcs: tgt.srcs.filter((s) => transcriptCache.get(s) === false) };
|
|
9401
|
+
if (!tgt.srcs.length) { renderTranscript(true); toast("Those files have transcripts now"); return; }
|
|
9402
|
+
}
|
|
9403
|
+
}
|
|
9404
|
+
}
|
|
9405
|
+
const { srcs } = tgt;
|
|
9406
|
+
if (!srcs.length) { toast(tgt.none ? "The selected clips have no speech — select clips with speech, or clear the selection" : "Put a clip with speech on the timeline first"); return; }
|
|
9204
9407
|
let out;
|
|
9205
|
-
try { out = await transcribeSrcs(srcs); } catch (e) { toast(e.message); return; }
|
|
9408
|
+
try { out = await transcribeSrcs(srcs, opts); } catch (e) { toast(e.message); return; }
|
|
9206
9409
|
const unsaved = out.done.filter((d) => !d.saved).length;
|
|
9207
9410
|
const words = out.done.reduce((n, d) => n + d.words, 0);
|
|
9208
9411
|
toast(out.cancelled ? `Stopped — ${out.done.length} file${out.done.length === 1 ? "" : "s"} transcribed`
|
|
@@ -9306,7 +9509,11 @@ async function runTranscribeJob(ticket, fail) {
|
|
|
9306
9509
|
if (trState.busy) return fail("this editor tab is already transcribing — wait for it, or cancel it there");
|
|
9307
9510
|
const srcs = [], skipped = [];
|
|
9308
9511
|
for (const src of spec.srcs || []) {
|
|
9309
|
-
|
|
9512
|
+
// a transcript only counts as there when the server just confirmed it (a failed read is no proof)
|
|
9513
|
+
if (!spec.again) {
|
|
9514
|
+
const r = await readTranscript(src);
|
|
9515
|
+
if (r.ok && r.doc) { skipped.push(src); continue; }
|
|
9516
|
+
}
|
|
9310
9517
|
srcs.push(src);
|
|
9311
9518
|
}
|
|
9312
9519
|
const report = (body, force) => fetch("/api/export/job/report?id=" + encodeURIComponent(ticket.id), { method: "POST", body: JSON.stringify(body) })
|
|
@@ -9330,6 +9537,108 @@ function clearSilences() {
|
|
|
9330
9537
|
state.dirtyTimeline = true;
|
|
9331
9538
|
renderInspector();
|
|
9332
9539
|
}
|
|
9540
|
+
|
|
9541
|
+
/* ── Beats (beats.js): the music's tempo and beat grid, ticks on the timeline, and
|
|
9542
|
+
edits on it — mark, snap the cuts, re-cut a track. The same plan and ops as
|
|
9543
|
+
fablecut_beats; here each action is one undo step. ── */
|
|
9544
|
+
const BEATS_KEY = "fablecut-beats";
|
|
9545
|
+
function beatsSettings() {
|
|
9546
|
+
let o = {};
|
|
9547
|
+
try { o = JSON.parse(localStorage.getItem(BEATS_KEY) || "{}"); } catch { }
|
|
9548
|
+
return { every: FableCutBeats.EVERY.includes(+o.every) ? +o.every : 2 };
|
|
9549
|
+
}
|
|
9550
|
+
/** What a found beat stands on: the clip's place, window, file and speed, and the frame rate. */
|
|
9551
|
+
function beatsSig(c) {
|
|
9552
|
+
if (!c) return "";
|
|
9553
|
+
// the open project and sequence too: a duplicate with the same clip ids must not inherit this beat
|
|
9554
|
+
return JSON.stringify([runtime.projectId ?? null, SeqLib.activeId(seqRoot()), !!state.compCtx, project.fps, c.id, c.start, c.in, c.duration,
|
|
9555
|
+
getMedia(c.mediaId)?.src ?? null, c.props?.speed ?? 1, c.keyframes?.speed ?? null]);
|
|
9556
|
+
}
|
|
9557
|
+
/** The project as beats.js reads it: the timeline plus the track switches. */
|
|
9558
|
+
function beatsDoc() {
|
|
9559
|
+
return { ...project, tracks: TRACKS, lockedTracks: [...state.lockedTracks], untargetedTracks: [...state.untargetedTracks] };
|
|
9560
|
+
}
|
|
9561
|
+
let beatsGen = 0;
|
|
9562
|
+
async function findBeats(c) {
|
|
9563
|
+
if (typeof FableCutBeats === "undefined") { toast("Beats module missing — reload the editor"); return; }
|
|
9564
|
+
if (!c || (c.kind !== "audio" && c.kind !== "video")) { toast("Select the music clip to find its beat"); return; }
|
|
9565
|
+
if (FableCutBeats.ramped(c)) { toast("This clip has a speed ramp — beats follow music playing at a steady speed"); return; }
|
|
9566
|
+
const m = getMedia(c.mediaId);
|
|
9567
|
+
if (!m) return;
|
|
9568
|
+
const gen = ++beatsGen, sig = beatsSig(c);
|
|
9569
|
+
state.beats = null; state.beatsBusy = true; state.dirtyTimeline = true;
|
|
9570
|
+
renderInspector();
|
|
9571
|
+
toast("Listening for the beat…");
|
|
9572
|
+
try {
|
|
9573
|
+
const buf = await getAudioBuffer(m);
|
|
9574
|
+
await new Promise((res) => setTimeout(res, 0)); // let "Listening…" paint and Cancel land before the analysis runs
|
|
9575
|
+
if (gen !== beatsGen) return;
|
|
9576
|
+
const a0 = clamp(Math.floor((c.in || 0) * buf.sampleRate), 0, buf.length);
|
|
9577
|
+
const a1 = clamp(Math.ceil(mediaTimeAt(c, clipEnd(c)) * buf.sampleRate), a0, buf.length);
|
|
9578
|
+
const chs = [];
|
|
9579
|
+
for (let ch = 0; ch < buf.numberOfChannels; ch++) chs.push(buf.getChannelData(ch).subarray(a0, a1));
|
|
9580
|
+
const a = FableCutBeats.analyze(FableCutBeats.resample(FableCutBeats.mono(chs), buf.sampleRate));
|
|
9581
|
+
const abs = { beats: a.beats.map((t) => t + (c.in || 0)), bpm: a.bpm, drop: a.drop != null ? a.drop + (c.in || 0) : null };
|
|
9582
|
+
if (beatsSig(getClip(c.id)) !== sig) { toast("The clip changed while listening — find the beat again"); return; }
|
|
9583
|
+
const r = FableCutBeats.plan(beatsDoc(), getClip(c.id), abs, {});
|
|
9584
|
+
state.beats = r.grid.length ? { clipId: c.id, sig, a: abs, grid: r.grid, bpm: r.bpm, drop: r.drop } : null;
|
|
9585
|
+
toast(r.grid.length ? `${r.bpm} BPM · ${r.grid.length} beats marked on the timeline` + (r.drop != null ? ` · the drop at ${fmt(r.drop)}` : "")
|
|
9586
|
+
: "No steady beat found in this clip");
|
|
9587
|
+
} catch (e) {
|
|
9588
|
+
toast("Couldn't read this clip's audio: " + (e?.message || e));
|
|
9589
|
+
} finally {
|
|
9590
|
+
if (gen === beatsGen) { state.beatsBusy = false; state.dirtyTimeline = true; renderInspector(); }
|
|
9591
|
+
}
|
|
9592
|
+
}
|
|
9593
|
+
function clearBeats() {
|
|
9594
|
+
beatsGen++;
|
|
9595
|
+
state.beats = null; state.beatsBusy = false; state.dirtyTimeline = true;
|
|
9596
|
+
renderInspector();
|
|
9597
|
+
}
|
|
9598
|
+
/** markers / snap / retime on the found beat: beats.js plans, the editor's own edits apply it. One undo step. */
|
|
9599
|
+
function beatsAction(acts) {
|
|
9600
|
+
const s = state.beats, c = s && getClip(s.clipId);
|
|
9601
|
+
if (!s || !c || s.sig !== beatsSig(c)) { state.beats = null; renderInspector(); toast("The music clip changed — find the beat again"); return; }
|
|
9602
|
+
let r;
|
|
9603
|
+
try { r = FableCutBeats.plan(beatsDoc(), c, s.a, acts); }
|
|
9604
|
+
catch (e) { toast(e.message); return; }
|
|
9605
|
+
if (!r.ops.length) { toast(r.done.join(" · ") || "Nothing to change"); return; }
|
|
9606
|
+
const snap = undoSnapshot();
|
|
9607
|
+
let rolls = 0, rolled = 0;
|
|
9608
|
+
for (const op of r.ops) {
|
|
9609
|
+
if (op.op === "setProject") project.markers = normalizeMarkers(op.set.markers);
|
|
9610
|
+
else if (op.op === "roll") {
|
|
9611
|
+
const x = getClip(op.id);
|
|
9612
|
+
rolls++;
|
|
9613
|
+
// what the roll really moved (a refusal is a string, a clamp a smaller number)
|
|
9614
|
+
if (!x) continue;
|
|
9615
|
+
// what this roll can touch: the clips on either side of the cut and their linked partners
|
|
9616
|
+
const end = x.start + x.duration;
|
|
9617
|
+
const next = project.clips.find((c) => c !== x && c.track === x.track && Math.abs(c.start - end) < 1e-3);
|
|
9618
|
+
const touched = withLinked(next ? [x, next] : [x]);
|
|
9619
|
+
const before = new Map(touched.map((c) => [c.id, JSON.stringify(c)]));
|
|
9620
|
+
const d = EDIT.rollEdit(x, op.side, op.delta);
|
|
9621
|
+
if (typeof d === "number" && Math.abs(d - op.delta) < 1e-3) rolled++;
|
|
9622
|
+
// a roll that couldn't reach the beat (clamped, refused) is undone exactly: the cut stays where it was
|
|
9623
|
+
else project.clips = project.clips.map((c) => (before.has(c.id) ? JSON.parse(before.get(c.id)) : c));
|
|
9624
|
+
} else if (op.op === "updateClip") {
|
|
9625
|
+
const x = getClip(op.id);
|
|
9626
|
+
if (x) for (const [k, v] of Object.entries(op.set)) { if (v === null) delete x[k]; else x[k] = v; }
|
|
9627
|
+
}
|
|
9628
|
+
}
|
|
9629
|
+
if (undoSnapshot() === snap) {
|
|
9630
|
+
state.dirtyTimeline = true; renderInspector();
|
|
9631
|
+
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");
|
|
9632
|
+
return;
|
|
9633
|
+
}
|
|
9634
|
+
pushUndo(snap);
|
|
9635
|
+
pruneSelection();
|
|
9636
|
+
state.dirtyTimeline = true;
|
|
9637
|
+
scheduleSave();
|
|
9638
|
+
renderInspector();
|
|
9639
|
+
const done = r.done.map((d) => (rolls && rolled < rolls && /^snapped /.test(d) ? d.replace(/^snapped \d+/, "snapped " + rolled) : d));
|
|
9640
|
+
toast(done.map((d) => d[0].toUpperCase() + d.slice(1)).join(" · "));
|
|
9641
|
+
}
|
|
9333
9642
|
async function autoDuckClips(clips, { under = null, amount = duckAmount(), threshold = -40 } = {}) {
|
|
9334
9643
|
if (typeof FableCutDucking === "undefined") { toast("Ducking module missing — reload the editor"); return; }
|
|
9335
9644
|
const music = withLinked(clips).filter((x) => x.kind === "audio" && !isGroupLocked(x));
|
|
@@ -11698,7 +12007,7 @@ function seqUndoPrint(d, withOthers) {
|
|
|
11698
12007
|
}
|
|
11699
12008
|
/** Open sequence `id` in the editor. False when it can't be opened now. */
|
|
11700
12009
|
function openSequence(id) {
|
|
11701
|
-
if (
|
|
12010
|
+
if (exportBusy()) { toast("Wait for the export to finish before opening another sequence"); return false; }
|
|
11702
12011
|
if (state.gesture) return false;
|
|
11703
12012
|
if (state.compCtx) exitComp(state.compCtx.path.length);
|
|
11704
12013
|
if (SeqLib.activeId(project) === id) return true;
|
|
@@ -11716,15 +12025,17 @@ function openSequence(id) {
|
|
|
11716
12025
|
return true;
|
|
11717
12026
|
}
|
|
11718
12027
|
/** Add a sequence ({name?, from?, width?, height?}) and open it. */
|
|
11719
|
-
function newSequence(opts) {
|
|
11720
|
-
if (
|
|
12028
|
+
function newSequence(opts, clips = null) {
|
|
12029
|
+
if (exportBusy()) { toast("Wait for the export to finish"); return; }
|
|
11721
12030
|
if (state.compCtx) exitComp(state.compCtx.path.length);
|
|
11722
12031
|
const doc = projectJSONHere();
|
|
11723
12032
|
let s;
|
|
11724
12033
|
try { s = SeqLib.add(doc, opts); } catch (e) { toast(e.message); return; }
|
|
12034
|
+
if (clips) s.clips = clips; // an empty sequence that starts with these (Highlights)
|
|
11725
12035
|
project.sequences = doc.sequences; project.sequence = doc.sequence;
|
|
11726
|
-
if (openSequence(s.id)) toast(`New sequence “${s.name}” · ${s.width}×${s.height}`);
|
|
11727
|
-
|
|
12036
|
+
if (openSequence(s.id)) { toast(`New sequence “${s.name}” · ${s.width}×${s.height}`); return true; }
|
|
12037
|
+
scheduleSave(); syncCompCrumb(); toast(`New sequence “${s.name}” added — open it from the sequence menu`);
|
|
12038
|
+
return false;
|
|
11728
12039
|
}
|
|
11729
12040
|
function renameSequence(id, name) {
|
|
11730
12041
|
const r = seqRoot();
|
|
@@ -11736,7 +12047,7 @@ function renameSequence(id, name) {
|
|
|
11736
12047
|
async function deleteSequence(id) {
|
|
11737
12048
|
const r = seqRoot(), s = SeqLib.find(r, id);
|
|
11738
12049
|
if (!s || SeqLib.entries(r).length < 2) return;
|
|
11739
|
-
if (
|
|
12050
|
+
if (exportBusy()) { toast("Wait for the export to finish"); return; }
|
|
11740
12051
|
if (state.compCtx) exitComp(state.compCtx.path.length);
|
|
11741
12052
|
let kept = null;
|
|
11742
12053
|
if (state.connected) {
|
|
@@ -11751,7 +12062,7 @@ async function deleteSequence(id) {
|
|
|
11751
12062
|
if (!kept) { toast(`Couldn't keep a version of the project, so “${s.name}” was not deleted. Try again in a moment.`); return; }
|
|
11752
12063
|
}
|
|
11753
12064
|
// the editor may have moved on while the version was saved
|
|
11754
|
-
if (
|
|
12065
|
+
if (exportBusy()) { toast("Wait for the export to finish"); return; }
|
|
11755
12066
|
if (state.compCtx) exitComp(state.compCtx.path.length);
|
|
11756
12067
|
if (!SeqLib.find(project, id) || SeqLib.entries(project).length < 2) return; // deleted or changed meanwhile (another tab, an agent)
|
|
11757
12068
|
const wasOpen = SeqLib.activeId(project) === id;
|
|
@@ -11801,6 +12112,8 @@ function showSequenceMenu(x, y) {
|
|
|
11801
12112
|
}
|
|
11802
12113
|
sep();
|
|
11803
12114
|
item(`<span>New sequence…</span>`, () => promptNewSequence(x, y));
|
|
12115
|
+
item(`<span>Highlights…</span>`, () => promptHighlights(x, y),
|
|
12116
|
+
state.compCtx ? "Close the composition first" : !project.clips.some((c) => c.kind === "video") ? "Put video on the timeline first" : null);
|
|
11804
12117
|
item(`<span>Duplicate “${escapeHtml(open.name)}”</span>`, () => newSequence({ from: "open" }));
|
|
11805
12118
|
item(`<span>Rename “${escapeHtml(open.name)}”…</span>`, () => promptBinText(x, y, "Sequence name", open.name, (v) => renameSequence(openId, v), { max: 120, ok: "Rename" }));
|
|
11806
12119
|
item(`<span>Delete “${escapeHtml(open.name)}”…</span>`, (b) => {
|
|
@@ -11815,21 +12128,35 @@ function promptNewSequence(x, y) {
|
|
|
11815
12128
|
const pop = document.createElement("div");
|
|
11816
12129
|
pop.className = "ctx-menu bin-pop seq-new";
|
|
11817
12130
|
const n = SeqLib.entries(seqRoot()).length + 1;
|
|
11818
|
-
const sizes = [{ label: `Same as “${openSequenceName()}” · ${
|
|
12131
|
+
const sizes = [{ label: `Same as “${openSequenceName()}” · ${seqRoot().width}×${seqRoot().height}`, w: 0, h: 0 }, ...ASPECT_PRESETS];
|
|
11819
12132
|
pop.innerHTML = `<label class="bin-pop-label" for="seqNewName">New sequence</label>
|
|
11820
12133
|
<input type="text" class="bin-pop-input" id="seqNewName" maxlength="120" spellcheck="false">
|
|
11821
12134
|
<label class="bin-pop-label" for="seqNewSize">Canvas</label>
|
|
11822
12135
|
<select id="seqNewSize" class="bin-pop-input">${sizes.map((s, i) => `<option value="${i}">${escapeHtml(s.label)}</option>`).join("")}</select>
|
|
11823
12136
|
<label class="seq-new-copy"><input type="checkbox" id="seqNewCopy"> Start from a copy of “${escapeHtml(openSequenceName())}”</label>
|
|
12137
|
+
<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
12138
|
<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
12139
|
<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
12140
|
pop.querySelector("#seqNewName").value = `Sequence ${n}`;
|
|
12141
|
+
const syncFollow = () => {
|
|
12142
|
+
const size = sizes[+pop.querySelector("#seqNewSize").value] || sizes[0];
|
|
12143
|
+
const root = seqRoot(); // a composition may be open: the copy is of the sequence around it
|
|
12144
|
+
const on = pop.querySelector("#seqNewCopy").checked && size.w && size.w * root.height !== size.h * root.width;
|
|
12145
|
+
pop.querySelector("#seqNewFollow").closest("label").hidden = !on;
|
|
12146
|
+
};
|
|
12147
|
+
pop.querySelector("#seqNewSize").addEventListener("change", syncFollow);
|
|
12148
|
+
pop.querySelector("#seqNewCopy").addEventListener("change", syncFollow);
|
|
12149
|
+
syncFollow();
|
|
11827
12150
|
const ok = () => {
|
|
11828
12151
|
const name = pop.querySelector("#seqNewName").value.trim();
|
|
11829
12152
|
const size = sizes[+pop.querySelector("#seqNewSize").value] || sizes[0];
|
|
11830
12153
|
const copy = pop.querySelector("#seqNewCopy").checked;
|
|
12154
|
+
const follow = pop.querySelector("#seqNewFollow").checked;
|
|
12155
|
+
const root = seqRoot();
|
|
12156
|
+
const reshaped = size.w && size.w * root.height !== size.h * root.width;
|
|
11831
12157
|
hideTrackCtxMenu();
|
|
11832
|
-
newSequence({ name: name || undefined, from: copy ? "open" : "empty", ...(size.w ? { width: size.w, height: size.h } : {}) });
|
|
12158
|
+
const opened = newSequence({ name: name || undefined, from: copy ? "open" : "empty", ...(size.w ? { width: size.w, height: size.h } : {}) });
|
|
12159
|
+
if (opened && copy && reshaped && follow) reframeClips(null, { follow: true });
|
|
11833
12160
|
};
|
|
11834
12161
|
pop.querySelector("[data-ok]").addEventListener("click", ok);
|
|
11835
12162
|
pop.querySelector("[data-cancel]").addEventListener("click", () => hideTrackCtxMenu());
|
|
@@ -11842,6 +12169,49 @@ function promptNewSequence(x, y) {
|
|
|
11842
12169
|
const input = pop.querySelector("#seqNewName");
|
|
11843
12170
|
input.focus(); input.select();
|
|
11844
12171
|
}
|
|
12172
|
+
/** Highlights: the best moments of this timeline's video (or the selected clips), cut into a new sequence. */
|
|
12173
|
+
function promptHighlights(x, y) {
|
|
12174
|
+
const sel = selectedClips().filter((c) => c.kind === "video");
|
|
12175
|
+
const from = sel.length ? sel : null;
|
|
12176
|
+
const n = Highlights.sourcesOf({ clips: project.clips, disabledTracks: [...state.disabledTracks] }, from && from.map((c) => c.id)).take.length;
|
|
12177
|
+
const sizes = [{ label: `Same as “${openSequenceName()}” · ${project.width}×${project.height}`, w: 0, h: 0 }, ...ASPECT_PRESETS];
|
|
12178
|
+
const pop = document.createElement("div");
|
|
12179
|
+
pop.className = "ctx-menu bin-pop seq-new";
|
|
12180
|
+
pop.innerHTML = `<label class="bin-pop-label" for="hlLen">Highlights</label>
|
|
12181
|
+
<select id="hlLen" class="bin-pop-input">${[15, 30, 60, 90].map((s) => `<option value="${s}" ${s === 30 ? "selected" : ""}>${s} s</option>`).join("")}</select>
|
|
12182
|
+
<label class="bin-pop-label" for="hlSize">Canvas</label>
|
|
12183
|
+
<select id="hlSize" class="bin-pop-input">${sizes.map((s, i) => `<option value="${i}">${escapeHtml(s.label)}</option>`).join("")}</select>
|
|
12184
|
+
<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>
|
|
12185
|
+
<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>
|
|
12186
|
+
<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>`;
|
|
12187
|
+
const size = () => sizes[+pop.querySelector("#hlSize").value] || sizes[0];
|
|
12188
|
+
const reshaped = () => { const s = size(); return !!(s.w && s.w * project.height !== s.h * project.width); };
|
|
12189
|
+
const syncFollow = () => { pop.querySelector("#hlFollow").closest("label").hidden = !reshaped(); };
|
|
12190
|
+
pop.querySelector("#hlSize").addEventListener("change", syncFollow);
|
|
12191
|
+
syncFollow();
|
|
12192
|
+
const status = pop.querySelector("[data-hl-status]");
|
|
12193
|
+
const ok = async () => {
|
|
12194
|
+
if (highlightRun.busy) return;
|
|
12195
|
+
const okBtn = pop.querySelector("[data-ok]");
|
|
12196
|
+
okBtn.disabled = true;
|
|
12197
|
+
pop.querySelectorAll("select, input").forEach((el) => { el.disabled = true; });
|
|
12198
|
+
const duration = +pop.querySelector("#hlLen").value, s = size();
|
|
12199
|
+
const made = await makeHighlights(from, { duration, size: s.w ? { width: s.w, height: s.h } : null, follow: reshaped() && pop.querySelector("#hlFollow").checked,
|
|
12200
|
+
progress: (f) => { status.textContent = `Looking at the footage… ${Math.round(f * 100)}%`; }, cancelled: () => !pop.isConnected });
|
|
12201
|
+
if (pop.isConnected) hideTrackCtxMenu();
|
|
12202
|
+
return made;
|
|
12203
|
+
};
|
|
12204
|
+
pop.querySelector("[data-ok]").addEventListener("click", ok);
|
|
12205
|
+
// closing the dialog stops a run that has started
|
|
12206
|
+
pop.querySelector("[data-cancel]").addEventListener("click", () => { highlightRun.cancel = true; hideTrackCtxMenu(); });
|
|
12207
|
+
pop.addEventListener("keydown", (e) => {
|
|
12208
|
+
if (e.key === "Enter" && e.target.tagName !== "SELECT") { e.preventDefault(); ok(); }
|
|
12209
|
+
else if (e.key === "Escape") { e.preventDefault(); highlightRun.cancel = true; hideTrackCtxMenu(); }
|
|
12210
|
+
e.stopPropagation();
|
|
12211
|
+
});
|
|
12212
|
+
showPopover(pop, x, y);
|
|
12213
|
+
pop.querySelector("#hlLen").focus();
|
|
12214
|
+
}
|
|
11845
12215
|
function initSequencesUi() {
|
|
11846
12216
|
const b = $("btnSequences");
|
|
11847
12217
|
if (!b || b.dataset.wired) return;
|
|
@@ -12965,6 +13335,216 @@ function seekFrame(el, t) {
|
|
|
12965
13335
|
el.currentTime = t;
|
|
12966
13336
|
});
|
|
12967
13337
|
}
|
|
13338
|
+
/* ── Reframe (reframe.js): fit each full-frame shot to the canvas and key its position to keep
|
|
13339
|
+
the subject in view. The frames come from a private <video>, small, 5 a second — the same
|
|
13340
|
+
samples, plan and keys as fablecut_reframe. One undo step. ── */
|
|
13341
|
+
const Reframe = self.FableCutReframe;
|
|
13342
|
+
const reframeRun = { busy: false, cancel: false, done: 0, of: 0 };
|
|
13343
|
+
/** RGB frames of clip c (SAMPLE_FPS across its window; one for a still), w×h each. With `onRgb`,
|
|
13344
|
+
* each frame goes to it as it is read and nothing is kept (a long shot needn't sit in memory). */
|
|
13345
|
+
async function sampleClipFrames(c, w, h, onFrame, onRgb, { fps = Reframe.SAMPLE_FPS, cancelled = () => reframeRun.cancel } = {}) {
|
|
13346
|
+
const m = getMedia(c.mediaId);
|
|
13347
|
+
const cv = document.createElement("canvas"); cv.width = w; cv.height = h;
|
|
13348
|
+
const x = cv.getContext("2d", { willReadFrequently: true });
|
|
13349
|
+
const rgb = () => {
|
|
13350
|
+
const d = x.getImageData(0, 0, w, h).data, out = new Uint8Array(w * h * 3);
|
|
13351
|
+
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]; }
|
|
13352
|
+
return out;
|
|
13353
|
+
};
|
|
13354
|
+
if (c.kind === "image") {
|
|
13355
|
+
const img = new Image();
|
|
13356
|
+
if (isCrossOriginSrc(m.src)) img.crossOrigin = "anonymous"; // else the canvas can't be read back
|
|
13357
|
+
await new Promise((res, rej) => { img.onload = res; img.onerror = () => rej(new Error("the picture could not be read")); img.src = m.src; });
|
|
13358
|
+
x.drawImage(img, 0, 0, w, h);
|
|
13359
|
+
if (onRgb) { onRgb(rgb()); return []; }
|
|
13360
|
+
return [rgb()];
|
|
13361
|
+
}
|
|
13362
|
+
const el = document.createElement("video");
|
|
13363
|
+
if (isCrossOriginSrc(m.src)) el.crossOrigin = "anonymous";
|
|
13364
|
+
el.muted = true; el.preload = "auto"; el.playsInline = true; el.src = m.src;
|
|
13365
|
+
try {
|
|
13366
|
+
await new Promise((res, rej) => {
|
|
13367
|
+
const tm = setTimeout(() => rej(new Error("the video did not load")), 15000);
|
|
13368
|
+
el.addEventListener("loadeddata", () => { clearTimeout(tm); res(); }, { once: true });
|
|
13369
|
+
el.addEventListener("error", () => { clearTimeout(tm); rej(new Error("the video could not be read")); }, { once: true });
|
|
13370
|
+
});
|
|
13371
|
+
const n = Math.max(1, Math.floor(c.duration * clipSpeed(c) * fps + 1e-6));
|
|
13372
|
+
const frames = [];
|
|
13373
|
+
for (let i = 0; i < n; i++) {
|
|
13374
|
+
if (cancelled()) break;
|
|
13375
|
+
await seekFrame(el, Math.max(0, (c.in || 0) + i / fps) + 0.001);
|
|
13376
|
+
x.drawImage(el, 0, 0, w, h);
|
|
13377
|
+
if (onRgb) onRgb(rgb()); else frames.push(rgb());
|
|
13378
|
+
if (onFrame) onFrame(i + 1, n);
|
|
13379
|
+
}
|
|
13380
|
+
return frames;
|
|
13381
|
+
} finally { el.removeAttribute("src"); el.load(); }
|
|
13382
|
+
}
|
|
13383
|
+
/** The picture size of clip c's media (probed, else read from the file). */
|
|
13384
|
+
async function pictureSize(c) {
|
|
13385
|
+
const m = getMedia(c.mediaId);
|
|
13386
|
+
if (m && m.width > 0 && m.height > 0) return { width: m.width, height: m.height };
|
|
13387
|
+
// a file that never answers mustn't hold Reframe busy for good
|
|
13388
|
+
const wait = (el, ok, what) => new Promise((res, rej) => {
|
|
13389
|
+
const tm = setTimeout(() => rej(new Error(`the ${what} did not load`)), 15000);
|
|
13390
|
+
el.addEventListener(ok, () => { clearTimeout(tm); res(); }, { once: true });
|
|
13391
|
+
el.addEventListener("error", () => { clearTimeout(tm); rej(new Error(`the ${what} could not be read`)); }, { once: true });
|
|
13392
|
+
});
|
|
13393
|
+
if (c.kind === "image") {
|
|
13394
|
+
const img = new Image();
|
|
13395
|
+
if (isCrossOriginSrc(m.src)) img.crossOrigin = "anonymous";
|
|
13396
|
+
const p = wait(img, "load", "picture"); img.src = m.src; await p;
|
|
13397
|
+
return { width: img.naturalWidth, height: img.naturalHeight };
|
|
13398
|
+
}
|
|
13399
|
+
const el = document.createElement("video");
|
|
13400
|
+
el.preload = "metadata";
|
|
13401
|
+
try {
|
|
13402
|
+
const p = wait(el, "loadedmetadata", "video"); el.src = m.src; await p;
|
|
13403
|
+
return { width: el.videoWidth, height: el.videoHeight };
|
|
13404
|
+
} finally { el.removeAttribute("src"); el.load(); }
|
|
13405
|
+
}
|
|
13406
|
+
/** Reframe `clips` (default: every full-frame shot on the timeline) for this canvas. Returns the plan lines. */
|
|
13407
|
+
async function reframeClips(clips, { follow = true, smooth = 0.5 } = {}) {
|
|
13408
|
+
if (!Reframe) { toast("Reframe module missing — reload the editor"); return null; }
|
|
13409
|
+
if (reframeRun.busy) { toast("Already reframing — wait for it, or Cancel"); return null; }
|
|
13410
|
+
// every clip, so a linked partner's lock counts; `clips` (the selection) picks which ones
|
|
13411
|
+
const doc = { clips: project.clips, lockedTracks: [...state.lockedTracks] };
|
|
13412
|
+
const { take, skip } = Reframe.targets(doc, { ids: clips ? clips.map((c) => c.id) : null });
|
|
13413
|
+
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; }
|
|
13414
|
+
Object.assign(reframeRun, { busy: true, cancel: false, done: 0, of: take.length, frac: 0 });
|
|
13415
|
+
renderInspector();
|
|
13416
|
+
const canvas = { width: project.width, height: project.height }, fps = projectFps() || 30;
|
|
13417
|
+
// what the plans were made for: if any of it changes while the footage is read, nothing is applied
|
|
13418
|
+
const gen = runtime.projectGen, seqId = SeqLib.activeId(seqRoot()), lanes = JSON.stringify([...state.lockedTracks]);
|
|
13419
|
+
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 || {}]); };
|
|
13420
|
+
const stamps = new Map(take.map((c) => [c.id, stamp(c)]));
|
|
13421
|
+
const plans = [];
|
|
13422
|
+
try {
|
|
13423
|
+
for (const c of take) {
|
|
13424
|
+
if (reframeRun.cancel) break;
|
|
13425
|
+
reframeRun.frac = 0;
|
|
13426
|
+
const src = await pictureSize(c);
|
|
13427
|
+
let samples = null;
|
|
13428
|
+
const cover = Reframe.coverRect(src.width, src.height, canvas.width, canvas.height, 1);
|
|
13429
|
+
if (follow && Math.max(cover.maxX, cover.maxY) > 0.5) { // no room to pan: nothing to look at
|
|
13430
|
+
const w = Reframe.SAMPLE_W, h = Math.max(8, Math.round(w * src.height / src.width / 2) * 2);
|
|
13431
|
+
// each frame is looked at as it is read, between seeks, so Cancel answers and nothing piles up
|
|
13432
|
+
const tr = Reframe.tracker(w, h);
|
|
13433
|
+
await sampleClipFrames(c, w, h, (i, n) => { reframeRun.frac = i / n; if (i % 10 === 0) renderInspector(); }, (f) => tr.push(f));
|
|
13434
|
+
if (reframeRun.cancel) break;
|
|
13435
|
+
samples = tr.samples;
|
|
13436
|
+
}
|
|
13437
|
+
plans.push({ id: c.id, ...Reframe.clipPlan(c, samples, src, canvas, { smooth, fps, follow }) });
|
|
13438
|
+
reframeRun.done++;
|
|
13439
|
+
renderInspector();
|
|
13440
|
+
}
|
|
13441
|
+
} catch (e) {
|
|
13442
|
+
plans.length = 0; // all or nothing, as with Cancel
|
|
13443
|
+
toast("Couldn't look at the footage: " + (e?.message || e) + " — nothing changed");
|
|
13444
|
+
} finally {
|
|
13445
|
+
reframeRun.busy = false;
|
|
13446
|
+
}
|
|
13447
|
+
if (reframeRun.cancel || !plans.length) { reframeRun.cancel = false; renderInspector(); if (plans.length) toast("Reframe stopped — nothing changed"); return null; }
|
|
13448
|
+
if (gen !== runtime.projectGen || seqId !== SeqLib.activeId(seqRoot()) || project.width !== canvas.width || project.height !== canvas.height ||
|
|
13449
|
+
(projectFps() || 30) !== fps || JSON.stringify([...state.lockedTracks]) !== lanes ||
|
|
13450
|
+
plans.some((p) => { const c = getClip(p.id); return !c || stamp(c) !== stamps.get(p.id); })) {
|
|
13451
|
+
renderInspector();
|
|
13452
|
+
toast("The project changed while reframing — nothing was applied; run it again");
|
|
13453
|
+
return null;
|
|
13454
|
+
}
|
|
13455
|
+
pushUndo();
|
|
13456
|
+
for (const p of plans) {
|
|
13457
|
+
const c = getClip(p.id);
|
|
13458
|
+
if (!c) continue;
|
|
13459
|
+
for (const [k, v] of Object.entries(p.set.props || {})) {
|
|
13460
|
+
if (v !== null) c.props[k] = v;
|
|
13461
|
+
else if (Object.hasOwn(DEFAULT_PROPS, k)) c.props[k] = DEFAULT_PROPS[k];
|
|
13462
|
+
else delete c.props[k];
|
|
13463
|
+
}
|
|
13464
|
+
if ("keyframes" in p.set) { if (p.set.keyframes === null) delete c.keyframes; else c.keyframes = p.set.keyframes; }
|
|
13465
|
+
}
|
|
13466
|
+
state.dirtyTimeline = true;
|
|
13467
|
+
scheduleSave();
|
|
13468
|
+
renderInspector();
|
|
13469
|
+
const moving = plans.filter((p) => p.keys).length;
|
|
13470
|
+
toast(`Reframed ${plans.length} shot${plans.length === 1 ? "" : "s"} for ${canvas.width}×${canvas.height}` +
|
|
13471
|
+
(follow ? ` · ${moving} follow${moving === 1 ? "s" : ""} the subject` : "") + (skip.length ? ` · ${skip.length} left as placed` : ""));
|
|
13472
|
+
return plans;
|
|
13473
|
+
}
|
|
13474
|
+
/* ── Highlights: the best moments of the timeline's video, cut into a new sequence. The frames
|
|
13475
|
+
come from a private <video> (2 a second, small), the sound from the decoded file — the same
|
|
13476
|
+
reading, scores and picks as fablecut_highlights. ── */
|
|
13477
|
+
const Highlights = self.FableCutHighlights;
|
|
13478
|
+
const highlightRun = { busy: false, cancel: false };
|
|
13479
|
+
const HL_AUDIO_MAX_SECS = 30 * 60;
|
|
13480
|
+
async function readHighlightSource(c, cancelled, onFrame) {
|
|
13481
|
+
const src = await pictureSize(c);
|
|
13482
|
+
const w = Highlights.SAMPLE_W, h = Math.max(8, Math.round(w * src.height / src.width / 2) * 2);
|
|
13483
|
+
const pic = Highlights.picture(w, h), sp = clipSpeed(c);
|
|
13484
|
+
await sampleClipFrames(c, w, h, onFrame, (f) => pic.push(f), { fps: Highlights.PIC_FPS, cancelled });
|
|
13485
|
+
let aud = null;
|
|
13486
|
+
const media = getMedia(c.mediaId);
|
|
13487
|
+
// stopped: the caller drops it; no audio stream: nothing to decode (a failed decode would fetch the file again next time);
|
|
13488
|
+
// a file longer than HL_AUDIO_MAX_SECS isn't decoded whole in a browser tab: its picture decides
|
|
13489
|
+
const done = () => ({ id: c.id, len: c.duration * sp, pic, aud, speed: sp });
|
|
13490
|
+
if (cancelled() || !media || media.audioChannels === 0 || +media.duration > HL_AUDIO_MAX_SECS) return done();
|
|
13491
|
+
try {
|
|
13492
|
+
const buf = await getAudioBuffer(media);
|
|
13493
|
+
const a0 = Math.max(0, Math.floor((c.in || 0) * buf.sampleRate));
|
|
13494
|
+
const a1 = Math.min(buf.length, Math.ceil(((c.in || 0) + c.duration * sp) * buf.sampleRate));
|
|
13495
|
+
if (a1 > a0) {
|
|
13496
|
+
const chs = [];
|
|
13497
|
+
for (let k = 0; k < buf.numberOfChannels; k++) chs.push(buf.getChannelData(k).subarray(a0, a1));
|
|
13498
|
+
aud = Highlights.sound(buf.sampleRate);
|
|
13499
|
+
aud.push(FableCutBeats.mono(chs));
|
|
13500
|
+
}
|
|
13501
|
+
} catch { aud = null; } // no sound to read: the picture alone decides
|
|
13502
|
+
return done();
|
|
13503
|
+
}
|
|
13504
|
+
/** Read `clips` (default: every video clip on this timeline), pick the moments, and open them as a
|
|
13505
|
+
* new sequence. Nothing changes if it is cancelled or the timeline changes meanwhile. */
|
|
13506
|
+
async function makeHighlights(clips, { duration = 30, shot, size = null, follow = false, progress, cancelled: stop } = {}) {
|
|
13507
|
+
if (!Highlights) { toast("Highlights module missing — reload the editor"); return null; }
|
|
13508
|
+
if (highlightRun.busy) { toast("Already making highlights — wait for it, or Cancel"); return null; }
|
|
13509
|
+
if (exportBusy()) { toast("Wait for the export to finish"); return null; }
|
|
13510
|
+
const { take, skip } = Highlights.sourcesOf({ clips: project.clips, disabledTracks: [...state.disabledTracks] }, clips && clips.map((c) => c.id));
|
|
13511
|
+
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; }
|
|
13512
|
+
Object.assign(highlightRun, { busy: true, cancel: false });
|
|
13513
|
+
const gen = runtime.projectGen, seqId = SeqLib.activeId(seqRoot());
|
|
13514
|
+
const cancelled = () => highlightRun.cancel || gen !== runtime.projectGen || (stop && stop());
|
|
13515
|
+
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]); };
|
|
13516
|
+
const stamps = new Map(take.map((c) => [c.id, stamp(c)]));
|
|
13517
|
+
const sources = [];
|
|
13518
|
+
let failed = 0;
|
|
13519
|
+
try {
|
|
13520
|
+
for (let i = 0; i < take.length && !cancelled(); i++) {
|
|
13521
|
+
try { sources.push(await readHighlightSource(take[i], cancelled, (k, n) => progress && progress((i + k / n) / take.length))); }
|
|
13522
|
+
catch { failed++; }
|
|
13523
|
+
}
|
|
13524
|
+
} finally { highlightRun.busy = false; }
|
|
13525
|
+
if (cancelled()) { highlightRun.cancel = false; toast("Highlights stopped — nothing changed"); return null; }
|
|
13526
|
+
if (!sources.length) { toast("Couldn't read the footage"); return null; }
|
|
13527
|
+
let picks;
|
|
13528
|
+
try { picks = Highlights.pick(sources, { duration, shot }); } catch (e) { toast(e.message); return null; }
|
|
13529
|
+
if (!picks.length) { toast("No moments long enough to use"); return null; }
|
|
13530
|
+
// the picks name clips by id and read their in points: the timeline must be as it was read
|
|
13531
|
+
// (and no video was added or taken away: the clips it would read now are the ones it read)
|
|
13532
|
+
const now = Highlights.sourcesOf({ clips: project.clips, disabledTracks: [...state.disabledTracks] }, clips && clips.map((c) => c.id)).take;
|
|
13533
|
+
if (seqId !== SeqLib.activeId(seqRoot()) || JSON.stringify(now.map((c) => c.id)) !== JSON.stringify(take.map((c) => c.id)) ||
|
|
13534
|
+
take.some((c) => { const cur = getClip(c.id); return !cur || stamp(cur) !== stamps.get(c.id); })) {
|
|
13535
|
+
toast("The timeline changed while reading — nothing was made; run it again");
|
|
13536
|
+
return null;
|
|
13537
|
+
}
|
|
13538
|
+
const name = `Highlights ${duration} s`;
|
|
13539
|
+
const ops = Highlights.ops(projectJSONHere(), picks, { name, ...(size || {}) });
|
|
13540
|
+
const opened = newSequence({ name, from: "empty", ...(size || {}) }, ops.slice(1).map((o) => o.clip));
|
|
13541
|
+
if (opened === undefined) return null; // nothing was made: newSequence said why
|
|
13542
|
+
if (opened && follow) reframeClips(null, { follow: true });
|
|
13543
|
+
const total = picks.reduce((n, p) => n + p.len, 0);
|
|
13544
|
+
toast(`Highlights: ${picks.length} moments, ${total.toFixed(1)} s` + (failed ? ` · ${failed} clip${failed === 1 ? "" : "s"} couldn't be read` : "") +
|
|
13545
|
+
(total < duration - 0.5 ? " — the footage has no more distinct moments" : ""));
|
|
13546
|
+
return picks;
|
|
13547
|
+
}
|
|
12968
13548
|
/**
|
|
12969
13549
|
* Follow `box` (picture fractions {x, y, w, h}) through clip c from clip-local
|
|
12970
13550
|
* `from` towards `to` (dir ±1), one sample per project frame. Returns
|
|
@@ -13274,6 +13854,7 @@ els.preview.addEventListener("pointerdown", (e) => {
|
|
|
13274
13854
|
}, true);
|
|
13275
13855
|
window.addEventListener("keydown", (e) => {
|
|
13276
13856
|
if (e.key !== "Escape" || (!trackUi.run && trackUi.tool !== "point")) return;
|
|
13857
|
+
if (!$("cmdkOverlay").classList.contains("hidden")) return; // Esc belongs to Search while it is open
|
|
13277
13858
|
e.preventDefault(); e.stopImmediatePropagation();
|
|
13278
13859
|
if (trackUi.run) trackUi.run.cancel = true;
|
|
13279
13860
|
else { trackUi.tool = null; renderInspector(); }
|
|
@@ -13696,6 +14277,7 @@ els.preview.addEventListener("dblclick", (e) => {
|
|
|
13696
14277
|
maskUi.pt = -1; scheduleSave(); renderInspector();
|
|
13697
14278
|
}, true);
|
|
13698
14279
|
window.addEventListener("keydown", (e) => {
|
|
14280
|
+
if (!$("cmdkOverlay").classList.contains("hidden")) return; // keys belong to Search while it is open
|
|
13699
14281
|
if (e.key === "Escape" && colorState.maskDraw) { // the Color tab's Draw
|
|
13700
14282
|
e.preventDefault(); e.stopImmediatePropagation();
|
|
13701
14283
|
colorState.maskDraw = false; colorState.maskStroke = null; state.dirtyTimeline = true; renderColorPage(true);
|
|
@@ -15899,6 +16481,7 @@ function refreshDeliveryNotes() {
|
|
|
15899
16481
|
$("dlvSummary").textContent = `${Delivery.describe(sp, { width: fr.outW, height: fr.outH, fps })}` +
|
|
15900
16482
|
(size ? ` · about ${Delivery.fmtBytes(size)}` : "");
|
|
15901
16483
|
$("dlvFilePreview").textContent = "→ exports/" + deliveryFileName(sp, fps) + Delivery.CONTAINERS[sp.container].ext;
|
|
16484
|
+
syncExportName();
|
|
15902
16485
|
const cv = deliveryCanvas();
|
|
15903
16486
|
const warn = [...dlvNotes.map((n) => n[0].toUpperCase() + n.slice(1)),
|
|
15904
16487
|
...Delivery.checks(sp, { duration: range.dur, fps, canvasW: cv.w, canvasH: cv.h, region: cv.region })];
|
|
@@ -15977,10 +16560,65 @@ function webCodecsBitrate(w, h, fps) {
|
|
|
15977
16560
|
// ~0.1 bit/pixel/frame, clamped — same heuristic as before
|
|
15978
16561
|
return Math.min(20_000_000, Math.max(2_000_000, Math.round(w * h * fps * 0.1)));
|
|
15979
16562
|
}
|
|
16563
|
+
/* The Export dialog's "Save as" name. The field shows the name the export would get;
|
|
16564
|
+
once typed in, that name is used for this export (cleared = the default, shown greyed). */
|
|
16565
|
+
let exportNameTyped = false;
|
|
16566
|
+
let exportNameShown = ""; // the default the Save as field shows (a {time} in it is the time it was filled in)
|
|
16567
|
+
/** The engine the dialog's choices lead to, as startChosenExport picks it. */
|
|
16568
|
+
function chosenExportEngine() {
|
|
16569
|
+
if (els.engineFast.checked && !els.engineFast.disabled) return "fast";
|
|
16570
|
+
if (!els.engineRealtime.checked || els.engineRealtime.disabled) return null;
|
|
16571
|
+
return state.connected && state.ffmpeg && state.webCodecs && !getExportFrame() ? "webcodecs" : "recorder";
|
|
16572
|
+
}
|
|
16573
|
+
function defaultExportName() {
|
|
16574
|
+
const c = selectedExportChoice();
|
|
16575
|
+
if (chosenExportEngine() === "fast" && c.kind === "delivery" && dlvSpec) return deliveryFileName(dlvSpec);
|
|
16576
|
+
return project.name.replace(/[^\w\- ]+/g, "").trim() || "export";
|
|
16577
|
+
}
|
|
16578
|
+
function exportNameExt() {
|
|
16579
|
+
const engine = chosenExportEngine(), c = selectedExportChoice();
|
|
16580
|
+
if (engine === "fast" && c.kind === "delivery" && dlvSpec) return Delivery.CONTAINERS[dlvSpec.container].ext;
|
|
16581
|
+
if (engine === "recorder") return (pickMime() || "").startsWith("video/mp4") ? ".mp4" : ".webm";
|
|
16582
|
+
if (engine === "fast" && c.kind === "profile") return encodeProfiles.profiles[c.id]?.extension || ".mp4";
|
|
16583
|
+
return ".mp4";
|
|
16584
|
+
}
|
|
16585
|
+
function syncExportName() {
|
|
16586
|
+
const el = $("exportName");
|
|
16587
|
+
if (!el) return;
|
|
16588
|
+
const def = exportNameShown = defaultExportName();
|
|
16589
|
+
el.placeholder = def;
|
|
16590
|
+
if (!exportNameTyped) el.value = def;
|
|
16591
|
+
const note = $("exportNameNote");
|
|
16592
|
+
if (!note) return;
|
|
16593
|
+
const file = (exportName() || def) + exportNameExt();
|
|
16594
|
+
note.textContent = chosenExportEngine() === "recorder"
|
|
16595
|
+
? "→ the browser downloads " + file
|
|
16596
|
+
: "→ exports/" + file + " · a number is added if that name is taken";
|
|
16597
|
+
// (the browser download names its own copies when the name is taken)
|
|
16598
|
+
}
|
|
16599
|
+
/** The typed name (file-safe), or null for the default. */
|
|
16600
|
+
function exportName() {
|
|
16601
|
+
const v = exportNameTyped ? ($("exportName")?.value || "").trim() : "";
|
|
16602
|
+
const ext = exportNameExt().toLowerCase();
|
|
16603
|
+
const base = ext && v.toLowerCase().endsWith(ext) ? v.slice(0, -ext.length) : v;
|
|
16604
|
+
const safe = base.replace(/\.(mp4|mov|m4v|mkv|webm|mxf)$/i, "").replace(/[^\w\- ()\[\].]+/g, "_").replace(/^[.\s]+/, "").slice(0, 120);
|
|
16605
|
+
return safe || null;
|
|
16606
|
+
}
|
|
16607
|
+
let exportSetupOpening = false; // one Export click at a time, while the dialog's lists load
|
|
16608
|
+
/* An export getting ready (its players, fonts, encoder check) holds the canvas before
|
|
16609
|
+
state.exporting is set: every engine, the queue and agent jobs wait for both. */
|
|
16610
|
+
let exportStarting = false;
|
|
16611
|
+
function exportBusy() { return state.exporting || exportStarting; }
|
|
16612
|
+
/** Which timeline an Export click was for: a project or sequence opened meanwhile isn't it. */
|
|
16613
|
+
function exportContext() { return (runtime.projectId || "") + "|" + (project.sequence || "") + "|" + (state.compCtx ? state.compCtx.path.join("/") : ""); }
|
|
15980
16614
|
async function openExportSetup() {
|
|
15981
|
-
if (
|
|
16615
|
+
if (exportBusy() || exportSetupOpening) return;
|
|
16616
|
+
const ctx = exportContext();
|
|
16617
|
+
// the dialog already open is being refreshed (a setting changed): keep what was typed in it
|
|
16618
|
+
const fresh = els.exportSetup.classList.contains("hidden");
|
|
15982
16619
|
if (!project.clips.length) { alert("Timeline is empty — add some clips first."); return; }
|
|
15983
|
-
|
|
16620
|
+
exportSetupOpening = true;
|
|
16621
|
+
try { await detectWebCodecs(); } catch { }
|
|
15984
16622
|
const ef = getExportFrame();
|
|
15985
16623
|
const fastOk = state.connected && state.ffmpeg;
|
|
15986
16624
|
// WebCodecs and MediaRecorder encode the full canvas — only Fast crops.
|
|
@@ -16045,14 +16683,62 @@ async function openExportSetup() {
|
|
|
16045
16683
|
syncExportRangeUi();
|
|
16046
16684
|
syncExportProfileVisibility();
|
|
16047
16685
|
Promise.all([fetchEncodeProfiles(), fetchDeliveryInfo()]).then(() => {
|
|
16686
|
+
if (exportContext() !== ctx) { toast("Another timeline opened — click Export again"); return; }
|
|
16048
16687
|
populateExportProfileSelect();
|
|
16049
16688
|
syncExportProfileVisibility();
|
|
16050
16689
|
renderBatchList();
|
|
16051
16690
|
renderQueue();
|
|
16691
|
+
if (fresh) {
|
|
16692
|
+
exportNameTyped = false;
|
|
16693
|
+
const skip = $("exportSkipAsk");
|
|
16694
|
+
if (skip) skip.checked = false;
|
|
16695
|
+
}
|
|
16696
|
+
syncExportName();
|
|
16697
|
+
if (fresh && !getSetting("exportAsk")) {
|
|
16698
|
+
// "Don't ask again": render with the last engine and settings under the default name;
|
|
16699
|
+
// if that engine can't run now, ask after all rather than switch engines silently
|
|
16700
|
+
const last = getSetting("exportEngine");
|
|
16701
|
+
// (older settings say "second" for either real-time encoder)
|
|
16702
|
+
const radio = last === "fast" ? els.engineFast : last === "second" || last === "webcodecs" || last === "recorder" ? els.engineRealtime : null;
|
|
16703
|
+
// ...and the last preset or profile picked, when it is still in the list
|
|
16704
|
+
const choice = getSetting("exportChoice");
|
|
16705
|
+
// (a raw profile has to still be on the server: a deleted one can linger in the list as a placeholder)
|
|
16706
|
+
const choiceOk = !choice || (choice.startsWith("p:") ? Object.hasOwn(encodeProfiles.profiles, choice.slice(2))
|
|
16707
|
+
: [...els.exportProfileSel.options].some((o) => o.value === choice));
|
|
16708
|
+
if (choiceOk && choice) {
|
|
16709
|
+
if (els.exportProfileSel.value !== choice) {
|
|
16710
|
+
els.exportProfileSel.value = choice;
|
|
16711
|
+
els.exportProfileSel.dispatchEvent(new Event("change"));
|
|
16712
|
+
}
|
|
16713
|
+
// the delivery as last exported (its size, codec…), even when the project pins the same preset
|
|
16714
|
+
const lastDlv = getSetting("delivery");
|
|
16715
|
+
if (choice.startsWith("d:") && lastDlv?.preset === choice.slice(2)) {
|
|
16716
|
+
dlvSpec = normalizeDelivery(lastDlv).spec;
|
|
16717
|
+
fillDeliveryControls(); // the dialog, if it opens, shows what Render will write
|
|
16718
|
+
refreshDeliveryNotes();
|
|
16719
|
+
}
|
|
16720
|
+
}
|
|
16721
|
+
if (radio) {
|
|
16722
|
+
els.engineFast.checked = radio === els.engineFast && !radio.disabled; els.engineRealtime.checked = radio === els.engineRealtime && !radio.disabled;
|
|
16723
|
+
// the dialog, if it opens, shows the engine's own controls
|
|
16724
|
+
syncExportProfileVisibility(); syncExportWcOpts();
|
|
16725
|
+
}
|
|
16726
|
+
// the range counted in frames of what will be written (a delivery may have its own frame rate)
|
|
16727
|
+
const outFps = chosenExportEngine() === "fast" && selectedExportChoice().kind === "delivery" && dlvSpec?.fps || projectFps();
|
|
16728
|
+
const engineOk = !radio || (!radio.disabled && (last === "second" || last === "fast" || chosenExportEngine() === last));
|
|
16729
|
+
if (engineOk && choiceOk && exportRange(outFps).frames >= 1) {
|
|
16730
|
+
syncExportName();
|
|
16731
|
+
toast(`Exporting “${defaultExportName()}” — Settings → Ask before exporting brings the dialog back`);
|
|
16732
|
+
startChosenExport();
|
|
16733
|
+
return;
|
|
16734
|
+
}
|
|
16735
|
+
toast(exportRange(outFps).frames < 1 ? "The export range is empty — pick one"
|
|
16736
|
+
: !choiceOk ? "The last export's preset isn't there any more — pick one" : "The last export's engine isn't available — pick one");
|
|
16737
|
+
}
|
|
16052
16738
|
els.exportSetup.classList.remove("hidden");
|
|
16053
16739
|
// aria-modal hides what is behind — focus has to come inside
|
|
16054
16740
|
if (!els.exportSetup.contains(document.activeElement)) $("exportRangeSel")?.focus();
|
|
16055
|
-
});
|
|
16741
|
+
}).finally(() => { exportSetupOpening = false; });
|
|
16056
16742
|
}
|
|
16057
16743
|
function closeExportSetup() {
|
|
16058
16744
|
els.exportSetup.classList.add("hidden");
|
|
@@ -16075,17 +16761,22 @@ function startChosenExport() {
|
|
|
16075
16761
|
alert("Export range is empty — IN/OUT is at or past the end of the timeline. Choose Entire timeline, or move the markers.");
|
|
16076
16762
|
return;
|
|
16077
16763
|
}
|
|
16764
|
+
// the name shown now (a default with {time} must not tick over while the audio mixes)
|
|
16765
|
+
const name = exportName() || exportNameShown || defaultExportName();
|
|
16766
|
+
if ($("exportSkipAsk")?.checked) setSetting("exportAsk", false);
|
|
16767
|
+
setSetting("exportEngine", chosenExportEngine());
|
|
16768
|
+
setSetting("exportChoice", els.exportProfileSel?.value || null);
|
|
16078
16769
|
closeExportSetup();
|
|
16079
16770
|
if (useFast) {
|
|
16080
16771
|
const c = selectedExportChoice();
|
|
16081
16772
|
setSetting("exportKind", c.kind);
|
|
16082
16773
|
if (c.kind === "delivery") {
|
|
16083
16774
|
setSetting("delivery", dlvSpec);
|
|
16084
|
-
fastExport({ delivery: dlvSpec });
|
|
16085
|
-
} else fastExport({ profile: c.id });
|
|
16775
|
+
fastExport({ delivery: dlvSpec, name });
|
|
16776
|
+
} else fastExport({ profile: c.id, name });
|
|
16086
16777
|
}
|
|
16087
|
-
else if (useSecond && state.connected && state.ffmpeg && state.webCodecs && !getExportFrame()) webCodecsExport();
|
|
16088
|
-
else startExport();
|
|
16778
|
+
else if (useSecond && state.connected && state.ffmpeg && state.webCodecs && !getExportFrame()) webCodecsExport(name);
|
|
16779
|
+
else startExport(name);
|
|
16089
16780
|
}
|
|
16090
16781
|
|
|
16091
16782
|
/* Keep Range's IN–OUT option in sync with marker presence without clobbering
|
|
@@ -16992,7 +17683,7 @@ async function prepareFrameAssets(t) {
|
|
|
16992
17683
|
* opts.silent: no overlay, alert or download (the export queue shows it);
|
|
16993
17684
|
* opts.onProgress(0…1). Resolves {outputs:[{file, ok, src?, error?}]} or {error, cancelled}. */
|
|
16994
17685
|
async function fastExport(opts = {}) {
|
|
16995
|
-
if (
|
|
17686
|
+
if (exportBusy()) return { error: "an export is already running in this tab", busy: true };
|
|
16996
17687
|
const job = opts.job || null;
|
|
16997
17688
|
pause();
|
|
16998
17689
|
state.exporting = true; state.rendering = true; renderCancelled = false;
|
|
@@ -17002,7 +17693,7 @@ async function fastExport(opts = {}) {
|
|
|
17002
17693
|
els.exportProgress.style.width = "0%";
|
|
17003
17694
|
els.exportNote.textContent = "Rendering frames → ffmpeg. You can switch tabs; export continues.";
|
|
17004
17695
|
restoreExportVideoState();
|
|
17005
|
-
const deliveries = opts.deliveries || (opts.delivery ? [{ delivery: opts.delivery }] : null);
|
|
17696
|
+
const deliveries = opts.deliveries || (opts.delivery ? [{ delivery: opts.delivery, name: opts.name || undefined }] : null);
|
|
17006
17697
|
const delivery = deliveries ? deliveries[0].delivery : null;
|
|
17007
17698
|
const fps = (delivery && delivery.fps) || projectFps();
|
|
17008
17699
|
let result = null;
|
|
@@ -17024,7 +17715,7 @@ async function fastExport(opts = {}) {
|
|
|
17024
17715
|
canvasW: cv.w, canvasH: cv.h, region: cv.region, hasAudio: !!wav,
|
|
17025
17716
|
} : {
|
|
17026
17717
|
fps,
|
|
17027
|
-
name: project.name.replace(/[^\w\- ]+/g, "") || "export",
|
|
17718
|
+
name: opts.name || project.name.replace(/[^\w\- ]+/g, "") || "export",
|
|
17028
17719
|
profile: profileId,
|
|
17029
17720
|
hasAudio: !!wav,
|
|
17030
17721
|
}),
|
|
@@ -17238,7 +17929,7 @@ function renderQueueProgress() {
|
|
|
17238
17929
|
}
|
|
17239
17930
|
}
|
|
17240
17931
|
async function runQueue() {
|
|
17241
|
-
if (queueRunning ||
|
|
17932
|
+
if (queueRunning || exportBusy()) return;
|
|
17242
17933
|
if (!(state.connected && state.ffmpeg)) { alert("The export queue needs the server and ffmpeg (Fast export)."); return; }
|
|
17243
17934
|
queueRunning = true; queueStop = false;
|
|
17244
17935
|
renderQueue();
|
|
@@ -17358,8 +18049,23 @@ async function reportExportJob(id, body, force = false) {
|
|
|
17358
18049
|
if (r?.cancel) { renderCancelled = true; exportAbort?.abort(); }
|
|
17359
18050
|
} catch { }
|
|
17360
18051
|
}
|
|
18052
|
+
let skippedTicket = null, skippedTimer = 0;
|
|
17361
18053
|
async function runExportJob(ticket) {
|
|
17362
|
-
if (!ticket?.id
|
|
18054
|
+
if (!ticket?.id) return;
|
|
18055
|
+
if (exportBusy()) {
|
|
18056
|
+
// a busy tab leaves it for another, but tries again when it is free (the server's claim
|
|
18057
|
+
// decides: a ticket another tab took, or one the agent cancelled, is refused)
|
|
18058
|
+
skippedTicket = ticket;
|
|
18059
|
+
clearInterval(skippedTimer);
|
|
18060
|
+
const until = Date.now() + 30000;
|
|
18061
|
+
skippedTimer = setInterval(() => {
|
|
18062
|
+
if (exportBusy() && Date.now() < until) return;
|
|
18063
|
+
clearInterval(skippedTimer);
|
|
18064
|
+
const t = skippedTicket; skippedTicket = null;
|
|
18065
|
+
if (t && !exportBusy()) runExportJob(t);
|
|
18066
|
+
}, 500);
|
|
18067
|
+
return;
|
|
18068
|
+
}
|
|
17363
18069
|
const claimed = await fetch("/api/export/job/claim?id=" + encodeURIComponent(ticket.id), { method: "POST" })
|
|
17364
18070
|
.then((r) => r.ok).catch(() => false);
|
|
17365
18071
|
if (!claimed) return;
|
|
@@ -17368,9 +18074,20 @@ async function runExportJob(ticket) {
|
|
|
17368
18074
|
for (let i = 0; i < 150 && ticket.revision != null && (project.revision || 0) < ticket.revision; i++)
|
|
17369
18075
|
await new Promise((r) => setTimeout(r, 100));
|
|
17370
18076
|
if (ticket.revision != null && (project.revision || 0) < ticket.revision) await syncFromServer();
|
|
18077
|
+
// a ticket that waited here while the tab switched projects must not render the other one
|
|
18078
|
+
if (ticket.project && runtime.projectId && ticket.project !== runtime.projectId && ticket.kind !== "transcribe")
|
|
18079
|
+
return fail("another project was opened before this job could start — open the project again and retry");
|
|
18080
|
+
if (ticket.kind === "transcribe") return runTranscribeJob(ticket, fail);
|
|
18081
|
+
// from here until the job ends, a project opened elsewhere waits: the job renders the one it was asked for
|
|
18082
|
+
runtime.jobHold = (runtime.jobHold || 0) + 1;
|
|
18083
|
+
try { return await runHeldJob(ticket, fail); } finally {
|
|
18084
|
+
runtime.jobHold--;
|
|
18085
|
+
if (!runtime.jobHold && runtime.pendingSync) syncFromServer();
|
|
18086
|
+
}
|
|
18087
|
+
}
|
|
18088
|
+
async function runHeldJob(ticket, fail) {
|
|
17371
18089
|
if (ticket.kind === "scopes") return runScopesJob(ticket, fail);
|
|
17372
18090
|
if (ticket.kind === "track") return runTrackJob(ticket, fail);
|
|
17373
|
-
if (ticket.kind === "transcribe") return runTranscribeJob(ticket, fail);
|
|
17374
18091
|
if (!state.ffmpeg) {
|
|
17375
18092
|
const j = await fetch("/api/export/ffmpeg").then((r) => r.json()).catch(() => ({}));
|
|
17376
18093
|
state.ffmpeg = !!j.available;
|
|
@@ -17393,7 +18110,7 @@ async function runExportJob(ticket) {
|
|
|
17393
18110
|
const specs = ticket.deliveries.map((d) => normalizeDelivery(d).spec);
|
|
17394
18111
|
const groups = new Map();
|
|
17395
18112
|
for (const sp of specs) { const k = sp.fps || projectFps(); if (!groups.has(k)) groups.set(k, []); groups.get(k).push(sp); }
|
|
17396
|
-
if (groups.size === 1) await fastExport({ job: ticket.id, deliveries: specs.map((delivery) => ({ delivery })) });
|
|
18113
|
+
if (groups.size === 1) { const res = await fastExport({ job: ticket.id, deliveries: specs.map((delivery) => ({ delivery })) }); if (res?.busy) return fail(res.error); }
|
|
17397
18114
|
else {
|
|
17398
18115
|
const all = [];
|
|
17399
18116
|
let i = 0;
|
|
@@ -17401,6 +18118,7 @@ async function runExportJob(ticket) {
|
|
|
17401
18118
|
const res = await fastExport({ deliveries: group.map((delivery) => ({ delivery })), silent: true,
|
|
17402
18119
|
onProgress: (f) => reportExportJob(ticket.id, { progress: (i + f) / groups.size }) });
|
|
17403
18120
|
i++;
|
|
18121
|
+
if (res?.busy) return fail(res.error);
|
|
17404
18122
|
if (res && res.cancelled) return reportExportJob(ticket.id, { status: "failed", error: "cancelled" }, true);
|
|
17405
18123
|
if (res && res.outputs) all.push(...res.outputs);
|
|
17406
18124
|
else all.push(...group.map((sp) => ({ file: deliveryFileName(sp), ok: false, error: (res && res.error) || "export failed" })));
|
|
@@ -17409,7 +18127,11 @@ async function runExportJob(ticket) {
|
|
|
17409
18127
|
if (!ok) return fail(all.map((o) => o.error).join(" · "));
|
|
17410
18128
|
await reportExportJob(ticket.id, { status: "done", src: ok.src, result: { outputs: all } }, true);
|
|
17411
18129
|
}
|
|
17412
|
-
} else
|
|
18130
|
+
} else {
|
|
18131
|
+
const res = await fastExport(want ? { job: ticket.id, delivery: normalizeDelivery(want).spec, name: ticket.name || null } : { job: ticket.id, profile: ticket.profile, name: ticket.name || null });
|
|
18132
|
+
// another export took the tab while this job was getting ready: say so rather than leave it running
|
|
18133
|
+
if (res?.busy) return fail(res.error);
|
|
18134
|
+
}
|
|
17413
18135
|
} finally {
|
|
17414
18136
|
exportRangeForced = null;
|
|
17415
18137
|
}
|
|
@@ -17490,7 +18212,10 @@ async function runTrackJob(ticket, fail) {
|
|
|
17490
18212
|
if (state.connected) {
|
|
17491
18213
|
clearTimeout(runtime.saveTimer); runtime.saveTimer = null;
|
|
17492
18214
|
project.revision++;
|
|
17493
|
-
|
|
18215
|
+
// the project this job tracked in: a project opened elsewhere meanwhile refuses the save (409)
|
|
18216
|
+
const headers = { "Content-Type": "application/json" };
|
|
18217
|
+
if (runtime.projectId) headers["X-FableCut-Project"] = runtime.projectId;
|
|
18218
|
+
const res = await fetch("/api/project", { method: "PUT", headers, body: JSON.stringify(projectJSON(), null, 2) });
|
|
17494
18219
|
if (!res.ok) {
|
|
17495
18220
|
project.revision--;
|
|
17496
18221
|
// put back only the clips this job changed (edits elsewhere since stay), and drop its undo step
|
|
@@ -17686,10 +18411,13 @@ function waitEncodeQueue(encoder, max = 2, { signal, getError } = {}) {
|
|
|
17686
18411
|
tick();
|
|
17687
18412
|
});
|
|
17688
18413
|
}
|
|
17689
|
-
async function webCodecsExport() {
|
|
18414
|
+
async function webCodecsExport(name) {
|
|
18415
|
+
if (exportBusy()) return;
|
|
18416
|
+
exportStarting = true;
|
|
18417
|
+
try { await detectWebCodecs(); } finally { exportStarting = false; }
|
|
17690
18418
|
if (state.exporting) return;
|
|
17691
|
-
|
|
17692
|
-
if (!state.webCodecs) { startExport(); return; }
|
|
18419
|
+
// no encoder: the recorder takes over at once, so nothing slips in between
|
|
18420
|
+
if (!state.webCodecs) { startExport(name); return; }
|
|
17693
18421
|
pause();
|
|
17694
18422
|
state.exporting = true; state.rendering = true; renderCancelled = false;
|
|
17695
18423
|
exportAbort = new AbortController();
|
|
@@ -17715,7 +18443,7 @@ async function webCodecsExport() {
|
|
|
17715
18443
|
method: "POST",
|
|
17716
18444
|
body: JSON.stringify({
|
|
17717
18445
|
fps,
|
|
17718
|
-
name: project.name.replace(/[^\w\- ]+/g, "") || "export",
|
|
18446
|
+
name: name || project.name.replace(/[^\w\- ]+/g, "") || "export",
|
|
17719
18447
|
mode: "annexb",
|
|
17720
18448
|
hasAudio: !!wav,
|
|
17721
18449
|
}),
|
|
@@ -17836,24 +18564,38 @@ function pickMime() {
|
|
|
17836
18564
|
];
|
|
17837
18565
|
return cands.find((m) => window.MediaRecorder && MediaRecorder.isTypeSupported(m)) || "";
|
|
17838
18566
|
}
|
|
17839
|
-
async function startExport() {
|
|
17840
|
-
if (
|
|
18567
|
+
async function startExport(name) {
|
|
18568
|
+
if (exportBusy()) return;
|
|
17841
18569
|
if (!project.clips.length) { alert("Timeline is empty — add some clips first."); return; }
|
|
17842
18570
|
const mime = pickMime();
|
|
17843
18571
|
if (!mime) { alert("MediaRecorder is not supported in this browser."); return; }
|
|
17844
|
-
|
|
17845
|
-
|
|
17846
|
-
|
|
17847
|
-
|
|
17848
|
-
|
|
17849
|
-
|
|
17850
|
-
|
|
17851
|
-
|
|
17852
|
-
|
|
17853
|
-
|
|
17854
|
-
|
|
18572
|
+
exportStarting = true;
|
|
18573
|
+
let stream = null;
|
|
18574
|
+
try {
|
|
18575
|
+
ensureAudio();
|
|
18576
|
+
await runtime.audio.ctx.resume();
|
|
18577
|
+
pause();
|
|
18578
|
+
const { start } = beginExportWindow();
|
|
18579
|
+
state.time = start;
|
|
18580
|
+
await useOriginalPlayers(); // proxies are for editing — export reads the originals
|
|
18581
|
+
seekMediaWhilePaused();
|
|
18582
|
+
await new Promise((r) => setTimeout(r, 350)); // let first frames decode
|
|
18583
|
+
await loadProjectFonts();
|
|
18584
|
+
stream = els.preview.captureStream(projectFps());
|
|
18585
|
+
for (const tr of runtime.audio.recDest.stream.getAudioTracks()) stream.addTrack(tr);
|
|
18586
|
+
recorder = new MediaRecorder(stream, { mimeType: mime, videoBitsPerSecond: 10_000_000 });
|
|
18587
|
+
} catch (e) {
|
|
18588
|
+
exportStarting = false;
|
|
18589
|
+
// the canvas track was made for this attempt; the audio track is shared, so it stays
|
|
18590
|
+
for (const tr of stream?.getVideoTracks() || []) tr.stop();
|
|
18591
|
+
recorder = null;
|
|
18592
|
+
releaseOriginalPlayers();
|
|
18593
|
+
endExportWindow();
|
|
18594
|
+
toast("Export couldn't start: " + (e.message || e));
|
|
18595
|
+
return;
|
|
18596
|
+
}
|
|
18597
|
+
exportStarting = false;
|
|
17855
18598
|
recChunks = []; recDiscard = false;
|
|
17856
|
-
recorder = new MediaRecorder(stream, { mimeType: mime, videoBitsPerSecond: 10_000_000 });
|
|
17857
18599
|
recorder.ondataavailable = (e) => { if (e.data.size) recChunks.push(e.data); };
|
|
17858
18600
|
recorder.onstop = () => {
|
|
17859
18601
|
els.exportOverlay.classList.add("hidden");
|
|
@@ -17862,14 +18604,23 @@ async function startExport() {
|
|
|
17862
18604
|
const blob = new Blob(recChunks, { type: mime.split(";")[0] });
|
|
17863
18605
|
const a = document.createElement("a");
|
|
17864
18606
|
a.href = URL.createObjectURL(blob);
|
|
17865
|
-
a.download = (project.name.replace(/[^\w\- ]+/g, "") || "export") + "." + ext;
|
|
18607
|
+
a.download = (name || project.name.replace(/[^\w\- ]+/g, "") || "export") + "." + ext;
|
|
17866
18608
|
a.click();
|
|
17867
18609
|
setTimeout(() => URL.revokeObjectURL(a.href), 30_000);
|
|
17868
18610
|
};
|
|
17869
18611
|
els.exportOverlay.classList.remove("hidden");
|
|
17870
18612
|
els.exportProgress.style.width = "0%";
|
|
17871
18613
|
state.exporting = true;
|
|
17872
|
-
recorder.start(250);
|
|
18614
|
+
try { recorder.start(250); }
|
|
18615
|
+
catch (e) {
|
|
18616
|
+
state.exporting = false;
|
|
18617
|
+
for (const tr of stream.getVideoTracks()) tr.stop();
|
|
18618
|
+
els.exportOverlay.classList.add("hidden");
|
|
18619
|
+
releaseOriginalPlayers();
|
|
18620
|
+
endExportWindow();
|
|
18621
|
+
toast("Export couldn't start: " + (e.message || e));
|
|
18622
|
+
return;
|
|
18623
|
+
}
|
|
17873
18624
|
pauseSource();
|
|
17874
18625
|
setMonitorMode("program");
|
|
17875
18626
|
state.playing = true;
|
|
@@ -17921,6 +18672,12 @@ $("btnRippleDelete").addEventListener("click", () => {
|
|
|
17921
18672
|
});
|
|
17922
18673
|
$("btnExport").addEventListener("click", openExportSetup);
|
|
17923
18674
|
$("btnStartExport").addEventListener("click", startChosenExport);
|
|
18675
|
+
$("exportName")?.addEventListener("input", () => { exportNameTyped = true; syncExportName(); });
|
|
18676
|
+
$("exportName")?.addEventListener("keydown", (e) => {
|
|
18677
|
+
if (e.key === "Enter" && !e.isComposing && !$("btnStartExport").disabled) { e.preventDefault(); startChosenExport(); }
|
|
18678
|
+
});
|
|
18679
|
+
els.engineFast?.addEventListener("change", syncExportName);
|
|
18680
|
+
els.engineRealtime?.addEventListener("change", syncExportName);
|
|
17924
18681
|
els.exportSetup?.addEventListener("change", (e) => {
|
|
17925
18682
|
if (e.target.name === "engine") {
|
|
17926
18683
|
syncExportProfileVisibility();
|
|
@@ -17933,6 +18690,7 @@ els.exportProfileSel?.addEventListener("change", () => {
|
|
|
17933
18690
|
if (c.kind === "profile" && !project.encodeProfile)
|
|
17934
18691
|
setSetting("encodeProfile", c.id === encodeProfiles.default ? null : c.id);
|
|
17935
18692
|
syncExportChoiceUi("preset");
|
|
18693
|
+
syncExportName();
|
|
17936
18694
|
});
|
|
17937
18695
|
$("dlvBody")?.addEventListener("change", onDeliveryControl);
|
|
17938
18696
|
$("dlvBody")?.addEventListener("input", onDeliveryControl);
|
|
@@ -18064,7 +18822,9 @@ $("btnHelp").addEventListener("click", () => {
|
|
|
18064
18822
|
});
|
|
18065
18823
|
$("btnCloseHelp").addEventListener("click", () => $("helpOverlay").classList.add("hidden"));
|
|
18066
18824
|
/** Keyboard shortcuts filter: keeps the rows (and whole sections, by heading) that match every typed word. */
|
|
18067
|
-
|
|
18825
|
+
/** `only` (a row of the list) shows just that one: what Search opened. */
|
|
18826
|
+
function filterHelp(only) {
|
|
18827
|
+
const row = only instanceof HTMLElement ? only : null;
|
|
18068
18828
|
const words = $("helpFilter").value.toLowerCase().split(/\s+/).filter(Boolean);
|
|
18069
18829
|
let any = false;
|
|
18070
18830
|
for (const sec of $("helpKeys").querySelectorAll(".keys-sec")) {
|
|
@@ -18072,7 +18832,7 @@ function filterHelp() {
|
|
|
18072
18832
|
let shown = 0;
|
|
18073
18833
|
for (const tr of sec.querySelectorAll("tr")) {
|
|
18074
18834
|
const text = head + " " + tr.textContent.toLowerCase();
|
|
18075
|
-
const hit = words.every((w) => text.includes(w));
|
|
18835
|
+
const hit = row ? tr === row : words.every((w) => text.includes(w));
|
|
18076
18836
|
tr.classList.toggle("hidden", !hit);
|
|
18077
18837
|
if (hit) shown++;
|
|
18078
18838
|
}
|
|
@@ -18089,6 +18849,226 @@ $("helpFilter").addEventListener("keydown", (e) => {
|
|
|
18089
18849
|
if ($("helpFilter").value) { $("helpFilter").value = ""; filterHelp(); }
|
|
18090
18850
|
else $("helpOverlay").classList.add("hidden");
|
|
18091
18851
|
});
|
|
18852
|
+
/* ── Command search (Ctrl/Cmd+K) ──
|
|
18853
|
+
One box that finds what the editor can do: toolbar actions, panels and
|
|
18854
|
+
tabs, Settings, the selected clip's Inspector sections, media in the bin,
|
|
18855
|
+
clips on the timeline and the keyboard shortcuts. The items are read from
|
|
18856
|
+
the page each time it opens, so a new button or setting turns up without a
|
|
18857
|
+
list to keep; command-search.js ranks them. */
|
|
18858
|
+
const cmdk = { items: [], shown: [], active: 0, back: null };
|
|
18859
|
+
/** A control's name: its aria-label, else the start of its title, else its text. */
|
|
18860
|
+
function cmdkName(el) {
|
|
18861
|
+
const text = (el.textContent || "").replace(/\s+/g, " ").trim();
|
|
18862
|
+
const title = (el.getAttribute("aria-label") || el.title || "").replace(/\s+/g, " ").trim();
|
|
18863
|
+
const short = title.split(/ — |: |\. | \(/)[0];
|
|
18864
|
+
// icons and single symbols (▶ ⊡ ?) say little; a title does
|
|
18865
|
+
return /[a-z]{3}/i.test(text) && text.length <= 32 ? text.replace(/^[^\w(]+/, "") : short || text;
|
|
18866
|
+
}
|
|
18867
|
+
const cmdkShown = (el) => !el.disabled && !el.closest(".hidden") && el.getClientRects().length > 0;
|
|
18868
|
+
function cmdkFlash(el) {
|
|
18869
|
+
if (!el) return;
|
|
18870
|
+
el.scrollIntoView({ block: "nearest" });
|
|
18871
|
+
el.classList.remove("cmdk-flash");
|
|
18872
|
+
void el.offsetWidth;
|
|
18873
|
+
el.classList.add("cmdk-flash");
|
|
18874
|
+
}
|
|
18875
|
+
function cmdkCollect() {
|
|
18876
|
+
const items = [], seen = new Set();
|
|
18877
|
+
const add = (it) => {
|
|
18878
|
+
const key = it.key || it.group + "|" + it.label; // media and clips by id: two of one name both show
|
|
18879
|
+
if (!it.label || seen.has(key)) return;
|
|
18880
|
+
seen.add(key);
|
|
18881
|
+
items.push(it);
|
|
18882
|
+
};
|
|
18883
|
+
// panels and tabs
|
|
18884
|
+
// (the Color workspace and the Color side tab share a name: where each lives tells them apart)
|
|
18885
|
+
const panelWhere = { sideTabs: "Side panel", binTabs: "Bin", wsSwitch: "Workspace" };
|
|
18886
|
+
for (const b of document.querySelectorAll("#sideTabs [data-side], #binTabs [data-tab], #wsSwitch [data-ws]")) {
|
|
18887
|
+
const where = panelWhere[b.parentElement.id] || "", title = (b.title || "").split(/ — |: /)[0] === cmdkName(b) ? "" : b.title;
|
|
18888
|
+
add({ key: "Panel|" + b.parentElement.id + "|" + cmdkName(b), label: cmdkName(b), group: "Panel", hint: [where, title].filter(Boolean).join(" · "),
|
|
18889
|
+
keywords: ["tab", "show", "open", where], run: () => { if (b.closest("#binTabs")) cmdkShowBin(); b.click(); } });
|
|
18890
|
+
}
|
|
18891
|
+
// toolbar actions: every named button outside dialogs, menus and the Inspector (and the timeline's edit tools)
|
|
18892
|
+
const actions = [];
|
|
18893
|
+
for (const b of document.querySelectorAll("button[id], button[data-edit-tool]")) {
|
|
18894
|
+
if (b.closest(".overlay, .ctx-menu, .style-menu, #inspector, #sideTabs, #binTabs, #wsSwitch") || b.id === "btnSearch") continue;
|
|
18895
|
+
if (!cmdkShown(b)) continue;
|
|
18896
|
+
actions.push(b);
|
|
18897
|
+
}
|
|
18898
|
+
// two buttons of one name (the monitor's Fit and the timeline's) go by their titles instead
|
|
18899
|
+
const named = new Map();
|
|
18900
|
+
for (const b of actions) named.set(cmdkName(b), (named.get(cmdkName(b)) || 0) + 1);
|
|
18901
|
+
for (const b of actions) {
|
|
18902
|
+
const title = (b.title || "").replace(/\s+/g, " ").trim(), short = title.split(/ — |: |\. | \(/)[0];
|
|
18903
|
+
const label = named.get(cmdkName(b)) > 1 && short ? short : cmdkName(b);
|
|
18904
|
+
add({ key: "a:" + (b.id || "tool-" + b.dataset.editTool), label, group: "Action", hint: title && title !== label ? title : "", run: () => b.click() });
|
|
18905
|
+
}
|
|
18906
|
+
// the selected clip's Inspector sections
|
|
18907
|
+
for (const h of document.querySelectorAll("#inspector .insp-section > h3")) {
|
|
18908
|
+
const name = h.textContent.replace(/\s+/g, " ").trim();
|
|
18909
|
+
add({ label: name, group: "Inspector", keywords: ["inspector", "section", "clip"], run: () => {
|
|
18910
|
+
setSideTab("inspector");
|
|
18911
|
+
// the tab rebuilds the Inspector: find the section in the new one
|
|
18912
|
+
const live = [...document.querySelectorAll("#inspector .insp-section > h3")].find((x) => x.textContent.replace(/\s+/g, " ").trim() === name);
|
|
18913
|
+
if (live) cmdkFlash(live.closest(".insp-section"));
|
|
18914
|
+
} });
|
|
18915
|
+
}
|
|
18916
|
+
// Settings
|
|
18917
|
+
for (const row of document.querySelectorAll("#settingsDialog .settings-row")) {
|
|
18918
|
+
const name = row.querySelector(".settings-label")?.textContent.trim();
|
|
18919
|
+
const hint = row.querySelector(".settings-hint")?.textContent.trim() || "";
|
|
18920
|
+
add({ label: name, group: "Setting", hint, keywords: ["settings", "preference", "option"], run: () => { openSettings(); const inp = row.querySelector("input, select"); inp?.focus(); cmdkFlash(row); } });
|
|
18921
|
+
}
|
|
18922
|
+
// media in the bin, clips on the timeline
|
|
18923
|
+
for (const m of project.media || []) {
|
|
18924
|
+
// the bin folder it sits in tells two files of one name apart
|
|
18925
|
+
const folders = [];
|
|
18926
|
+
for (let f = m.folderId && getFolder(m.folderId), n = 0; f && n < 16; f = f.parentId && getFolder(f.parentId), n++) folders.unshift(f.name);
|
|
18927
|
+
add({ key: "m:" + m.id, label: m.name, group: "Media", hint: folders.length ? `${m.kind} · ${folders.join(" / ")}` : m.kind, keywords: [m.kind, ...(m.tags || [])], run: () => { cmdkShowBin(); revealInProject({ kind: m.kind, mediaId: m.id }); } });
|
|
18928
|
+
}
|
|
18929
|
+
for (const c of project.clips || []) {
|
|
18930
|
+
const name = c.kind === "text" ? (c.props?.text || "Title").split("\n")[0].slice(0, 60) : c.name || getMedia(c.mediaId)?.name || c.kind;
|
|
18931
|
+
add({ key: "c:" + c.id, label: name, group: "Clip", hint: `${c.track} · ${fmt(c.start)}`, keywords: [c.kind, c.track], run: () => {
|
|
18932
|
+
// where the clip is now (an edit may have arrived while Search was open)
|
|
18933
|
+
const cur = project.clips.find((x) => x.id === c.id);
|
|
18934
|
+
if (!cur) { toast("That clip isn't on the timeline any more"); return; }
|
|
18935
|
+
if (isSourceMode()) setMonitorMode("program");
|
|
18936
|
+
selectClip(cur.id);
|
|
18937
|
+
setTime(cur.start);
|
|
18938
|
+
revealTime(cur.start);
|
|
18939
|
+
} });
|
|
18940
|
+
}
|
|
18941
|
+
// keyboard shortcuts: Enter opens the list, filtered to that one
|
|
18942
|
+
for (const tr of document.querySelectorAll("#helpKeys tr")) {
|
|
18943
|
+
const cells = tr.querySelectorAll("td");
|
|
18944
|
+
if (cells.length < 2) continue;
|
|
18945
|
+
const keys = cells[0].textContent.replace(/\s+/g, " ").trim(), what = cells[1].textContent.replace(/\s+/g, " ").trim();
|
|
18946
|
+
const label = what.split(/ — |; |\. /)[0].slice(0, 70);
|
|
18947
|
+
const section = tr.closest(".keys-sec")?.querySelector("h3")?.textContent || "";
|
|
18948
|
+
add({ label, group: "Shortcut", hint: keys, keys: [keys], keywords: [section, keys, what], run: () => {
|
|
18949
|
+
$("helpOverlay").classList.remove("hidden");
|
|
18950
|
+
// the row itself, not every row its first words also start
|
|
18951
|
+
$("helpFilter").value = label;
|
|
18952
|
+
filterHelp(tr);
|
|
18953
|
+
$("helpFilter").focus();
|
|
18954
|
+
} });
|
|
18955
|
+
}
|
|
18956
|
+
return items;
|
|
18957
|
+
}
|
|
18958
|
+
function cmdkRender() {
|
|
18959
|
+
const list = $("cmdkList");
|
|
18960
|
+
cmdk.shown = FableCutSearch.rank($("cmdkInput").value, cmdk.items, 60);
|
|
18961
|
+
cmdk.active = Math.min(cmdk.active, Math.max(0, cmdk.shown.length - 1));
|
|
18962
|
+
list.innerHTML = cmdk.shown.length
|
|
18963
|
+
? cmdk.shown.map((it, i) => `<li class="cmdk-item${i === cmdk.active ? " active" : ""}" role="option" id="cmdk-${i}" data-i="${i}" aria-selected="${i === cmdk.active}">` +
|
|
18964
|
+
`<span class="cmdk-label">${escapeHtml(it.label)}</span>${it.hint ? `<span class="cmdk-hint">${escapeHtml(it.hint)}</span>` : ""}` +
|
|
18965
|
+
`<span class="cmdk-group">${it.group}</span></li>`).join("")
|
|
18966
|
+
: `<li class="cmdk-empty">Nothing matches — try another word.</li>`;
|
|
18967
|
+
$("cmdkInput").setAttribute("aria-activedescendant", cmdk.shown.length ? "cmdk-" + cmdk.active : "");
|
|
18968
|
+
list.querySelector(".cmdk-item.active")?.scrollIntoView({ block: "nearest" });
|
|
18969
|
+
}
|
|
18970
|
+
function openCmdk() {
|
|
18971
|
+
if (state.exporting) return;
|
|
18972
|
+
cmdk.pid = runtime.projectId; // results belong to this project
|
|
18973
|
+
cmdk.back = document.activeElement;
|
|
18974
|
+
cmdk.items = cmdkCollect();
|
|
18975
|
+
cmdk.active = 0;
|
|
18976
|
+
$("cmdkInput").value = "";
|
|
18977
|
+
$("cmdkOverlay").classList.remove("hidden");
|
|
18978
|
+
cmdkRender();
|
|
18979
|
+
$("cmdkInput").focus();
|
|
18980
|
+
}
|
|
18981
|
+
/** Another dialog is open over the editor (Export setup finishing its load, …). */
|
|
18982
|
+
const cmdkOtherOverlay = () => [...document.querySelectorAll(".overlay")].some((o) => o.id !== "cmdkOverlay" && !o.classList.contains("hidden"));
|
|
18983
|
+
/** The Color workspace hides the bin: a result that shows the bin goes back to Edit first. */
|
|
18984
|
+
function cmdkShowBin() {
|
|
18985
|
+
if (colorState.ws === "color") setWorkspace("edit");
|
|
18986
|
+
}
|
|
18987
|
+
function closeCmdk(refocus = true) {
|
|
18988
|
+
$("cmdkOverlay").classList.add("hidden");
|
|
18989
|
+
if (refocus && cmdk.back && document.contains(cmdk.back)) cmdk.back.focus();
|
|
18990
|
+
cmdk.back = null;
|
|
18991
|
+
}
|
|
18992
|
+
function runCmdk(i) {
|
|
18993
|
+
const it = cmdk.shown[i];
|
|
18994
|
+
if (!it) return;
|
|
18995
|
+
const back = cmdk.back, pid = cmdk.pid;
|
|
18996
|
+
closeCmdk(false);
|
|
18997
|
+
if (pid !== runtime.projectId) { toast("Another project opened — search again"); return; }
|
|
18998
|
+
// after the box has gone, so the action sees the editor as it was
|
|
18999
|
+
setTimeout(() => {
|
|
19000
|
+
// an export (an agent's too) may have taken the timeline meanwhile
|
|
19001
|
+
if (state.exporting) { toast("Wait for the export to finish"); return; }
|
|
19002
|
+
if (pid !== runtime.projectId) { toast("Another project opened — search again"); return; }
|
|
19003
|
+
if (cmdkOtherOverlay()) return; // a dialog that opened meanwhile keeps the screen
|
|
19004
|
+
try { it.run(); } catch (e) { toast(String(e.message || e)); }
|
|
19005
|
+
// an action that puts focus nowhere hands it back to where it was before Search
|
|
19006
|
+
const a = document.activeElement;
|
|
19007
|
+
if ((!a || a === document.body || a === $("cmdkInput")) && back && document.contains(back)) back.focus();
|
|
19008
|
+
}, 0);
|
|
19009
|
+
}
|
|
19010
|
+
const cmdkOpen = () => !$("cmdkOverlay").classList.contains("hidden");
|
|
19011
|
+
$("btnSearch")?.addEventListener("click", openCmdk);
|
|
19012
|
+
$("cmdkInput").addEventListener("input", () => { cmdk.active = 0; cmdkRender(); });
|
|
19013
|
+
$("cmdkInput").addEventListener("keydown", (e) => {
|
|
19014
|
+
if (e.isComposing || e.keyCode === 229) return; // the IME is choosing a word
|
|
19015
|
+
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
|
|
19016
|
+
e.preventDefault();
|
|
19017
|
+
const n = cmdk.shown.length;
|
|
19018
|
+
if (n) cmdk.active = (cmdk.active + (e.key === "ArrowDown" ? 1 : n - 1)) % n;
|
|
19019
|
+
cmdkRender();
|
|
19020
|
+
} else if (e.key === "Enter") {
|
|
19021
|
+
e.preventDefault();
|
|
19022
|
+
runCmdk(cmdk.active);
|
|
19023
|
+
} else if (e.key === "Escape") {
|
|
19024
|
+
e.preventDefault();
|
|
19025
|
+
e.stopPropagation();
|
|
19026
|
+
if ($("cmdkInput").value) { $("cmdkInput").value = ""; cmdk.active = 0; cmdkRender(); }
|
|
19027
|
+
else closeCmdk();
|
|
19028
|
+
} else if (e.key === "Tab") e.preventDefault(); // the box is the dialog's only control
|
|
19029
|
+
});
|
|
19030
|
+
$("cmdkList").addEventListener("mousemove", (e) => {
|
|
19031
|
+
const li = e.target.closest(".cmdk-item");
|
|
19032
|
+
if (!li || +li.dataset.i === cmdk.active) return;
|
|
19033
|
+
cmdk.active = +li.dataset.i;
|
|
19034
|
+
cmdkRender();
|
|
19035
|
+
});
|
|
19036
|
+
$("cmdkList").addEventListener("click", (e) => {
|
|
19037
|
+
const li = e.target.closest(".cmdk-item");
|
|
19038
|
+
if (li) runCmdk(+li.dataset.i);
|
|
19039
|
+
});
|
|
19040
|
+
$("cmdkOverlay").addEventListener("mousedown", (e) => {
|
|
19041
|
+
if (e.target === $("cmdkOverlay")) closeCmdk();
|
|
19042
|
+
else if (e.target !== $("cmdkInput")) e.preventDefault(); // a click on the list or footer keeps the focus in the box
|
|
19043
|
+
});
|
|
19044
|
+
/* Ctrl/Cmd+K, before any field's own key handling (the bin's search stops its keys): one
|
|
19045
|
+
toggle per press. While Search is open, the editor's other shortcuts wait; the box keeps
|
|
19046
|
+
its own keys. */
|
|
19047
|
+
window.addEventListener("keydown", (e) => {
|
|
19048
|
+
const k = e.key;
|
|
19049
|
+
// e.code: the K key on any layout (a Cyrillic one reports "л")
|
|
19050
|
+
if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && (k === "k" || k === "K" || e.code === "KeyK")) {
|
|
19051
|
+
e.preventDefault();
|
|
19052
|
+
e.stopImmediatePropagation();
|
|
19053
|
+
if (e.repeat) return;
|
|
19054
|
+
// (focus stays with a dialog that opened over Search)
|
|
19055
|
+
if (cmdkOpen()) closeCmdk(!cmdkOtherOverlay());
|
|
19056
|
+
// another dialog keeps the keyboard until it closes
|
|
19057
|
+
else if (!cmdkOtherOverlay()) openCmdk();
|
|
19058
|
+
return;
|
|
19059
|
+
}
|
|
19060
|
+
if (!cmdkOpen()) return;
|
|
19061
|
+
// a dialog that opened meanwhile (Export setup finishing its load) takes the keyboard over
|
|
19062
|
+
if (cmdkOtherOverlay()) { closeCmdk(false); return; }
|
|
19063
|
+
if (e.target !== $("cmdkInput")) { e.stopImmediatePropagation(); return; }
|
|
19064
|
+
// Esc is Search's (before any picker or tool listening for it): clear the box, then close
|
|
19065
|
+
if (k === "Escape" && !e.isComposing) {
|
|
19066
|
+
e.preventDefault();
|
|
19067
|
+
e.stopImmediatePropagation();
|
|
19068
|
+
if ($("cmdkInput").value) { $("cmdkInput").value = ""; cmdk.active = 0; cmdkRender(); }
|
|
19069
|
+
else closeCmdk();
|
|
19070
|
+
}
|
|
19071
|
+
}, true);
|
|
18092
19072
|
function settingsFocusables() {
|
|
18093
19073
|
const root = $("settingsDialog");
|
|
18094
19074
|
if (!root) return [];
|
|
@@ -18111,6 +19091,8 @@ function onSettingsTabTrap(e) {
|
|
|
18111
19091
|
function openSettings() {
|
|
18112
19092
|
const cb = $("setLinkSelect");
|
|
18113
19093
|
if (cb) cb.checked = !!getSetting("linkSelect");
|
|
19094
|
+
const ask = $("setExportAsk");
|
|
19095
|
+
if (ask) ask.checked = getSetting("exportAsk") !== false;
|
|
18114
19096
|
const overlay = $("settingsOverlay");
|
|
18115
19097
|
overlay.classList.remove("hidden");
|
|
18116
19098
|
overlay.addEventListener("keydown", onSettingsTabTrap);
|
|
@@ -18128,6 +19110,7 @@ $("btnCloseSettings").addEventListener("click", closeSettings);
|
|
|
18128
19110
|
$("settingsOverlay").addEventListener("click", (e) => {
|
|
18129
19111
|
if (e.target === $("settingsOverlay")) closeSettings();
|
|
18130
19112
|
});
|
|
19113
|
+
$("setExportAsk")?.addEventListener("change", (e) => setSetting("exportAsk", !!e.target.checked));
|
|
18131
19114
|
$("setLinkSelect").addEventListener("change", (e) => {
|
|
18132
19115
|
setSetting("linkSelect", !!e.target.checked);
|
|
18133
19116
|
if (!getSetting("linkSelect")) {
|
|
@@ -18615,6 +19598,7 @@ els.exportFrameOverlay?.querySelector(".ef-handle")?.addEventListener("keydown",
|
|
|
18615
19598
|
|
|
18616
19599
|
window.addEventListener("keydown", (e) => {
|
|
18617
19600
|
const k = e.key;
|
|
19601
|
+
if (!$("cmdkOverlay").classList.contains("hidden")) return; // Search has the keyboard (its box handles its own keys)
|
|
18618
19602
|
if ((k === "Delete" || k === "Backspace") && !e.ctrlKey && !e.metaKey && !e.altKey) {
|
|
18619
19603
|
if (!isTypingTarget(document.activeElement) && clearFocusedTransition()) {
|
|
18620
19604
|
e.preventDefault();
|
|
@@ -18627,6 +19611,7 @@ window.addEventListener("keydown", (e) => {
|
|
|
18627
19611
|
if (!e.repeat && $("btnProjectsDash") && !$("btnProjectsDash").classList.contains("hidden")) saveVersionNow(); // holding the keys makes one
|
|
18628
19612
|
return;
|
|
18629
19613
|
}
|
|
19614
|
+
// (Ctrl/Cmd+K, the command search, is handled before this, by its own listener)
|
|
18630
19615
|
// Ctrl/Cmd+O: the Projects dashboard (where the editor server has projects)
|
|
18631
19616
|
if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && (k === "o" || k === "O") && $("btnProjectsDash") && !$("btnProjectsDash").classList.contains("hidden")) {
|
|
18632
19617
|
e.preventDefault();
|