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/CLAUDE.md +107 -3
- package/README.md +22 -1
- package/analyze.js +3 -96
- package/app.js +486 -6
- package/beats.js +458 -0
- package/highlights.js +296 -0
- package/index.html +3 -0
- package/mcp-server.js +274 -7
- package/package.json +1 -1
- package/reframe.js +297 -0
- package/style.css +3 -0
package/highlights.js
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
/* FableCut highlights — the best moments of long footage, cut into a short
|
|
2
|
+
edit. Zero dependencies; loaded by the editor as a plain script (global
|
|
3
|
+
`FableCutHighlights`) and required by the MCP server, so the editor,
|
|
4
|
+
fablecut_highlights and Studio pick the same moments.
|
|
5
|
+
|
|
6
|
+
picture: small RGB frames sampled through each source (PIC_FPS a second) →
|
|
7
|
+
how much moves, how sharp it is, how dark. sound: the source's mono sound →
|
|
8
|
+
its loudness every AUD_STEP seconds. shots: sudden picture changes, the cuts
|
|
9
|
+
already in the footage. pick: score every half second (movement, loudness
|
|
10
|
+
against its surroundings, a clear picture), then take the best moments of
|
|
11
|
+
`shot` seconds, never across a cut, apart from each other, until the edit is
|
|
12
|
+
`duration` long; in story order, their ends nudged to quiet points. ops: the
|
|
13
|
+
patch that lays them back to back in a new sequence. */
|
|
14
|
+
(function (root, factory) {
|
|
15
|
+
const api = factory();
|
|
16
|
+
if (typeof module === "object" && module.exports) module.exports = api;
|
|
17
|
+
else root.FableCutHighlights = api;
|
|
18
|
+
})(typeof self !== "undefined" ? self : this, function () {
|
|
19
|
+
"use strict";
|
|
20
|
+
|
|
21
|
+
const PIC_FPS = 2; // frames looked at per second of footage (one score bin each)
|
|
22
|
+
const BIN = 1 / PIC_FPS; // seconds
|
|
23
|
+
const SAMPLE_W = 64; // their width in px
|
|
24
|
+
const AUD_STEP = 0.1; // seconds per loudness reading
|
|
25
|
+
const DEFAULTS = { duration: 30, minShot: 1.5, maxShot: 4 };
|
|
26
|
+
const LIMITS = { duration: [5, 600], shot: [0.5, 20] };
|
|
27
|
+
const MAX_SOURCE_SECS = 60 * 60; // footage looked at per call
|
|
28
|
+
const clamp = (v, a, b) => (v < a ? a : v > b ? b : v);
|
|
29
|
+
const round3 = (v) => Math.round(v * 1000) / 1000;
|
|
30
|
+
const median = (a) => { if (!a.length) return 0; const s = [...a].sort((x, y) => x - y); return s[s.length >> 1]; };
|
|
31
|
+
const quantile = (a, q) => { if (!a.length) return 0; const s = [...a].sort((x, y) => x - y); return s[Math.min(s.length - 1, Math.floor(q * s.length))]; };
|
|
32
|
+
|
|
33
|
+
/** Checked options: duration (seconds of edit), shot (seconds per moment; default from duration). */
|
|
34
|
+
function options(o = {}) {
|
|
35
|
+
const duration = o.duration == null ? DEFAULTS.duration : +o.duration;
|
|
36
|
+
if (!(duration >= LIMITS.duration[0] && duration <= LIMITS.duration[1]))
|
|
37
|
+
throw new Error(`duration must be ${LIMITS.duration[0]}…${LIMITS.duration[1]} seconds`);
|
|
38
|
+
let shot = o.shot == null ? clamp(duration / 8, DEFAULTS.minShot, DEFAULTS.maxShot) : +o.shot;
|
|
39
|
+
if (!(shot >= LIMITS.shot[0] && shot <= LIMITS.shot[1])) throw new Error(`shot must be ${LIMITS.shot[0]}…${LIMITS.shot[1]} seconds`);
|
|
40
|
+
shot = Math.min(shot, duration);
|
|
41
|
+
return { duration, shot };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/* ── reading the footage ── */
|
|
45
|
+
|
|
46
|
+
/** The picture, a frame at a time: push(rgb) for each frame (w×h×3 bytes, PIC_FPS a
|
|
47
|
+
* second); `motion`, `sharp` and `dark` grow by one value per frame (0…255 scales). */
|
|
48
|
+
function picture(w, h) {
|
|
49
|
+
const n = w * h, motion = [], sharp = [], dark = [];
|
|
50
|
+
let prev = null;
|
|
51
|
+
return {
|
|
52
|
+
motion, sharp, dark,
|
|
53
|
+
push(rgb) {
|
|
54
|
+
const y = new Float32Array(n);
|
|
55
|
+
let sum = 0;
|
|
56
|
+
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]; sum += y[i]; }
|
|
57
|
+
let g = 0, d = 0;
|
|
58
|
+
for (let r = 0; r < h - 1; r++) for (let c = 0; c < w - 1; c++) {
|
|
59
|
+
const i = r * w + c;
|
|
60
|
+
g += Math.abs(y[i + 1] - y[i]) + Math.abs(y[i + w] - y[i]);
|
|
61
|
+
}
|
|
62
|
+
if (prev) for (let i = 0; i < n; i++) d += Math.abs(y[i] - prev[i]);
|
|
63
|
+
motion.push(prev ? d / n : 0);
|
|
64
|
+
sharp.push(g / ((w - 1) * (h - 1) * 2));
|
|
65
|
+
dark.push(sum / n);
|
|
66
|
+
prev = y;
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The sound, a chunk at a time: push(mono Float32Array) at `rate`; `db` grows by one
|
|
72
|
+
* RMS reading (dBFS, -90 floor) per AUD_STEP. */
|
|
73
|
+
function sound(rate) {
|
|
74
|
+
const step = Math.max(1, Math.round(rate * AUD_STEP)), db = [];
|
|
75
|
+
let acc = 0, k = 0;
|
|
76
|
+
return {
|
|
77
|
+
db,
|
|
78
|
+
push(x) {
|
|
79
|
+
for (let i = 0; i < x.length; i++) {
|
|
80
|
+
acc += x[i] * x[i];
|
|
81
|
+
if (++k === step) { db.push(Math.max(-90, 10 * Math.log10(acc / step + 1e-12))); acc = 0; k = 0; }
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Cuts already in the footage: bins (seconds) where the picture changes all at once,
|
|
88
|
+
* far beyond the movement around them. */
|
|
89
|
+
function shots(motion) {
|
|
90
|
+
const cuts = [];
|
|
91
|
+
for (let i = 1; i < motion.length; i++) {
|
|
92
|
+
const around = motion.slice(Math.max(1, i - 10), i).concat(motion.slice(i + 1, i + 11));
|
|
93
|
+
if (motion[i] > Math.max(28, 4 * median(around) + 6)) cuts.push(round3(i * BIN));
|
|
94
|
+
}
|
|
95
|
+
return cuts;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/* ── scoring and picking ── */
|
|
99
|
+
|
|
100
|
+
/** Per-bin scores (0…1) for each source {pic: picture(), aud: sound() | null}; normalised
|
|
101
|
+
* across all of them so a busy source outranks a quiet one. Also each source's cuts. */
|
|
102
|
+
function score(sources) {
|
|
103
|
+
const cutsOf = sources.map((s) => shots(s.pic.motion));
|
|
104
|
+
// movement without the cut spikes, which are edits, not action
|
|
105
|
+
const moves = sources.map((s, k) => {
|
|
106
|
+
const at = new Set(cutsOf[k].map((t) => Math.round(t / BIN)));
|
|
107
|
+
return s.pic.motion.map((m, i) => (at.has(i) ? (s.pic.motion[i - 1] || 0) : m));
|
|
108
|
+
});
|
|
109
|
+
const mHi = Math.max(1, quantile(moves.flat(), 0.9));
|
|
110
|
+
const sHi = Math.max(1, quantile(sources.flatMap((s) => s.pic.sharp), 0.75));
|
|
111
|
+
return sources.map((s, k) => {
|
|
112
|
+
const n = s.pic.motion.length, db = s.aud && s.aud.db.length ? s.aud.db : null;
|
|
113
|
+
const loudAt = (i) => {
|
|
114
|
+
if (!db) return null;
|
|
115
|
+
const a = Math.floor((i * BIN) / AUD_STEP), b = Math.max(a + 1, Math.floor(((i + 1) * BIN) / AUD_STEP));
|
|
116
|
+
let v = -90;
|
|
117
|
+
for (let j = a; j < b && j < db.length; j++) v = Math.max(v, db[j]);
|
|
118
|
+
return v;
|
|
119
|
+
};
|
|
120
|
+
const loud = Array.from({ length: n }, (_, i) => loudAt(i));
|
|
121
|
+
const out = new Float32Array(n);
|
|
122
|
+
for (let i = 0; i < n; i++) {
|
|
123
|
+
const m = clamp(moves[k][i] / mHi, 0, 1);
|
|
124
|
+
const v = clamp(s.pic.sharp[i] / sHi, 0, 1);
|
|
125
|
+
const blank = s.pic.dark[i] < 16 || s.pic.sharp[i] < 0.6; // black, or a flat colour
|
|
126
|
+
let x;
|
|
127
|
+
if (loud[i] != null) {
|
|
128
|
+
// louder than the 20 s around it: a cheer, a laugh, a hit
|
|
129
|
+
const ctx = median(loud.slice(Math.max(0, i - 20), i + 21).filter((d) => d != null));
|
|
130
|
+
const lift = clamp((loud[i] - ctx) / 12, 0, 1), level = clamp((loud[i] + 50) / 40, 0, 1);
|
|
131
|
+
x = 0.45 * m + 0.25 * lift + 0.15 * level + 0.15 * v;
|
|
132
|
+
} else x = 0.75 * m + 0.25 * v;
|
|
133
|
+
out[i] = blank ? x * 0.2 : x;
|
|
134
|
+
}
|
|
135
|
+
return { scores: out, cuts: cutsOf[k] };
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** The best moments: sources [{id, len, pic, aud, speed?}] (len: seconds of footage looked at,
|
|
140
|
+
* times from its start; speed: how fast the clip plays it, default 1) → [{source, from, to, len,
|
|
141
|
+
* score, why}] in story order: from / to in seconds of footage, len in seconds of edit, `duration`
|
|
142
|
+
* seconds of edit in all (the last ones trimmed to fit). */
|
|
143
|
+
function pick(sources, opts = {}) {
|
|
144
|
+
const { duration, shot } = options(opts);
|
|
145
|
+
const scored = score(sources);
|
|
146
|
+
const gap = Math.max(1, shot * 0.5);
|
|
147
|
+
const cands = [];
|
|
148
|
+
sources.forEach((s, k) => {
|
|
149
|
+
const sc = scored[k].scores, n = sc.length, sp = speedOfSource(s);
|
|
150
|
+
const len = Math.min(s.len, n * BIN);
|
|
151
|
+
const bounds = [0, ...scored[k].cuts, len];
|
|
152
|
+
for (let b = 0; b + 1 < bounds.length; b++) {
|
|
153
|
+
const a0 = bounds[b], a1 = bounds[b + 1];
|
|
154
|
+
const L = Math.min(shot * sp, a1 - a0); // `shot` seconds of edit, in seconds of footage
|
|
155
|
+
if (L / sp < Math.min(1, shot)) continue; // a flash between two cuts
|
|
156
|
+
for (let t = a0; t + L <= a1 + 1e-6; t += BIN) {
|
|
157
|
+
const i0 = Math.round(t / BIN), i1 = Math.max(i0 + 1, Math.round((t + L) / BIN));
|
|
158
|
+
let sum = 0;
|
|
159
|
+
for (let i = i0; i < i1 && i < n; i++) sum += sc[i];
|
|
160
|
+
cands.push({ k, shotNo: b, from: t, to: t + L, score: sum / (i1 - i0), lo: a0, hi: a1 });
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
const chosen = [], perShot = new Map();
|
|
165
|
+
let total = 0;
|
|
166
|
+
while (total < duration - 1e-6) {
|
|
167
|
+
let best = null, bestV = -1;
|
|
168
|
+
for (const c of cands) {
|
|
169
|
+
if (c.used) continue;
|
|
170
|
+
if (chosen.some((p) => p.k === c.k && c.from < p.to + gap && c.to > p.from - gap)) { c.used = true; continue; }
|
|
171
|
+
const v = c.score * Math.pow(0.8, perShot.get(c.k + ":" + c.shotNo) || 0); // variety: a shot already used counts less
|
|
172
|
+
if (v > bestV) { bestV = v; best = c; }
|
|
173
|
+
}
|
|
174
|
+
if (!best) break;
|
|
175
|
+
best.used = true;
|
|
176
|
+
chosen.push(best);
|
|
177
|
+
perShot.set(best.k + ":" + best.shotNo, (perShot.get(best.k + ":" + best.shotNo) || 0) + 1);
|
|
178
|
+
total += (best.to - best.from) / speedOfSource(sources[best.k]);
|
|
179
|
+
}
|
|
180
|
+
chosen.sort((a, b) => a.k - b.k || a.from - b.from);
|
|
181
|
+
// ends on a quiet moment nearby (not through a word or a hit), never past a cut
|
|
182
|
+
for (const c of chosen) {
|
|
183
|
+
const db = sources[c.k].aud && sources[c.k].aud.db;
|
|
184
|
+
if (!db || !db.length) continue;
|
|
185
|
+
const quiet = (lo, hi, t) => {
|
|
186
|
+
let bestT = t, bestD = Infinity;
|
|
187
|
+
for (let u = lo; u <= hi + 1e-6; u += AUD_STEP) {
|
|
188
|
+
const d = db[Math.round(u / AUD_STEP)];
|
|
189
|
+
if (d != null && d < bestD - 1) { bestD = d; bestT = u; }
|
|
190
|
+
}
|
|
191
|
+
return bestT;
|
|
192
|
+
};
|
|
193
|
+
// the start moves either way and the moment keeps its length; the end only moves later, so the
|
|
194
|
+
// edit never comes out short (the trim below takes any extra off the last moments)
|
|
195
|
+
const L = c.to - c.from;
|
|
196
|
+
c.from = quiet(Math.max(c.lo, c.from - 0.3), Math.max(c.lo, Math.min(c.from + 0.3, c.hi - L)), c.from);
|
|
197
|
+
c.to = c.from + L;
|
|
198
|
+
c.to = quiet(c.to, Math.min(c.hi, c.to + 0.3), c.to);
|
|
199
|
+
}
|
|
200
|
+
// exactly `duration`: trim the moments from the end
|
|
201
|
+
// (in seconds of edit: a clip at 2× spends two seconds of footage on each)
|
|
202
|
+
let over = chosen.reduce((n, c) => n + (c.to - c.from) / speedOfSource(sources[c.k]), 0) - duration;
|
|
203
|
+
for (let i = chosen.length - 1; i >= 0 && over > 1e-3; i--) {
|
|
204
|
+
const c = chosen[i], sp = speedOfSource(sources[c.k]), cut = Math.min(over, (c.to - c.from) / sp - 0.5);
|
|
205
|
+
if (cut > 0) { c.to -= cut * sp; over -= cut; }
|
|
206
|
+
}
|
|
207
|
+
return chosen.map((c) => {
|
|
208
|
+
const sc = scored[c.k].scores, i0 = Math.round(c.from / BIN), i1 = Math.max(i0 + 1, Math.round(c.to / BIN));
|
|
209
|
+
const moves = sources[c.k].pic.motion.slice(i0, i1);
|
|
210
|
+
const busy = moves.length && median(moves) > quantile(sources[c.k].pic.motion, 0.6);
|
|
211
|
+
// loud: well above the footage's usual level somewhere in the moment
|
|
212
|
+
const db = sources[c.k].aud && sources[c.k].aud.db;
|
|
213
|
+
const peak = db ? Math.max(-90, ...db.slice(Math.floor(c.from / AUD_STEP), Math.ceil(c.to / AUD_STEP))) : -90;
|
|
214
|
+
const loud = !!(db && db.length && peak > median(db) + 8);
|
|
215
|
+
return { source: sources[c.k].id, from: round3(c.from), to: round3(c.to), len: round3((c.to - c.from) / speedOfSource(sources[c.k])),
|
|
216
|
+
score: Math.round(c.score * 100) / 100,
|
|
217
|
+
why: busy && loud ? "movement and sound" : busy ? "movement" : loud ? "sound" : "a clear picture", bins: sc.slice(i0, i1).length };
|
|
218
|
+
}).map(({ bins, ...p }) => p);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/* ── the edit ── */
|
|
222
|
+
|
|
223
|
+
/** Clips this tool reads: video clips with a picture, at a steady speed. `ids` limits them. */
|
|
224
|
+
function sourcesOf(doc, ids = null) {
|
|
225
|
+
const take = [], skip = [];
|
|
226
|
+
const off = new Set(Array.isArray(doc.disabledTracks) ? doc.disabledTracks : []);
|
|
227
|
+
for (const c of doc.clips || []) {
|
|
228
|
+
if (ids && !ids.includes(c.id)) continue;
|
|
229
|
+
const why = c.kind !== "video" ? (ids ? `${/^[aeiou]/.test(c.kind) ? "an" : "a"} ${c.kind} clip` : null)
|
|
230
|
+
: c.disabled || off.has(c.track) ? "disabled"
|
|
231
|
+
: Array.isArray(c.keyframes?.speed) && c.keyframes.speed.length ? "a speed ramp"
|
|
232
|
+
: null;
|
|
233
|
+
if (c.kind !== "video" && !ids) continue;
|
|
234
|
+
if (why) skip.push({ id: c.id, why }); else take.push(c);
|
|
235
|
+
}
|
|
236
|
+
return { take, skip };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const speedOf = (c) => clamp(+(c.props && c.props.speed) || 1, 0.1, 8);
|
|
240
|
+
function speedOfSource(s) { return clamp(+s.speed || 1, 0.1, 8); }
|
|
241
|
+
|
|
242
|
+
/** The patch: a new sequence (`seq`: {name, width?, height?, fps?}) holding each moment as
|
|
243
|
+
* a clip back to back on V1, with the sound clips linked to its source alongside.
|
|
244
|
+
* `picks` from pick(), whose `source` is a clip id in `doc` or "media:<id>" for a whole file
|
|
245
|
+
* (its `from` / `to` in seconds from the start of that clip's window). */
|
|
246
|
+
function ops(doc, picks, seq) {
|
|
247
|
+
const out = [{ op: "addSequence", from: "empty", name: seq.name, ...(seq.width ? { width: seq.width, height: seq.height } : {}),
|
|
248
|
+
...(seq.fps ? { fps: seq.fps } : {}), open: true }];
|
|
249
|
+
const clips = doc.clips || [];
|
|
250
|
+
// ids no clip in the project has, in any sequence or composition (a second run gets hl1_2, …)
|
|
251
|
+
const used = new Set([...clips, ...(doc.sequences || []).flatMap((q) => q.clips || []), ...(doc.comps || []).flatMap((q) => q.clips || [])].map((c) => c.id));
|
|
252
|
+
let run = 1;
|
|
253
|
+
const tag = () => (run === 1 ? "" : `_${run}`);
|
|
254
|
+
while (picks.some((_, n) => [...used].some((u) => u === `hl${n + 1}${tag()}` || u.startsWith(`hl${n + 1}${tag()}a`)))) run++;
|
|
255
|
+
let at = 0;
|
|
256
|
+
picks.forEach((p, n) => {
|
|
257
|
+
const id = `hl${n + 1}${tag()}`;
|
|
258
|
+
let c = clips.find((x) => x.id === p.source);
|
|
259
|
+
if (!c && String(p.source).startsWith("media:")) {
|
|
260
|
+
const m = (doc.media || []).find((x) => x.id === p.source.slice(6));
|
|
261
|
+
if (m) c = { id, mediaId: m.id, kind: "video", track: "V1", start: 0, in: 0, duration: m.duration, props: {} };
|
|
262
|
+
}
|
|
263
|
+
if (!c) return;
|
|
264
|
+
const sp = speedOf(c), len = (p.to - p.from) / sp;
|
|
265
|
+
const props = { ...(c.props || {}) };
|
|
266
|
+
delete props.reframe; // the new canvas gets framed anew
|
|
267
|
+
const partners = clips.filter((x) => x !== c && x.id !== c.id && x.kind === "audio" &&
|
|
268
|
+
((c.linkGroup && x.linkGroup === c.linkGroup) || (c.linkedId && c.linkedId === x.id) || x.linkedId === c.id));
|
|
269
|
+
const group = partners.length ? `hl_${n + 1}` : null;
|
|
270
|
+
out.push({ op: "addClip", clip: { id, mediaId: c.mediaId, kind: "video", track: "V1", start: round3(at),
|
|
271
|
+
in: round3((c.in || 0) + p.from), duration: round3(len), props, ...(group ? { linkGroup: group } : {}) } });
|
|
272
|
+
partners.forEach((x, j) => {
|
|
273
|
+
// the same moment of the sound: through where the two sit on the timeline
|
|
274
|
+
const t0 = c.start + p.from / sp, xs = speedOf(x);
|
|
275
|
+
const xin = (x.in || 0) + (t0 - x.start) * xs;
|
|
276
|
+
if (xin < (x.in || 0) - 1e-3 || t0 + len > x.start + x.duration + 1e-3) return;
|
|
277
|
+
out.push({ op: "addClip", clip: { id: `${id}a${j + 1}`, mediaId: x.mediaId, kind: "audio", track: x.track, start: round3(at),
|
|
278
|
+
in: round3(xin), duration: round3(len), props: { ...(x.props || {}) }, linkGroup: group } });
|
|
279
|
+
});
|
|
280
|
+
at += len;
|
|
281
|
+
});
|
|
282
|
+
return out;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** The reply: what was picked, and why. */
|
|
286
|
+
function describe(picks, { duration, seqName, made = false } = {}) {
|
|
287
|
+
const clock = (t) => `${Math.floor(t / 60)}:${(t % 60).toFixed(1).padStart(4, "0")}`;
|
|
288
|
+
const lenOf = (p) => (p.len != null ? p.len : p.to - p.from);
|
|
289
|
+
const total = picks.reduce((n, p) => n + lenOf(p), 0);
|
|
290
|
+
const lines = picks.map((p, i) => ` ${i + 1}. ${p.source} ${clock(p.from)}–${clock(p.to)} (${lenOf(p).toFixed(1)} s, ${p.why}, score ${p.score})`);
|
|
291
|
+
return (made ? `New sequence "${seqName}", opened: ` : "") + `${picks.length} moment${picks.length === 1 ? "" : "s"}, ${total.toFixed(1)} s` +
|
|
292
|
+
(duration && total < duration - 0.5 ? ` (asked for ${duration} s: the footage has no more distinct moments)` : "") + ":\n" + lines.join("\n");
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
return { PIC_FPS, BIN, SAMPLE_W, AUD_STEP, DEFAULTS, LIMITS, MAX_SOURCE_SECS, options, picture, sound, shots, score, pick, sourcesOf, ops, describe };
|
|
296
|
+
});
|
package/index.html
CHANGED
|
@@ -676,11 +676,14 @@
|
|
|
676
676
|
<script src="loudness.js"></script>
|
|
677
677
|
<script src="ducking.js"></script>
|
|
678
678
|
<script src="silence.js"></script>
|
|
679
|
+
<script src="beats.js"></script>
|
|
679
680
|
<script src="transcribe.js"></script>
|
|
680
681
|
<script src="captions.js"></script>
|
|
681
682
|
<script src="audio-fx.js"></script>
|
|
682
683
|
<script src="mask.js"></script>
|
|
683
684
|
<script src="tracker.js"></script>
|
|
685
|
+
<script src="reframe.js"></script>
|
|
686
|
+
<script src="highlights.js"></script>
|
|
684
687
|
<script src="motion.js"></script>
|
|
685
688
|
<script src="color.js"></script>
|
|
686
689
|
<script src="edit-ops.js"></script>
|
package/mcp-server.js
CHANGED
|
@@ -291,6 +291,52 @@ const TOOLS = [
|
|
|
291
291
|
required: ["clipIds"],
|
|
292
292
|
},
|
|
293
293
|
},
|
|
294
|
+
{
|
|
295
|
+
name: "fablecut_beats",
|
|
296
|
+
description: "The music's beat on the timeline, and cuts that land on it. Listens to a music clip (an audio clip, or a video's sound) and finds its tempo (BPM), a steady beat grid phased to the hits, and the drop — all in timeline seconds, through the clip's in point and speed. Then, in one revision: markers:true puts a cyan marker on every beat; snap:true rolls each cut on the video tracks (the targeted ones, or snap:{tracks}) to the nearest beat within half a beat (snap:{maxShift} seconds) — nothing else moves, linked stems follow; retime:{track?, every?, from?} lays the clips on a track (default the lowest video track with clips) back to back on the beat, `every` beats each (1, 2, 4, 8 or 16; default 2), from the first beat at or after `from` (default the music's start) — a clip whose footage runs out gets fewer beats, and the order is kept. Locked clips are left alone (snap) or refuse (retime) unless force:true. A version is saved before snap or retime (if that fails the edit still goes ahead and the reply warns). Without markers / snap / retime it only reports. The same as the Inspector's Beats section. Needs ffmpeg on PATH.",
|
|
297
|
+
inputSchema: {
|
|
298
|
+
type: "object",
|
|
299
|
+
properties: {
|
|
300
|
+
clipId: { type: "string", description: "The music clip to listen to" },
|
|
301
|
+
markers: { type: "boolean", description: "Put a cyan marker on every beat (other markers stay)" },
|
|
302
|
+
snap: { description: "true, or {tracks?:[…], maxShift?: seconds}: roll each cut on those video tracks to the nearest beat" },
|
|
303
|
+
retime: { description: "true, or {track?: 'V1', every?: 1|2|4|8|16, from?: seconds}: re-cut that track's clips to the beat, `every` beats each" },
|
|
304
|
+
every: { type: "number", description: "Beats per shot for retime (1, 2, 4, 8 or 16; default 2)" },
|
|
305
|
+
force: { type: "boolean", description: "Also move locked clips (only when the user asked)" },
|
|
306
|
+
},
|
|
307
|
+
required: ["clipId"],
|
|
308
|
+
},
|
|
309
|
+
},
|
|
310
|
+
{
|
|
311
|
+
name: "fablecut_reframe",
|
|
312
|
+
description: "Reframe for another shape, following the subject: a 16:9 edit made 9:16 (Reels, Shorts, TikTok), 1:1 or 4:5. With aspect, a copy of the open sequence is made on that canvas (the project's shorter side kept, e.g. 1920×1080 → 1080×1920) and opened, so the original cut stays as it was; without aspect, the open sequence is reframed on its own canvas. Each full-frame shot (a video or still that isn't moved, scaled, cropped or animated by hand) is fitted to cover the canvas, and its position follows what matters in it: frames are sampled 5 times a second, the subject is found by motion against the shot's own movement, detail and colour, and a virtual camera operator holds still until the subject leaves a dead zone, then eases after it no faster than a pan speed. The result is ordinary x (or y) keyframes, thinned to a few, or one steady position — edit them like any keys. Shots without a clear subject are centred. Titles, picture-in-picture, clips placed by hand and locked clips are left alone (listed in the reply) — check them with fablecut_frame on the new canvas. clipIds limits it to some clips; follow:false only fits and centres; smooth 0…1 (default 0.5) — higher holds longer and pans slower. A version is saved first. Needs ffmpeg on PATH.",
|
|
313
|
+
inputSchema: {
|
|
314
|
+
type: "object",
|
|
315
|
+
properties: {
|
|
316
|
+
aspect: { type: "string", enum: ["9:16", "1:1", "4:5", "16:9", "4:3", "2:3"], description: "Make a copy of the open sequence on this canvas shape and reframe it (default: reframe the open sequence as it is)" },
|
|
317
|
+
name: { type: "string", description: "With aspect: the new sequence's name (default: the open one's name and the shape)" },
|
|
318
|
+
clipIds: { type: "array", items: { type: "string" }, description: "Only these clips (default: every full-frame shot)" },
|
|
319
|
+
follow: { type: "boolean", description: "Follow the subject (default true); false only fits and centres" },
|
|
320
|
+
smooth: { type: "number", description: "0…1, default 0.5: higher holds longer and pans slower" },
|
|
321
|
+
force: { type: "boolean", description: "Also reframe locked clips (only when the user asked)" },
|
|
322
|
+
},
|
|
323
|
+
},
|
|
324
|
+
},
|
|
325
|
+
{
|
|
326
|
+
name: "fablecut_highlights",
|
|
327
|
+
description: "The best moments of long footage, cut into a short edit: a 30 s reel from a 20-minute vlog, a match, a talk, a day of B-roll. Looks at the video clips on the open timeline (or clipIds, or whole files with mediaIds) — frames twice a second and the sound — and scores every half second: movement, sound louder than around it (a cheer, a laugh, a hit), a clear picture. Cuts already in the footage are found and never crossed. It takes the best moments of `shot` seconds (default: duration / 8, 1.5–4 s), apart from each other and spread over the shots, until the edit is `duration` seconds (default 30), and nudges each end to a quiet point so no word or hit is cut through. They go back to back on V1 of a new sequence, in story order, with their linked sound, and the sequence is opened; the timeline you started from is left as it was. aspect makes the new sequence 9:16, 1:1 or 4:5 (then fablecut_reframe {} fits the shots and follows the subject). The reply lists each moment (source, times, why it was picked). A version is saved first. Then: music under it and fablecut_beats {clipId, retime:{every:2}} cuts it on the beat. Needs ffmpeg on PATH.",
|
|
328
|
+
inputSchema: {
|
|
329
|
+
type: "object",
|
|
330
|
+
properties: {
|
|
331
|
+
duration: { type: "number", description: "Seconds of edit to make, 5…600 (default 30)" },
|
|
332
|
+
shot: { type: "number", description: "Seconds per moment, 0.5…20 (default: duration / 8, kept within 1.5–4)" },
|
|
333
|
+
clipIds: { type: "array", items: { type: "string" }, description: "Video clips to look through (default: every video clip on the open timeline)" },
|
|
334
|
+
mediaIds: { type: "array", items: { type: "string" }, description: "Instead of clips: whole video files from the project's media" },
|
|
335
|
+
name: { type: "string", description: "The new sequence's name (default: Highlights <duration> s)" },
|
|
336
|
+
aspect: { type: "string", enum: ["9:16", "1:1", "4:5", "16:9", "4:3", "2:3"], description: "The new sequence's shape (default: the open one's canvas)" },
|
|
337
|
+
},
|
|
338
|
+
},
|
|
339
|
+
},
|
|
294
340
|
{
|
|
295
341
|
name: "fablecut_transcribe",
|
|
296
342
|
description: "What is said, word by word, with times — and text-based editing. Transcribes the clips' speech with Whisper in the editor (an open tab, else headless Chrome / Edge; the speech model downloads once, the audio never leaves the machine), keeps one transcript per file (analysis/transcripts/), and answers with the timeline's words as timed lines (timeline seconds), so you can read an interview, pick the good takes, or find where something is said. find:\"phrase\" (or a list) reports every place it is said — case, punctuation and spacing ignored, whole words only — with the exact span; cut:true then extracts each of them on the targeted tracks (or `tracks`), the words and the pause after them, last first, in one revision: later material moves up, linked stems stay in sync, locked clips stay put (lock the music bed first). A version is saved before a cut. Files already transcribed aren't done again unless again:true. Default clips: every video / audio clip with sound on the open timeline. mediaIds reads whole files instead (file seconds; no cut). The same as the editor's Transcript tab.",
|
|
@@ -634,8 +680,7 @@ async function silenceTool(args) {
|
|
|
634
680
|
let verWarn = "";
|
|
635
681
|
try { createHistory({ projects: createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR }) }).beforeAgent("Before cutting silences"); }
|
|
636
682
|
catch (e) { verWarn = ` Warning: no version was saved before the cut (${e.message}).`; }
|
|
637
|
-
|
|
638
|
-
try { diskRev = readProject().revision || 0; } catch {}
|
|
683
|
+
const diskRev = readProject().revision || 0; // a failed read stops it: never write over what we can't see
|
|
639
684
|
if (diskRev !== readRev) throw new Error(`the project changed while cutting (revision ${readRev} → ${diskRev}) — nothing cut; run fablecut_silence again`);
|
|
640
685
|
proj.revision = readRev + 1;
|
|
641
686
|
writeProject(proj);
|
|
@@ -643,6 +688,224 @@ async function silenceTool(args) {
|
|
|
643
688
|
return `Cut ${head} — timeline ${fmtDur(before)} → ${fmtDur(end(proj))} (revision ${proj.revision}). UI hot-reloaded.` +
|
|
644
689
|
(verWarn || ` The project as it was is kept as a version (fablecut_versions lists it; restore undoes the cut).`);
|
|
645
690
|
}
|
|
691
|
+
/* fablecut_beats: beats.js on the music clip's sound, then its ops (markers, snap, retime). */
|
|
692
|
+
const BEATS_MAX_SECS = 20 * 60;
|
|
693
|
+
async function beatsTool(args) {
|
|
694
|
+
const Bt = require("./beats.js");
|
|
695
|
+
const doc = readProject();
|
|
696
|
+
const readRev = doc.revision || 0;
|
|
697
|
+
const clip = doc.clips.find((c) => c.id === String(args.clipId || ""));
|
|
698
|
+
if (!clip) throw new Error("`clipId` must name the music clip on the timeline (fablecut_get_project {compact:true} lists them)");
|
|
699
|
+
if (clip.kind !== "audio" && clip.kind !== "video") throw new Error(`clip ${clip.id} is ${clip.kind} — no sound to find a beat in`);
|
|
700
|
+
if (Bt.ramped(clip)) throw new Error(`clip ${clip.id} has a speed ramp — beats follow music playing at a steady speed`);
|
|
701
|
+
const sp = Math.min(8, Math.max(0.1, +clip.props?.speed || 1));
|
|
702
|
+
if (clip.duration * sp > BEATS_MAX_SECS) throw new Error(`clip ${clip.id} is longer than ${BEATS_MAX_SECS / 60} minutes of music — split it, or find the beat on a part of it`);
|
|
703
|
+
const parts = [];
|
|
704
|
+
const nCh = await streamClipAudio(doc, clip, () => true, (chs) => parts.push(Bt.mono(chs)));
|
|
705
|
+
if (!nCh) throw new Error(`clip ${clip.id} has no audio stream — nothing to listen to`);
|
|
706
|
+
const len = parts.reduce((n, p) => n + p.length, 0), all = new Float32Array(len);
|
|
707
|
+
let at = 0;
|
|
708
|
+
for (const p of parts) { all.set(p, at); at += p.length; }
|
|
709
|
+
const a = Bt.analyze(Bt.resample(all, NORM_SR));
|
|
710
|
+
const src0 = clip.in || 0;
|
|
711
|
+
const abs = { beats: a.beats.map((t) => t + src0), bpm: a.bpm, drop: a.drop != null ? a.drop + src0 : null };
|
|
712
|
+
const acts = { markers: args.markers === true, snap: args.snap || false, retime: args.retime || false, every: args.every, force: args.force === true };
|
|
713
|
+
const r = Bt.plan(doc, clip, abs, acts);
|
|
714
|
+
if (!r.ops.length) return Bt.describe(r);
|
|
715
|
+
const proj = readProject();
|
|
716
|
+
if ((proj.revision || 0) !== readRev)
|
|
717
|
+
throw new Error(`the project changed while listening (revision ${readRev} → ${proj.revision}) — nothing changed; run fablecut_beats again`);
|
|
718
|
+
ProjectOps.applyPatch(proj, r.ops, { savedItems });
|
|
719
|
+
let verWarn = "";
|
|
720
|
+
if (acts.snap || acts.retime) {
|
|
721
|
+
try { createHistory({ projects: createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR }) }).beforeAgent(acts.retime ? "Before re-cutting to the beat" : "Before snapping cuts to the beat"); }
|
|
722
|
+
catch (e) { verWarn = ` Warning: no version was saved first (${e.message}).`; }
|
|
723
|
+
}
|
|
724
|
+
const diskRev = readProject().revision || 0; // a failed read stops it: never write over what we can't see
|
|
725
|
+
if (diskRev !== readRev) throw new Error(`the project changed meanwhile (revision ${readRev} → ${diskRev}) — nothing changed; run fablecut_beats again`);
|
|
726
|
+
proj.revision = readRev + 1;
|
|
727
|
+
writeProject(proj);
|
|
728
|
+
lastReadRevision = proj.revision;
|
|
729
|
+
return Bt.describe(r, { applied: true }) + ` (revision ${proj.revision}; UI hot-reloaded.)` +
|
|
730
|
+
(acts.snap || acts.retime ? verWarn || " The project as it was is kept as a version (fablecut_versions; restore undoes it)." : "");
|
|
731
|
+
}
|
|
732
|
+
/* fablecut_reframe: a new sequence on the canvas asked for (or the open one), then reframe.js on frames
|
|
733
|
+
ffmpeg samples from each full-frame shot's window. */
|
|
734
|
+
const REFRAME_MAX_SECS = 15 * 60;
|
|
735
|
+
function sampleFrames(file, c, w, h) {
|
|
736
|
+
const R = require("./reframe.js");
|
|
737
|
+
const sp = Math.min(8, Math.max(0.1, +c.props?.speed || 1));
|
|
738
|
+
const len = Math.max(0.1, Math.min(REFRAME_MAX_SECS, c.duration * sp));
|
|
739
|
+
const args = c.kind === "image"
|
|
740
|
+
? ["-v", "error", "-i", file, "-frames:v", "1", "-vf", `scale=${w}:${h}`, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]
|
|
741
|
+
: ["-v", "error", "-ss", String(Math.max(0, +c.in || 0)), "-t", String(len), "-i", file, "-an",
|
|
742
|
+
"-vf", `fps=${R.SAMPLE_FPS},scale=${w}:${h}`, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"];
|
|
743
|
+
const r = require("child_process").spawnSync("ffmpeg", args, { maxBuffer: 1 << 29, timeout: Math.max(120000, len * 2000) });
|
|
744
|
+
if (r.error?.code === "ENOENT") throw new Error("ffmpeg not found on PATH — needed to look at the footage");
|
|
745
|
+
if (r.error) throw new Error(`ffmpeg couldn't read ${c.id}: ${r.error.code === "ETIMEDOUT" ? "it took too long" : r.error.message}`);
|
|
746
|
+
if (r.status !== 0) throw new Error(`ffmpeg couldn't read ${c.id}: ${String(r.stderr).trim().split("\n").pop()}`);
|
|
747
|
+
const fb = w * h * 3, frames = [];
|
|
748
|
+
for (let o = 0; o + fb <= r.stdout.length; o += fb) frames.push(r.stdout.subarray(o, o + fb));
|
|
749
|
+
return frames;
|
|
750
|
+
}
|
|
751
|
+
async function reframeTool(args) {
|
|
752
|
+
const R = require("./reframe.js");
|
|
753
|
+
const doc = readProject();
|
|
754
|
+
const readRev = doc.revision || 0;
|
|
755
|
+
const smooth = args.smooth == null ? 0.5 : +args.smooth;
|
|
756
|
+
if (!(smooth >= 0 && smooth <= 1)) throw new Error("smooth must be 0…1");
|
|
757
|
+
const ids = Array.isArray(args.clipIds) && args.clipIds.length ? args.clipIds.map(String) : null;
|
|
758
|
+
const ops = [];
|
|
759
|
+
// the sequence as it will be: a copy on the new canvas, opened — or the open one
|
|
760
|
+
let work = doc, made = "";
|
|
761
|
+
if (args.aspect) {
|
|
762
|
+
const canvas = R.canvasFor(args.aspect, doc.width, doc.height);
|
|
763
|
+
const open = (doc.sequences || []).find((s) => s.id === doc.sequence);
|
|
764
|
+
const seqName = String(args.name || `${open?.name || "Main"} ${args.aspect}`).slice(0, 80);
|
|
765
|
+
const add = { op: "addSequence", from: "open", name: seqName, width: canvas.width, height: canvas.height, open: true };
|
|
766
|
+
work = JSON.parse(JSON.stringify(doc));
|
|
767
|
+
ProjectOps.applyPatch(work, [add], { savedItems });
|
|
768
|
+
ops.push(add);
|
|
769
|
+
made = `New sequence "${seqName}" ${canvas.width}×${canvas.height}, opened. `;
|
|
770
|
+
}
|
|
771
|
+
const canvas = { width: work.width, height: work.height };
|
|
772
|
+
const { take, skip } = R.targets(work, { ids, force: args.force === true });
|
|
773
|
+
if (!take.length) throw new Error("no full-frame shots to reframe" + (skip.length ? ` (${skip.map((x) => `${x.id}: ${x.why}`).join("; ")})` : ""));
|
|
774
|
+
const lines = [];
|
|
775
|
+
for (const c of take) {
|
|
776
|
+
const m = work.media.find((x) => x.id === c.mediaId);
|
|
777
|
+
const file = m && mediaFile(m.src);
|
|
778
|
+
if (!file) { skip.push({ id: c.id, why: "media file not found" }); continue; }
|
|
779
|
+
let src = m.width > 0 && m.height > 0 ? { width: m.width, height: m.height } : null;
|
|
780
|
+
if (!src) {
|
|
781
|
+
const pr = require("child_process").spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", file], { timeout: 10000 });
|
|
782
|
+
const [w, h] = String(pr.stdout).trim().split(",").map(Number);
|
|
783
|
+
if (w > 0 && h > 0) src = { width: w, height: h };
|
|
784
|
+
}
|
|
785
|
+
if (!src) { skip.push({ id: c.id, why: "couldn't read its size" }); continue; }
|
|
786
|
+
let samples = null;
|
|
787
|
+
const cover = R.coverRect(src.width, src.height, canvas.width, canvas.height, 1);
|
|
788
|
+
if (args.follow !== false && Math.max(cover.maxX, cover.maxY) > 0.5) { // no room to pan: nothing to look at
|
|
789
|
+
const w = R.SAMPLE_W, h = Math.max(8, Math.round(w * src.height / src.width / 2) * 2);
|
|
790
|
+
try { samples = R.subjectTrack(sampleFrames(file, c, w, h), w, h); }
|
|
791
|
+
catch (e) { skip.push({ id: c.id, why: e.message }); continue; }
|
|
792
|
+
}
|
|
793
|
+
const p = R.clipPlan(c, samples, src, canvas, { smooth, fps: work.fps || 30, follow: args.follow !== false });
|
|
794
|
+
ops.push({ op: "updateClip", id: c.id, set: p.set, ...(args.force === true ? { force: true } : {}) });
|
|
795
|
+
lines.push(` ${c.id}: ${p.note}`);
|
|
796
|
+
}
|
|
797
|
+
if (!lines.length) throw new Error("nothing could be reframed: " + skip.map((x) => `${x.id}: ${x.why}`).join("; "));
|
|
798
|
+
const proj = readProject();
|
|
799
|
+
if ((proj.revision || 0) !== readRev)
|
|
800
|
+
throw new Error(`the project changed while looking at the footage (revision ${readRev} → ${proj.revision}) — nothing changed; run fablecut_reframe again`);
|
|
801
|
+
let verWarn = "";
|
|
802
|
+
try { createHistory({ projects: createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR }) }).beforeAgent("Before reframing"); }
|
|
803
|
+
catch (e) { verWarn = ` Warning: no version was saved first (${e.message}).`; }
|
|
804
|
+
const diskRev = readProject().revision || 0; // a failed read stops it: never write over what we can't see
|
|
805
|
+
if (diskRev !== readRev) throw new Error(`the project changed meanwhile (revision ${readRev} → ${diskRev}) — nothing changed; run fablecut_reframe again`);
|
|
806
|
+
ProjectOps.applyPatch(proj, ops, { savedItems });
|
|
807
|
+
proj.revision = readRev + 1;
|
|
808
|
+
writeProject(proj);
|
|
809
|
+
lastReadRevision = proj.revision;
|
|
810
|
+
return `${made}Reframed ${lines.length} shot${lines.length === 1 ? "" : "s"} for ${canvas.width}×${canvas.height} (revision ${proj.revision}):\n` + lines.join("\n") +
|
|
811
|
+
(skip.length ? `\nLeft as they were: ${skip.map((x) => `${x.id} (${x.why})`).join(", ")} — check them on the new canvas with fablecut_frame {time}.` : "") +
|
|
812
|
+
(verWarn || "\nThe project as it was is kept as a version (fablecut_versions; restore undoes it).");
|
|
813
|
+
}
|
|
814
|
+
/* fablecut_highlights: highlights.js on the frames and sound ffmpeg streams from each source
|
|
815
|
+
(frame by frame, without holding the server), then a new sequence holding the best moments. */
|
|
816
|
+
function streamPicture(file, from, len, w, h, push) {
|
|
817
|
+
const H = require("./highlights.js");
|
|
818
|
+
return new Promise((resolve, reject) => {
|
|
819
|
+
const proc = spawn("ffmpeg", ["-v", "error", "-ss", String(Math.max(0, from)), "-t", String(Math.max(0.1, len)), "-i", file, "-an",
|
|
820
|
+
"-vf", `fps=${H.PIC_FPS},scale=${w}:${h}`, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]);
|
|
821
|
+
const fb = w * h * 3;
|
|
822
|
+
let rest = Buffer.alloc(0), err = "", n = 0;
|
|
823
|
+
const tm = setTimeout(() => { proc.kill(); reject(new Error("ffmpeg took too long reading the footage")); }, Math.max(120000, len * 1000));
|
|
824
|
+
proc.stdout.on("data", (chunk) => {
|
|
825
|
+
const buf = rest.length ? Buffer.concat([rest, chunk]) : chunk;
|
|
826
|
+
let o = 0;
|
|
827
|
+
for (; o + fb <= buf.length; o += fb) { push(buf.subarray(o, o + fb)); n++; }
|
|
828
|
+
rest = Buffer.from(buf.subarray(o));
|
|
829
|
+
});
|
|
830
|
+
proc.stderr.on("data", (d) => { err += d; });
|
|
831
|
+
proc.on("error", (e) => { clearTimeout(tm); reject(new Error(e.code === "ENOENT" ? "ffmpeg not found on PATH — needed to look at the footage" : e.message)); });
|
|
832
|
+
proc.on("close", (code) => { clearTimeout(tm); if (code === 0) resolve(n); else reject(new Error(`ffmpeg couldn't read the footage: ${err.trim().split("\n").pop() || code}`)); });
|
|
833
|
+
});
|
|
834
|
+
}
|
|
835
|
+
async function highlightsTool(args) {
|
|
836
|
+
const H = require("./highlights.js"), Bt = require("./beats.js");
|
|
837
|
+
const opts = H.options(args);
|
|
838
|
+
const doc = readProject();
|
|
839
|
+
const readRev = doc.revision || 0;
|
|
840
|
+
const canvas = args.aspect ? require("./reframe.js").canvasFor(args.aspect, doc.width, doc.height) : {}; // a bad shape refuses before any reading
|
|
841
|
+
const srcs = [];
|
|
842
|
+
let skip = [];
|
|
843
|
+
if (Array.isArray(args.mediaIds) && args.mediaIds.length) {
|
|
844
|
+
for (const id of args.mediaIds.map(String)) {
|
|
845
|
+
const m = (doc.media || []).find((x) => x.id === id);
|
|
846
|
+
if (!m) throw new Error(`no media ${id}`);
|
|
847
|
+
if (m.kind !== "video") throw new Error(`media ${id} is ${m.kind} — highlights are cut from video`);
|
|
848
|
+
if (!(m.duration > 0)) throw new Error(`media ${id}: its length isn't known yet — open the editor so it probes the file, then call again`);
|
|
849
|
+
srcs.push({ id: "media:" + id, clip: { id: "media:" + id, mediaId: id, kind: "video", in: 0, duration: m.duration, props: {} }, media: m });
|
|
850
|
+
}
|
|
851
|
+
} else {
|
|
852
|
+
const ids = Array.isArray(args.clipIds) && args.clipIds.length ? args.clipIds.map(String) : null;
|
|
853
|
+
const r = H.sourcesOf(doc, ids);
|
|
854
|
+
skip = r.skip;
|
|
855
|
+
for (const c of r.take) {
|
|
856
|
+
const m = (doc.media || []).find((x) => x.id === c.mediaId);
|
|
857
|
+
if (m) srcs.push({ id: c.id, clip: c, media: m });
|
|
858
|
+
else skip.push({ id: c.id, why: "its media isn't in the project" });
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
const why = () => skip.map((x) => `${x.id} (${x.why})`).join(", ");
|
|
862
|
+
if (!srcs.length) throw new Error("no video to make highlights from" + (skip.length ? `: ${why()}` : "") + " — put footage on the timeline, or pass mediaIds");
|
|
863
|
+
const total = srcs.reduce((n, s) => n + clipSourceLen(s.clip), 0);
|
|
864
|
+
if (total > H.MAX_SOURCE_SECS)
|
|
865
|
+
throw new Error(`that's ${Math.round(total / 60)} minutes of footage — up to ${H.MAX_SOURCE_SECS / 60} at a time; pass clipIds or mediaIds`);
|
|
866
|
+
const sources = [];
|
|
867
|
+
for (const s of srcs) {
|
|
868
|
+
const file = mediaFile(s.media.src);
|
|
869
|
+
if (!file) { skip.push({ id: s.id, why: "media file not found" }); continue; }
|
|
870
|
+
let mw = s.media.width, mh = s.media.height;
|
|
871
|
+
if (!(mw > 0 && mh > 0)) {
|
|
872
|
+
const pr = spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", file], { timeout: 10000 });
|
|
873
|
+
[mw, mh] = String(pr.stdout || "").trim().split(",").map(Number);
|
|
874
|
+
}
|
|
875
|
+
const w = H.SAMPLE_W, h = Math.max(8, Math.round((w * (mw > 0 && mh > 0 ? mh / mw : 9 / 16)) / 2) * 2);
|
|
876
|
+
const len = clipSourceLen(s.clip), pic = H.picture(w, h);
|
|
877
|
+
try { await streamPicture(file, s.clip.in || 0, len, w, h, (f) => pic.push(f)); }
|
|
878
|
+
catch (e) { skip.push({ id: s.id, why: e.message }); continue; }
|
|
879
|
+
if (pic.motion.length < 2) { skip.push({ id: s.id, why: "too short to look at" }); continue; }
|
|
880
|
+
let aud = H.sound(NORM_SR);
|
|
881
|
+
try { if (!(await streamClipAudio(doc, s.clip, () => true, (chs) => aud.push(Bt.mono(chs))))) aud = null; }
|
|
882
|
+
catch { aud = null; } // no sound to read: the picture alone decides
|
|
883
|
+
sources.push({ id: s.id, len, pic, aud, speed: Math.min(8, Math.max(0.1, +s.clip.props?.speed || 1)) });
|
|
884
|
+
}
|
|
885
|
+
if (!sources.length) throw new Error("none of the footage could be read: " + why());
|
|
886
|
+
const picks = H.pick(sources, opts);
|
|
887
|
+
if (!picks.length) throw new Error("no moments long enough to use — try a shorter shot");
|
|
888
|
+
const seqName = String(args.name || `Highlights ${opts.duration} s`).slice(0, 80);
|
|
889
|
+
const ops = H.ops(doc, picks, { name: seqName, ...canvas });
|
|
890
|
+
const proj = readProject();
|
|
891
|
+
if ((proj.revision || 0) !== readRev)
|
|
892
|
+
throw new Error(`the project changed while looking at the footage (revision ${readRev} → ${proj.revision}) — nothing changed; run fablecut_highlights again`);
|
|
893
|
+
let verWarn = "";
|
|
894
|
+
try { createHistory({ projects: createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR }) }).beforeAgent("Before making highlights"); }
|
|
895
|
+
catch (e) { verWarn = ` Warning: no version was saved first (${e.message}).`; }
|
|
896
|
+
const diskRev = readProject().revision || 0; // a failed read stops it: never write over what we can't see
|
|
897
|
+
if (diskRev !== readRev) throw new Error(`the project changed meanwhile (revision ${readRev} → ${diskRev}) — nothing changed; run fablecut_highlights again`);
|
|
898
|
+
ProjectOps.applyPatch(proj, ops, { savedItems });
|
|
899
|
+
proj.revision = readRev + 1;
|
|
900
|
+
writeProject(proj);
|
|
901
|
+
lastReadRevision = proj.revision;
|
|
902
|
+
const reshaped = canvas.width && canvas.width * doc.height !== canvas.height * doc.width;
|
|
903
|
+
return H.describe(picks, { duration: opts.duration, seqName, made: true }) + `\n(revision ${proj.revision}; UI hot-reloaded.)` +
|
|
904
|
+
(skip.length ? `\nNot looked at: ${why()}.` : "") +
|
|
905
|
+
(reshaped ? "\nThe shots are letterboxed on the new canvas: fablecut_reframe {} fits them and follows the subject." : "") +
|
|
906
|
+
"\nCheck a moment with fablecut_frame {time}; with music under it, fablecut_beats {clipId, retime:{every:2}} cuts it on the beat." +
|
|
907
|
+
(verWarn || "\nThe project as it was is kept as a version (fablecut_versions; restore undoes it).");
|
|
908
|
+
}
|
|
646
909
|
/** What words are placed by and cuts land on: where each clip sits and plays from, the track
|
|
647
910
|
* switches and the frame rate. An editor saving probed media details while a transcription runs
|
|
648
911
|
* doesn't change it; a moved, trimmed or cut clip does. */
|
|
@@ -781,8 +1044,7 @@ async function transcribeTool(args) {
|
|
|
781
1044
|
let verWarn = "";
|
|
782
1045
|
try { createHistory({ projects: createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR }) }).beforeAgent("Before cutting words"); }
|
|
783
1046
|
catch (e) { verWarn = ` Warning: no version was saved before the cut (${e.message}).`; }
|
|
784
|
-
|
|
785
|
-
try { diskRev = readProject().revision || 0; } catch {}
|
|
1047
|
+
const diskRev = readProject().revision || 0; // a failed read stops it: never write over what we can't see
|
|
786
1048
|
if (diskRev !== readRev) throw new Error(`the project changed while cutting (revision ${readRev} → ${diskRev}) — nothing cut; run fablecut_transcribe again`);
|
|
787
1049
|
proj.revision = readRev + 1;
|
|
788
1050
|
writeProject(proj);
|
|
@@ -1320,6 +1582,12 @@ async function callTool(name, args, attempt = 0) {
|
|
|
1320
1582
|
return frameTool(args);
|
|
1321
1583
|
case "fablecut_silence":
|
|
1322
1584
|
return silenceTool(args);
|
|
1585
|
+
case "fablecut_beats":
|
|
1586
|
+
return beatsTool(args);
|
|
1587
|
+
case "fablecut_reframe":
|
|
1588
|
+
return reframeTool(args);
|
|
1589
|
+
case "fablecut_highlights":
|
|
1590
|
+
return highlightsTool(args);
|
|
1323
1591
|
case "fablecut_transcribe":
|
|
1324
1592
|
return transcribeTool(args);
|
|
1325
1593
|
case "fablecut_captions":
|
|
@@ -1443,8 +1711,7 @@ async function callTool(name, args, attempt = 0) {
|
|
|
1443
1711
|
const verWarn = versionBeforeAgent(false);
|
|
1444
1712
|
// Someone else saved while the ops ran: writing now would drop their change.
|
|
1445
1713
|
// Without a baseRevision the ops just re-apply on the newer document.
|
|
1446
|
-
|
|
1447
|
-
try { diskRev = readProject().revision || 0; } catch {}
|
|
1714
|
+
const diskRev = readProject().revision || 0; // a failed read stops it: never write over what we can't see
|
|
1448
1715
|
if (diskRev !== readRev) {
|
|
1449
1716
|
if (base == null && attempt < 3) return callTool(name, args, attempt + 1);
|
|
1450
1717
|
throw conflict(diskRev);
|
|
@@ -1746,7 +2013,7 @@ async function handle(msg) {
|
|
|
1746
2013
|
result: {
|
|
1747
2014
|
protocolVersion: negotiateProtocolVersion(params?.protocolVersion),
|
|
1748
2015
|
capabilities: { tools: {} },
|
|
1749
|
-
serverInfo: { name: "fablecut", version: "1.
|
|
2016
|
+
serverInfo: { name: "fablecut", version: "1.18.0" },
|
|
1750
2017
|
},
|
|
1751
2018
|
});
|
|
1752
2019
|
}
|