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/media-files.js ADDED
@@ -0,0 +1,271 @@
1
+ /* The project's files on disk: folders, moves and a trash, all inside media/.
2
+
3
+ The media bin's folders and collections only organize entries in
4
+ project.json; this is the folder itself — so an agent (or the user) can
5
+ tidy downloads into subfolders, rename a file, and throw away what isn't
6
+ used, without leaving the editor. Nothing here deletes a file: "trash"
7
+ moves it into media/.trash/<id>/files/ beside a note of where it came from
8
+ (<id>/item.json), and "restore" puts it back. Dot-folders are never listed,
9
+ served as media or offered by Relink, so trashed files are out of the way
10
+ but still there.
11
+
12
+ createMediaFiles({mediaDir}) → {
13
+ list(dir?) → {dir, folders:[name], files:[{name, src, size}]} (one level)
14
+ mkdir(dir) → {dir} (parents too; an existing one is fine)
15
+ move(from, to, {exact}?) → {from, to, moved:[{from, to}]} (srcs: the item, and every file in it;
16
+ exact: `to` is the new path itself, never a folder to go into)
17
+ trash(paths) → {trashed:[{id, src}], moved:[{from, to}]}
18
+ trashList() → [{id, src, kind, size, trashed}]
19
+ restore(id) → {restored:{id, src}, moved:[{from, to}]}
20
+ filesOf(path) → the /media/… srcs of the files at or under a path
21
+ pathOf(src) → the absolute path of a /media/… src inside media/, or null
22
+ }
23
+ canonicalSrc(src) → a /media/… src decoded with doubled slashes folded,
24
+ the form two srcs of the same file share
25
+ Paths are relative to media/ ("b-roll/day 1/a.mp4") or /media/… srcs; "..",
26
+ dot-segments and symlinks on the way are refused. `moved` lists every file
27
+ that changed place as /media/… srcs, so callers can repoint media entries. */
28
+ "use strict";
29
+ const fs = require("fs");
30
+ const path = require("path");
31
+
32
+ const TRASH = ".trash";
33
+ const toSrc = (rel) => "/media/" + rel.split(/[\\/]/).map(encodeURIComponent).join("/");
34
+ function canonicalSrc(src) {
35
+ let s = String(src || "").split("?")[0];
36
+ try { s = decodeURIComponent(s); } catch { }
37
+ return s.replace(/\\/g, "/").replace(/\/{2,}/g, "/");
38
+ }
39
+
40
+ function createMediaFiles({ mediaDir }) {
41
+ const root = path.resolve(mediaDir);
42
+ const trashDir = path.join(root, TRASH);
43
+
44
+ /** Throws when a path on the way from media/ to `abs` (as far as it exists) is a symlink. */
45
+ function noLinks(abs) {
46
+ const parts = path.relative(root, abs).split(path.sep).filter(Boolean);
47
+ let cur = root;
48
+ for (const part of parts) {
49
+ cur = path.join(cur, part);
50
+ let st;
51
+ try { st = fs.lstatSync(cur); } catch { return; } // nothing there yet: nothing to follow
52
+ if (st.isSymbolicLink()) throw new Error(`${JSON.stringify(path.relative(root, cur).split(path.sep).join("/"))} is a link — FableCut only moves real files and folders in media/`);
53
+ }
54
+ }
55
+ /** "a/b.mp4" or "/media/a/b.mp4" → {rel, abs}; throws on anything outside media/.
56
+ raw: a path as stored (no "/media" / "media" shorthand for the folder itself). */
57
+ function resolve(p, { allowRoot = false, raw = false } = {}) {
58
+ let s = String(p == null ? "" : p).replace(/\\/g, "/");
59
+ if (!raw) s = s.trim(); // a stored path keeps its spaces: " take.mp4" is a real name
60
+ if (!raw) {
61
+ if (s.startsWith("/media/")) { try { s = decodeURIComponent(s.slice(7)); } catch { throw new Error(`bad path ${JSON.stringify(p)}`); } }
62
+ else if (s === "/media" || s === "media" || s === "media/") s = "";
63
+ }
64
+ s = s.replace(/^\/+|\/+$/g, "");
65
+ const parts = s ? s.split("/") : [];
66
+ if (parts.some((x) => !x || x === "." || x === ".." || x.startsWith(".")))
67
+ throw new Error(`${JSON.stringify(p)} is not a path inside media/ (no "..", no dot-folders)`);
68
+ if (parts.some((x) => /[<>:"|?*\x00-\x1f]/.test(x) || x.length > 120))
69
+ throw new Error(`${JSON.stringify(p)} has a name that isn't allowed (< > : " | ? * or over 120 characters)`);
70
+ if (!parts.length && !allowRoot) throw new Error("name a file or folder inside media/");
71
+ const rel = parts.join("/");
72
+ const abs = rel ? path.join(root, ...parts) : root;
73
+ noLinks(abs);
74
+ return { rel, abs };
75
+ }
76
+ const stat = (abs) => { try { return fs.statSync(abs); } catch { return null; } };
77
+ /** Every file under `abs` as paths relative to media/ (a file: itself). */
78
+ function filesUnder(abs) {
79
+ const st = stat(abs);
80
+ if (!st) return [];
81
+ if (st.isFile()) return [path.relative(root, abs).split(path.sep).join("/")];
82
+ const out = [];
83
+ const walk = (d) => {
84
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
85
+ const full = path.join(d, e.name);
86
+ if (e.isSymbolicLink()) throw new Error(`${JSON.stringify(path.relative(root, full).split(path.sep).join("/"))} is a link — FableCut only moves real files and folders in media/`);
87
+ if (e.isDirectory()) walk(full); else if (e.isFile()) out.push(path.relative(root, full).split(path.sep).join("/"));
88
+ }
89
+ };
90
+ walk(abs);
91
+ return out;
92
+ }
93
+ const relOf = (abs) => path.relative(root, abs).split(path.sep).join("/");
94
+ const taken = (toAbs) => Object.assign(new Error(`${JSON.stringify(relOf(toAbs))} already exists — pick another name`), { code: "EEXIST" });
95
+ /** Put `fromAbs` at `toAbs` without replacing anything there: a file is hard-linked to
96
+ its new name (which fails if the name is taken) and then unlinked; a folder is
97
+ renamed, which never lands on a folder with something in it. */
98
+ function publish(fromAbs, toAbs) {
99
+ if (fs.lstatSync(fromAbs).isFile()) {
100
+ try { fs.linkSync(fromAbs, toAbs); }
101
+ catch (e) {
102
+ if (e.code === "EEXIST") throw taken(toAbs);
103
+ if (e.code === "EXDEV") throw e;
104
+ // a file system without hard links: check, then rename
105
+ if (fs.existsSync(toAbs)) throw taken(toAbs);
106
+ fs.renameSync(fromAbs, toAbs);
107
+ return;
108
+ }
109
+ fs.unlinkSync(fromAbs);
110
+ return;
111
+ }
112
+ // a folder: Windows never renames onto an existing folder; elsewhere an empty folder made
113
+ // here first holds the name (mkdir fails if it is taken), and the rename replaces only it
114
+ if (process.platform === "win32") {
115
+ if (fs.existsSync(toAbs)) throw taken(toAbs);
116
+ fs.renameSync(fromAbs, toAbs);
117
+ return;
118
+ }
119
+ try { fs.mkdirSync(toAbs); } catch (e) { if (e.code === "EEXIST") throw taken(toAbs); throw e; }
120
+ try { fs.renameSync(fromAbs, toAbs); }
121
+ catch (e) { try { fs.rmdirSync(toAbs); } catch { } throw e.code === "ENOTEMPTY" || e.code === "EEXIST" ? taken(toAbs) : e; }
122
+ }
123
+ /** Move `fromAbs` to `toAbs` (both inside media/), creating the folder above; a name
124
+ taken meanwhile is refused, never replaced. Across drives the copy goes to a staging
125
+ name first (timestamps kept, so the file's transcript still matches it) and takes
126
+ the final name only once it is complete. If removing the original then fails, the
127
+ error says so with `published: true`: the copy is whole and stays. */
128
+ function rename(fromAbs, toAbs) {
129
+ fs.mkdirSync(path.dirname(toAbs), { recursive: true });
130
+ try { publish(fromAbs, toAbs); return; }
131
+ catch (e) { if (e.code !== "EXDEV") throw e; }
132
+ const stage = path.join(path.dirname(toAbs), `.fc-move-${process.pid}-${Date.now().toString(36)}`);
133
+ try {
134
+ fs.cpSync(fromAbs, stage, { recursive: true, errorOnExist: true, force: false, preserveTimestamps: true });
135
+ publish(stage, toAbs);
136
+ } catch (e) {
137
+ fs.rmSync(stage, { recursive: true, force: true });
138
+ throw e;
139
+ }
140
+ try { fs.rmSync(fromAbs, { recursive: true, force: true }); }
141
+ catch (e) {
142
+ throw Object.assign(new Error(`copied to ${relOf(toAbs)}, but the original could not be removed (${e.code || e.message}) — both copies are there`), { published: true });
143
+ }
144
+ }
145
+ /** [{from, to}] srcs for what moved from `fromRel` to `toRel`, given the files that were under fromRel. */
146
+ const pairs = (files, fromRel, toRel) => files.map((f) => ({ from: toSrc(f), to: toSrc(toRel + f.slice(fromRel.length)) }));
147
+ const readItem = (id) => {
148
+ if (!/^t[a-z0-9]{4,20}$/.test(String(id || ""))) return null;
149
+ try { return JSON.parse(fs.readFileSync(path.join(trashDir, id, "item.json"), "utf8")); } catch { return null; }
150
+ };
151
+
152
+ return {
153
+ filesOf(p) { const r = resolve(p); if (!stat(r.abs)) throw new Error(`no file or folder ${JSON.stringify(r.rel)} in media/`); return filesUnder(r.abs).map(toSrc); },
154
+ pathOf(src) { try { const r = resolve(src); return stat(r.abs)?.isFile() ? r.abs : null; } catch { return null; } },
155
+ list(dir) {
156
+ const { rel, abs } = resolve(dir, { allowRoot: true });
157
+ const st = stat(abs);
158
+ if (!st || !st.isDirectory()) throw new Error(`no folder ${rel ? JSON.stringify(rel) : "media/"}`);
159
+ const folders = [], files = [];
160
+ for (const e of fs.readdirSync(abs, { withFileTypes: true })) {
161
+ if (e.name.startsWith(".") || e.isSymbolicLink()) continue;
162
+ const r = rel ? rel + "/" + e.name : e.name;
163
+ if (e.isDirectory()) folders.push(e.name);
164
+ else if (e.isFile()) files.push({ name: e.name, src: toSrc(r), size: stat(path.join(abs, e.name))?.size || 0 });
165
+ }
166
+ const byName = (a, b) => String(a.name || a).localeCompare(String(b.name || b), undefined, { numeric: true });
167
+ return { dir: rel, folders: folders.sort(byName), files: files.sort(byName) };
168
+ },
169
+ mkdir(dir) {
170
+ const { rel, abs } = resolve(dir);
171
+ const st = stat(abs);
172
+ if (st && !st.isDirectory()) throw new Error(`${JSON.stringify(rel)} is a file`);
173
+ fs.mkdirSync(abs, { recursive: true });
174
+ return { dir: rel };
175
+ },
176
+ move(from, to, { exact = false } = {}) {
177
+ if (to == null || String(to).trim() === "") throw new Error("say where to move it: a folder, a new name, or \"/media/\" for the top of media/");
178
+ const a = resolve(from), b = resolve(to, { allowRoot: true });
179
+ const st = stat(a.abs);
180
+ if (!st) throw new Error(`no file or folder ${JSON.stringify(a.rel)} in media/`);
181
+ // into an existing folder keeps the name; otherwise `to` is the new path
182
+ const into = !exact && stat(b.abs)?.isDirectory();
183
+ const destRel = into ? (b.rel ? b.rel + "/" : "") + path.basename(a.abs) : b.rel;
184
+ const destAbs = into ? path.join(b.abs, path.basename(a.abs)) : b.abs;
185
+ if (destAbs === a.abs) return { from: toSrc(a.rel), to: toSrc(a.rel), moved: [] };
186
+ if (st.isDirectory() && (destAbs + path.sep).startsWith(a.abs + path.sep)) throw new Error(`can't move ${JSON.stringify(a.rel)} into itself`);
187
+ if (stat(destAbs)) throw new Error(`${JSON.stringify(destRel)} already exists — pick another name`);
188
+ noLinks(destAbs);
189
+ const files = filesUnder(a.abs);
190
+ const result = { from: toSrc(a.rel), to: toSrc(destRel), moved: pairs(files, a.rel, destRel) };
191
+ // a copy that is whole at the new place but left part of the original: it moved (with a warning)
192
+ try { rename(a.abs, destAbs); } catch (e) { if (e.published) e.result = result; throw e; }
193
+ return result;
194
+ },
195
+ trash(paths) {
196
+ const list = (Array.isArray(paths) ? paths : [paths]).map((p) => resolve(p));
197
+ for (const r of list) if (!stat(r.abs)) throw new Error(`no file or folder ${JSON.stringify(r.rel)} in media/`);
198
+ // one item inside another would be gone by the time its turn came
199
+ for (const r of list) for (const o of list) {
200
+ if (r === o) continue;
201
+ if (r.rel === o.rel) throw new Error(`${JSON.stringify(r.rel)} is listed twice`);
202
+ if ((r.rel + "/").startsWith(o.rel + "/")) throw new Error(`${JSON.stringify(r.rel)} is inside ${JSON.stringify(o.rel)} — trash the folder, or the file, not both`);
203
+ }
204
+ const trashed = [], moved = [];
205
+ // a failure part-way through says what already went (`partial`), so those can be restored
206
+ const fail = (e, src) => { throw Object.assign(e, { partial: { trashed, moved, failed: src } }); };
207
+ fs.mkdirSync(trashDir, { recursive: true });
208
+ for (const r of list) {
209
+ const st = stat(r.abs);
210
+ const files = filesUnder(r.abs);
211
+ // each item's folder is made without `recursive`, so a taken id is never shared
212
+ let id, box;
213
+ for (let i = 0; ; i++) {
214
+ id = "t" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
215
+ box = path.join(trashDir, id);
216
+ try { fs.mkdirSync(box); break; }
217
+ catch (e) { if (e.code !== "EEXIST" || i > 20) fail(e, toSrc(r.rel)); }
218
+ }
219
+ // the record goes first: if the move then fails it is removed, and nothing is lost either way
220
+ try {
221
+ fs.writeFileSync(path.join(box, "item.json"), JSON.stringify({
222
+ id, src: toSrc(r.rel), rel: r.rel, kind: st.isDirectory() ? "folder" : "file",
223
+ size: st.isDirectory() ? files.length : st.size, trashed: new Date().toISOString(),
224
+ }, null, 2));
225
+ rename(r.abs, path.join(box, "files", path.basename(r.abs)));
226
+ } catch (e) {
227
+ if (e.published) {
228
+ // the trash holds a whole copy, and part of the original may be gone: keep the copy
229
+ trashed.push({ id, src: toSrc(r.rel), warning: e.message });
230
+ for (const f of files) moved.push({ from: toSrc(f), to: null });
231
+ continue;
232
+ }
233
+ fs.rmSync(box, { recursive: true, force: true });
234
+ fail(e, toSrc(r.rel));
235
+ }
236
+ trashed.push({ id, src: toSrc(r.rel) });
237
+ for (const f of files) moved.push({ from: toSrc(f), to: null });
238
+ }
239
+ return { trashed, moved };
240
+ },
241
+ trashList() {
242
+ let ids = [];
243
+ try { ids = fs.readdirSync(trashDir); } catch { return []; }
244
+ const out = [];
245
+ for (const id of ids) {
246
+ const it = readItem(id);
247
+ if (it) out.push({ id: it.id, src: it.src, kind: it.kind, size: it.size, trashed: it.trashed });
248
+ }
249
+ return out.sort((a, b) => String(b.trashed).localeCompare(String(a.trashed)));
250
+ },
251
+ restore(id) {
252
+ const it = readItem(id);
253
+ if (!it) throw new Error(`no trashed item ${JSON.stringify(id)} (list the trash first)`);
254
+ const back = resolve(it.rel, { raw: true });
255
+ if (stat(back.abs)) throw new Error(`${JSON.stringify(it.rel)} exists again — move it away first, then restore`);
256
+ const src = path.join(trashDir, id, "files", path.basename(back.abs));
257
+ if (!fs.existsSync(src)) throw new Error(`trashed item ${id} has no files left to restore`);
258
+ const inner = filesUnder(src).map((f) => f.slice((TRASH + "/" + id + "/files/").length));
259
+ let warning;
260
+ try { rename(src, back.abs); }
261
+ catch (e) { if (!e.published) throw e; warning = e.message; }
262
+ // the file is back: a record left behind is only clutter in the trash list
263
+ try { if (!warning) fs.rmSync(path.join(trashDir, id), { recursive: true, force: true }); }
264
+ catch (e) { warning = `restored, but its trash entry ${id} couldn't be removed (${e.code || e.message})`; }
265
+ const parent = back.rel.slice(0, back.rel.length - path.basename(back.abs).length);
266
+ return { restored: { id, src: it.src, ...(warning ? { warning } : {}) }, moved: inner.map((f) => ({ from: null, to: toSrc(parent + f) })) };
267
+ },
268
+ };
269
+ }
270
+
271
+ module.exports = { createMediaFiles, canonicalSrc, TRASH };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fablecut",
3
- "version": "1.17.0",
3
+ "version": "1.19.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": {
@@ -42,6 +42,6 @@
42
42
  "mcpName": "io.github.ronak-create/fablecut",
43
43
  "license": "MIT",
44
44
  "engines": {
45
- "node": ">=18"
45
+ "node": ">=22"
46
46
  }
47
47
  }
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
+ });