fablecut 1.16.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.16.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/project-ops.js CHANGED
@@ -54,7 +54,7 @@
54
54
  bold: true, weight: 0, italic: false, uppercase: false, align: "center",
55
55
  letterSpacing: 0, lineHeight: 1.2, textShadow: 12, glow: 0, glowColor: "",
56
56
  strokeWidth: 0, strokeColor: "#000", bgColor: "#000", bgOpacity: 0,
57
- textAnim: "none", wordRate: 0.15, direction: "auto", boxW: 0, boxH: 0, boxFit: false, vAlign: "middle",
57
+ textAnim: "none", wordRate: 0.15, highlightColor: "#ffd166", direction: "auto", boxW: 0, boxH: 0, boxFit: false, vAlign: "middle",
58
58
  anchorX: 0, anchorY: 0, trimStart: 0, trimEnd: 100, trimOffset: 0,
59
59
  autoOrient: false, motionBlur: 0, motionBlurSamples: 8, pathOffset: 0, pathAlign: "start",
60
60
  };
@@ -1169,14 +1169,15 @@
1169
1169
  kept[k] = v;
1170
1170
  continue;
1171
1171
  }
1172
- if (k === "masks" || k === "tracks" || k === "shapes" || k === "textPath") continue; // summarized below — point lists and samples are long
1172
+ if (k === "masks" || k === "tracks" || k === "shapes" || k === "textPath" || k === "wordTimes") continue; // summarized below — point lists and samples are long
1173
1173
  if (hex(PROP_DEFAULTS[k]) !== hex(v)) kept[k] = v;
1174
1174
  }
1175
1175
  const masks = Mask.describe(Mask.normalizeMasks(o.masks)), tracks = Tracker.describe(Tracker.normalizeTracks(o.tracks));
1176
1176
  const shapes = Motion.describe(Motion.normalizeShapes(o.shapes));
1177
1177
  const tp = o.textPath && Motion.normalizeTextPath(o.textPath);
1178
1178
  if (tp) kept.textPath = tp.type + (tp.points ? `(${tp.points.length})` : tp.w ? ` ${tp.w}×${tp.h}` : "");
1179
- return (Object.keys(kept).length ? " " + JSON.stringify(kept) : "") + (shapes ? ` [${shapes}]` : "") + (masks ? ` [${masks}]` : "") + (tracks ? ` [tracks: ${tracks}]` : "");
1179
+ const timed = Array.isArray(o.wordTimes) && o.wordTimes.length ? ` [${o.wordTimes.length} words timed to speech]` : "";
1180
+ return (Object.keys(kept).length ? " " + JSON.stringify(kept) : "") + (shapes ? ` [${shapes}]` : "") + (masks ? ` [${masks}]` : "") + (tracks ? ` [tracks: ${tracks}]` : "") + timed;
1180
1181
  };
1181
1182
  // Mixer: only off-default faders / pans, so a fresh project adds no line.
1182
1183
  const signed = (v) => (v > 0 ? "+" : "") + v;
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/server.js CHANGED
@@ -46,6 +46,7 @@ const Templates = require("./templates");
46
46
  const { probeFile } = require("./media-probe");
47
47
  const MediaLib = require("./media-lib");
48
48
  const { createProxies } = require("./proxy");
49
+ const { createTranscripts } = require("./transcripts");
49
50
  const Delivery = require("./delivery");
50
51
  const { createProjects } = require("./projects");
51
52
  const { createHistory } = require("./history");
@@ -124,6 +125,8 @@ function broadcast(event = "change", data = event) {
124
125
  for (const res of sseClients) res.write(payload);
125
126
  }
126
127
  const proxies = createProxies({ dir: PROXIES_DIR, resolveSrc, probe: probeFile, broadcast: (ev, data) => broadcast(ev, data) });
128
+ /* Word transcripts, one per version of a file (fablecut_transcribe, the Transcript tab). */
129
+ const transcripts = createTranscripts({ dir: path.join(ANALYSIS_DIR, "transcripts"), resolveSrc });
127
130
  let debounce = null;
128
131
  let profilesDebounce = null;
