fablecut 1.14.0 → 1.16.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/server.js CHANGED
@@ -16,11 +16,13 @@
16
16
  ═══════════════════════════════════════════════════════════════════════════ */
17
17
  "use strict";
18
18
  const http = require("http");
19
+ const crypto = require("crypto");
19
20
  const fs = require("fs");
21
+ const os = require("os");
20
22
  const path = require("path");
21
23
  const { spawn, spawnSync, execFile } = require("child_process");
22
24
 
23
- const { analyze } = require("./analyze");
25
+ const { analyze, frame, frameGrid } = require("./analyze");
24
26
  const {
25
27
  PROFILES_FILE,
26
28
  loadEncodeProfiles,
@@ -32,14 +34,21 @@ const {
32
34
  dryRunProfile,
33
35
  } = require("./encode-profiles");
34
36
  const { downloadImportUrl, maybeFaststart } = require("./import-url");
37
+ const { pruneCache } = require("./frame-cache");
35
38
  const { createExportJobs } = require("./export-jobs");
36
39
  const { denoiseFile, AMOUNT_IDS: DENOISE_AMOUNTS } = require("./denoise");
37
40
 
38
41
  const {
39
42
  APP_DIR, DATA_DIR, MEDIA_DIR, EXPORTS_DIR, ANALYSIS_DIR, LIBRARY_DIR,
40
- PROJECT_FILE, LIBRARY_SUBDIRS, ensureDirs, readSaved, writeSaved,
43
+ PROJECT_FILE, LIBRARY_SUBDIRS, FRAMES_DIR, PROXIES_DIR, ensureDirs, readSaved, writeSaved,
41
44
  } = require("./paths");
42
45
  const Templates = require("./templates");
46
+ const { probeFile } = require("./media-probe");
47
+ const MediaLib = require("./media-lib");
48
+ const { createProxies } = require("./proxy");
49
+ const Delivery = require("./delivery");
50
+ const { createProjects } = require("./projects");
51
+ const { createHistory } = require("./history");
43
52
 
44
53
  /* Static app files are served from the install dir; everything the user creates
45
54
  lives under DATA_DIR. The two are the same unless FABLECUT_DATA_DIR is set. */
@@ -89,6 +98,18 @@ const MIME = {
89
98
  };
90
99
 
91
100
  ensureDirs();
101
+ const projects = createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR });
102
+ const history = createHistory({ projects, autoMinutes: Number(process.env.FABLECUT_AUTO_VERSION_MIN) || 10 });
103
+ /* project.json that can't be read at startup (a crash mid-write by another tool, a
104
+ bad hand edit): keep it aside and put back the newest good copy. */
105
+ if (fs.existsSync(PROJECT_FILE)) {
106
+ try { JSON.parse(fs.readFileSync(PROJECT_FILE, "utf8").replace(/^/, "")); }
107
+ catch (e) {
108
+ const r = history.recover(PROJECT_FILE);
109
+ console.warn(` ⚠ project.json could not be read (${e.message}); kept as ${path.basename(r.aside)}` +
110
+ (r.recovered ? ` and restored from ${r.from}` : " — starting a new project"));
111
+ }
112
+ }
92
113
  if (!fs.existsSync(PROJECT_FILE)) {
93
114
  fs.writeFileSync(PROJECT_FILE, JSON.stringify({
94
115
  name: "Untitled Project", width: 1280, height: 720, fps: 30,
@@ -102,6 +123,7 @@ function broadcast(event = "change", data = event) {
102
123
  const payload = `event: ${event}\ndata: ${data}\n\n`;
103
124
  for (const res of sseClients) res.write(payload);
104
125
  }
126
+ const proxies = createProxies({ dir: PROXIES_DIR, resolveSrc, probe: probeFile, broadcast: (ev, data) => broadcast(ev, data) });
105
127
  let debounce = null;
106
128
  let profilesDebounce = null;
107
129
  function onFsChange() {
@@ -176,6 +198,32 @@ function run(cmd, args) {
176
198
  });
177
199
  }
178
200
 
201
+ /** A "/media/…" or "/library/…" src → an existing file inside that root, or null.
202
+ * Every src-accepting endpoint resolves through here: basename alone is not
203
+ * enough (library has subfolders) and a bare join is a traversal hole. */
204
+ function resolveSrc(src) {
205
+ const p = decodeURIComponent(String(src || "").split("?")[0]);
206
+ const [root, rel] = p.startsWith("/media/") ? [MEDIA_DIR, p.slice(7)]
207
+ : p.startsWith("/library/") ? [LIBRARY_DIR, p.slice(9)] : [null, null];
208
+ if (!root || !rel) return null;
209
+ const file = path.normalize(path.join(root, rel));
210
+ if (!file.startsWith(path.normalize(root + path.sep))) return null;
211
+ try { return fs.statSync(file).isFile() ? file : null; } catch { return null; }
212
+ }
213
+
214
+ /** An explicit absolute/relative path argument → an existing file, or null.
215
+ * Used by /api/frame only. This deliberately reaches outside media/ and
216
+ * library/: looking at a clip must not require putting it in the project
217
+ * folder. The caller is the local MCP server or the user's own fetch, both
218
+ * already able to read any file the user can — and unlike resolveSrc() it
219
+ * never turns a request string into a path *inside* a served root, so there
220
+ * is no traversal to defend. It is deliberately NOT how a src is resolved. */
221
+ function resolvePathArg(p) {
222
+ if (!p || typeof p !== "string") return null;
223
+ let file = path.resolve(p);
224
+ try { return fs.statSync(file).isFile() ? file : null; } catch { return null; }
225
+ }
226
+
179
227
  /* Remux MP4-family uploads with `+faststart` so the moov atom leads the file —
180
228
  without it <video> stalls for seconds probing over Range requests. */
181
229
  function faststart(file) { return maybeFaststart(file); }
@@ -210,6 +258,140 @@ function attachProc(sess, proc) {
210
258
  proc.stdin.on("error", () => {}); // EPIPE if ffmpeg dies mid-stream
211
259
  sess.done = new Promise((res) => proc.on("close", res));
212
260
  }
261
+ /* Delivery presets (delivery.js) — structured settings instead of raw args.
262
+ Which encoders exist: `ffmpeg -encoders`, and for the hardware ones a 2-frame
263
+ test encode, because a build lists h264_nvenc / _qsv / _amf whether or not
264
+ this machine has the GPU. Asked once, in the background, on first use. */
265
+ let deliveryEncodersP = null;
266
+ function runFfmpeg(args, timeout = 15000) {
267
+ return new Promise((resolve) => {
268
+ execFile("ffmpeg", args, { timeout, maxBuffer: 8 * 1024 * 1024, windowsHide: true },
269
+ (err, stdout, stderr) => resolve({ code: err ? (err.code ?? 1) : 0, stdout: String(stdout || ""), stderr: String(stderr || "") }));
270
+ });
271
+ }
272
+ function deliveryEncoders() {
273
+ if (!HAS_FFMPEG) return Promise.resolve(new Set());
274
+ if (deliveryEncodersP) return deliveryEncodersP;
275
+ deliveryEncodersP = (async () => {
276
+ const listed = Delivery.parseEncoders((await runFfmpeg(["-hide_banner", "-encoders"])).stdout);
277
+ const usable = new Set([...listed].filter((e) => !Delivery.ENCODERS[e]?.hw));
278
+ await Promise.all([...listed].filter((e) => Delivery.ENCODERS[e]?.hw).map(async (e) => {
279
+ const r = await runFfmpeg(["-hide_banner", "-v", "error", "-f", "lavfi", "-i", "color=c=black:s=256x144:r=30:d=0.1",
280
+ "-frames:v", "2", "-c:v", e, "-pix_fmt", Delivery.ENCODERS[e].hw === "nvenc" ? "yuv420p" : "nv12", "-f", "null", "-"]);
281
+ if (r.code === 0) usable.add(e);
282
+ }));
283
+ return usable;
284
+ })();
285
+ return deliveryEncodersP;
286
+ }
287
+ /** Saved delivery presets: library/delivery/<id>.json, each a spec plus a label. */
288
+ function savedDeliveryPresets() { return Delivery.savedPresets(readSaved("delivery")); }
289
+ /* One render, several files: `deliveries:[{delivery, name}, …]` (up to 8) or a
290
+ single `delivery` + name. Every output gets its own ffmpeg, fed the same
291
+ frames; the browser renders each frame once. Frames are raw RGBA when any
292
+ output needs more than 4:2:0 8-bit, else JPEG at the highest quality asked. */
293
+ const MAX_OUTPUTS = 8;
294
+ async function beginDeliveryExport(rate, name, hasAudio, extra) {
295
+ const available = await deliveryEncoders();
296
+ const presets = savedDeliveryPresets();
297
+ const list = Array.isArray(extra.deliveries) ? extra.deliveries : [{ delivery: extra.delivery, name }];
298
+ if (!list.length) throw new Error("deliveries is empty");
299
+ if (list.length > MAX_OUTPUTS) throw new Error(`at most ${MAX_OUTPUTS} outputs per render`);
300
+ const canvasW = extra.canvasW | 0, canvasH = extra.canvasH | 0;
301
+ if (canvasW < 2 || canvasH < 2 || canvasW > 16384 || canvasH > 16384) throw new Error("export width/height required (canvasW, canvasH)");
302
+ const r = extra.region;
303
+ const region = r && typeof r === "object" && [r.x, r.y, r.w, r.h].every(Number.isFinite) && r.w > 0 && r.h > 0 &&
304
+ r.x >= 0 && r.y >= 0 && r.x + r.w <= canvasW + 0.5 && r.y + r.h <= canvasH + 0.5 ? r : null;
305
+ const outs = list.map((d) => {
306
+ const { spec, notes } = Delivery.normalize(d && d.delivery !== undefined ? d.delivery : d, { available, presets });
307
+ return { spec, notes, name: d && typeof d.name === "string" ? d.name : name, frame: Delivery.reframe(spec, canvasW, canvasH, region) };
308
+ });
309
+ // one render has one frame rate: an output asking for another needs a render of its own
310
+ const off = outs.map((o, i) => [o, i]).filter(([o]) => o.spec.fps != null && Math.abs(o.spec.fps - rate) > 0.01);
311
+ if (off.length) throw new Error(off.map(([o, i]) => `output ${i + 1} asks for ${o.spec.fps} fps but this render is ${rate} fps`).join("; ") + " — render each frame rate separately");
312
+ const input = outs.some((o) => Delivery.frameInput(o.spec) === "rgba") ? "rgba" : "jpeg";
313
+ // check every output on a 0.1 s synthetic canvas before the browser renders anything
314
+ const dryDir = fs.mkdtempSync(path.join(os.tmpdir(), "fablecut-dry-"));
315
+ try {
316
+ const dry = await Promise.all(outs.map((o, i) => runFfmpeg(Delivery.ffmpegArgs(o.spec, { fps: rate, input, canvasW, canvasH, frame: o.frame,
317
+ hasAudio, dry: true, outPath: path.join(dryDir, `probe${i}` + Delivery.CONTAINERS[o.spec.container].ext) }), 30000)));
318
+ const bad = dry.map((d, i) => [d, outs[i]]).filter(([d]) => d.code !== 0);
319
+ if (bad.length) {
320
+ throw new Error(bad.map(([d, o]) => {
321
+ const why = d.stderr.trim().split("\n").filter(Boolean).slice(-3).map((l) => l.trim()).join(" · ");
322
+ return `ffmpeg rejected these settings (${Delivery.describe(o.spec)}): ${why || "exit " + d.code}`;
323
+ }).join("\n"));
324
+ }
325
+ } finally { try { fs.rmSync(dryDir, { recursive: true, force: true }); } catch {} }
326
+ const id = Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
327
+ const dir = fs.mkdtempSync(path.join(EXPORTS_DIR, "fablecut-"));
328
+ const duration = Number.isFinite(+extra.duration) && +extra.duration > 0 ? +extra.duration : null;
329
+ for (const o of outs) {
330
+ const ext = Delivery.CONTAINERS[o.spec.container].ext;
331
+ Object.assign(o, reserveExportPaths(EXPORTS_DIR, safeName(o.name || "export"), ext), { proc: null, stderr: "", done: null, failed: null });
332
+ o.err = () => o.stderr.trim().split("\n").filter(Boolean).slice(-3).map((l) => l.trim()).join(" · ");
333
+ }
334
+ const sess = {
335
+ mode: "jpeg", proc: null, fps: rate, outputs: outs, input, canvasW, canvasH, duration,
336
+ hasAudio: !!hasAudio, dir, wav: null, partPath: null, outPath: null,
337
+ stderr: "", done: null, lastTouch: Date.now(), err: () => "",
338
+ };
339
+ sess.writeLock = Promise.resolve();
340
+ exportSessions.set(id, sess);
341
+ const jpegQuality = Math.max(...outs.map((o) => Delivery.jpegQuality(o.spec)));
342
+ const view = outs.map((o) => ({ file: path.basename(o.outPath), spec: o.spec, notes: o.notes, summary: Delivery.describe(o.spec), size: { w: o.frame.outW, h: o.frame.outH } }));
343
+ // the single-output fields stay as they were for one delivery
344
+ return { id, mode: "jpeg", input, jpegQuality, outputs: view, ...view[0] };
345
+ }
346
+ /** Integrated loudness and true peak of a file's first audio stream (ffmpeg ebur128). */
347
+ async function measureLoudness(file, timeout = 10 * 60 * 1000) {
348
+ const r = await runFfmpeg(Delivery.LOUDNESS_ARGS(file), timeout);
349
+ return r.code === 0 ? Delivery.parseEbur128(r.stderr) : null;
350
+ }
351
+ function ffprobeJSON(file) {
352
+ return new Promise((resolve) => {
353
+ execFile("ffprobe", ["-v", "error", "-show_streams", "-show_format", "-of", "json", file], { timeout: 60000, maxBuffer: 8 * 1024 * 1024, windowsHide: true },
354
+ (err, stdout) => { try { resolve(err ? null : JSON.parse(stdout)); } catch { resolve(null); } });
355
+ });
356
+ }
357
+ /** Check a finished output against its spec: size, frames, fps, codecs, length, loudness, file size. */
358
+ const VERIFY_LOUDNESS_MS = 120 * 1000; // the file is already saved; a long re-measure must not hold the reply
359
+ async function verifyDeliveryOutput(sess, o, file) {
360
+ const failed = (text) => ({ ok: false, checks: [{ ok: false, text }], line: "⚠ " + text });
361
+ try {
362
+ const loudWanted = o.spec.audio.codec !== "none" && !!sess.wav;
363
+ const [probe, loud] = await Promise.all([ffprobeJSON(file), loudWanted ? measureLoudness(file, VERIFY_LOUDNESS_MS) : null]);
364
+ if (!probe) return failed("could not read the file back to check it (ffprobe)");
365
+ let size = 0;
366
+ try { size = fs.statSync(file).size; } catch {}
367
+ return Delivery.verify(o.spec, probe, {
368
+ fps: sess.fps, frames: sess.frames || (sess.duration ? Math.round(sess.duration * sess.fps) : null), duration: sess.duration,
369
+ size, loud, loudWanted, frame: o.frame, hasAudio: !!sess.wav,
370
+ });
371
+ } catch (e) { return failed("could not check the file: " + (e.message || e)); }
372
+ }
373
+ /** Spawn one ffmpeg per output of a delivery session. */
374
+ function startDeliveryEncoders(sess) {
375
+ for (const o of sess.outputs) {
376
+ const proc = spawn("ffmpeg", Delivery.ffmpegArgs(o.spec, {
377
+ fps: sess.fps, input: sess.input, canvasW: sess.canvasW, canvasH: sess.canvasH, frame: o.frame,
378
+ wavPath: sess.wav, outPath: o.partPath, duration: sess.duration, loudnorm: o.loudnorm,
379
+ }), { stdio: ["pipe", "ignore", "pipe"] });
380
+ proc.stderr.on("data", (d) => { o.stderr = (o.stderr + d).slice(-2000); });
381
+ proc.stdin.on("error", () => { });
382
+ o.proc = proc;
383
+ o.done = new Promise((res) => proc.on("close", res));
384
+ }
385
+ sess.proc = sess.outputs[0].proc; // "started"
386
+ }
387
+ /** The same frames to every output still running. One that fails is marked and
388
+ * left behind; the render goes on for the rest, and fails only when none is left. */
389
+ async function writeDeliveryFrame(sess, body) {
390
+ const live = sess.outputs.filter((o) => !o.failed);
391
+ await Promise.all(live.map((o) => writeExportFrame(o, body).catch((e) => { o.failed = String(e.message || e); })));
392
+ if (!sess.outputs.some((o) => !o.failed))
393
+ throw new Error(sess.outputs.map((o) => `${path.basename(o.outPath)}: ${o.failed}`).join(" · "));
394
+ }
213
395
  async function beginExport(fps, name, profileId, hasAudio, mode, extra = {}) {
214
396
  const m = mode === "annexb" ? "annexb" : "jpeg";
215
397
  const rate = Number(fps);
@@ -222,6 +404,7 @@ async function beginExport(fps, name, profileId, hasAudio, mode, extra = {}) {
222
404
  if (pixelFormat === "rgba" && (width < 2 || height < 2)) {
223
405
  throw new Error("export width/height required for rgba");
224
406
  }
407
+ if (m === "jpeg" && (extra.delivery || extra.deliveries)) return beginDeliveryExport(rate, name, hasAudio, extra);
225
408
  const id = Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
226
409
  const safe = safeName(name || "export");
227
410
  // Same filesystem as the finished file so renameSync(partPath, out) cannot EXDEV.
@@ -263,10 +446,12 @@ async function beginExport(fps, name, profileId, hasAudio, mode, extra = {}) {
263
446
  /* Encode into the paths reserved at /begin; rename .part → final on clean exit
264
447
  so an aborted render never leaves something that looks like a finished file. */
265
448
  function startEncoder(sess) {
266
- const proc = spawn("ffmpeg", buildExportArgs(sess.profile, {
449
+ if (sess.outputs) return startDeliveryEncoders(sess);
450
+ const args = buildExportArgs(sess.profile, {
267
451
  fps: sess.fps, wavPath: sess.wav, outPath: sess.partPath,
268
452
  pixelFormat: sess.pixelFormat, width: sess.width, height: sess.height,
269
- }), { stdio: ["pipe", "ignore", "pipe"] });
453
+ });
454
+ const proc = spawn("ffmpeg", args, { stdio: ["pipe", "ignore", "pipe"] });
270
455
  proc.stderr.on("data", (d) => { sess.stderr = (sess.stderr + d).slice(-2000); });
271
456
  // EPIPE on end()/late writes is normal once ffmpeg has exited; writeExportFrame
272
457
  // attaches its own error listener while a backpressured write is in flight.
@@ -332,6 +517,10 @@ function cleanupExport(id) {
332
517
  if (!s) return;
333
518
  exportSessions.delete(id);
334
519
  try { s.proc?.kill(); } catch {}
520
+ for (const o of s.outputs || []) {
521
+ try { o.proc?.kill(); } catch {}
522
+ if (o.partPath) try { fs.rmSync(o.partPath, { force: true }); } catch {}
523
+ }
335
524
  try { fs.rmSync(s.dir, { recursive: true, force: true }); } catch {}
336
525
  if (s.partPath) try { fs.rmSync(s.partPath, { force: true }); } catch {}
337
526
  }
@@ -406,10 +595,96 @@ const server = http.createServer(async (req, res) => {
406
595
  /* API: project */
407
596
  if (p === "/api/project" && req.method === "GET") {
408
597
  // strip UTF-8 BOM some editors/PowerShell prepend, which breaks JSON.parse
409
- try { sendJSON(res, 200, JSON.parse(fs.readFileSync(PROJECT_FILE, "utf8").replace(new RegExp("^\\uFEFF"), ""))); }
598
+ try {
599
+ const doc = JSON.parse(fs.readFileSync(PROJECT_FILE, "utf8").replace(new RegExp("^\\uFEFF"), ""));
600
+ // which project this is, once there are several: the editor resets undo when it changes
601
+ const id = projects.peekActive();
602
+ res.setHeader("X-FableCut-Projects", "1");
603
+ if (id) res.setHeader("X-FableCut-Project", id);
604
+ sendJSON(res, 200, doc);
605
+ }
410
606
  catch (e) { sendJSON(res, 500, { error: String(e) }); }
411
607
  return;
412
608
  }
609
+
610
+ /* API: projects — the dashboard. GET lists them (?archived=only|all) with the
611
+ project templates; POST {action, …} creates, opens, duplicates, renames,
612
+ archives, deletes, imports, and saves / deletes templates (projects.js).
613
+ GET / PUT /api/projects/thumb?id= is a project's JPEG thumbnail. */
614
+ if (p === "/api/projects" && req.method === "GET") {
615
+ try {
616
+ const archived = ["only", "all"].includes(url.searchParams.get("archived")) ? url.searchParams.get("archived") : "exclude";
617
+ sendJSON(res, 200, projects.act({ action: "list", archived }));
618
+ } catch (e) { sendJSON(res, 500, { error: e.message }); }
619
+ return;
620
+ }
621
+ if (p === "/api/projects" && req.method === "POST") {
622
+ let a;
623
+ try { a = JSON.parse((await readBody(req)).toString("utf8") || "{}"); }
624
+ catch { sendJSON(res, 400, { error: "body must be JSON {action, …}" }); return; }
625
+ try {
626
+ // a backup file (a project with its versions) imports through history.js
627
+ const out = a.action === "import" && a.project?.fablecut === "backup" ? history.importBackup(a.project, a) : projects.act(a);
628
+ broadcast("projects", JSON.stringify({ action: a.action, id: out.id || a.id || null, active: projects.activeId() }));
629
+ // opening, or renaming the open project, rewrites ./project.json: reload the tabs now, watcher or not
630
+ if (out.from || ((a.action === "update" || a.action === "rename") && out.project?.active)) onFsChange();
631
+ sendJSON(res, 200, out);
632
+ } catch (e) { sendJSON(res, /^no (project|saved template)/.test(e.message) ? 404 : 400, { error: e.message }); }
633
+ return;
634
+ }
635
+ /* API: versions (history.js) — GET ?project= lists them (default: the open project);
636
+ POST {action, project?, version?, …} saves, restores, compares, renames / marks
637
+ final, deletes; GET /api/versions/file?project=&version= is one version's document.
638
+ GET /api/projects/backup?id= is a project with all its versions, as one file. */
639
+ if (p === "/api/versions" && req.method === "GET") {
640
+ try { sendJSON(res, 200, history.list(url.searchParams.get("project") || null)); }
641
+ catch (e) { sendJSON(res, /^no project/.test(e.message) ? 404 : 400, { error: e.message }); }
642
+ return;
643
+ }
644
+ if (p === "/api/versions" && req.method === "POST") {
645
+ let a;
646
+ try { a = JSON.parse((await readBody(req)).toString("utf8") || "{}"); }
647
+ catch { sendJSON(res, 400, { error: "body must be JSON {action, …}" }); return; }
648
+ try {
649
+ const out = history.act(a);
650
+ if (a.action && a.action !== "list" && a.action !== "diff") broadcast("versions", JSON.stringify({ project: out.project, action: a.action }));
651
+ const isOpen = out.project === projects.peekActive();
652
+ if (a.action === "restore" && isOpen) onFsChange(); // the tabs load the restored document
653
+ sendJSON(res, 200, a.action === "restore" ? { ...out, open: isOpen } : out);
654
+ } catch (e) { sendJSON(res, /^no (project|version)/.test(e.message) ? 404 : 400, { error: e.message }); }
655
+ return;
656
+ }
657
+ if (p === "/api/versions/file" && req.method === "GET") {
658
+ try {
659
+ const doc = history.get(url.searchParams.get("project") || null, url.searchParams.get("version"));
660
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store",
661
+ "Content-Disposition": `attachment; filename="${safeName(doc.name || "project")}-v${String(url.searchParams.get("version")).replace(/\D/g, "")}.json"` });
662
+ res.end(JSON.stringify(doc, null, 2));
663
+ } catch (e) { sendJSON(res, /^no (project|version)/.test(e.message) ? 404 : 400, { error: e.message }); }
664
+ return;
665
+ }
666
+ if (p === "/api/projects/backup" && req.method === "GET") {
667
+ try {
668
+ const b = history.backup(url.searchParams.get("id") || null);
669
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store",
670
+ "Content-Disposition": `attachment; filename="${safeName(b.name || "project")}.fablecut-backup.json"` });
671
+ res.end(JSON.stringify(b));
672
+ } catch (e) { sendJSON(res, /^no project/.test(e.message) ? 404 : 400, { error: e.message }); }
673
+ return;
674
+ }
675
+ if (p === "/api/projects/thumb" && (req.method === "GET" || req.method === "PUT")) {
676
+ const id = url.searchParams.get("id") || "";
677
+ if (req.method === "GET") {
678
+ const file = projects.thumbPath(id);
679
+ if (!file) { res.writeHead(404); res.end(); return; }
680
+ res.writeHead(200, { "Content-Type": "image/jpeg", "Cache-Control": "no-store" });
681
+ fs.createReadStream(file).pipe(res);
682
+ return;
683
+ }
684
+ try { sendJSON(res, 200, projects.setThumb(id, await readBody(req))); }
685
+ catch (e) { sendJSON(res, /^no project/.test(e.message) ? 404 : 400, { error: e.message }); }
686
+ return;
687
+ }
413
688
  if (p === "/api/project" && req.method === "PUT") {
414
689
  try {
415
690
  const body = await readBody(req);
@@ -420,6 +695,12 @@ const server = http.createServer(async (req, res) => {
420
695
  ?force=1 skips the check for deliberate overwrites. */
421
696
  let cur = {};
422
697
  try { cur = JSON.parse(fs.readFileSync(PROJECT_FILE, "utf8").replace(new RegExp("^\\uFEFF"), "")); } catch {}
698
+ // a save the editor made for another project (it sends the id it loaded) never lands here
699
+ const meant = req.headers["x-fablecut-project"], open = projects.peekActive();
700
+ if (meant && open && meant !== open) {
701
+ sendJSON(res, 409, { error: "another project is open now", revision: cur.revision || 0, project: open });
702
+ return;
703
+ }
423
704
  if ((data.revision || 0) <= (cur.revision || 0) && url.searchParams.get("force") !== "1") {
424
705
  sendJSON(res, 409, { error: "stale revision — project changed since it was read", revision: cur.revision || 0 });
425
706
  return;
@@ -443,6 +724,91 @@ const server = http.createServer(async (req, res) => {
443
724
  return;
444
725
  }
445
726
 
727
+ /* API: media metadata (ffprobe; size only without it).
728
+ GET /api/media-info?src=/media/x.mp4 → {src, info} (info null = file missing)
729
+ POST /api/media-info {srcs:[…], stat?} → {info:{src: info | null}} — up to 2000 per call;
730
+ stat:true answers {size, mtimeMs} without ffprobe (the editor's offline check) */
731
+ if (p === "/api/media-info" && (req.method === "GET" || req.method === "POST")) {
732
+ try {
733
+ if (req.method === "GET") {
734
+ const src = url.searchParams.get("src") || "";
735
+ const file = resolveSrc(src);
736
+ sendJSON(res, 200, { src, info: file ? await probeFile(file) : null });
737
+ return;
738
+ }
739
+ const body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
740
+ const srcs = Array.isArray(body.srcs) ? body.srcs.slice(0, 2000).map(String) : [];
741
+ const info = Object.create(null); // any src is a plain key, "__proto__" too
742
+ // probed side by side (media-probe.js caps how many ffprobes run at once)
743
+ await Promise.all(srcs.map(async (src) => {
744
+ const file = resolveSrc(src);
745
+ if (!file) { info[src] = null; return; }
746
+ // stat:true only asks "is it there?" (offline checks) — no ffprobe
747
+ if (body.stat) { const st = await fs.promises.stat(file); info[src] = { size: st.size, mtimeMs: Math.round(st.mtimeMs) }; }
748
+ else info[src] = await probeFile(file);
749
+ }));
750
+ sendJSON(res, 200, { info });
751
+ } catch (e) { sendJSON(res, 400, { error: String(e.message || e) }); }
752
+ return;
753
+ }
754
+
755
+ /* API: where might a missing file be now? Body {media:[{id, name, size?}]} →
756
+ {candidates:{id:[{src, name, size, score, why}]}} — files under media/ and
757
+ library/ ranked by name and size (MediaLib.relinkScore), best first, at most 5 each. */
758
+ if (p === "/api/relink/candidates" && req.method === "POST") {
759
+ try {
760
+ const body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
761
+ const want = Array.isArray(body.media) ? body.media.slice(0, 2000) : [];
762
+ const files = [];
763
+ const walk = (root, prefix, d, depth) => {
764
+ let list = [];
765
+ try { list = fs.readdirSync(d, { withFileTypes: true }); } catch { return; }
766
+ for (const e of list) {
767
+ if (e.name.startsWith(".")) continue;
768
+ const full = path.join(d, e.name);
769
+ if (e.isDirectory()) { if (depth < 6 && !(root === LIBRARY_DIR && /^(presets|templates|fonts)$/.test(e.name) && depth === 0)) walk(root, prefix, full, depth + 1); continue; }
770
+ let size = 0;
771
+ try { size = fs.statSync(full).size; } catch { continue; }
772
+ const rel = path.relative(root, full).split(path.sep).map(encodeURIComponent).join("/");
773
+ files.push({ src: prefix + rel, name: e.name, size });
774
+ }
775
+ };
776
+ walk(MEDIA_DIR, "/media/", MEDIA_DIR, 0);
777
+ walk(LIBRARY_DIR, "/library/", LIBRARY_DIR, 0);
778
+ const candidates = Object.create(null);
779
+ for (const m of want) {
780
+ if (!m || !m.id) continue;
781
+ candidates[m.id] = files.map((f) => ({ ...f, ...MediaLib.relinkScore(m, f) }))
782
+ .filter((f) => f.score > 0).sort((a, b) => b.score - a.score || a.name.localeCompare(b.name)).slice(0, 5);
783
+ }
784
+ sendJSON(res, 200, { candidates });
785
+ } catch (e) { sendJSON(res, 400, { error: String(e.message || e) }); }
786
+ return;
787
+ }
788
+
789
+ /* API: proxies (see proxy.js).
790
+ POST /api/proxy {srcs:[…], height?:540|720|1080} → {status:{src: status}} — queue them
791
+ POST /api/proxy/status {srcs:[…]} → {status:{src: status | null}}
792
+ POST /api/proxy/delete {srcs:[…]} → {deleted:{src: n}}
793
+ Progress and results also arrive as SSE event "proxy". */
794
+ if ((p === "/api/proxy" || p === "/api/proxy/status" || p === "/api/proxy/delete") && req.method === "POST") {
795
+ try {
796
+ const body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
797
+ const srcs = Array.isArray(body.srcs) ? body.srcs.slice(0, 2000).map(String) : [];
798
+ if (p === "/api/proxy/delete") {
799
+ const deleted = {};
800
+ for (const src of srcs) deleted[src] = proxies.remove(src);
801
+ sendJSON(res, 200, { deleted });
802
+ return;
803
+ }
804
+ if (p === "/api/proxy" && !HAS_FFMPEG) { sendJSON(res, 503, { error: "proxies need ffmpeg on PATH" }); return; }
805
+ const status = {};
806
+ for (const src of srcs) status[src] = p === "/api/proxy" ? await proxies.start(src, body.height) : await proxies.status(src);
807
+ sendJSON(res, 200, { status });
808
+ } catch (e) { sendJSON(res, 400, { error: String(e.message || e) }); }
809
+ return;
810
+ }
811
+
446
812
  /* API: default-asset library listing (./library/{sfx,elements,svg,fonts}) */
447
813
  if (p === "/api/library" && req.method === "GET") {
448
814
  const dir = url.searchParams.get("dir");
@@ -537,9 +903,39 @@ const server = http.createServer(async (req, res) => {
537
903
  const opts = JSON.parse((await readBody(req)).toString("utf8") || "{}");
538
904
  if (!HAS_FFMPEG) { sendJSON(res, 400, { error: "ffmpeg not found on PATH — export needs it" }); return; }
539
905
  if (opts.profile) resolveProfile(String(opts.profile));
906
+ if (opts.profile && (opts.preset || opts.delivery || opts.outputs)) { sendJSON(res, 400, { error: "pass a profile (raw ffmpeg args) or a preset / delivery spec / outputs, not both" }); return; }
907
+ // several files from one render: outputs:true = the project's checked batch outputs, or a list of specs
908
+ let deliveries = null, outNotes = [];
909
+ if (opts.outputs) {
910
+ let list = opts.outputs;
911
+ if (list === true) {
912
+ let proj = {};
913
+ try { proj = JSON.parse(fs.readFileSync(PROJECT_FILE, "utf8").replace(/^\uFEFF/, "")); } catch {}
914
+ list = (Array.isArray(proj.outputs) ? proj.outputs : []).filter((o) => o && o.on !== false);
915
+ if (!list.length) { sendJSON(res, 400, { error: "the project has no checked batch outputs — pass outputs:[{preset…}, …], or add some with setProject {outputs}" }); return; }
916
+ }
917
+ if (!Array.isArray(list) || !list.length) { sendJSON(res, 400, { error: "outputs is true or a list of delivery specs" }); return; }
918
+ if (list.length > 16) { sendJSON(res, 400, { error: "at most 16 outputs" }); return; }
919
+ const available = await deliveryEncoders(), presets = savedDeliveryPresets();
920
+ deliveries = list.map((o, i) => {
921
+ const n = Delivery.normalize(typeof o === "string" ? o : o, { available, presets });
922
+ for (const note of n.notes) outNotes.push(`output ${i + 1}: ${note}`);
923
+ return n.spec;
924
+ });
925
+ }
926
+ // a delivery preset with overrides → one complete spec, checked against this ffmpeg
927
+ let delivery = null, notes = [];
928
+ if (opts.preset || opts.delivery) {
929
+ const d = opts.delivery && typeof opts.delivery === "object" ? opts.delivery : {};
930
+ const n = Delivery.normalize({ ...d, preset: opts.preset || d.preset || undefined },
931
+ { available: await deliveryEncoders(), presets: savedDeliveryPresets() });
932
+ delivery = n.spec; notes = n.notes;
933
+ }
540
934
  let revision = null;
541
935
  try { revision = JSON.parse(fs.readFileSync(PROJECT_FILE, "utf8").replace(/^\uFEFF/, "")).revision ?? null; } catch {}
542
- sendJSON(res, 200, exportJobs.request({ range: opts.range, profile: opts.profile, where: opts.where, revision }));
936
+ const job = exportJobs.request({ range: opts.range, profile: opts.profile, delivery: deliveries ? null : delivery, deliveries, where: opts.where, revision });
937
+ sendJSON(res, 200, deliveries ? { ...job, delivery: `${deliveries.length} outputs from one render`, notes: outNotes }
938
+ : delivery ? { ...job, delivery: Delivery.describe(delivery), notes } : job);
543
939
  } catch (e) {
544
940
  const code = e.code === 409 || e.code === 400 ? e.code : /^Unknown encoding profile/.test(e.message || "") ? 400 : 500;
545
941
  sendJSON(res, code, { error: String(e.message || e) });
@@ -564,7 +960,7 @@ const server = http.createServer(async (req, res) => {
564
960
  if (mk != null && (typeof mk !== "object" || typeof mk.clip !== "string")) {
565
961
  sendJSON(res, 400, { error: "mask must be {clip: \"<clip id>\"}" }); return;
566
962
  }
567
- sendJSON(res, 200, exportJobs.request({ kind: "scopes", time, where: opts.where, revision, matte: m || null, mask: mk || null }));
963
+ sendJSON(res, 200, exportJobs.request({ kind: "scopes", time, where: opts.where, revision, matte: m || null, mask: mk || null, image: opts.image === true }));
568
964
  } catch (e) {
569
965
  sendJSON(res, e.code === 409 || e.code === 400 ? e.code : 500, { error: String(e.message || e) });
570
966
  }
@@ -618,6 +1014,40 @@ const server = http.createServer(async (req, res) => {
618
1014
  } catch (e) { sendJSON(res, 500, { error: String(e) }); }
619
1015
  return;
620
1016
  }
1017
+ /* API: delivery presets — GET lists the saved ones and the encoders this
1018
+ ffmpeg can use (the built-in presets live in delivery.js, which the page
1019
+ loads too); POST {name, spec} saves one to library/delivery/; POST
1020
+ /api/export/presets/delete {id} removes it. */
1021
+ if (p === "/api/export/presets" && req.method === "GET") {
1022
+ const encoders = [...(await deliveryEncoders())].filter((e) => Delivery.ENCODERS[e]).sort();
1023
+ sendJSON(res, 200, { ffmpeg: HAS_FFMPEG, encoders, saved: savedDeliveryPresets(), builtin: Delivery.PRESET_IDS });
1024
+ return;
1025
+ }
1026
+ if ((p === "/api/export/presets" || p === "/api/export/presets/delete") && req.method === "POST") {
1027
+ try {
1028
+ const opts = JSON.parse((await readBody(req)).toString("utf8") || "{}");
1029
+ if (p.endsWith("/delete")) {
1030
+ const id = Delivery.presetId(opts.id);
1031
+ const file = path.join(LIBRARY_DIR, "delivery", id + ".json");
1032
+ if (!id || !fs.existsSync(file)) { sendJSON(res, 404, { error: "no saved delivery preset " + JSON.stringify(opts.id) }); return; }
1033
+ fs.unlinkSync(file);
1034
+ broadcast("delivery-presets");
1035
+ sendJSON(res, 200, { ok: true, id });
1036
+ return;
1037
+ }
1038
+ const label = String(opts.name || "").trim().slice(0, 60);
1039
+ const id = Delivery.presetId(label);
1040
+ if (!id) { sendJSON(res, 400, { error: "name the preset (letters or digits)" }); return; }
1041
+ if (Delivery.PRESETS[id]) { sendJSON(res, 400, { error: `"${label}" is a built-in preset — pick another name` }); return; }
1042
+ // what the spec leaves out comes from the preset it names (built-in or saved), not from Custom
1043
+ const { spec, notes } = Delivery.normalize(opts.spec || {}, { presets: savedDeliveryPresets() });
1044
+ delete spec.preset;
1045
+ writeSaved("delivery", id, { id, label, ...spec });
1046
+ broadcast("delivery-presets");
1047
+ sendJSON(res, 200, { ok: true, id, label, notes });
1048
+ } catch (e) { sendJSON(res, 400, { error: String(e.message || e) }); }
1049
+ return;
1050
+ }
621
1051
  if (p === "/api/export/begin" && req.method === "POST") {
622
1052
  try {
623
1053
  const opts = JSON.parse((await readBody(req)).toString("utf8") || "{}");
@@ -627,7 +1057,7 @@ const server = http.createServer(async (req, res) => {
627
1057
  sendJSON(res, 200, await beginExport(opts.fps, opts.name, opts.profile, opts.hasAudio !== false, mode, opts));
628
1058
  } catch (e) {
629
1059
  // an unusable profile is the caller's problem, not a server fault
630
- const bad = /^Unknown encoding profile|was rejected by ffmpeg|export fps required|export width\/height required/.test(e.message || "");
1060
+ const bad = /^Unknown encoding profile|was rejected by ffmpeg|ffmpeg rejected these settings|at most \d+ outputs|deliveries is empty|render each frame rate separately|export fps required|export width\/height required/.test(e.message || "");
631
1061
  sendJSON(res, bad ? 400 : 500, { error: String(e.message || e) });
632
1062
  }
633
1063
  return;
@@ -646,7 +1076,7 @@ const server = http.createServer(async (req, res) => {
646
1076
  // queue behind any in-flight write so concurrent POSTs cannot interleave stdin
647
1077
  const run = async () => {
648
1078
  if (!sess.proc) sess.mode === "annexb" ? startAnnexbEncoder(sess) : startEncoder(sess);
649
- await writeExportFrame(sess, body);
1079
+ await (sess.outputs ? writeDeliveryFrame(sess, body) : writeExportFrame(sess, body));
650
1080
  };
651
1081
  const writeJob = sess.writeLock.then(run, run);
652
1082
  sess.writeLock = writeJob.catch(() => {}); // keep the chain alive after a failed write
@@ -665,6 +1095,14 @@ const server = http.createServer(async (req, res) => {
665
1095
  try {
666
1096
  const wavPath = path.join(sess.dir, "audio.wav");
667
1097
  fs.writeFileSync(wavPath, await readBody(req));
1098
+ // outputs that normalize loudness need the mix measured (loudnorm pass one) before ffmpeg starts
1099
+ const byTarget = new Map();
1100
+ for (const o of sess.outputs || []) {
1101
+ if (o.spec.audio.loudness == null || o.spec.audio.codec === "none") continue;
1102
+ const k = `${o.spec.audio.loudness}/${o.spec.audio.truePeak}`;
1103
+ if (!byTarget.has(k)) byTarget.set(k, runFfmpeg(Delivery.LOUDNORM_ARGS(wavPath, o.spec), 10 * 60 * 1000).then((r) => Delivery.parseLoudnorm(r.stderr)));
1104
+ o.loudnorm = await byTarget.get(k);
1105
+ }
668
1106
  sess.wav = wavPath;
669
1107
  touchExport(sess);
670
1108
  sendJSON(res, 200, { ok: true });
@@ -679,6 +1117,30 @@ const server = http.createServer(async (req, res) => {
679
1117
  if (url.searchParams.get("discard")) { cleanupExport(id); sendJSON(res, 200, { ok: true }); return; }
680
1118
  touchExport(sess); // keep alive through final mux
681
1119
  if (!sess.proc) throw new Error("no frames were uploaded");
1120
+ if (sess.outputs) {
1121
+ // every output finishes on its own; the reply lists each file or why it failed
1122
+ const results = await Promise.all(sess.outputs.map(async (o) => {
1123
+ const file = path.basename(o.outPath);
1124
+ if (!o.failed) {
1125
+ o.proc.stdin.end();
1126
+ const code = await o.done;
1127
+ if (code !== 0) o.failed = "ffmpeg encode failed: " + o.err();
1128
+ }
1129
+ if (o.failed) return { file, ok: false, error: o.failed };
1130
+ // a file that cannot be put in place fails alone; the others keep finishing
1131
+ try { fs.renameSync(o.partPath, o.outPath); }
1132
+ catch (e) { return { file, ok: false, error: "could not save the file: " + (e.message || e) }; }
1133
+ o.partPath = null; // renamed — cleanup must not delete the finished file
1134
+ const report = await verifyDeliveryOutput(sess, o, o.outPath);
1135
+ return { file, ok: true, src: "/exports/" + encodeURIComponent(file), ...(report ? { report } : {}),
1136
+ ...(o.loudnorm ? { mixLoudness: o.loudnorm.input_i } : {}) };
1137
+ }));
1138
+ cleanupExport(id);
1139
+ const ok = results.filter((x) => x.ok);
1140
+ if (!ok.length) throw new Error(results.map((x) => `${x.file}: ${x.error}`).join(" · "));
1141
+ sendJSON(res, 200, { ok: true, src: ok[0].src, outputs: results });
1142
+ return;
1143
+ }
682
1144
  sess.proc.stdin.end();
683
1145
  const code = await sess.done;
684
1146
  if (code !== 0) throw new Error("ffmpeg encode failed: " + sess.err());
@@ -723,6 +1185,127 @@ const server = http.createServer(async (req, res) => {
723
1185
  return;
724
1186
  }
725
1187
 
1188
+ /* API: one frame of a source clip, or an N-up contact sheet across it —
1189
+ the "eyes" to go with /api/analyze's ears, so an agent can look at a
1190
+ moment instead of guessing from an energy number. JPEG in, JPEG out.
1191
+
1192
+ GET /api/frame?src=/media/x.mp4&t=3.2[&w=768][&q=4]
1193
+ GET /api/frame?src=/media/x.mp4&frames=12[&cols=][&from=0][&to=30][&w=320]
1194
+ (cols omitted → the squarest layout: 6 frames give 3×2, 12 give 4×3)
1195
+ GET /api/frame?path=C:\clips\x.mp4&t=3.2
1196
+
1197
+ `src` is a served /media/ or /library/ path. `path` is any readable path on
1198
+ this machine — it does NOT copy the file into media/, because looking at a
1199
+ clip must not change the user's project folder. `path` is answered only
1200
+ with the `X-FableCut-Client: mcp` request header, which only the local MCP
1201
+ client sends: without it a web page could otherwise probe which files
1202
+ exist (`onload` vs `onerror`), make ffmpeg decode them, and fill the cache
1203
+ below with junk. resolveSrc() remains the guard for anything that turns a
1204
+ request string into a path inside a served root.
1205
+
1206
+ &text=1 returns JSON statistics instead of the image, for agents (or
1207
+ models) that cannot see one. Needs ffmpeg on PATH.
1208
+
1209
+ Results are cached under analysis/frames/ by a hash of every argument, so
1210
+ polling the same timestamp costs nothing and the mtime/size of the cached
1211
+ file answers "did the source change underneath this?". The cache is capped
1212
+ (500 files / 128 MB, oldest mtime first — see frame-cache.js), so no
1213
+ combination of arguments can fill the disk. */
1214
+ if (p === "/api/frame" && req.method === "GET") {
1215
+ const pathArg = url.searchParams.get("path");
1216
+ /* `path=` reads any file on this machine, so it is only answered for the
1217
+ local MCP client, which proves itself with a custom header. An <img> or
1218
+ <form> on a web page cannot set one, and a cross-site fetch() that sets
1219
+ one needs a CORS preflight this server never grants — so a page in the
1220
+ user's browser can neither render a frame nor probe which files exist
1221
+ (a missing header is refused before the path is even resolved, so the
1222
+ answer leaks nothing). `src=` needs no header: those files are already
1223
+ served over HTTP at /media/ and /library/. */
1224
+ if (pathArg && req.headers["x-fablecut-client"] !== "mcp") {
1225
+ sendJSON(res, 403, { error: "path= needs the X-FableCut-Client: mcp request header — only the local MCP client may read files outside media/ and library/" });
1226
+ return;
1227
+ }
1228
+ /* The path is resolved next: whether a file is readable never depends on
1229
+ whether ffmpeg happens to be installed. */
1230
+ const src = url.searchParams.get("src") || "";
1231
+ const file = pathArg ? resolvePathArg(pathArg) : resolveSrc(src);
1232
+ if (!file) {
1233
+ sendJSON(res, 404, { error: pathArg
1234
+ ? "path must be an existing file on this machine"
1235
+ : "src must name an existing file under /media/ or /library/" });
1236
+ return;
1237
+ }
1238
+ if (!HAS_FFMPEG) { sendJSON(res, 400, { error: "ffmpeg not found on PATH — frame extraction needs it" }); return; }
1239
+ const num = (k, dflt) => {
1240
+ const raw = url.searchParams.get(k);
1241
+ if (raw === null || raw === "") return dflt;
1242
+ const n = Number(raw);
1243
+ if (!Number.isFinite(n)) throw new Error(`${k} must be a number`);
1244
+ return n;
1245
+ };
1246
+ try {
1247
+ fs.mkdirSync(FRAMES_DIR, { recursive: true });
1248
+ const isSheet = url.searchParams.get("frames") != null;
1249
+ const opts = isSheet
1250
+ ? { frames: num("frames"), cols: num("cols", null), from: num("from", 0), to: num("to", undefined), width: num("w", 320), quality: url.searchParams.get("q") }
1251
+ : { t: num("t", 0), width: num("w", 768), quality: url.searchParams.get("q") };
1252
+ // Key on the source's identity + size + mtime so an overwritten file
1253
+ // never serves a stale grab.
1254
+ const st = fs.statSync(file);
1255
+ const key = crypto.createHash("sha1")
1256
+ .update(JSON.stringify([file, st.size, Math.round(st.mtimeMs), opts])).digest("hex");
1257
+ const cache = path.join(FRAMES_DIR, key + ".jpg");
1258
+ let meta = null;
1259
+ try {
1260
+ meta = JSON.parse(fs.readFileSync(cache.replace(/\.jpg$/, ".json"), "utf8"));
1261
+ } catch { /* render below */ }
1262
+ // Self-healing: if the JPEG exists but meta doesn't, re-render so both are
1263
+ // written together. A partial write (JPEG with no meta) otherwise serves
1264
+ // 500 forever because meta stays null.
1265
+ if (!fs.existsSync(cache) || !meta) {
1266
+ const r = isSheet ? await frameGrid(file, opts) : await frame(file, opts);
1267
+ meta = isSheet
1268
+ ? { frames: r.frames, cols: r.cols, rows: r.rows, times: r.times, duration: r.duration, cellWidth: r.width, stats: r.stats }
1269
+ : { frames: 1, times: [r.time], stats: r.stats };
1270
+ meta.source = pathArg ? pathArg : src;
1271
+ const tmp = cache + ".tmp";
1272
+ fs.writeFileSync(tmp, r.jpeg);
1273
+ fs.renameSync(tmp, cache); // atomic: a half-written jpeg never gets cached
1274
+ fs.writeFileSync(cache.replace(/\.jpg$/, ".json"), JSON.stringify(meta));
1275
+ /* Bound the cache: every distinct argument set mints a file, so cap
1276
+ the directory oldest-first rather than letting it grow forever. */
1277
+ try { pruneCache(FRAMES_DIR); } catch { /* a prune failure is not the request's problem */ }
1278
+ } else {
1279
+ // Refresh LRU order so hot entries survive the prune above.
1280
+ try { fs.utimesSync(cache, new Date(), new Date()); } catch {}
1281
+ }
1282
+ /* text=1 answers JSON measurements instead of the picture, for agents and
1283
+ models that cannot see one. Same decode, no pixels over the wire. */
1284
+ if (url.searchParams.get("text") === "1") {
1285
+ sendJSON(res, 200, {
1286
+ source: meta.source, frames: meta.frames, times: meta.times,
1287
+ cols: meta.cols || null, rows: meta.rows || null, duration: meta.duration ?? null,
1288
+ stats: meta.stats || null,
1289
+ });
1290
+ return;
1291
+ }
1292
+ res.writeHead(200, {
1293
+ "Content-Type": "image/jpeg",
1294
+ "Content-Length": fs.statSync(cache).size,
1295
+ "Cache-Control": "no-cache",
1296
+ "X-FableCut-Frame-Times": (meta.times || []).join(","),
1297
+ "X-FableCut-Frame-Source": encodeURI(meta.source || src),
1298
+ });
1299
+ fs.createReadStream(cache).pipe(res);
1300
+ } catch (e) {
1301
+ const msg = e && e.message ? e.message : String(e);
1302
+ /* A bad argument, a missing file, or a timestamp past the end is the
1303
+ caller's problem; anything else is ours. */
1304
+ sendJSON(res, /must be|File not found|no video|no frame|past the end/.test(msg) ? 400 : 500, { error: msg });
1305
+ }
1306
+ return;
1307
+ }
1308
+
726
1309
  /* API: noise reduction — POST {src:"/media/…"|"/library/…", amount:"light"|"medium"|"strong"}
727
1310
  writes a denoised FLAC of the whole file into media/ (reused if it exists)
728
1311
  and returns {src, name, duration, channels}. Registering it is the caller's job. */
@@ -731,11 +1314,8 @@ const server = http.createServer(async (req, res) => {
731
1314
  try {
732
1315
  const opts = JSON.parse((await readBody(req)).toString("utf8") || "{}");
733
1316
  if (!DENOISE_AMOUNTS.includes(opts.amount)) { sendJSON(res, 400, { error: `amount must be one of ${DENOISE_AMOUNTS.join(", ")}` }); return; }
734
- const src = decodeURIComponent(String(opts.src || "").split("?")[0]);
735
- const [root, rel] = src.startsWith("/media/") ? [MEDIA_DIR, src.slice(7)]
736
- : src.startsWith("/library/") ? [LIBRARY_DIR, src.slice(9)] : [null, null];
737
- const file = root && path.normalize(path.join(root, rel));
738
- if (!file || !file.startsWith(path.normalize(root + path.sep)) || !fs.existsSync(file)) {
1317
+ const file = resolveSrc(opts.src);
1318
+ if (!file) {
739
1319
  sendJSON(res, 404, { error: "src must name an existing file under /media/ or /library/" });
740
1320
  return;
741
1321
  }
@@ -757,9 +1337,18 @@ const server = http.createServer(async (req, res) => {
757
1337
  return;
758
1338
  }
759
1339
 
760
- /* Media files */
1340
+ /* Media files (subfolders too — relinked footage can sit in one) */
761
1341
  if (p.startsWith("/media/")) {
762
- const file = path.join(MEDIA_DIR, path.basename(p));
1342
+ const file = path.normalize(path.join(MEDIA_DIR, p.slice("/media/".length)));
1343
+ if (!file.startsWith(MEDIA_DIR + path.sep)) { res.writeHead(403); res.end(); return; }
1344
+ serveFile(req, res, file);
1345
+ return;
1346
+ }
1347
+
1348
+ /* Proxies (analysis/proxies) */
1349
+ if (p.startsWith("/proxies/")) {
1350
+ const file = proxies.file(p.slice("/proxies/".length));
1351
+ if (!file) { res.writeHead(404); res.end(); return; }
763
1352
  serveFile(req, res, file);
764
1353
  return;
765
1354
  }
@@ -785,6 +1374,15 @@ const server = http.createServer(async (req, res) => {
785
1374
  serveFile(req, res, file);
786
1375
  });
787
1376
 
1377
+ /* Auto-save versions of the open project while it changes (every FABLECUT_AUTO_VERSION_MIN
1378
+ minutes at most, default 10), whoever edits it: the editor, an agent, a script. */
1379
+ setInterval(() => {
1380
+ try {
1381
+ const v = history.maybeAuto();
1382
+ if (v) broadcast("versions", JSON.stringify({ project: projects.peekActive(), action: "auto" }));
1383
+ } catch { }
1384
+ }, 60_000).unref();
1385
+
788
1386
  server.listen(PORT, HOST, () => {
789
1387
  console.log(`\n FableCut running → http://localhost:${PORT}\n`);
790
1388
  if (!["127.0.0.1", "localhost", "::1"].includes(HOST))