fablecut 1.17.0 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fablecut",
3
- "version": "1.17.0",
3
+ "version": "1.18.0",
4
4
  "description": "Zero-dependency browser video editor that AI agents can drive — JSON timeline, MCP server, REST API, live-reloading UI.",
5
5
  "main": "server.js",
6
6
  "bin": {
package/reframe.js ADDED
@@ -0,0 +1,297 @@
1
+ /* FableCut reframe — follow the subject when a shot is shown on a canvas of
2
+ another shape (a 16:9 edit made 9:16, 1:1 or 4:5). Zero dependencies; loaded
3
+ by the editor as a plain script (global `FableCutReframe`) and required by
4
+ the MCP server, so the editor, fablecut_reframe and Studio frame the same.
5
+
6
+ subjectTrack: small RGB frames sampled through a clip → where the subject is
7
+ in each (motion against the shot's own movement, detail and colour, with a
8
+ gentle pull to the centre) and how sure that is. camera: a virtual operator
9
+ on those samples — it holds while the subject stays inside a dead zone, then
10
+ eases toward it no faster than a pan speed. keys: the camera as the clip's
11
+ own x / y keyframes for a "cover"-fitted picture on the new canvas, kept
12
+ inside the picture and thinned to the few keys that matter. */
13
+ (function (root, factory) {
14
+ const api = factory();
15
+ if (typeof module === "object" && module.exports) module.exports = api;
16
+ else root.FableCutReframe = api;
17
+ })(typeof self !== "undefined" ? self : this, function () {
18
+ "use strict";
19
+
20
+ const SAMPLE_FPS = 5; // frames looked at per second of a clip
21
+ const SAMPLE_W = 96; // their width in px (height follows the picture)
22
+ const ASPECTS = { "9:16": [9, 16], "1:1": [1, 1], "4:5": [4, 5], "16:9": [16, 9], "4:3": [4, 3], "2:3": [2, 3] };
23
+ const clamp = (v, a, b) => (v < a ? a : v > b ? b : v);
24
+
25
+ /* ── where the subject is ── */
26
+
27
+ function lumaOf(rgb, n) {
28
+ const y = new Float32Array(n);
29
+ for (let i = 0, j = 0; i < n; i++, j += 3) y[i] = 0.2126 * rgb[j] + 0.7152 * rgb[j + 1] + 0.0722 * rgb[j + 2];
30
+ return y;
31
+ }
32
+ /** Box blur radius r, separable, in place on a copy. */
33
+ function blur(src, w, h, r) {
34
+ const tmp = new Float32Array(w * h), out = new Float32Array(w * h);
35
+ for (let y = 0; y < h; y++) {
36
+ let s = 0;
37
+ for (let x = -r; x <= r; x++) s += src[y * w + clamp(x, 0, w - 1)];
38
+ for (let x = 0; x < w; x++) {
39
+ tmp[y * w + x] = s / (2 * r + 1);
40
+ s += src[y * w + clamp(x + r + 1, 0, w - 1)] - src[y * w + clamp(x - r, 0, w - 1)];
41
+ }
42
+ }
43
+ for (let x = 0; x < w; x++) {
44
+ let s = 0;
45
+ for (let y = -r; y <= r; y++) s += tmp[clamp(y, 0, h - 1) * w + x];
46
+ for (let y = 0; y < h; y++) {
47
+ out[y * w + x] = s / (2 * r + 1);
48
+ s += tmp[clamp(y + r + 1, 0, h - 1) * w + x] - tmp[clamp(y - r, 0, h - 1) * w + x];
49
+ }
50
+ }
51
+ return out;
52
+ }
53
+ /** Values scaled to 0…1 by their 98th percentile (one bright speck doesn't flatten the rest). */
54
+ function norm(a) {
55
+ const s = Array.from(a).sort((x, y) => x - y);
56
+ const top = s[Math.floor(s.length * 0.98)] || 0;
57
+ const out = new Float32Array(a.length);
58
+ if (top <= 1e-6) return out;
59
+ for (let i = 0; i < a.length; i++) out[i] = Math.min(1, a[i] / top);
60
+ return out;
61
+ }
62
+
63
+ /** One frame's saliency map. `prev` is the previous frame's luma (or null). */
64
+ function saliency(rgb, w, h, prev) {
65
+ const n = w * h, y = lumaOf(rgb, n);
66
+ // detail: gradient magnitude
67
+ const det = new Float32Array(n);
68
+ for (let j = 1; j < h - 1; j++) for (let i = 1; i < w - 1; i++) {
69
+ const k = j * w + i;
70
+ det[k] = Math.abs(y[k + 1] - y[k - 1]) + Math.abs(y[k + w] - y[k - w]);
71
+ }
72
+ // colour: saturation (vivid things and skin stand out from grey surroundings)
73
+ const sat = new Float32Array(n);
74
+ for (let i = 0, j = 0; i < n; i++, j += 3) {
75
+ const mx = Math.max(rgb[j], rgb[j + 1], rgb[j + 2]), mn = Math.min(rgb[j], rgb[j + 1], rgb[j + 2]);
76
+ sat[i] = mx > 8 ? (mx - mn) / mx : 0;
77
+ }
78
+ // motion against the frame's own typical change (a pan or a flicker moves everything alike)
79
+ let mot = null;
80
+ if (prev) {
81
+ mot = new Float32Array(n);
82
+ for (let i = 0; i < n; i++) mot[i] = Math.abs(y[i] - prev[i]);
83
+ const s = Array.from(mot).sort((a, b) => a - b), med = s[Math.floor(n / 2)];
84
+ for (let i = 0; i < n; i++) mot[i] = Math.max(0, mot[i] - med * 1.5);
85
+ }
86
+ const r = Math.max(1, Math.round(w / 24));
87
+ const D = norm(blur(det, w, h, r)), C = norm(blur(sat, w, h, r)), M = mot ? norm(blur(mot, w, h, r)) : null;
88
+ const map = new Float32Array(n);
89
+ for (let j = 0; j < h; j++) for (let i = 0; i < w; i++) {
90
+ const k = j * w + i, dx = (i + 0.5) / w - 0.5, dy = (j + 0.5) / h - 0.5;
91
+ const prior = 0.55 + 0.45 * Math.exp(-(dx * dx + dy * dy) / (2 * 0.3 * 0.3));
92
+ map[k] = prior * (M ? 0.5 * M[k] + 0.32 * D[k] + 0.18 * C[k] : 0.62 * D[k] + 0.38 * C[k]);
93
+ }
94
+ return { map, luma: y };
95
+ }
96
+
97
+ /** The subject's centre in a saliency map: the weighted centre of its strongest 12 %,
98
+ * and how gathered that is (1 = one tight spot, 0 = spread over the frame). */
99
+ function centre(map, w, h) {
100
+ const s = Array.from(map).sort((a, b) => a - b), cut = s[Math.floor(s.length * 0.88)];
101
+ let sw = 0, sx = 0, sy = 0;
102
+ for (let j = 0; j < h; j++) for (let i = 0; i < w; i++) {
103
+ const v = map[j * w + i] - cut;
104
+ if (v <= 0) continue;
105
+ sw += v; sx += v * (i + 0.5); sy += v * (j + 0.5);
106
+ }
107
+ if (sw <= 0) return { u: 0.5, v: 0.5, conf: 0 };
108
+ const cx = sx / sw, cy = sy / sw;
109
+ let spread = 0;
110
+ for (let j = 0; j < h; j++) for (let i = 0; i < w; i++) {
111
+ const v = map[j * w + i] - cut;
112
+ if (v > 0) spread += v * Math.hypot((i + 0.5 - cx) / w, (j + 0.5 - cy) / h);
113
+ }
114
+ spread /= sw;
115
+ return { u: cx / w, v: cy / h, conf: clamp(1 - spread / 0.3, 0, 1) };
116
+ }
117
+
118
+ /** Frames → samples [[t, u, v, conf], …]: t in seconds from the first frame (at `fps`),
119
+ * u / v the subject's centre as fractions of the picture. `frames` are RGB bytes (w×h×3). */
120
+ function subjectTrack(frames, w, h, opts) {
121
+ const t = tracker(w, h, opts);
122
+ for (const f of frames) t.push(f);
123
+ return t.samples;
124
+ }
125
+ /** The same, a frame at a time, so a long shot needn't be held in memory:
126
+ * push(frame) as each one is read; `samples` grows as they come. */
127
+ function tracker(w, h, { fps = SAMPLE_FPS } = {}) {
128
+ let prev = null;
129
+ const samples = [];
130
+ return {
131
+ samples,
132
+ push(frame) {
133
+ const { map, luma } = saliency(frame, w, h, prev);
134
+ const c = centre(map, w, h);
135
+ samples.push([Math.round((samples.length / fps) * 1000) / 1000, c.u, c.v, c.conf]);
136
+ prev = luma;
137
+ },
138
+ };
139
+ }
140
+
141
+ /* ── the virtual camera ── */
142
+
143
+ /** Smooth the subject's path along one axis (k = 1 for u, 2 for v) into where the
144
+ * camera looks: a median against jitter, low-confidence samples held, then an operator
145
+ * that only moves once the subject leaves a dead zone around the frame's centre, and
146
+ * eases toward it no faster than `maxSpeed` (fractions of the picture per second).
147
+ * `smooth` 0…1 widens the dead zone and slows the pan. Returns [[t, pos], …]. */
148
+ function camera(samples, k = 1, { smooth = 0.5, minConf = 0.15 } = {}) {
149
+ if (!samples.length) return [];
150
+ const sm = clamp(+smooth || 0, 0, 1);
151
+ const dead = 0.04 + 0.1 * sm, maxSpeed = 0.6 - 0.4 * sm, ease = 0.35 + 0.4 * sm;
152
+ // median of 5 against jitter
153
+ const raw = samples.map((s) => s[k]);
154
+ const med = raw.map((_, i) => { const win = raw.slice(Math.max(0, i - 2), i + 3).sort((a, b) => a - b); return win[Math.floor(win.length / 2)]; });
155
+ // unsure samples hold the last sure position (the first sure one, at the start)
156
+ const firstSure = samples.findIndex((s) => s[3] >= minConf);
157
+ let held = firstSure >= 0 ? med[firstSure] : 0.5;
158
+ const target = samples.map((s, i) => (s[3] >= minConf ? (held = med[i]) : held));
159
+ // the operator: starts on the subject, moves when it leaves the dead zone, eases, caps its speed
160
+ let pos = target[0];
161
+ const out = [[samples[0][0], pos]];
162
+ for (let i = 1; i < samples.length; i++) {
163
+ const dt = Math.max(1e-3, samples[i][0] - samples[i - 1][0]);
164
+ const off = target[i] - pos;
165
+ if (Math.abs(off) > dead) {
166
+ const want = (off - Math.sign(off) * dead * 0.5) * (1 - Math.pow(1 - ease, dt * SAMPLE_FPS));
167
+ pos += clamp(want, -maxSpeed * dt, maxSpeed * dt);
168
+ }
169
+ out.push([samples[i][0], pos]);
170
+ }
171
+ return out;
172
+ }
173
+
174
+ /** Fewest points that stay within `tol` of a path [[t, v], …] (Ramer–Douglas–Peucker). */
175
+ function simplify(path, tol) {
176
+ if (path.length <= 2) return path.slice();
177
+ const keep = new Uint8Array(path.length);
178
+ keep[0] = keep[path.length - 1] = 1;
179
+ const stack = [[0, path.length - 1]];
180
+ while (stack.length) {
181
+ const [a, b] = stack.pop();
182
+ let worst = -1, at = -1;
183
+ for (let i = a + 1; i < b; i++) {
184
+ const f = (path[i][0] - path[a][0]) / Math.max(1e-9, path[b][0] - path[a][0]);
185
+ const d = Math.abs(path[i][1] - (path[a][1] + f * (path[b][1] - path[a][1])));
186
+ if (d > worst) { worst = d; at = i; }
187
+ }
188
+ if (worst > tol) { keep[at] = 1; stack.push([a, at], [at, b]); }
189
+ }
190
+ return path.filter((_, i) => keep[i]);
191
+ }
192
+
193
+ /* ── on the canvas ── */
194
+
195
+ /** A picture srcW×srcH fitted with "cover" on a canvas W×H at clip scale `scale`:
196
+ * its drawn size and how far it may move each way before an edge shows. */
197
+ function coverRect(srcW, srcH, W, H, scale = 1) {
198
+ const s = Math.max(W / srcW, H / srcH) * scale;
199
+ const pw = srcW * s, ph = srcH * s;
200
+ return { pw, ph, maxX: Math.max(0, (pw - W) / 2), maxY: Math.max(0, (ph - H) / 2) };
201
+ }
202
+ /** The clip's x (or y) offset that puts picture fraction u at the canvas centre, kept inside the picture. */
203
+ function offsetFor(u, size, max) { return clamp((0.5 - u) * size, -max, max); }
204
+
205
+ /** A camera path [[t, u], …] (t in clip-source seconds from the clip's in point, at speed 1)
206
+ * → keyframes for the clip's x or y on the canvas: {static} when it hardly moves, else
207
+ * {keys:[{t, v, ease}]} in clip seconds, within ~2 px. */
208
+ function keysFor(path, size, max, { speed = 1, fps = 30, tolPx = 2 } = {}) {
209
+ if (!path.length || max <= 0.5) return { static: 0 };
210
+ const px = path.map(([t, u]) => [t / speed, Math.round(offsetFor(u, size, max) * 10) / 10]);
211
+ const lo = Math.min(...px.map((p) => p[1])), hi = Math.max(...px.map((p) => p[1]));
212
+ if (hi - lo <= tolPx * 2) return { static: Math.round((lo + hi) / 2) };
213
+ const keys = simplify(px, tolPx).map(([t, v], i) => ({ t: Math.round(t * fps) / fps, v: Math.round(v), ...(i ? { ease: "linear" } : {}) }));
214
+ // two keys can land on one frame after rounding: keep the later
215
+ return { keys: keys.filter((k, i) => i === keys.length - 1 || keys[i + 1].t > k.t) };
216
+ }
217
+
218
+ /** "9:16" (or [w, h]) → a canvas of that shape, as big as the project's longer side allows,
219
+ * even sizes (H.264): a 1920×1080 edit gives 1080×1920 for 9:16, 1080×1080 for 1:1. */
220
+ function canvasFor(aspect, W, H) {
221
+ const a = Array.isArray(aspect) ? aspect : ASPECTS[String(aspect)];
222
+ if (!a || !(a[0] > 0 && a[1] > 0)) throw new Error(`aspect must be one of ${Object.keys(ASPECTS).join(", ")}`);
223
+ const short = Math.min(W, H), even = (v) => Math.max(2, Math.round(v / 2) * 2);
224
+ // the shorter side of the new canvas is the project's shorter side
225
+ return a[0] <= a[1] ? { width: even(short), height: even(short * a[1] / a[0]) } : { width: even(short * a[0] / a[1]), height: even(short) };
226
+ }
227
+
228
+ /* ── on a project: which clips, and what to write ── */
229
+
230
+ const near0 = (v) => v == null || Math.abs(+v) < 0.5;
231
+ const hasKeys = (c, k) => Array.isArray(c.keyframes?.[k]) && c.keyframes[k].length > 0;
232
+
233
+ /** The clips a reframe works on, from `doc` (the sequence as it will be): full-frame
234
+ * pictures — video clips (and stills) not moved, scaled, cropped or animated by hand,
235
+ * not fitted "none" or "stretch", not locked (unless force). Returns {take, skip:[{id, why}]}. */
236
+ function targets(doc, { ids = null, force = false } = {}) {
237
+ const lanes = new Set(Array.isArray(doc.lockedTracks) ? doc.lockedTracks : []);
238
+ // a clip linked to a locked one is locked with it (its stems move and lock together)
239
+ const isLocked = (x) => x.locked || lanes.has(x.track);
240
+ const lockedGroups = new Set((doc.clips || []).filter((x) => x.linkGroup && isLocked(x)).map((x) => x.linkGroup));
241
+ // older projects pair a picture and its sound with linkedId instead of a linkGroup
242
+ const lockedPairs = new Set();
243
+ for (const x of doc.clips || []) if (x.linkedId && isLocked(x)) { lockedPairs.add(x.id); lockedPairs.add(x.linkedId); }
244
+ const take = [], skip = [];
245
+ for (const c of doc.clips || []) {
246
+ if (ids && !ids.includes(c.id)) continue;
247
+ // audio has no picture; a title, shape or other layer on the picture is listed, to be checked on the new canvas
248
+ if (c.kind !== "video" && c.kind !== "image") { if (ids || c.kind !== "audio") skip.push({ id: c.id, why: c.kind === "text" ? "a title" : `a ${c.kind} clip` }); continue; }
249
+ const p = c.props || {};
250
+ const ours = p.reframe === "follow" || p.reframe === "centre"; // reframed before: its fit and keys are ours to redo
251
+ const ramped = Array.isArray(c.keyframes?.speed) && c.keyframes.speed.length > 0;
252
+ const why = !force && (c.locked || lanes.has(c.track) || (c.linkGroup && lockedGroups.has(c.linkGroup)) || lockedPairs.has(c.id)) ? "locked"
253
+ : ramped ? "a speed ramp"
254
+ : ours ? (["cropL", "cropR", "cropT", "cropB"].some((k) => +p[k] > 0) ? "cropped" : null)
255
+ : p.fit === "none" || p.fit === "stretch" ? `fit:${p.fit}`
256
+ : !near0(p.x) || !near0(p.y) || (p.scale != null && Math.abs(+p.scale - 1) > 0.01) ? "placed by hand (moved or scaled)"
257
+ : hasKeys(c, "x") || hasKeys(c, "y") || hasKeys(c, "scale") ? "animated by hand (position or scale keys)"
258
+ : ["cropL", "cropR", "cropT", "cropB"].some((k) => +p[k] > 0) ? "cropped"
259
+ : null;
260
+ if (why) skip.push({ id: c.id, why }); else take.push(c);
261
+ }
262
+ return { take, skip };
263
+ }
264
+
265
+ /** What one clip gets: fit cover, and an x (or y) that follows the subject — keys, or one
266
+ * steady value. `samples` from subjectTrack (null: centre it); `src` {width, height} the
267
+ * picture; `canvas` {width, height}. Returns {set, note} for an updateClip op. */
268
+ function clipPlan(c, samples, src, canvas, { smooth = 0.5, fps = 30, follow = true } = {}) {
269
+ const r = coverRect(src.width, src.height, canvas.width, canvas.height, 1);
270
+ const axis = r.maxX >= r.maxY ? "x" : "y";
271
+ const size = axis === "x" ? r.pw : r.ph, max = axis === "x" ? r.maxX : r.maxY;
272
+ // only what changes: updateClip merges props key by key, and null takes one away. props.reframe marks the
273
+ // fit and position as reframe's own, so running it again redoes them instead of calling them hand-made.
274
+ const props = { fit: "cover", x: null, y: null, reframe: follow ? "follow" : "centre" };
275
+ const rest = { ...(c.keyframes || {}) };
276
+ delete rest.x; delete rest.y;
277
+ const set = { props };
278
+ if (c.keyframes && (c.keyframes.x || c.keyframes.y)) set.keyframes = Object.keys(rest).length ? rest : null;
279
+ const sp = Math.min(8, Math.max(0.1, +c.props?.speed || 1));
280
+ const sure = samples && samples.length ? samples.reduce((n, s) => n + s[3], 0) / samples.length : 0;
281
+ if (!follow || max <= 0.5 || !samples || !samples.length || sure < 0.12) {
282
+ const why = max <= 0.5 ? "already this shape" : !follow ? "centred" : "no clear subject — centred";
283
+ return { set, note: why, axis, keys: 0 };
284
+ }
285
+ const path = camera(samples, axis === "x" ? 1 : 2, { smooth });
286
+ const k = keysFor(path, size, max, { speed: sp, fps });
287
+ if (k.keys) {
288
+ set.keyframes = { ...rest, [axis]: k.keys };
289
+ const vals = k.keys.map((q) => q.v), span = (Math.max(...vals) - Math.min(...vals)) / (2 * max || 1);
290
+ return { set, note: `follows the subject (${k.keys.length} keys, pans ${Math.round(span * 100)}% of the room)`, axis, keys: k.keys.length };
291
+ }
292
+ props[axis] = k.static;
293
+ return { set, note: k.static ? `held on the subject (${axis} ${k.static > 0 ? "+" : ""}${k.static})` : "subject in the middle — centred", axis, keys: 0 };
294
+ }
295
+
296
+ return { SAMPLE_FPS, SAMPLE_W, ASPECTS, targets, clipPlan, saliency, centre, subjectTrack, tracker, camera, simplify, coverRect, offsetFor, keysFor, canvasFor };
297
+ });
package/style.css CHANGED
@@ -2382,6 +2382,9 @@ input[type=range] {
2382
2382
  }
2383
2383
 
2384
2384
  /* Silences Find marked (Inspector → Silence) — a band over the span, above the clips */
2385
+ .beat-band { position: absolute; top: 0; bottom: 0; pointer-events: none; z-index: 3; }
2386
+ :root { --beat-tick: rgba(34, 211, 238, .45); }
2387
+ .beat-tick { position: absolute; top: 0; bottom: 0; width: 1px; margin-left: -0.5px; background: rgba(34, 211, 238, .45); pointer-events: none; z-index: 3; }
2385
2388
  .silence-span {
2386
2389
  position: absolute;
2387
2390
  top: 2px;