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/beats.js ADDED
@@ -0,0 +1,458 @@
1
+ /* FableCut beats — the music's beat, and cuts that land on it. Zero
2
+ dependencies; loaded by the editor as a plain script (global
3
+ `FableCutBeats`) and required by the MCP server and analyze.js, so the
4
+ Inspector's Beats section, `fablecut_beats` and the reference analyzer hear
5
+ the same beats.
6
+
7
+ analyze: mono samples at SR → onset envelope → beats (onsets), BPM, a
8
+ loudness curve and the drop. grid: a steady beat (from the BPM and the
9
+ onsets' phase) that cuts snap to. Then, on a timeline: snapOps rolls
10
+ each cut to the nearest beat (nothing else moves), retimeOps lays a
11
+ track's clips back to back, `every` beats each. */
12
+ (function (root, factory) {
13
+ const api = factory();
14
+ if (typeof module === "object" && module.exports) module.exports = api;
15
+ else root.FableCutBeats = api;
16
+ })(typeof self !== "undefined" ? self : this, function () {
17
+ "use strict";
18
+
19
+ const SR = 22050; // analysis sample rate
20
+ const HOP = 512; // onset-envelope hop (~23 ms)
21
+ const WIN = 1024; // energy window
22
+ const EVERY = [1, 2, 4, 8, 16];
23
+ /** An onset is timed at the middle of the window its energy rise shows up in: about
24
+ * half a window after the hit. The grid takes it back, so cuts land on the hit itself. */
25
+ const ONSET_LAG = WIN / 2 / SR;
26
+ const EPS = 1e-6;
27
+ const MIN_DUR = 0.05; // edit-ops.js: the shortest a clip may be
28
+
29
+ /** Mono samples at another rate → SR (box average when shrinking, linear otherwise). */
30
+ function resample(x, rate) {
31
+ if (!(rate > 0)) throw new Error("sample rate must be > 0");
32
+ if (rate === SR) return x instanceof Float32Array ? x : Float32Array.from(x);
33
+ const n = Math.floor(x.length * SR / rate), out = new Float32Array(n), r = rate / SR;
34
+ if (r > 1) {
35
+ for (let i = 0; i < n; i++) {
36
+ const a = Math.floor(i * r), b = Math.max(a + 1, Math.min(x.length, Math.floor((i + 1) * r)));
37
+ let s = 0;
38
+ for (let j = a; j < b; j++) s += x[j];
39
+ out[i] = s / (b - a);
40
+ }
41
+ } else {
42
+ for (let i = 0; i < n; i++) {
43
+ const p = i * r, a = Math.floor(p), f = p - a;
44
+ out[i] = (x[a] || 0) * (1 - f) + (x[Math.min(x.length - 1, a + 1)] || 0) * f;
45
+ }
46
+ }
47
+ return out;
48
+ }
49
+
50
+ /** Several channels → one (their mean). */
51
+ function mono(channels) {
52
+ if (channels.length === 1) return channels[0];
53
+ const n = Math.min(...channels.map((c) => c.length)), out = new Float32Array(n);
54
+ for (const c of channels) for (let i = 0; i < n; i++) out[i] += c[i];
55
+ for (let i = 0; i < n; i++) out[i] /= channels.length;
56
+ return out;
57
+ }
58
+
59
+ /** Beats, BPM, energy curve and drop of mono samples at SR (seconds from the
60
+ * first sample). `scale` turns integer PCM into −1…1 (1 / 32768 for s16). */
61
+ function analyze(pcm, { scale = 1 } = {}) {
62
+ const nFrames = Math.max(0, Math.floor((pcm.length - WIN) / HOP));
63
+ if (nFrames < 20) return { beats: [], bpm: null, energy: { step: 0.5, values: [] }, drop: null };
64
+
65
+ // frame energies
66
+ const E = new Float64Array(nFrames);
67
+ for (let i = 0; i < nFrames; i++) {
68
+ let s = 0;
69
+ const o = i * HOP;
70
+ for (let j = 0; j < WIN; j++) { const x = pcm[o + j] * scale; s += x * x; }
71
+ E[i] = s / WIN;
72
+ }
73
+
74
+ // onset envelope: energy rise vs. trailing average
75
+ const O = new Float64Array(nFrames);
76
+ for (let i = 1; i < nFrames; i++) {
77
+ let m = 0, k = 0;
78
+ for (let j = Math.max(0, i - 8); j < i; j++) { m += E[j]; k++; }
79
+ O[i] = Math.max(0, E[i] - m / k);
80
+ }
81
+ let oMax = 0;
82
+ for (let i = 0; i < nFrames; i++) if (O[i] > oMax) oMax = O[i];
83
+ if (oMax > 0) for (let i = 0; i < nFrames; i++) O[i] /= oMax;
84
+
85
+ // peak-pick beats: local max, above an adaptive floor, min 0.25 s apart
86
+ const frameT = (i) => Math.round(((i * HOP + WIN / 2) / SR) * 1000) / 1000;
87
+ const minGap = Math.round(0.25 * SR / HOP);
88
+ const halfWin = Math.round(1.0 * SR / HOP);
89
+ const beats = [];
90
+ let last = -minGap;
91
+ for (let i = 3; i < nFrames - 3; i++) {
92
+ if (O[i] < 0.05) continue;
93
+ let isMax = true;
94
+ for (let j = -3; j <= 3; j++) if (O[i + j] > O[i]) { isMax = false; break; }
95
+ if (!isMax) continue;
96
+ let m = 0, k = 0;
97
+ for (let j = Math.max(0, i - halfWin); j < Math.min(nFrames, i + halfWin); j++) { m += O[j]; k++; }
98
+ if (O[i] < (m / k) * 1.5) continue;
99
+ if (i - last < minGap) continue;
100
+ beats.push(frameT(i));
101
+ last = i;
102
+ }
103
+
104
+ // BPM: autocorrelation of the onset envelope over 60–200 BPM lags,
105
+ // with a mild prior toward ~120; fold octaves into 70–180.
106
+ let bpm = null;
107
+ const lagMin = Math.round(60 / 200 * SR / HOP), lagMax = Math.round(60 / 60 * SR / HOP);
108
+ let best = 0, bestLag = 0;
109
+ for (let lag = lagMin; lag <= Math.min(lagMax, nFrames - 1); lag++) {
110
+ let s = 0;
111
+ for (let i = 0; i + lag < nFrames; i++) s += O[i] * O[i + lag];
112
+ const cand = 60 / (lag * HOP / SR);
113
+ const w = Math.exp(-0.5 * Math.pow(Math.log2(cand / 120) / 1.0, 2));
114
+ if (s * w > best) { best = s * w; bestLag = lag; }
115
+ }
116
+ if (bestLag) {
117
+ bpm = 60 / (bestLag * HOP / SR);
118
+ while (bpm < 70) bpm *= 2;
119
+ while (bpm > 180) bpm /= 2;
120
+ // refine: if the picked beats are regular, the median inter-beat interval
121
+ // is a much finer tempo estimate than the autocorrelation lag grid
122
+ if (beats.length >= 6) {
123
+ const gaps = beats.slice(1).map((t, i) => t - beats[i]).sort((a, b) => a - b);
124
+ const med = gaps[Math.floor(gaps.length / 2)];
125
+ const spread = gaps[Math.floor(gaps.length * 0.85)] - gaps[Math.floor(gaps.length * 0.15)];
126
+ if (med > 0 && spread < med * 0.15) {
127
+ // full span / count averages out the hop-grid quantization of each beat
128
+ let refined = 60 / ((beats[beats.length - 1] - beats[0]) / (beats.length - 1));
129
+ while (refined < 70) refined *= 2;
130
+ while (refined > 180) refined /= 2;
131
+ if (Math.abs(refined - bpm) / bpm < 0.15) bpm = refined;
132
+ }
133
+ }
134
+ bpm = Math.round(bpm * 10) / 10;
135
+ }
136
+
137
+ // loudness curve, one value per 0.5 s, normalized 0–100
138
+ const step = 0.5;
139
+ const perStep = Math.round(step * SR / HOP);
140
+ const values = [];
141
+ for (let i = 0; i < nFrames; i += perStep) {
142
+ let s = 0, k = 0;
143
+ for (let j = i; j < Math.min(nFrames, i + perStep); j++) { s += Math.sqrt(E[j]); k++; }
144
+ values.push(k ? s / k : 0);
145
+ }
146
+ const vMax = Math.max(...values, 1e-9);
147
+ const energy = values.map((v) => Math.round(v / vMax * 100));
148
+
149
+ // the drop: biggest sustained energy rise (skip the very start)
150
+ let drop = null, bestRise = 0;
151
+ for (let i = 2; i < energy.length - 1; i++) {
152
+ const before = (energy[i - 2] + energy[i - 1]) / 2;
153
+ const after = (energy[i] + energy[Math.min(i + 1, energy.length - 1)]) / 2;
154
+ if (after - before > bestRise && after > 55) { bestRise = after - before; drop = Math.round(i * step * 10) / 10; }
155
+ }
156
+
157
+ return { beats, bpm, energy: { step, values: energy }, drop };
158
+ }
159
+
160
+ /** A steady beat from `from` to `to` (seconds, same clock as `beats`): the BPM's
161
+ * period, phased to where the onsets fall (their circular mean). Without a
162
+ * tempo, or with too few onsets to phase it, the onsets themselves. */
163
+ function grid(beats, bpm, from, to) {
164
+ const inside = (t) => t >= from - EPS && t <= to + EPS;
165
+ if (!(bpm > 0) || beats.length < 4) return beats.filter(inside);
166
+ let p = 60 / bpm;
167
+ let sx = 0, sy = 0;
168
+ for (const t of beats) { const a = 2 * Math.PI * ((t % p) / p); sx += Math.cos(a); sy += Math.sin(a); }
169
+ let phase = (Math.atan2(sy, sx) / (2 * Math.PI)) * p;
170
+ // refine period and phase together: a least-squares line through the onsets that sit
171
+ // near a grid beat (beat index → time), so a slightly-off tempo doesn't drift over a song
172
+ for (let pass = 0; pass < 3; pass++) {
173
+ let n = 0, sk = 0, st = 0, skk = 0, skt = 0;
174
+ for (const t of beats) {
175
+ const k = Math.round((t - phase) / p);
176
+ if (Math.abs(t - (phase + k * p)) > p / 4) continue;
177
+ n++; sk += k; st += t; skk += k * k; skt += k * t;
178
+ }
179
+ const den = n * skk - sk * sk;
180
+ if (n < 4 || !den) break;
181
+ const np = (n * skt - sk * st) / den;
182
+ if (!(np > p * 0.97 && np < p * 1.03)) break; // a fit that changes the tempo isn't a refinement
183
+ p = np; phase = (st - p * sk) / n;
184
+ }
185
+ phase = (((phase - ONSET_LAG) % p) + p) % p;
186
+ const out = [];
187
+ for (let k = Math.ceil((from - phase) / p - EPS); ; k++) {
188
+ const t = phase + k * p;
189
+ if (t > to + EPS) break;
190
+ if (t >= from - EPS) out.push(Math.round(t * 1000) / 1000);
191
+ }
192
+ return out;
193
+ }
194
+
195
+ /** Seconds in a clip's source (from its `in`) → timeline seconds, at its steady speed; inside the clip. */
196
+ function toTimeline(times, clip) {
197
+ const sp = Math.min(8, Math.max(0.1, +clip.props?.speed || 1));
198
+ const end = clip.start + clip.duration;
199
+ return times.map((t) => Math.round((clip.start + (t - (clip.in || 0)) / sp) * 1000) / 1000)
200
+ .filter((t) => t >= clip.start - EPS && t <= end + EPS);
201
+ }
202
+
203
+ /** What a clip's timed data becomes when its length changes at the tail (as edit-ops trims do):
204
+ * keyframes past the new end dropped, transitions no longer than the clip. Only changed keys;
205
+ * null removes the keyframes. */
206
+ function fitTimed(c, dur) {
207
+ const set = {};
208
+ if (c.keyframes && typeof c.keyframes === "object") {
209
+ const out = {};
210
+ let changed = false;
211
+ for (const [k, arr] of Object.entries(c.keyframes)) {
212
+ if (!Array.isArray(arr)) { out[k] = arr; continue; }
213
+ const keep = arr.filter((kf) => !(kf.t > dur + 1e-3));
214
+ if (keep.length !== arr.length) changed = true;
215
+ if (keep.length) out[k] = keep;
216
+ }
217
+ if (changed) set.keyframes = Object.keys(out).length ? out : null;
218
+ }
219
+ for (const k of ["transitionIn", "transitionOut"])
220
+ if (c[k] && c[k].duration > dur) set[k] = { ...c[k], duration: Math.round(dur * 1000) / 1000 };
221
+ return set;
222
+ }
223
+
224
+ /** A clip whose speed is keyframed: its sound doesn't keep the music's time on the timeline. */
225
+ const ramped = (c) => Array.isArray(c.keyframes?.speed) && c.keyframes.speed.length > 0;
226
+
227
+ function every(v) {
228
+ const n = v == null ? 2 : +v;
229
+ if (!EVERY.includes(n)) throw new Error(`every must be one of ${EVERY.join(", ")} (beats per shot)`);
230
+ return n;
231
+ }
232
+
233
+ /** The nearest grid time to t, or null when the grid is empty. */
234
+ function nearest(g, t) {
235
+ let best = null;
236
+ for (const b of g) if (best == null || Math.abs(b - t) < Math.abs(best - t)) best = b;
237
+ return best;
238
+ }
239
+
240
+ /** The cuts on `tracks` (where one clip ends and the next on the same track starts),
241
+ * inside the beat grid's span: [{t, a, b}] with a the clip before, b the one after. */
242
+ function cuts(clips, tracks, g, fps) {
243
+ const tol = 0.5 / (fps || 30);
244
+ const touch = 1e-3; // edit-ops.js TRIM_EPS: what a roll counts as clips that meet
245
+ const out = [];
246
+ for (const tr of tracks) {
247
+ const on = clips.filter((c) => c.track === tr).sort((x, y) => x.start - y.start);
248
+ for (let i = 0; i + 1 < on.length; i++) {
249
+ const a = on[i], b = on[i + 1], t = a.start + a.duration;
250
+ if (Math.abs(b.start - t) > touch) continue; // a gap or an overlap (even a hair's): not a cut a roll can move
251
+ if (!g.length || t < g[0] - tol || t > g[g.length - 1] + tol) continue;
252
+ out.push({ t, a, b });
253
+ }
254
+ }
255
+ return out;
256
+ }
257
+
258
+ /** Roll each cut on `tracks` to the nearest beat when it is within `maxShift` seconds
259
+ * (default: half a beat) and off by more than half a frame: [{op:"roll", id, side, delta}]
260
+ * — patch ops for project-ops.js (and EDIT.rollEdit in the editor). The rolls touch
261
+ * different cuts, so their order doesn't matter. A roll needs spare footage: earlier,
262
+ * the clip after the cut shows more of its head; later, the clip before shows more of
263
+ * its tail. `spare(c)` gives {head, tail} in timeline seconds (default: unlimited);
264
+ * a cut that can't reach its beat is left where it is (`blocked` counts them). */
265
+ function snapOps(clips, tracks, g, { fps = 30, maxShift, bpm, spare = () => ({ head: Infinity, tail: Infinity }), blocked } = {}) {
266
+ const beat = bpm > 0 ? 60 / bpm : g.length > 1 ? (g[g.length - 1] - g[0]) / (g.length - 1) : 0.5;
267
+ const limit = maxShift == null ? beat / 2 : +maxShift;
268
+ if (!(limit > 0)) throw new Error("maxShift must be > 0 seconds");
269
+ const half = 0.5 / fps, ops = [];
270
+ // the rolls are planned one after another, each on the clips as the earlier ones left them:
271
+ // two cuts beside one short clip can't both take its time
272
+ const now = new Map();
273
+ const cur = (c) => now.get(c.id) || { ...c };
274
+ const speed = (c) => Math.min(8, Math.max(0.1, +c.props?.speed || 1));
275
+ for (const { t, a, b } of cuts(clips, tracks, g, fps).sort((x, y) => x.t - y.t)) {
276
+ const to = nearest(g, Math.round(t * fps) / fps);
277
+ if (to == null) continue;
278
+ const snapped = Math.round(to * fps) / fps, delta = snapped - t;
279
+ if (Math.abs(delta) <= half || Math.abs(delta) > limit + half) continue;
280
+ const A = cur(a), B = cur(b);
281
+ const room = delta < 0 ? spare(B).head : spare(A).tail;
282
+ const keeps = (delta < 0 ? A.duration + delta : B.duration - delta) >= MIN_DUR - 1e-9;
283
+ if (room + 1e-6 < Math.abs(delta) || !keeps) { if (blocked) blocked.n++; continue; }
284
+ now.set(a.id, { ...A, duration: A.duration + delta });
285
+ now.set(b.id, { ...B, start: B.start + delta, in: (B.in || 0) + delta * speed(B), duration: B.duration - delta });
286
+ ops.push({ op: "roll", id: a.id, side: "out", delta: Math.round(delta * 1e6) / 1e6 });
287
+ }
288
+ return ops;
289
+ }
290
+
291
+ /** Lay the clips on `track` that start at or after `from` back to back on the beat:
292
+ * each takes `n` beats of the grid (fewer when its source runs out, at least one),
293
+ * starting at the first beat at or after `from`. `mediaDur(clip)` is how many seconds
294
+ * of source a clip may use from its `in` (Infinity for pictures). Clips past the
295
+ * grid's end follow on at their own length. Returns {plan:[{id, start, duration, beats?}]
296
+ * (beats: how many it was given; none for the ones past the grid),
297
+ * short:[ids that got fewer beats], skipped:[ids too short for one beat]}; partners
298
+ * (linked stems) are the caller's to move with their picture. */
299
+ function retimePlan(clips, track, g, { n = 2, from = 0, fps = 30, mediaDur = () => Infinity } = {}) {
300
+ const snap = (t) => Math.round(t * fps) / fps;
301
+ const on = clips.filter((c) => c.track === track && c.start >= from - 0.5 / fps).sort((x, y) => x.start - y.start);
302
+ const beats = g.filter((t) => t >= from - EPS).map(snap);
303
+ const plan = [], short = [], skipped = [];
304
+ let k = 0, at = beats.length ? beats[0] : snap(from);
305
+ for (const c of on) {
306
+ const sp = Math.min(8, Math.max(0.1, +c.props?.speed || 1));
307
+ const room = mediaDur(c) / sp; // timeline seconds of source left from its in
308
+ if (k < beats.length - 1) {
309
+ let m = Math.min(n, beats.length - 1 - k);
310
+ while (m > 0 && beats[k + m] - beats[k] > room + 1e-3) m--;
311
+ if (m === 0) { skipped.push(c.id); continue; }
312
+ if (m < n && k + n <= beats.length - 1) short.push(c.id);
313
+ plan.push({ id: c.id, start: beats[k], duration: Math.round((beats[k + m] - beats[k]) * 1e6) / 1e6, beats: m });
314
+ k += m;
315
+ at = beats[k];
316
+ } else {
317
+ plan.push({ id: c.id, start: at, duration: c.duration });
318
+ at = snap(at + c.duration);
319
+ }
320
+ }
321
+ return { plan, short, skipped };
322
+ }
323
+
324
+ /* ── On a project: what fablecut_beats (and Studio's relay) does with an analysis ── */
325
+
326
+ const DEFAULT_VIDEO = ["V3", "V2", "V1"];
327
+ const fmt = (s) => `${Math.floor(s / 60)}:${(s % 60).toFixed(2).padStart(5, "0")}`;
328
+
329
+ /** Ids of clips that may not be edited: their own lock, a locked lane, or a linked partner of one. */
330
+ function lockedIds(doc) {
331
+ const lanes = new Set(Array.isArray(doc.lockedTracks) ? doc.lockedTracks : []);
332
+ const own = (c) => c.locked === true || lanes.has(c.track);
333
+ const groups = new Set(doc.clips.filter((c) => c.linkGroup && own(c)).map((c) => c.linkGroup));
334
+ return new Set(doc.clips.filter((c) => own(c) || (c.linkGroup && groups.has(c.linkGroup))).map((c) => c.id));
335
+ }
336
+ /** Video lanes, bottom (V1) first. */
337
+ function videoTracks(doc) {
338
+ const ids = Array.isArray(doc.tracks) && doc.tracks.length ? doc.tracks.filter((t) => t.kind === "video").map((t) => t.id) : DEFAULT_VIDEO;
339
+ return ids.slice().sort((a, b) => (+a.slice(1) || 0) - (+b.slice(1) || 0));
340
+ }
341
+
342
+ /** The beat on the timeline under a music clip, and the ops for what `o` asks:
343
+ * markers (a cyan marker on every beat), snap (roll cuts to the beat) and retime
344
+ * ({track?, every?, from?}: lay a track's clips on the beat). `a` is analyze()'s
345
+ * result with its times in the file's seconds (beats + the clip's in point).
346
+ * Throws on anything it can't do safely; nothing is half done. */
347
+ function plan(doc, clip, a, o = {}) {
348
+ if (!clip || (clip.kind !== "audio" && clip.kind !== "video")) throw new Error("the music must be an audio or video clip");
349
+ if (ramped(clip)) throw new Error(`clip ${clip.id} has a speed ramp — beats follow music playing at a steady speed`);
350
+ const fps = doc.fps || 30, force = o.force === true;
351
+ const sp = Math.min(8, Math.max(0.1, +clip.props?.speed || 1));
352
+ const src0 = clip.in || 0, src1 = src0 + clip.duration * sp;
353
+ const g = toTimeline(grid(a.beats, a.bpm, src0, src1), clip);
354
+ const drop = a.drop != null && a.drop >= src0 && a.drop <= src1 ? toTimeline([a.drop], clip)[0] : null;
355
+ const out = { clip: clip.id, bpm: a.bpm ? Math.round(a.bpm * sp * 10) / 10 : null, grid: g, drop, ops: [], done: [] };
356
+ if (!g.length) return out;
357
+ const locked = force ? new Set() : lockedIds(doc);
358
+ const steady = (c) => !ramped(c);
359
+ const media = new Map((doc.media || []).map((m) => [m.id, m]));
360
+ const timed = (c) => (c.kind === "video" || c.kind === "audio") && media.get(c.mediaId)?.duration > 0;
361
+ const speedOf = (c) => Math.min(8, Math.max(0.1, +c.props?.speed || 1));
362
+ /** source seconds a clip may still use from its in point (Infinity for pictures and titles) */
363
+ const mediaDur = (c) => timed(c) ? media.get(c.mediaId).duration - (c.in || 0) : Infinity;
364
+ /** timeline seconds of footage before the clip's head and after its tail — the tightest of
365
+ * its linked group, which a roll moves together (a stem may sit on a shorter file) */
366
+ const own = (c) => timed(c)
367
+ ? { head: (c.in || 0) / speedOf(c), tail: Math.max(0, mediaDur(c) - c.duration * speedOf(c)) / speedOf(c) }
368
+ : { head: Infinity, tail: Infinity };
369
+ const spare = (c) => {
370
+ const group = c.linkGroup ? doc.clips.filter((x) => x.linkGroup === c.linkGroup && x.id !== c.id).concat([c]) : [c];
371
+ // c may carry an earlier roll's timing (snapOps); its partners moved by the same amount
372
+ const shift = (x) => x.id === c.id ? c : { ...x, in: (x.in || 0) + ((c.in || 0) - (doc.clips.find((y) => y.id === c.id)?.in || 0)) * speedOf(x) / speedOf(c),
373
+ duration: c.duration };
374
+ return group.map((x) => own(shift(x))).reduce((m, r) => ({ head: Math.min(m.head, r.head), tail: Math.min(m.tail, r.tail) }), { head: Infinity, tail: Infinity });
375
+ };
376
+
377
+ if (o.markers) {
378
+ const have = doc.markers || [];
379
+ const free = g.filter((t) => !have.some((m) => Math.abs(t - m.t) < 0.01));
380
+ const add = free.slice(0, 1000).map((t) => ({ t, color: "cyan" }));
381
+ out.ops.push({ op: "setProject", set: { markers: have.concat(add).sort((x, y) => x.t - y.t) } });
382
+ out.done.push(`marked ${add.length} beat${add.length === 1 ? "" : "s"} (cyan markers)` +
383
+ (free.length > add.length ? ` — the first ${add.length}` : "") + (g.length > free.length ? ` (${g.length - free.length} already had a marker)` : ""));
384
+ }
385
+
386
+ if (o.snap) {
387
+ const s = typeof o.snap === "object" ? o.snap : {};
388
+ const untargeted = new Set(Array.isArray(doc.untargetedTracks) ? doc.untargetedTracks : []);
389
+ const tracks = Array.isArray(s.tracks) && s.tracks.length ? s.tracks.map(String)
390
+ : videoTracks(doc).filter((t) => !untargeted.has(t));
391
+ const clips = doc.clips.filter((c) => c.id !== clip.id && steady(c));
392
+ const blocked = { n: 0 };
393
+ const all = snapOps(clips, tracks, g, { fps, bpm: out.bpm, maxShift: s.maxShift, spare, blocked });
394
+ const byId = new Map(doc.clips.map((c) => [c.id, c]));
395
+ const next = (id) => { const c = byId.get(id); return clips.find((x) => x.track === c.track && Math.abs(x.start - (c.start + c.duration)) < 0.5 / fps); };
396
+ const ok = all.filter((op) => !locked.has(op.id) && !locked.has(next(op.id)?.id));
397
+ for (const op of ok) out.ops.push(force ? { ...op, force: true } : op);
398
+ const near = cuts(clips, tracks, g, fps).length;
399
+ out.done.push(`snapped ${ok.length} of ${near} cut${near === 1 ? "" : "s"} on ${tracks.join(", ")} to the beat` +
400
+ (all.length > ok.length ? ` (${all.length - ok.length} beside locked clips left alone)` : "") +
401
+ (blocked.n ? ` (${blocked.n} without spare footage to reach the beat)` : "") +
402
+ (near - all.length - blocked.n > 0 ? ` (${near - all.length - blocked.n} already on a beat or more than ${s.maxShift ?? "half a beat"}${s.maxShift != null ? " s" : ""} away)` : ""));
403
+ }
404
+
405
+ if (o.retime) {
406
+ const r = typeof o.retime === "object" ? o.retime : {};
407
+ const n = every(r.every ?? o.every);
408
+ const lanes = videoTracks(doc);
409
+ const track = r.track != null ? String(r.track) : lanes.find((t) => doc.clips.some((c) => c.track === t)) || "V1";
410
+ const from = r.from != null ? +r.from : clip.start;
411
+ if (!Number.isFinite(from)) throw new Error("retime.from must be a time in seconds");
412
+ const music = (c) => c.id === clip.id || (clip.linkGroup && c.linkGroup === clip.linkGroup);
413
+ const rest = doc.clips.filter((c) => !music(c));
414
+ const on = rest.filter((c) => c.track === track && c.start >= from - 0.5 / fps);
415
+ if (!on.length) throw new Error(`no clips on ${track} from ${fmt(from)} — nothing to re-cut`);
416
+ const bad = on.filter((c) => locked.has(c.id));
417
+ if (bad.length) throw new Error(`${bad.map((c) => c.id).join(", ")} ${bad.length === 1 ? "is" : "are"} locked — unlock, or pass force:true if the user asked`);
418
+ const rampedOnes = on.filter(ramped);
419
+ if (rampedOnes.length) throw new Error(`${rampedOnes.map((c) => c.id).join(", ")} ${rampedOnes.length === 1 ? "has" : "have"} a speed ramp — re-cutting needs clips at a steady speed`);
420
+ // a clip's linked stems take its new length too: the tightest of the group sets how long it can be
421
+ const groupDur = (c) => {
422
+ const group = c.linkGroup ? rest.filter((x) => x.linkGroup === c.linkGroup) : [c];
423
+ return Math.min(...group.map((x) => mediaDur(x) / speedOf(x))) * speedOf(c);
424
+ };
425
+ const p = retimePlan(rest, track, g, { n, from, fps, mediaDur: groupDur });
426
+ if (p.skipped.length) throw new Error(`${p.skipped.join(", ")} ${p.skipped.length === 1 ? "has" : "have"} less than one beat of footage ` +
427
+ "left after the in point — slip it earlier, shorten its in point, or take it off this track; nothing re-cut");
428
+ const partners = (c) => c.linkGroup ? doc.clips.filter((x) => x.linkGroup === c.linkGroup && x.id !== c.id) : [];
429
+ const byId = new Map(doc.clips.map((c) => [c.id, c]));
430
+ for (const q of p.plan) {
431
+ for (const c of [byId.get(q.id), ...partners(byId.get(q.id))]) {
432
+ const op = { op: "updateClip", id: c.id, set: { start: q.start, duration: q.duration, ...fitTimed(c, q.duration) } };
433
+ out.ops.push(force ? { ...op, force: true } : op);
434
+ }
435
+ }
436
+ const onBeat = p.plan.filter((q) => q.beats).length;
437
+ out.done.push(`re-cut ${onBeat} clip${onBeat === 1 ? "" : "s"} on ${track} to ${n} beat${n === 1 ? "" : "s"} each from ${fmt(p.plan[0]?.start ?? from)}` +
438
+ (p.short.length ? ` (${p.short.join(", ")} ran out of footage: fewer beats)` : "") +
439
+ (p.plan.length > onBeat ? ` (${p.plan.length - onBeat} past the music kept their length)` : ""));
440
+ out.retime = { track, n, plan: p.plan };
441
+ }
442
+ return out;
443
+ }
444
+
445
+ /** The answer's text for a plan. */
446
+ function describe(r, { applied = false, limit = 48 } = {}) {
447
+ if (!r.grid.length) return `No steady beat found in clip ${r.clip} — it may be too quiet, too short or have no clear rhythm. Nothing changed.`;
448
+ const per = r.grid.length > 1 ? (r.grid[r.grid.length - 1] - r.grid[0]) / (r.grid.length - 1) : 0;
449
+ const lines = [`Beat of ${r.clip}: ${r.bpm != null ? r.bpm + " BPM, " : ""}${r.grid.length} beats from ${fmt(r.grid[0])} to ` +
450
+ `${fmt(r.grid[r.grid.length - 1])} (one every ${per.toFixed(3)} s)` + (r.drop != null ? `; the drop at ${fmt(r.drop)}` : "") + ".",
451
+ `Beats (timeline): ${r.grid.slice(0, limit).map((t) => t.toFixed(3)).join(" ")}${r.grid.length > limit ? ` … +${r.grid.length - limit} more` : ""}`];
452
+ if (r.done.length) lines.push((applied ? "Done: " : "Would do: ") + r.done.join("; ") + ".");
453
+ else lines.push("Nothing changed: markers:true marks the beats, snap:true rolls the cuts onto them, retime:{track, every} re-cuts a track's clips to the beat.");
454
+ return lines.join("\n");
455
+ }
456
+
457
+ return { SR, HOP, WIN, EVERY, ONSET_LAG, MIN_DUR, fitTimed, lockedIds, videoTracks, plan, describe, resample, mono, analyze, grid, toTimeline, ramped, every, nearest, cuts, snapOps, retimePlan };
458
+ });
@@ -0,0 +1,79 @@
1
+ /* FableCut command search (Ctrl/Cmd+K) — how typed words find editor actions,
2
+ panels, settings, Inspector sections, media, clips and shortcuts. Zero
3
+ dependencies. Loaded by the editor as a plain script (global
4
+ `FableCutSearch`) and required by the tests; the editor builds the items
5
+ (app.js) and runs the one that is picked.
6
+
7
+ rank(query, items, limit?) → items that match, best first
8
+ item: {label, group?, keywords?, ...anything}
9
+ score(query, item) → a number, 0 = no match
10
+
11
+ Every typed word has to be found in the item's label, group or keywords:
12
+ at the start of a word (best), inside a word, or as letters in order
13
+ from the start of a word in the label ("rpdl" finds "Ripple delete",
14
+ weakest). Case, accents and punctuation don't matter; letters of any script
15
+ count ("猫" finds "猫.mp4"). A query of symbols only (";") matches items
16
+ whose `keys` hold it. An empty query matches everything, in the order given. */
17
+ (function (root, factory) {
18
+ const api = factory();
19
+ if (typeof module === "object" && module.exports) module.exports = api;
20
+ else root.FableCutSearch = api;
21
+ })(typeof self !== "undefined" ? self : this, function () {
22
+ "use strict";
23
+
24
+ const fold = (s) => String(s == null ? "" : s).toLowerCase().normalize("NFD")
25
+ // accents on Latin, Greek and Cyrillic letters go (Café = cafe); other scripts' marks are
26
+ // part of the letter (दिन is not दीन), so they stay
27
+ .replace(/(\p{Script=Latin}|\p{Script=Greek}|\p{Script=Cyrillic})\p{M}+/gu, "$1")
28
+ .replace(/[^\p{L}\p{N}\p{M}]+/gu, " ").trim();
29
+ const words = (s) => fold(s).split(" ").filter(Boolean);
30
+
31
+ /** How well one typed word matches a text (folded, its words given): 0 when it doesn't.
32
+ Letters in order count only when asked (the label), starting at one of its words. */
33
+ function wordScore(w, text, parts, loose) {
34
+ if (parts.some((p) => p === w)) return 10;
35
+ if (parts.some((p) => p.startsWith(w))) return 8;
36
+ if (text.includes(w)) return 5;
37
+ if (!loose || w.length < 2) return 0;
38
+ for (let s = 0; s < text.length; s++) {
39
+ if (text[s] !== w[0] || (s && text[s - 1] !== " ")) continue;
40
+ let i = 1;
41
+ for (let k = s + 1; k < text.length && i < w.length; k++) if (text[k] === w[i]) i++;
42
+ if (i === w.length) return 2;
43
+ }
44
+ return 0;
45
+ }
46
+ /** A query with no letters or digits: the items whose `keys` hold exactly that. */
47
+ const symbolOnly = (query) => !words(query).length && String(query || "").trim() !== "";
48
+ const symbolScore = (query, item) => {
49
+ const q = String(query).trim();
50
+ // "+ / -" holds "+"; "Shift+;" holds ";"
51
+ return (item.keys || []).some((k) => String(k).trim() === q || String(k).split(/[\s/,·]+/).includes(q) || String(k).split(/[\s/,+·]+/).includes(q)) ? 10 : 0;
52
+ };
53
+ function score(query, item) {
54
+ if (symbolOnly(query)) return symbolScore(query, item);
55
+ const q = words(query);
56
+ if (!q.length) return 1;
57
+ const label = fold(item.label), lp = label.split(" ");
58
+ const extra = fold([item.group, ...(item.keywords || [])].join(" ")), ep = extra.split(" ").filter(Boolean);
59
+ let total = 0;
60
+ for (const w of q) {
61
+ const inLabel = wordScore(w, label, lp, true);
62
+ const inExtra = wordScore(w, extra, ep, false) * 0.6; // the label counts for more than group and keywords
63
+ const s = Math.max(inLabel, inExtra);
64
+ if (!s) return 0;
65
+ total += s;
66
+ }
67
+ if (label.startsWith(q.join(" "))) total += 6; // the label begins with what was typed
68
+ return total - Math.min(label.length, 60) / 100; // a shorter label wins a tie
69
+ }
70
+ function rank(query, items, limit = 50) {
71
+ if (!words(query).length && !symbolOnly(query)) return items.slice(0, limit);
72
+ return items.map((it, i) => ({ it, i, s: score(query, it) }))
73
+ .filter((x) => x.s > 0)
74
+ .sort((a, b) => b.s - a.s || a.i - b.i)
75
+ .slice(0, limit)
76
+ .map((x) => x.it);
77
+ }
78
+ return { rank, score, fold };
79
+ });
package/export-jobs.js CHANGED
@@ -112,7 +112,7 @@ function createExportJobs(opts) {
112
112
  * kind "transcribe" turns files' speech into words and saves them (fablecut_transcribe).
113
113
  * A scopes job's `image` flag also returns that still as a JPEG data URL,
114
114
  * which is how fablecut_frame shows an agent the composed program picture. */
115
- request({ kind = "export", range, profile, delivery = null, deliveries = null, time, revision, where = "auto", matte = null, mask = null, track = null, transcribe = null, image = false }) {
115
+ request({ kind = "export", range, profile, delivery = null, deliveries = null, name = null, time, revision, project = null, where = "auto", matte = null, mask = null, track = null, transcribe = null, image = false }) {
116
116
  if (!["auto", "tab", "headless"].includes(where)) throw Object.assign(new Error("where must be auto, tab or headless"), { code: 400 });
117
117
  if (!["export", "scopes", "track", "transcribe"].includes(kind)) throw Object.assign(new Error("kind must be export, scopes, track or transcribe"), { code: 400 });
118
118
  if (time != null && !(Number.isFinite(time) && time >= 0)) throw Object.assign(new Error("time must be seconds ≥ 0"), { code: 400 });
@@ -125,7 +125,9 @@ function createExportJobs(opts) {
125
125
  const j = {
126
126
  id: "x_" + Math.random().toString(36).slice(2, 10), kind, status: "pending", progress: 0,
127
127
  range: range || null, profile: profile || null, delivery: kind === "export" && delivery ? delivery : null,
128
+ name: kind === "export" && typeof name === "string" && name.trim() ? name.trim().slice(0, 120) : null,
128
129
  deliveries: kind === "export" && Array.isArray(deliveries) && deliveries.length ? deliveries : null, time: time ?? null, revision: Number.isFinite(revision) ? revision : null,
130
+ project: typeof project === "string" && project ? project : null, // the project it was asked for
129
131
  matte: kind === "scopes" && matte ? { clip: String(matte.clip), layer: matte.layer } : null,
130
132
  mask: kind === "scopes" && mask ? { clip: String(mask.clip) } : null,
131
133
  track: kind === "track" && track ? track : null,
@@ -142,7 +144,7 @@ function createExportJobs(opts) {
142
144
  },
143
145
  get(id) { const j = jobs.get(id); return j ? view(j) : null; },
144
146
  /** What a tab needs to run the job (headless pages fetch it by id). */
145
- ticket(id) { const j = jobs.get(id); return j ? { id: j.id, kind: j.kind, range: j.range, profile: j.profile, delivery: j.delivery || null, deliveries: j.deliveries || null, time: j.time, revision: j.revision, matte: j.matte || null, mask: j.mask || null, track: j.track || null, transcribe: j.transcribe || null, image: !!j.image, status: j.status } : null; },
147
+ ticket(id) { const j = jobs.get(id); return j ? { id: j.id, kind: j.kind, range: j.range, profile: j.profile, delivery: j.delivery || null, deliveries: j.deliveries || null, name: j.name || null, time: j.time, revision: j.revision, project: j.project || null, matte: j.matte || null, mask: j.mask || null, track: j.track || null, transcribe: j.transcribe || null, image: !!j.image, status: j.status } : null; },
146
148
  /** First tab to claim a pending job runs it. */
147
149
  claim(id) {
148
150
  const j = jobs.get(id);