129
132
  function onFsChange() {
@@ -544,6 +547,8 @@ function stopExportSweep() {
544
547
  headless browser the server starts (export-jobs.js). */
545
548
  const exportJobs = createExportJobs({
546
549
  url: (id) => `http://localhost:${PORT}/?exportJob=${encodeURIComponent(id)}`,
550
+ // a transcription's headless browser keeps its profile, so the speech model is downloaded once
551
+ keepProfile: (kind) => kind === "transcribe" ? path.join(ANALYSIS_DIR, "browser-profile") : null,
547
552
  broadcast,
548
553
  editors: () => sseClients.size,
549
554
  });
@@ -786,6 +791,61 @@ const server = http.createServer(async (req, res) => {
786
791
  return;
787
792
  }
788
793
 
794
+ /* API: word transcripts (transcripts.js) — one per version of a file, times in file seconds.
795
+ GET /api/transcript?src= → {transcript} (null when there is none; 404 when the file is missing)
796
+ POST /api/transcript?src= {doc} → {src, words} — saved by the tab that transcribed it
797
+ POST /api/transcript/status {srcs} → {status:{src: {words, language, model, duration, created} | false | null}}
798
+ POST /api/transcript/delete {src} → {deleted}
799
+ Saves and deletes also arrive as SSE event "transcript" ({src}). */
800
+ if (p === "/api/transcript" && req.method === "GET") {
801
+ const src = url.searchParams.get("src") || "";
802
+ const d = transcripts.get(src);
803
+ if (d === null) { sendJSON(res, 404, { error: "no such file: " + src }); return; }
804
+ if (d === false) { sendJSON(res, 200, { transcript: null }); return; } // none yet: not an error
805
+ sendJSON(res, 200, { transcript: d });
806
+ return;
807
+ }
808
+ if ((p === "/api/transcript" || p === "/api/transcript/status" || p === "/api/transcript/delete") && req.method === "POST") {
809
+ try {
810
+ const body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
811
+ if (p === "/api/transcript") {
812
+ const src = url.searchParams.get("src") || body.src || "";
813
+ const d = transcripts.put(src, body);
814
+ broadcast("transcript", JSON.stringify({ src }));
815
+ sendJSON(res, 200, { src, words: d.words.length });
816
+ } else if (p === "/api/transcript/delete") {
817
+ const deleted = transcripts.remove(String(body.src || ""));
818
+ if (deleted) broadcast("transcript", JSON.stringify({ src: String(body.src) }));
819
+ sendJSON(res, 200, { deleted });
820
+ } else {
821
+ const status = {};
822
+ for (const src of (Array.isArray(body.srcs) ? body.srcs.slice(0, 2000).map(String) : [])) status[src] = transcripts.info(src);
823
+ sendJSON(res, 200, { status });
824
+ }
825
+ } catch (e) { sendJSON(res, e.code === 404 ? 404 : 400, { error: String(e.message || e) }); }
826
+ return;
827
+ }
828
+ /* API: transcribe files (fablecut_transcribe) — a "transcribe" job on the
829
+ export-job queue; the tab that runs it saves each transcript. */
830
+ if (p === "/api/transcribe/request" && req.method === "POST") {
831
+ try {
832
+ const opts = JSON.parse((await readBody(req)).toString("utf8") || "{}");
833
+ const t = opts.transcribe;
834
+ if (!t || typeof t !== "object" || !Array.isArray(t.srcs) || !t.srcs.length || t.srcs.length > 200 || !t.srcs.every((x) => typeof x === "string")) {
835
+ sendJSON(res, 400, { error: "transcribe must be {srcs: [\"/media/…\", …] (1–200), model?, language?, again?}" }); return;
836
+ }
837
+ const missing = t.srcs.find((x) => !resolveSrc(x));
838
+ if (missing) { sendJSON(res, 404, { error: "no such file: " + missing }); return; }
839
+ const TR = require("./transcribe.js");
840
+ let spec;
841
+ try { spec = { srcs: [...new Set(t.srcs)], model: TR.model(t.model), language: TR.language(t.language), again: t.again === true }; }
842
+ catch (e) { sendJSON(res, 400, { error: e.message }); return; }
843
+ sendJSON(res, 200, exportJobs.request({ kind: "transcribe", where: opts.where, transcribe: spec }));
844
+ } catch (e) {
845
+ sendJSON(res, e.code === 409 || e.code === 400 ? e.code : 500, { error: String(e.message || e) });
846
+ }
847
+ return;
848
+ }
789
849
  /* API: proxies (see proxy.js).
790
850
  POST /api/proxy {srcs:[…], height?:540|720|1080} → {status:{src: status}} — queue them
791
851
  POST /api/proxy/status {srcs:[…]} → {status:{src: status | null}}
package/silence.js ADDED
@@ -0,0 +1,97 @@
1
+ /* FableCut silence — find the quiet stretches between phrases and cut them
2
+ out. Zero dependencies; loaded by the editor as a plain script (global
3
+ `FableCutSilence`) and required by the MCP server, so the inspector's
4
+ Silence section and `fablecut_silence` find the same spans and cut them
5
+ with the same `extract` ops.
6
+
7
+ Sound comes from ducking.js (rmsEnvelope → activeRegions → mergeRegions,
8
+ no gap bridging). Here: silentSpans (what lies between the sounds, inside
9
+ the clips, keeping `padding` of quiet around each phrase, on whole frames)
10
+ → cutOps (one extract per span, last first, so earlier times stay put). */
11
+ (function (root, factory) {
12
+ const api = factory();
13
+ if (typeof module === "object" && module.exports) module.exports = api;
14
+ else root.FableCutSilence = api;
15
+ })(typeof self !== "undefined" ? self : this, function () {
16
+ "use strict";
17
+
18
+ const DEFAULTS = { threshold: -40, minSilence: 0.5, padding: 0.15 };
19
+ const LIMITS = { threshold: [-80, -10], minSilence: [0.1, 10], padding: [0, 2] };
20
+ /** Sound shorter than this still counts (a short word); quieter blips don't. */
21
+ const MIN_SOUND = 0.08;
22
+ /** edit-ops.js MIN_DUR: extract refuses a range this short or shorter. */
23
+ const MIN_CUT = 0.05;
24
+
25
+ /** The settings, defaulted and checked. Throws on a value out of range. */
26
+ function options(o = {}) {
27
+ const out = {};
28
+ for (const k of Object.keys(DEFAULTS)) {
29
+ const v = o[k] == null ? DEFAULTS[k] : +o[k];
30
+ const [lo, hi] = LIMITS[k];
31
+ if (!Number.isFinite(v) || v < lo || v > hi) throw new Error(`${k} must be ${lo}…${hi}`);
32
+ out[k] = v;
33
+ }
34
+ return out;
35
+ }
36
+
37
+ /** Union of [start, end] spans, sorted. */
38
+ function union(list) {
39
+ const out = [];
40
+ for (const [s, e] of list.filter((r) => r[1] > r[0]).sort((x, y) => x[0] - y[0])) {
41
+ const last = out[out.length - 1];
42
+ if (last && s <= last[1] + 1e-6) last[1] = Math.max(last[1], e);
43
+ else out.push([s, e]);
44
+ }
45
+ return out;
46
+ }
47
+
48
+ /** Silent spans to cut, timeline seconds: the gaps between `sound` regions
49
+ * inside `ranges` (the clips' extents) that last at least `minSilence`,
50
+ * less `padding` kept after the phrase before and before the phrase after
51
+ * (none at a range's own start or end), snapped inward to whole frames.
52
+ * Returns [{from, to}] in time order. */
53
+ function silentSpans(sound, ranges, { minSilence = DEFAULTS.minSilence, padding = DEFAULTS.padding, fps = 30 } = {}) {
54
+ const snd = union(sound);
55
+ const frame = 1 / Math.max(1, +fps || 30);
56
+ const out = [];
57
+ for (const [rs, re] of union(ranges)) {
58
+ let t = rs;
59
+ const gaps = [];
60
+ for (const [s, e] of snd) {
61
+ if (e <= rs || s >= re) continue;
62
+ if (s > t) gaps.push([t, s]);
63
+ t = Math.max(t, e);
64
+ }
65
+ if (t < re) gaps.push([t, re]);
66
+ for (const [a, b] of gaps) {
67
+ if (b - a < minSilence - 1e-9) continue;
68
+ const from = Math.ceil(((a > rs + 1e-6 ? a + padding : a) - 1e-6) / frame) * frame;
69
+ const to = Math.floor(((b < re - 1e-6 ? b - padding : b) + 1e-6) / frame) * frame;
70
+ // compared after rounding, against the strict minimum extract accepts (more than 0.05 s, at least a frame)
71
+ const span = { from: r4(from), to: r4(to) };
72
+ if (span.to - span.from > Math.max(frame - 1e-4, MIN_CUT)) out.push(span);
73
+ }
74
+ }
75
+ return out;
76
+ }
77
+ const r4 = (x) => Math.round(x * 10000) / 10000 || 0; // as the editor stores times; never -0
78
+
79
+ /** Patch ops that cut the spans out, last first. `tracks` limits the lanes
80
+ * (default: the targeted tracks), `force` cuts through locked material. */
81
+ function cutOps(spans, { tracks = null, force = false } = {}) {
82
+ return spans.slice().sort((x, y) => y.from - x.from).map((s) => ({
83
+ op: "extract", from: s.from, to: s.to,
84
+ ...(Array.isArray(tracks) && tracks.length ? { tracks: tracks.slice() } : {}),
85
+ ...(force ? { force: true } : {}),
86
+ }));
87
+ }
88
+
89
+ /** A clip whose speed follows keyframes (a speed ramp): its sound can't be placed on the timeline
90
+ * from one speed, so it is left out of silence detection rather than risk cutting speech. */
91
+ const ramped = (c) => !!(c && c.keyframes && Array.isArray(c.keyframes.speed) && c.keyframes.speed.length);
92
+
93
+ /** Seconds the spans add up to. */
94
+ const total = (spans) => r4(spans.reduce((n, s) => n + (s.to - s.from), 0));
95
+
96
+ return { DEFAULTS, LIMITS, MIN_SOUND, options, union, silentSpans, cutOps, total, ramped };
97
+ });