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/CLAUDE.md +295 -6
- package/README.md +45 -10
- package/analyze.js +3 -96
- package/app.js +1254 -25
- package/beats.js +458 -0
- package/captions.js +227 -0
- package/delivery.js +22 -2
- package/encoding-profiles.json +26 -0
- package/export-jobs.js +14 -8
- package/highlights.js +296 -0
- package/index.html +17 -0
- package/mcp-server.js +639 -7
- package/package.json +1 -1
- package/project-ops.js +4 -3
- package/reframe.js +297 -0
- package/server.js +60 -0
- package/silence.js +97 -0
- package/style.css +170 -4
- package/transcribe-worker.js +39 -0
- package/transcribe.js +294 -0
- package/transcripts.js +78 -0
package/mcp-server.js
CHANGED
|
@@ -274,6 +274,116 @@ const TOOLS = [
|
|
|
274
274
|
required: ["clipIds"],
|
|
275
275
|
},
|
|
276
276
|
},
|
|
277
|
+
{
|
|
278
|
+
name: "fablecut_silence",
|
|
279
|
+
description: "Find the silences in speech and, with cut:true, cut them out. Listens to the given clips (a video's linked audio stems, after channel routing, gain and volume) and reports every stretch where none of them is above `threshold` for at least `minSilence` seconds, keeping `padding` seconds of quiet beside each phrase so words aren't clipped. Gaps between clips are left alone. With cut:true each silence is removed with an `extract` on the targeted tracks (or `tracks`), last first, in one revision: later material moves up, linked stems stay in sync, locked tracks and clips stay put — lock the music bed first if it should keep running. A version is saved before the cut. Without cut it only reports, so check the spans (and fablecut_frame them) first. The same as the inspector's Silence section. Needs ffmpeg + ffprobe on PATH.",
|
|
280
|
+
inputSchema: {
|
|
281
|
+
type: "object",
|
|
282
|
+
properties: {
|
|
283
|
+
clipIds: { type: "array", items: { type: "string" }, description: "The speech clips to listen to (a video clip brings its linked stems)" },
|
|
284
|
+
threshold: { type: "number", description: "Below this level (dBFS) counts as silence, -80…-10 (default -40; raise it toward -30 for a noisy room)" },
|
|
285
|
+
minSilence: { type: "number", description: "Shortest silence to report or cut, seconds 0.1…10 (default 0.5)" },
|
|
286
|
+
padding: { type: "number", description: "Quiet kept beside each phrase, seconds 0…2 (default 0.15)" },
|
|
287
|
+
cut: { type: "boolean", description: "Cut the silences out (default false: only report them)" },
|
|
288
|
+
tracks: { type: "array", items: { type: "string" }, description: "cut: the lanes to cut on (default: the targeted tracks)" },
|
|
289
|
+
force: { type: "boolean", description: "cut: also cut through locked clips (only when the user asked)" },
|
|
290
|
+
},
|
|
291
|
+
required: ["clipIds"],
|
|
292
|
+
},
|
|
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
|
+
},
|
|
340
|
+
{
|
|
341
|
+
name: "fablecut_transcribe",
|
|
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.",
|
|
343
|
+
inputSchema: {
|
|
344
|
+
type: "object",
|
|
345
|
+
properties: {
|
|
346
|
+
clipIds: { type: "array", items: { type: "string" }, description: "Clips to transcribe and read (a video brings its linked stems). Default: every clip with sound on the timeline" },
|
|
347
|
+
mediaIds: { type: "array", items: { type: "string" }, description: "Instead of clips: whole files, read in file seconds (find works, cut doesn't)" },
|
|
348
|
+
model: { type: "string", enum: ["base", "small"], description: "Whisper model: base (default, 77 MB, quick) or small (250 MB, more accurate, slower)" },
|
|
349
|
+
language: { type: "string", description: "The spoken language as a Whisper code (en, es, hi, ja, …) or auto (default: detected)" },
|
|
350
|
+
again: { type: "boolean", description: "Transcribe again even when a transcript exists (another model or language)" },
|
|
351
|
+
find: { anyOf: [{ type: "string" }, { type: "array", items: { type: "string" } }], description: "A word or phrase (or several) to find; matches are reported with their timeline spans" },
|
|
352
|
+
from: { type: "number", description: "Only words from this time on (timeline seconds; file seconds with mediaIds)" },
|
|
353
|
+
to: { type: "number", description: "Only words before this time" },
|
|
354
|
+
cut: { type: "boolean", description: "Cut every match of `find` out (default false: only report)" },
|
|
355
|
+
tracks: { type: "array", items: { type: "string" }, description: "cut: the lanes to cut on (default: the targeted tracks)" },
|
|
356
|
+
force: { type: "boolean", description: "cut: also cut through locked clips (only when the user asked)" },
|
|
357
|
+
where: { type: "string", enum: ["auto", "tab", "headless"], description: "Where to transcribe: auto (default): an open editor tab, else headless · tab · headless" },
|
|
358
|
+
timeout: { type: "number", description: "Seconds to wait for the transcription (default 1800)" },
|
|
359
|
+
},
|
|
360
|
+
},
|
|
361
|
+
},
|
|
362
|
+
{
|
|
363
|
+
name: "fablecut_captions",
|
|
364
|
+
description: "Captions from what is said: makes caption clips on the timeline from the clips' transcripts (transcribing first when there is none, like fablecut_transcribe), each one a text clip with `wordTimes` so its words follow the speech. Captions are cut at pauses and sentences, one or two lines as wide as the canvas allows. Styles: subtitle (plain, on a dark bar), karaoke (words light up as they are said), highlight (bold, the word being said in a colour — the reel look), pop (one to three big words at a time, each popping in). They go on the lane captions are already on, else the top video lane, else a new lane above it, and replace the captions there (replace:false keeps them). export:\"srt\"|\"vtt\" writes the timeline's captions to a subtitle file in exports/; import: a path to an SRT / WebVTT file (or its text) places its captions instead of the transcript's. remove:true deletes the captions. Captions are text clips: restyle them with updateClip, and make them after the cutting is done (a cut through a caption doesn't re-time its words — run this again). The same as the Transcript tab's Captions row.",
|
|
365
|
+
inputSchema: {
|
|
366
|
+
type: "object",
|
|
367
|
+
properties: {
|
|
368
|
+
style: { type: "string", enum: ["subtitle", "karaoke", "highlight", "pop"], description: "The look (default subtitle)" },
|
|
369
|
+
clipIds: { type: "array", items: { type: "string" }, description: "Caption only these clips' speech (default: every clip with sound)" },
|
|
370
|
+
from: { type: "number", description: "Only speech from this time on (timeline seconds)" },
|
|
371
|
+
to: { type: "number", description: "Only speech before this time" },
|
|
372
|
+
lines: { type: "number", description: "Lines per caption, 1–3 (default: the style's)" },
|
|
373
|
+
words: { type: "number", description: "At most this many words per caption (pop and highlight have their own default)" },
|
|
374
|
+
size: { type: "number", description: "Scale the style's text size, e.g. 1.2 (default 1)" },
|
|
375
|
+
track: { type: "string", description: "The video lane to put them on (default: chosen as described)" },
|
|
376
|
+
replace: { type: "boolean", description: "Remove the captions already on the timeline first (default true)" },
|
|
377
|
+
export: { type: "string", enum: ["srt", "vtt"], description: "Write the timeline's captions to exports/ as SubRip or WebVTT, and change nothing" },
|
|
378
|
+
import: { type: "string", description: "An SRT or WebVTT file (absolute path, or a /media/… src) or its text: place its captions" },
|
|
379
|
+
remove: { type: "boolean", description: "Delete every caption clip" },
|
|
380
|
+
force: { type: "boolean", description: "Also replace or remove locked captions (only when the user asked)" },
|
|
381
|
+
model: { type: "string", enum: ["base", "small"], description: "Transcribing first: the Whisper model (see fablecut_transcribe)" },
|
|
382
|
+
language: { type: "string", description: "Transcribing first: the spoken language (default: detected)" },
|
|
383
|
+
where: { type: "string", enum: ["auto", "tab", "headless"], description: "Transcribing first: where (see fablecut_transcribe)" },
|
|
384
|
+
},
|
|
385
|
+
},
|
|
386
|
+
},
|
|
277
387
|
{
|
|
278
388
|
name: "fablecut_denoise",
|
|
279
389
|
description: "Reduce background noise (hiss, hum, room tone) on audio clips: ffmpeg's FFT denoiser renders a cleaned FLAC of each clip's whole source file into media/, and the clip — with its linked stems — switches to it (the picture keeps its own file, so links and timing stay intact). The same as the inspector's Noise control. amount 'off' switches back to the original. Re-running reuses a file already rendered. Needs ffmpeg + ffprobe on PATH. Refuses locked clips unless force:true.",
|
|
@@ -493,19 +603,530 @@ async function measureClipGroup(proj, clips) {
|
|
|
493
603
|
return meter ? meter.result() : null;
|
|
494
604
|
}
|
|
495
605
|
/** Timeline spans with sound on these voice clips (ducking.js pipeline). */
|
|
496
|
-
async function voiceRegions(proj, voices, threshold) {
|
|
606
|
+
async function voiceRegions(proj, voices, threshold, minLen, heard) {
|
|
497
607
|
const L = require("./loudness.js"), D = require("./ducking.js");
|
|
498
608
|
const lists = [];
|
|
499
609
|
for (const v of voices) {
|
|
500
610
|
let env = null;
|
|
501
611
|
await streamClipAudio(proj, v, (nCh) => { env = new D.EnvelopeMeter(nCh, NORM_SR); },
|
|
502
612
|
(chs) => env.push(L.routeChannels(chs, v.props || {})));
|
|
503
|
-
if (!env) continue;
|
|
613
|
+
if (!env) continue; // no audio stream
|
|
614
|
+
if (heard) heard.add(v.id);
|
|
504
615
|
const sp = Math.min(8, Math.max(0.1, +v.props?.speed || 1));
|
|
505
616
|
const gain = Math.pow(10, (+v.props?.gain || 0) / 20) * Math.min(2, Math.max(0, +(v.props?.volume ?? 1)));
|
|
506
|
-
lists.push(D.activeRegions(env.result(), { t0: v.start, speed: sp, gain, threshold }));
|
|
617
|
+
lists.push(D.activeRegions(env.result(), { t0: v.start, speed: sp, gain, threshold, ...(minLen != null ? { minLen } : {}) }));
|
|
507
618
|
}
|
|
508
|
-
return D.mergeRegions(lists);
|
|
619
|
+
return D.mergeRegions(lists, minLen != null ? 0 : undefined);
|
|
620
|
+
}
|
|
621
|
+
/** The clips that carry a selection's sound, one list per linked group: its
|
|
622
|
+
* audio stems, else the clip itself (audio, or a video without stems). */
|
|
623
|
+
function speechGroups(proj, ids) {
|
|
624
|
+
const groups = new Map();
|
|
625
|
+
for (const id of ids) {
|
|
626
|
+
const c = proj.clips.find((x) => x.id === id);
|
|
627
|
+
if (!c) throw new Error("no clip " + id);
|
|
628
|
+
if (c.kind !== "audio" && c.kind !== "video") throw new Error(`clip ${id} is ${c.kind} — no sound to listen to`);
|
|
629
|
+
const key = c.linkGroup || c.id;
|
|
630
|
+
if (groups.has(key)) continue;
|
|
631
|
+
const members = c.linkGroup ? proj.clips.filter((x) => x.linkGroup === c.linkGroup) : [c];
|
|
632
|
+
const stems = members.filter((x) => x.kind === "audio");
|
|
633
|
+
groups.set(key, stems.length ? stems : [c]);
|
|
634
|
+
}
|
|
635
|
+
return [...groups.values()];
|
|
636
|
+
}
|
|
637
|
+
const fmtClock = (s) => `${Math.floor(s / 60)}:${(s % 60).toFixed(2).padStart(5, "0")}`;
|
|
638
|
+
const fmtDur = (s) => { const t = Math.round(s); return `${Math.floor(t / 60)}:${String(t % 60).padStart(2, "0")}`; };
|
|
639
|
+
/* fablecut_silence: silence.js on the clips' sound, then (cut:true) its extract ops. */
|
|
640
|
+
async function silenceTool(args) {
|
|
641
|
+
const S = require("./silence.js");
|
|
642
|
+
const ids = Array.isArray(args.clipIds) ? args.clipIds.map(String) : [];
|
|
643
|
+
if (!ids.length) throw new Error("`clipIds` must list the speech clip(s) to listen to");
|
|
644
|
+
const opts = S.options(args);
|
|
645
|
+
const doc = readProject();
|
|
646
|
+
const readRev = doc.revision || 0;
|
|
647
|
+
const groups = speechGroups(doc, ids);
|
|
648
|
+
const disabled = new Set(Array.isArray(doc.disabledTracks) ? doc.disabledTracks : []);
|
|
649
|
+
const enabled = groups.map((g) => g.filter((x) => !disabled.has(x.track) && x.disabled !== true)).filter((g) => g.length);
|
|
650
|
+
if (!enabled.length) throw new Error("those clips are disabled (or on disabled tracks) — nothing to listen to");
|
|
651
|
+
// a speed ramp moves the sound along the timeline unevenly: those clips are left alone
|
|
652
|
+
const live = enabled.filter((g) => !g.some(S.ramped));
|
|
653
|
+
const rampedN = enabled.length - live.length;
|
|
654
|
+
if (!live.length) throw new Error("those clips have a speed ramp (speed keyframes) — silence removal works on clips at a steady speed");
|
|
655
|
+
const heard = new Set();
|
|
656
|
+
const sound = await voiceRegions(doc, live.flat(), opts.threshold, S.MIN_SOUND, heard);
|
|
657
|
+
// only time that was actually listened to can be silent: a clip with no audio stream is left alone
|
|
658
|
+
const usable = live.filter((g) => g.every((x) => heard.has(x.id)));
|
|
659
|
+
if (!usable.length) throw new Error("those clips have no audio stream — nothing to listen to");
|
|
660
|
+
const ranges = usable.map((g) => [Math.min(...g.map((x) => x.start)), Math.max(...g.map((x) => x.start + x.duration))]);
|
|
661
|
+
const spans = S.silentSpans(sound, ranges, { ...opts, fps: doc.fps });
|
|
662
|
+
const listen = S.union(ranges).reduce((n, [a, b]) => n + b - a, 0);
|
|
663
|
+
const head = `${spans.length} silence${spans.length === 1 ? "" : "s"}, ${S.total(spans).toFixed(1)} s of ${fmtDur(listen)} ` +
|
|
664
|
+
`(threshold ${opts.threshold} dBFS, at least ${opts.minSilence} s, ${opts.padding} s kept beside speech` +
|
|
665
|
+
(usable.length < live.length ? `; ${live.length - usable.length} clip(s) with no audio stream left alone` : "") +
|
|
666
|
+
(rampedN ? `; ${rampedN} clip(s) with a speed ramp left alone` : "") + ")";
|
|
667
|
+
const list = spans.slice(0, 60).map((s) => ` ${fmtClock(s.from)} → ${fmtClock(s.to)} (${(s.to - s.from).toFixed(2)} s)`)
|
|
668
|
+
.concat(spans.length > 60 ? [` … +${spans.length - 60} more`] : []);
|
|
669
|
+
if (args.cut !== true) return [head + (spans.length ? ":" : "."), ...list,
|
|
670
|
+
...(spans.length ? ["Nothing cut yet: call again with cut:true to remove them (lock the music bed first if it should keep running)."] : [])].join("\n");
|
|
671
|
+
if (!spans.length) return head + " — nothing to cut.";
|
|
672
|
+
// the timeline must be the one that was listened to
|
|
673
|
+
const proj = readProject();
|
|
674
|
+
if ((proj.revision || 0) !== readRev)
|
|
675
|
+
throw new Error(`the project changed while listening (revision ${readRev} → ${proj.revision}) — nothing cut; run fablecut_silence again`);
|
|
676
|
+
const end = (p) => p.clips.reduce((m, c) => Math.max(m, c.start + c.duration), 0);
|
|
677
|
+
const before = end(proj);
|
|
678
|
+
ProjectOps.applyPatch(proj, S.cutOps(spans, { tracks: args.tracks, force: args.force === true }), { savedItems });
|
|
679
|
+
// a cut this size always keeps the project as it was, not once per session like other edits
|
|
680
|
+
let verWarn = "";
|
|
681
|
+
try { createHistory({ projects: createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR }) }).beforeAgent("Before cutting silences"); }
|
|
682
|
+
catch (e) { verWarn = ` Warning: no version was saved before the cut (${e.message}).`; }
|
|
683
|
+
const diskRev = readProject().revision || 0; // a failed read stops it: never write over what we can't see
|
|
684
|
+
if (diskRev !== readRev) throw new Error(`the project changed while cutting (revision ${readRev} → ${diskRev}) — nothing cut; run fablecut_silence again`);
|
|
685
|
+
proj.revision = readRev + 1;
|
|
686
|
+
writeProject(proj);
|
|
687
|
+
lastReadRevision = proj.revision;
|
|
688
|
+
return `Cut ${head} — timeline ${fmtDur(before)} → ${fmtDur(end(proj))} (revision ${proj.revision}). UI hot-reloaded.` +
|
|
689
|
+
(verWarn || ` The project as it was is kept as a version (fablecut_versions lists it; restore undoes the cut).`);
|
|
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
|
+
}
|
|
909
|
+
/** What words are placed by and cuts land on: where each clip sits and plays from, the track
|
|
910
|
+
* switches and the frame rate. An editor saving probed media details while a transcription runs
|
|
911
|
+
* doesn't change it; a moved, trimmed or cut clip does. */
|
|
912
|
+
function timelineSig(doc) {
|
|
913
|
+
return JSON.stringify([doc.fps, doc.lockedTracks || [], doc.untargetedTracks || [], doc.disabledTracks || [],
|
|
914
|
+
(doc.clips || []).map((c) => [c.id, c.track, c.start, c.in, c.duration, c.mediaId, c.props?.speed ?? 1, c.keyframes?.speed ?? null, !!c.locked, !!c.disabled])]);
|
|
915
|
+
}
|
|
916
|
+
/* The words said on the timeline (or in whole files, mediaIds): transcribes what has no
|
|
917
|
+
transcript yet as a job in an open tab, else headless, then lays the words out. Shared by
|
|
918
|
+
fablecut_transcribe and fablecut_captions. */
|
|
919
|
+
async function speechWords(args, fileMode) {
|
|
920
|
+
const T = require("./transcribe.js");
|
|
921
|
+
const model = T.model(args.model), language = T.language(args.language);
|
|
922
|
+
const doc = readProject();
|
|
923
|
+
const readRev = doc.revision || 0;
|
|
924
|
+
const mediaById = new Map((doc.media || []).map((m) => [m.id, m]));
|
|
925
|
+
const disabled = new Set(Array.isArray(doc.disabledTracks) ? doc.disabledTracks : []);
|
|
926
|
+
let entries = [], files = [], rampedN = 0;
|
|
927
|
+
if (fileMode) {
|
|
928
|
+
for (const id of args.mediaIds.map(String)) {
|
|
929
|
+
const m = mediaById.get(id);
|
|
930
|
+
if (!m) throw new Error("no media " + id);
|
|
931
|
+
if (m.kind !== "audio" && m.kind !== "video") throw new Error(`media ${id} is ${m.kind} — no sound to transcribe`);
|
|
932
|
+
files.push(m);
|
|
933
|
+
}
|
|
934
|
+
} else {
|
|
935
|
+
const ids = Array.isArray(args.clipIds) && args.clipIds.length ? args.clipIds.map(String)
|
|
936
|
+
: doc.clips.filter((c) => (c.kind === "audio" || c.kind === "video") && mediaById.get(c.mediaId) && mediaById.get(c.mediaId).audioChannels !== 0
|
|
937
|
+
// a picture whose sound is on linked stems (they are read instead), or one with its sound off
|
|
938
|
+
&& !(c.kind === "video" && (c.linkGroup ? doc.clips.some((x) => x.linkGroup === c.linkGroup && x.kind === "audio") : +(c.props?.volume ?? 1) === 0))).map((c) => c.id);
|
|
939
|
+
if (!ids.length) throw new Error("the timeline has no clips with sound — add some, or pass mediaIds");
|
|
940
|
+
const groups = speechGroups(doc, ids).map((g) => g.filter((x) => !disabled.has(x.track) && x.disabled !== true)).filter((g) => g.length);
|
|
941
|
+
if (!groups.length) throw new Error("those clips are disabled (or on disabled tracks) — nothing to read");
|
|
942
|
+
for (const g of groups) {
|
|
943
|
+
if (g.some(T.ramped)) { rampedN++; continue; }
|
|
944
|
+
const m = mediaById.get(g[0].mediaId);
|
|
945
|
+
if (m) entries.push({ clip: g[0], media: m });
|
|
946
|
+
}
|
|
947
|
+
if (!entries.length) throw new Error("those clips have a speed ramp (speed keyframes) — their words can't be placed on the timeline");
|
|
948
|
+
files = [...new Map(entries.map((e) => [e.media.src, e.media])).values()];
|
|
949
|
+
}
|
|
950
|
+
if (!(await ensureUIServer())) throw new Error(`the editor server is not running and could not be started on port ${PORT}`);
|
|
951
|
+
const srcs = files.map((m) => m.src);
|
|
952
|
+
const st = await apiJSON("POST", "/api/transcript/status", { srcs });
|
|
953
|
+
if (st.status !== 200) throw new Error(st.body?.error || "could not read the transcripts");
|
|
954
|
+
const gone = srcs.filter((s) => st.body.status[s] === null);
|
|
955
|
+
if (gone.length) throw new Error("these files are missing (offline): " + gone.join(", "));
|
|
956
|
+
const todo = args.again === true ? srcs : srcs.filter((s) => !st.body.status[s]);
|
|
957
|
+
let note = "";
|
|
958
|
+
if (todo.length) {
|
|
959
|
+
const r = await apiJSON("POST", "/api/transcribe/request", { where: args.where || "auto", transcribe: { srcs: todo, model, language, again: args.again === true } });
|
|
960
|
+
if (r.status !== 200) throw new Error(r.body?.error || `transcribe request failed (${r.status})`);
|
|
961
|
+
let job = r.body;
|
|
962
|
+
const deadline = Date.now() + 1000 * (Number.isFinite(args.timeout) && args.timeout > 0 ? args.timeout : 1800);
|
|
963
|
+
while (job.status === "pending" || job.status === "running") {
|
|
964
|
+
if (Date.now() > deadline) {
|
|
965
|
+
await apiJSON("POST", "/api/export/job/cancel?id=" + encodeURIComponent(job.id));
|
|
966
|
+
throw new Error("timed out waiting for the transcription — try fewer clips, or a larger timeout");
|
|
967
|
+
}
|
|
968
|
+
await sleep(1000);
|
|
969
|
+
const q = await apiJSON("GET", "/api/export/job?id=" + encodeURIComponent(job.id));
|
|
970
|
+
if (q.status !== 200) throw new Error(q.body?.error || "lost track of the transcription job");
|
|
971
|
+
job = q.body;
|
|
972
|
+
}
|
|
973
|
+
if (job.status !== "done") throw new Error(`transcription ${job.status}: ${job.error || "no reason given"}`);
|
|
974
|
+
const res = job.result || {};
|
|
975
|
+
note = `Transcribed ${(res.done || []).length} file${(res.done || []).length === 1 ? "" : "s"} (${model}${language ? ", " + language : ""}, in ${job.via === "headless" ? "a headless browser" : "the open editor tab"})` +
|
|
976
|
+
((res.failed || []).length ? `; failed: ${res.failed.map((f) => `${f.src} (${f.error})`).join(", ")}` : "") + ".\n";
|
|
977
|
+
}
|
|
978
|
+
const docs = new Map();
|
|
979
|
+
for (const src of srcs) {
|
|
980
|
+
const g = await apiJSON("GET", "/api/transcript?src=" + encodeURIComponent(src));
|
|
981
|
+
if (g.status === 200 && g.body?.transcript) docs.set(src, T.validate(g.body.transcript));
|
|
982
|
+
}
|
|
983
|
+
const langs = [...new Set([...docs.values()].map((d) => d.language === "auto" ? "detected" : d.language).filter(Boolean))];
|
|
984
|
+
const without = srcs.filter((s) => !docs.has(s));
|
|
985
|
+
let words, scope;
|
|
986
|
+
if (fileMode) {
|
|
987
|
+
// file seconds, one file after another
|
|
988
|
+
words = [];
|
|
989
|
+
for (const m of files) { const d = docs.get(m.src); if (d) words.push(...d.words.map(([w, s, e]) => ({ w, s, e, clip: m.id, r: [0, d.duration || e] }))); }
|
|
990
|
+
scope = `${files.length} file${files.length === 1 ? "" : "s"} (file seconds)`;
|
|
991
|
+
} else {
|
|
992
|
+
words = T.layout(entries.filter((e) => docs.has(e.media.src)).map((e) => ({ clip: e.clip, words: docs.get(e.media.src).words })));
|
|
993
|
+
scope = `${entries.length} clip${entries.length === 1 ? "" : "s"} on the timeline (timeline seconds)`;
|
|
994
|
+
}
|
|
995
|
+
return { doc, readRev, sig: timelineSig(doc), words, scope, note, langs, without, rampedN };
|
|
996
|
+
}
|
|
997
|
+
/* fablecut_transcribe: transcripts from the editor (a job), read on the timeline, found, cut. */
|
|
998
|
+
async function transcribeTool(args) {
|
|
999
|
+
const T = require("./transcribe.js");
|
|
1000
|
+
const model = T.model(args.model), language = T.language(args.language);
|
|
1001
|
+
const finds = (args.find == null ? [] : Array.isArray(args.find) ? args.find : [args.find]).map(String).filter((q) => T.norm(q));
|
|
1002
|
+
if (args.find != null && !finds.length) throw new Error("find needs a word or phrase with letters or digits in it");
|
|
1003
|
+
const fileMode = Array.isArray(args.mediaIds) && args.mediaIds.length;
|
|
1004
|
+
if (args.cut === true && !finds.length) throw new Error("cut:true needs find — the words or phrases to cut");
|
|
1005
|
+
if (args.cut === true && fileMode) throw new Error("cut works on the timeline — pass clipIds (or nothing), not mediaIds");
|
|
1006
|
+
const { doc, sig, words, scope, note, langs, without, rampedN } = await speechWords(args, fileMode);
|
|
1007
|
+
const fmtT = (x) => fmtClock(Math.max(0, x));
|
|
1008
|
+
const lo = Number.isFinite(args.from) ? args.from : -Infinity, hi = Number.isFinite(args.to) ? args.to : Infinity;
|
|
1009
|
+
const inWin = (w) => w.e >= lo && w.s <= hi;
|
|
1010
|
+
const head = note + `${words.filter(inWin).length} words, ${scope}` + (langs.length ? `, language ${langs.join("/")}` : "") +
|
|
1011
|
+
(without.length ? `; no transcript for ${without.join(", ")}` : "") + (rampedN ? `; ${rampedN} clip(s) with a speed ramp left out` : "");
|
|
1012
|
+
if (!finds.length) {
|
|
1013
|
+
const segs = T.segments(words).filter((sg) => sg.to >= lo && sg.from <= hi);
|
|
1014
|
+
const MAX = 300;
|
|
1015
|
+
const lines = segs.slice(0, MAX).map((sg) => `[${fmtT(sg.from)}] ${sg.text}`);
|
|
1016
|
+
return [head + (segs.length ? ":" : "."), ...lines,
|
|
1017
|
+
...(segs.length > MAX ? [`… ${segs.length - MAX} more lines — pass from (e.g. ${segs[MAX].from.toFixed(1)}) to read on`] : []),
|
|
1018
|
+
...(segs.length ? ["find:\"…\" locates a phrase; with cut:true it is cut out."] : [])].join("\n");
|
|
1019
|
+
}
|
|
1020
|
+
// find (and cut)
|
|
1021
|
+
const runs = [], report = [];
|
|
1022
|
+
for (const q of finds) {
|
|
1023
|
+
const hits = T.find(words, q).filter((r) => inWin(words[r.i]) && inWin(words[r.j]));
|
|
1024
|
+
const spans = T.cutSpans(words, hits, { fps: doc.fps });
|
|
1025
|
+
report.push(`"${q}": ${hits.length} match${hits.length === 1 ? "" : "es"}` + (hits.length ? ":" : ""));
|
|
1026
|
+
for (const r of hits.slice(0, 50)) {
|
|
1027
|
+
const ctx = `${T.text(words, Math.max(0, r.i - 4), r.i - 1)} «${T.text(words, r.i, r.j)}» ${T.text(words, r.j + 1, Math.min(words.length - 1, r.j + 4))}`.trim();
|
|
1028
|
+
report.push(` ${fmtT(words[r.i].s)} → ${fmtT(words[r.j].e)} ${ctx}`);
|
|
1029
|
+
}
|
|
1030
|
+
if (hits.length > 50) report.push(` … +${hits.length - 50} more`);
|
|
1031
|
+
runs.push(...hits);
|
|
1032
|
+
if (!spans.length && hits.length) report.push(" (each is too short to cut on its own)");
|
|
1033
|
+
}
|
|
1034
|
+
const spans = T.cutSpans(words, runs, { fps: doc.fps });
|
|
1035
|
+
if (args.cut !== true) return [head + ".", ...report,
|
|
1036
|
+
...(spans.length && !fileMode ? [`Cutting them would remove ${spans.length} span${spans.length === 1 ? "" : "s"}, ${T.total(spans).toFixed(1)} s (the words and the pause after each): call again with cut:true.`] : [])].join("\n");
|
|
1037
|
+
if (!spans.length) return [head + ".", ...report, "Nothing to cut."].join("\n");
|
|
1038
|
+
const proj = readProject(), readRev = proj.revision || 0;
|
|
1039
|
+
if (timelineSig(proj) !== sig)
|
|
1040
|
+
throw new Error("the timeline changed while transcribing (a clip was moved, trimmed or cut) — nothing cut; run fablecut_transcribe again");
|
|
1041
|
+
const end = (p) => p.clips.reduce((m, c) => Math.max(m, c.start + c.duration), 0);
|
|
1042
|
+
const before = end(proj);
|
|
1043
|
+
ProjectOps.applyPatch(proj, T.cutOps(spans, { tracks: args.tracks, force: args.force === true }), { savedItems });
|
|
1044
|
+
let verWarn = "";
|
|
1045
|
+
try { createHistory({ projects: createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR }) }).beforeAgent("Before cutting words"); }
|
|
1046
|
+
catch (e) { verWarn = ` Warning: no version was saved before the cut (${e.message}).`; }
|
|
1047
|
+
const diskRev = readProject().revision || 0; // a failed read stops it: never write over what we can't see
|
|
1048
|
+
if (diskRev !== readRev) throw new Error(`the project changed while cutting (revision ${readRev} → ${diskRev}) — nothing cut; run fablecut_transcribe again`);
|
|
1049
|
+
proj.revision = readRev + 1;
|
|
1050
|
+
writeProject(proj);
|
|
1051
|
+
lastReadRevision = proj.revision;
|
|
1052
|
+
return [head + ".", ...report,
|
|
1053
|
+
`Cut ${spans.length} span${spans.length === 1 ? "" : "s"}, ${T.total(spans).toFixed(1)} s — timeline ${fmtDur(before)} → ${fmtDur(end(proj))} (revision ${proj.revision}). UI hot-reloaded.` +
|
|
1054
|
+
(verWarn || " The project as it was is kept as a version (fablecut_versions lists it; restore undoes the cut).")].join("\n");
|
|
1055
|
+
}
|
|
1056
|
+
/* fablecut_captions: caption clips from the transcripts (captions.js), subtitle files out and in. */
|
|
1057
|
+
async function captionsTool(args) {
|
|
1058
|
+
const C = require("./captions.js");
|
|
1059
|
+
const st = C.style(args.style);
|
|
1060
|
+
const ownLocks = (proj, c) => c.locked === true || (Array.isArray(proj.lockedTracks) && proj.lockedTracks.includes(c.track));
|
|
1061
|
+
if (args.export != null) {
|
|
1062
|
+
if (args.export !== "srt" && args.export !== "vtt") throw new Error("export must be srt or vtt");
|
|
1063
|
+
const proj = readProject(), list = C.fromClips(proj.clips, proj.disabledTracks);
|
|
1064
|
+
if (!list.length) throw new Error("there are no captions on the timeline to export — make them first (fablecut_captions {})");
|
|
1065
|
+
fs.mkdirSync(EXPORTS_DIR, { recursive: true });
|
|
1066
|
+
const base = String(proj.name || "captions").replace(/[^\w\- ]+/g, "_").trim().slice(0, 80) || "captions";
|
|
1067
|
+
let file = path.join(EXPORTS_DIR, `${base}.${args.export}`);
|
|
1068
|
+
for (let n = 2; fs.existsSync(file); n++) file = path.join(EXPORTS_DIR, `${base} ${n}.${args.export}`);
|
|
1069
|
+
fs.writeFileSync(file, args.export === "srt" ? C.toSRT(list) : C.toVTT(list));
|
|
1070
|
+
return `Wrote ${list.length} caption${list.length === 1 ? "" : "s"} to ${file} (${args.export === "srt" ? "SubRip" : "WebVTT"}, ${fmtClock(list[0].start)} → ${fmtClock(list[list.length - 1].end)}).`;
|
|
1071
|
+
}
|
|
1072
|
+
if (args.remove === true) {
|
|
1073
|
+
const proj = readProject(), caps = proj.clips.filter(C.isCaption);
|
|
1074
|
+
if (!caps.length) return "There are no captions on the timeline.";
|
|
1075
|
+
const locked = caps.filter((c) => ownLocks(proj, c));
|
|
1076
|
+
if (locked.length && args.force !== true) throw new Error(`${locked.length} caption(s) are locked — nothing removed (pass force:true only if the user asked)`);
|
|
1077
|
+
ProjectOps.applyPatch(proj, caps.map((c) => ({ op: "removeClip", id: c.id, ...(args.force === true ? { force: true } : {}) })), { savedItems });
|
|
1078
|
+
proj.revision = (proj.revision || 0) + 1;
|
|
1079
|
+
writeProject(proj);
|
|
1080
|
+
lastReadRevision = proj.revision;
|
|
1081
|
+
return `Removed ${caps.length} caption${caps.length === 1 ? "" : "s"} (revision ${proj.revision}). UI hot-reloaded.`;
|
|
1082
|
+
}
|
|
1083
|
+
let list, note = "", sig;
|
|
1084
|
+
const first = readProject();
|
|
1085
|
+
const m = C.metrics(st, first.width || 1920, first.height || 1080, { lines: args.lines, words: args.words, scale: args.size });
|
|
1086
|
+
if (args.import != null) {
|
|
1087
|
+
let text = String(args.import);
|
|
1088
|
+
const asFile = text.length < 1024 && !text.includes("-->");
|
|
1089
|
+
if (asFile) {
|
|
1090
|
+
const file = text.startsWith("/media/") ? path.join(MEDIA_DIR, decodeURIComponent(text.slice(7))) : path.resolve(text);
|
|
1091
|
+
if (!fs.existsSync(file)) throw new Error("no such subtitle file: " + text);
|
|
1092
|
+
text = fs.readFileSync(file, "utf8");
|
|
1093
|
+
}
|
|
1094
|
+
list = C.fit(C.parse(text), m.chars, m.lines);
|
|
1095
|
+
sig = timelineSig(first);
|
|
1096
|
+
note = `Read ${list.length} caption${list.length === 1 ? "" : "s"} from the ${/^WEBVTT/m.test(text) ? "WebVTT" : "SubRip"} file.\n`;
|
|
1097
|
+
} else {
|
|
1098
|
+
const r = await speechWords(args, false);
|
|
1099
|
+
const lo = Number.isFinite(args.from) ? args.from : -Infinity, hi = Number.isFinite(args.to) ? args.to : Infinity;
|
|
1100
|
+
const words = r.words.filter((w) => w.s >= lo && w.e <= hi);
|
|
1101
|
+
if (!words.length) throw new Error("no words to caption" + (r.without.length ? ` — no transcript for ${r.without.join(", ")}` : " in that stretch"));
|
|
1102
|
+
list = C.cues(words, { chars: m.chars, lines: m.lines, words: m.words, maxDur: m.maxDur, fps: r.doc.fps });
|
|
1103
|
+
sig = r.sig;
|
|
1104
|
+
note = r.note;
|
|
1105
|
+
}
|
|
1106
|
+
const proj = readProject(), readRev = proj.revision || 0;
|
|
1107
|
+
if (timelineSig(proj) !== sig)
|
|
1108
|
+
throw new Error("the timeline changed while transcribing (a clip was moved, trimmed or cut) — nothing added; run fablecut_captions again");
|
|
1109
|
+
const old = args.replace === false ? [] : proj.clips.filter(C.isCaption);
|
|
1110
|
+
const lockedOld = old.filter((c) => ownLocks(proj, c));
|
|
1111
|
+
if (lockedOld.length && args.force !== true) throw new Error(`${lockedOld.length} existing caption(s) are locked — nothing changed (pass replace:false to keep them, or force:true if the user asked)`);
|
|
1112
|
+
const from = list[0].start, to = list[list.length - 1].end;
|
|
1113
|
+
let lane = args.track ? { track: String(args.track), add: false } : C.trackFor(old.length ? proj : { ...proj, clips: proj.clips.filter((c) => !C.isCaption(c)) }, from, to);
|
|
1114
|
+
if (!/^V\d+$/.test(lane.track)) throw new Error("track must be a video lane such as V3");
|
|
1115
|
+
if (args.track && !(proj.tracks || C.DEFAULT_TRACKS).some((t) => t.id === lane.track)) lane.add = true;
|
|
1116
|
+
if (Array.isArray(proj.lockedTracks) && proj.lockedTracks.includes(lane.track) && args.force !== true) throw new Error(`${lane.track} is locked — pick another track, or unlock it`);
|
|
1117
|
+
if (lane.add) proj.tracks = [{ id: lane.track, kind: "video" }, ...(Array.isArray(proj.tracks) && proj.tracks.length ? proj.tracks : C.DEFAULT_TRACKS)];
|
|
1118
|
+
const ops = [
|
|
1119
|
+
...old.map((c) => ({ op: "removeClip", id: c.id, ...(args.force === true ? { force: true } : {}) })),
|
|
1120
|
+
...list.map((cue) => ({ op: "addClip", clip: C.clip(cue, { style: st, width: proj.width, height: proj.height, track: lane.track, scale: args.size }), ...(args.force === true ? { force: true } : {}) })),
|
|
1121
|
+
];
|
|
1122
|
+
ProjectOps.applyPatch(proj, ops, { savedItems });
|
|
1123
|
+
proj.revision = readRev + 1;
|
|
1124
|
+
writeProject(proj);
|
|
1125
|
+
lastReadRevision = proj.revision;
|
|
1126
|
+
const sample = list.slice(0, 3).map((c) => ` [${fmtClock(c.start)}] ${c.text.replace(/\n/g, " / ")}`);
|
|
1127
|
+
return note + `Added ${list.length} caption${list.length === 1 ? "" : "s"} (${C.STYLES[st].label}, ${m.fontSize} px) on ${lane.track}${lane.add ? " (a new lane)" : ""}, ${fmtClock(from)} → ${fmtClock(to)}` +
|
|
1128
|
+
(old.length ? `, replacing ${old.length}` : "") + ` (revision ${proj.revision}). UI hot-reloaded.\n` + sample.join("\n") +
|
|
1129
|
+
(list.length > 3 ? `\n … ${list.length - 3} more` : "") + "\nfablecut_frame {time} shows how one looks; export:\"srt\" writes a subtitle file.";
|
|
509
1130
|
}
|
|
510
1131
|
/** The clips that sound for a selection: a linked group's audio stems, else the clip. */
|
|
511
1132
|
function normalizeGroups(proj, ids) {
|
|
@@ -959,6 +1580,18 @@ async function callTool(name, args, attempt = 0) {
|
|
|
959
1580
|
return scopesTool(args);
|
|
960
1581
|
case "fablecut_frame":
|
|
961
1582
|
return frameTool(args);
|
|
1583
|
+
case "fablecut_silence":
|
|
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);
|
|
1591
|
+
case "fablecut_transcribe":
|
|
1592
|
+
return transcribeTool(args);
|
|
1593
|
+
case "fablecut_captions":
|
|
1594
|
+
return captionsTool(args);
|
|
962
1595
|
case "fablecut_denoise":
|
|
963
1596
|
return denoiseTool(args);
|
|
964
1597
|
case "fablecut_proxy":
|
|
@@ -1078,8 +1711,7 @@ async function callTool(name, args, attempt = 0) {
|
|
|
1078
1711
|
const verWarn = versionBeforeAgent(false);
|
|
1079
1712
|
// Someone else saved while the ops ran: writing now would drop their change.
|
|
1080
1713
|
// Without a baseRevision the ops just re-apply on the newer document.
|
|
1081
|
-
|
|
1082
|
-
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
|
|
1083
1715
|
if (diskRev !== readRev) {
|
|
1084
1716
|
if (base == null && attempt < 3) return callTool(name, args, attempt + 1);
|
|
1085
1717
|
throw conflict(diskRev);
|
|
@@ -1381,7 +2013,7 @@ async function handle(msg) {
|
|
|
1381
2013
|
result: {
|
|
1382
2014
|
protocolVersion: negotiateProtocolVersion(params?.protocolVersion),
|
|
1383
2015
|
capabilities: { tools: {} },
|
|
1384
|
-
serverInfo: { name: "fablecut", version: "1.
|
|
2016
|
+
serverInfo: { name: "fablecut", version: "1.18.0" },
|
|
1385
2017
|
},
|
|
1386
2018
|
});
|
|
1387
2019
|
}
|