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/CLAUDE.md +612 -17
- package/README.md +51 -5
- package/analyze.js +161 -9
- package/app.js +2995 -141
- package/comp.js +5 -1
- package/delivery.js +779 -0
- package/encode-profiles.js +9 -3
- package/encoding-profiles.json +26 -0
- package/export-jobs.js +9 -5
- package/frame-cache.js +49 -0
- package/frame-stats.js +267 -0
- package/history.js +341 -0
- package/index.html +179 -4
- package/mcp-server.js +455 -1072
- package/media-lib.js +298 -0
- package/media-probe.js +88 -0
- package/mp4-demux.js +256 -0
- package/package.json +1 -1
- package/paths.js +9 -2
- package/project-ops.js +1358 -0
- package/projects.js +324 -0
- package/proxy.js +180 -0
- package/sequences.js +216 -0
- package/server.js +614 -16
- package/style.css +617 -0
package/projects.js
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
/* ═══════════════════════════════════════════════════════════════════════════
|
|
2
|
+
Projects: several projects in one data folder.
|
|
3
|
+
|
|
4
|
+
./project.json stays THE open project — the editor, the MCP server, agents
|
|
5
|
+
and scripts all keep reading and writing that one file. Every project also
|
|
6
|
+
has its own folder:
|
|
7
|
+
|
|
8
|
+
projects/index.json {active: "<id>"}
|
|
9
|
+
projects/<id>/meta.json {id, created, opened, archived, notes, tags}
|
|
10
|
+
projects/<id>/project.json the document (stale while that project is open:
|
|
11
|
+
the live copy is ./project.json)
|
|
12
|
+
projects/<id>/thumb.jpg the editor's last picture of it
|
|
13
|
+
library/project-templates/<id>.json saved templates {name, created, project}
|
|
14
|
+
|
|
15
|
+
Opening another project parks ./project.json in the open project's folder,
|
|
16
|
+
then copies the chosen one over it with a revision above both, so a save
|
|
17
|
+
from an editor tab or agent that read the old project is refused (409 /
|
|
18
|
+
CONFLICT) instead of landing on the new one. media/, exports/ and analysis/
|
|
19
|
+
are shared, so a duplicate or a template copies no footage.
|
|
20
|
+
═══════════════════════════════════════════════════════════════════════════ */
|
|
21
|
+
"use strict";
|
|
22
|
+
const crypto = require("crypto");
|
|
23
|
+
const fs = require("fs");
|
|
24
|
+
const path = require("path");
|
|
25
|
+
|
|
26
|
+
/* Canvas presets offered next to the user's saved templates. */
|
|
27
|
+
const BUILTIN_TEMPLATES = [
|
|
28
|
+
{ id: "landscape-1080", name: "Landscape 16:9 · 1080p", width: 1920, height: 1080, fps: 30 },
|
|
29
|
+
{ id: "vertical-1080", name: "Vertical 9:16 · Reels, Shorts, TikTok", width: 1080, height: 1920, fps: 30 },
|
|
30
|
+
{ id: "square-1080", name: "Square 1:1", width: 1080, height: 1080, fps: 30 },
|
|
31
|
+
{ id: "portrait-1350", name: "Portrait 4:5 · feed post", width: 1080, height: 1350, fps: 30 },
|
|
32
|
+
{ id: "uhd-4k", name: "4K UHD 16:9", width: 3840, height: 2160, fps: 30 },
|
|
33
|
+
{ id: "landscape-720", name: "Landscape 16:9 · 720p", width: 1280, height: 720, fps: 30 },
|
|
34
|
+
];
|
|
35
|
+
const FPS_CHOICES = [23.976, 24, 25, 29.97, 30, 50, 59.94, 60];
|
|
36
|
+
const MAX_NOTES = 4000, MAX_TAGS = 12, MAX_NAME = 120;
|
|
37
|
+
|
|
38
|
+
const readJSON = (file) => JSON.parse(fs.readFileSync(file, "utf8").replace(/^/, ""));
|
|
39
|
+
function writeJSON(file, obj) {
|
|
40
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
41
|
+
// unique tmp: the editor and the MCP server may write at once
|
|
42
|
+
const tmp = `${file}.${crypto.randomUUID()}.tmp`;
|
|
43
|
+
fs.writeFileSync(tmp, JSON.stringify(obj, null, 2));
|
|
44
|
+
fs.renameSync(tmp, file);
|
|
45
|
+
}
|
|
46
|
+
const newId = () => "p_" + crypto.randomBytes(5).toString("hex");
|
|
47
|
+
const validId = (id) => typeof id === "string" && /^p_[a-z0-9]{4,24}$/.test(id);
|
|
48
|
+
const slug = (s) => String(s || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
|
|
49
|
+
const cleanName = (s) => String(s ?? "").replace(/[\u0000-\u001f]/g, " ").trim().slice(0, MAX_NAME);
|
|
50
|
+
function cleanTags(v) {
|
|
51
|
+
const list = Array.isArray(v) ? v : String(v ?? "").split(",");
|
|
52
|
+
const out = [];
|
|
53
|
+
for (const t of list) {
|
|
54
|
+
const s = String(t ?? "").trim().replace(/^#+/, "").trim().slice(0, 32);
|
|
55
|
+
if (s && !out.some((x) => x.toLowerCase() === s.toLowerCase())) out.push(s);
|
|
56
|
+
}
|
|
57
|
+
return out.slice(0, MAX_TAGS);
|
|
58
|
+
}
|
|
59
|
+
const timelineEnd = (doc) => (Array.isArray(doc.clips) ? doc.clips : [])
|
|
60
|
+
.reduce((m, c) => Math.max(m, (+c.start || 0) + (+c.duration || 0)), 0);
|
|
61
|
+
const blankProject = (name, t) => ({
|
|
62
|
+
name, width: t.width, height: t.height, fps: t.fps, revision: 0, media: [], clips: [],
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
function createProjects({ dataDir, projectFile, libraryDir }) {
|
|
66
|
+
const DIR = path.join(dataDir, "projects");
|
|
67
|
+
const INDEX = path.join(DIR, "index.json");
|
|
68
|
+
const TEMPLATES = path.join(libraryDir, "project-templates");
|
|
69
|
+
const folder = (id) => path.join(DIR, id);
|
|
70
|
+
const metaFile = (id) => path.join(folder(id), "meta.json");
|
|
71
|
+
const docFile = (id) => path.join(folder(id), "project.json");
|
|
72
|
+
const thumbFile = (id) => path.join(folder(id), "thumb.jpg");
|
|
73
|
+
|
|
74
|
+
const readRoot = () => {
|
|
75
|
+
try { return readJSON(projectFile); }
|
|
76
|
+
catch (e) { throw new Error(`project.json can't be read (${e.message}) — fix or replace it before switching projects`); }
|
|
77
|
+
};
|
|
78
|
+
const readMeta = (id) => { try { return readJSON(metaFile(id)); } catch { return null; } };
|
|
79
|
+
const writeMeta = (id, meta) => writeJSON(metaFile(id), meta);
|
|
80
|
+
const exists = (id) => validId(id) && fs.existsSync(metaFile(id));
|
|
81
|
+
|
|
82
|
+
/* The open project's id. The first call gives the existing ./project.json
|
|
83
|
+
a folder of its own, so a data folder from before projects just works. */
|
|
84
|
+
function activeId() {
|
|
85
|
+
let id = null;
|
|
86
|
+
try { id = readJSON(INDEX).active; } catch { }
|
|
87
|
+
if (exists(id)) return id;
|
|
88
|
+
id = newId();
|
|
89
|
+
let created = new Date().toISOString();
|
|
90
|
+
try { created = fs.statSync(projectFile).mtime.toISOString(); } catch { }
|
|
91
|
+
writeMeta(id, { id, created, opened: new Date().toISOString(), archived: false, notes: "", tags: [] });
|
|
92
|
+
writeJSON(INDEX, { active: id });
|
|
93
|
+
return id;
|
|
94
|
+
}
|
|
95
|
+
/* The open project's id without creating anything (null before the first dashboard use). */
|
|
96
|
+
function peekActive() {
|
|
97
|
+
try { const id = readJSON(INDEX).active; return exists(id) ? id : null; } catch { return null; }
|
|
98
|
+
}
|
|
99
|
+
const mustExist = (id) => {
|
|
100
|
+
if (!exists(id)) throw new Error(`no project ${JSON.stringify(id)} (fablecut_projects {action:"list"} lists them)`);
|
|
101
|
+
};
|
|
102
|
+
/* The document of a project: ./project.json for the open one. */
|
|
103
|
+
const readDoc = (id) => (id === activeId() ? readRoot() : readJSON(docFile(id)));
|
|
104
|
+
const writeDoc = (id, doc) => {
|
|
105
|
+
if (id !== activeId()) { writeJSON(docFile(id), doc); return; }
|
|
106
|
+
// the open project: bump the revision like any other save, so tabs reload
|
|
107
|
+
const cur = readRoot();
|
|
108
|
+
writeJSON(projectFile, { ...doc, revision: Math.max(cur.revision || 0, doc.revision || 0) + 1 });
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
function summary(id, active) {
|
|
112
|
+
const meta = readMeta(id) || { id };
|
|
113
|
+
let doc = null, modified = null;
|
|
114
|
+
const file = id === active ? projectFile : docFile(id);
|
|
115
|
+
try { doc = readJSON(file); modified = fs.statSync(file).mtime.toISOString(); } catch { }
|
|
116
|
+
let thumb = null;
|
|
117
|
+
try { thumb = Math.round(fs.statSync(thumbFile(id)).mtimeMs); } catch { }
|
|
118
|
+
return {
|
|
119
|
+
id, name: doc?.name || "Untitled Project", active: id === active,
|
|
120
|
+
archived: !!meta.archived, notes: meta.notes || "", tags: meta.tags || [],
|
|
121
|
+
created: meta.created || null, opened: meta.opened || null, modified,
|
|
122
|
+
width: doc?.width ?? null, height: doc?.height ?? null, fps: doc?.fps ?? null,
|
|
123
|
+
duration: doc ? +timelineEnd(doc).toFixed(2) : null,
|
|
124
|
+
clips: doc?.clips?.length ?? 0, media: doc?.media?.length ?? 0,
|
|
125
|
+
thumb, unreadable: !doc,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function list({ archived = "exclude" } = {}) {
|
|
130
|
+
const active = activeId();
|
|
131
|
+
let ids = [];
|
|
132
|
+
try { ids = fs.readdirSync(DIR, { withFileTypes: true }).filter((e) => e.isDirectory() && exists(e.name)).map((e) => e.name); } catch { }
|
|
133
|
+
let projects = ids.map((id) => summary(id, active));
|
|
134
|
+
if (archived === "exclude") projects = projects.filter((p) => !p.archived || p.active);
|
|
135
|
+
else if (archived === "only") projects = projects.filter((p) => p.archived);
|
|
136
|
+
projects.sort((a, b) => String(b.opened || b.modified || "").localeCompare(String(a.opened || a.modified || "")));
|
|
137
|
+
return { active, projects };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/* Park the open project in its folder, then put `id` in ./project.json. */
|
|
141
|
+
function open(id) {
|
|
142
|
+
mustExist(id);
|
|
143
|
+
const cur = activeId();
|
|
144
|
+
if (id === cur) return { id, already: true, project: summary(id, cur) };
|
|
145
|
+
const root = readRoot();
|
|
146
|
+
let next;
|
|
147
|
+
try { next = readJSON(docFile(id)); }
|
|
148
|
+
catch (e) { throw new Error(`project ${id} can't be read (${e.message})`); }
|
|
149
|
+
writeJSON(docFile(cur), root);
|
|
150
|
+
next.revision = Math.max(root.revision || 0, next.revision || 0) + 1;
|
|
151
|
+
try {
|
|
152
|
+
writeJSON(projectFile, next);
|
|
153
|
+
writeJSON(INDEX, { active: id });
|
|
154
|
+
} catch (e) {
|
|
155
|
+
// ./project.json and index.json must agree: put the open project back
|
|
156
|
+
try { writeJSON(projectFile, { ...root, revision: next.revision + 1 }); } catch { }
|
|
157
|
+
throw new Error(`switching to ${id} failed (${e.message}) — ${cur} is still open`);
|
|
158
|
+
}
|
|
159
|
+
const meta = readMeta(id) || { id };
|
|
160
|
+
writeMeta(id, { ...meta, opened: new Date().toISOString(), archived: false });
|
|
161
|
+
return { id, from: cur, project: summary(id, id) };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function add(doc, { name, notes, tags, template } = {}) {
|
|
165
|
+
const id = newId();
|
|
166
|
+
const now = new Date().toISOString();
|
|
167
|
+
const out = { ...doc, name: cleanName(name) || doc.name || "Untitled Project", revision: 0 };
|
|
168
|
+
writeJSON(docFile(id), out);
|
|
169
|
+
const meta = { id, created: now, opened: null, archived: false, notes: String(notes || "").slice(0, MAX_NOTES), tags: cleanTags(tags) };
|
|
170
|
+
if (template) meta.template = template;
|
|
171
|
+
writeMeta(id, meta);
|
|
172
|
+
return id;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function findTemplate(tid) {
|
|
176
|
+
const b = BUILTIN_TEMPLATES.find((t) => t.id === tid);
|
|
177
|
+
if (b) return { builtin: true, ...b };
|
|
178
|
+
const s = templates().find((t) => t.id === tid);
|
|
179
|
+
if (!s) throw new Error(`no project template ${JSON.stringify(tid)} (built-in: ${BUILTIN_TEMPLATES.map((t) => t.id).join(", ")}${templates().some((t) => !t.builtin) ? "; saved: " + templates().filter((t) => !t.builtin).map((t) => t.id).join(", ") : ""})`);
|
|
180
|
+
return s;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/* A new project from a template (default: 1080p landscape), optionally opened. */
|
|
184
|
+
function create({ name, template = "landscape-1080", fps, width, height, notes, tags, open: andOpen = true } = {}) {
|
|
185
|
+
const t = findTemplate(template);
|
|
186
|
+
let doc;
|
|
187
|
+
if (t.builtin) doc = blankProject("", t);
|
|
188
|
+
else doc = structuredClone(readJSON(path.join(TEMPLATES, t.id + ".json")).project);
|
|
189
|
+
if (fps != null) {
|
|
190
|
+
if (!(Number(fps) > 0 && Number(fps) <= 120)) throw new Error("fps must be a frame rate between 1 and 120");
|
|
191
|
+
doc.fps = Number(fps);
|
|
192
|
+
}
|
|
193
|
+
for (const [k, v] of [["width", width], ["height", height]]) {
|
|
194
|
+
if (v == null) continue;
|
|
195
|
+
if (!Number.isInteger(v) || v < 16 || v > 8192 || v % 2) throw new Error(`${k} must be an even number of pixels, 16…8192`);
|
|
196
|
+
doc[k] = v;
|
|
197
|
+
}
|
|
198
|
+
const id = add(doc, { name: cleanName(name) || "Untitled Project", notes, tags, template: t.id });
|
|
199
|
+
return andOpen ? open(id) : { id, project: summary(id, activeId()) };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function duplicate(id, { name, open: andOpen = false } = {}) {
|
|
203
|
+
mustExist(id);
|
|
204
|
+
const src = readDoc(id);
|
|
205
|
+
const meta = readMeta(id) || {};
|
|
206
|
+
const nid = add(structuredClone(src), { name: cleanName(name) || `${src.name || "Untitled Project"} copy`, notes: meta.notes, tags: meta.tags });
|
|
207
|
+
try { fs.copyFileSync(thumbFile(id), thumbFile(nid)); } catch { }
|
|
208
|
+
return andOpen ? open(nid) : { id: nid, project: summary(nid, activeId()) };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/* Rename / notes / tags. */
|
|
212
|
+
function update(id, { name, notes, tags } = {}) {
|
|
213
|
+
mustExist(id);
|
|
214
|
+
if (name != null) {
|
|
215
|
+
const n = cleanName(name);
|
|
216
|
+
if (!n) throw new Error("name can't be empty");
|
|
217
|
+
const doc = readDoc(id);
|
|
218
|
+
if (doc.name !== n) writeDoc(id, { ...doc, name: n });
|
|
219
|
+
}
|
|
220
|
+
if (notes != null || tags != null) {
|
|
221
|
+
const meta = readMeta(id) || { id };
|
|
222
|
+
if (notes != null) meta.notes = String(notes).slice(0, MAX_NOTES);
|
|
223
|
+
if (tags != null) meta.tags = cleanTags(tags);
|
|
224
|
+
writeMeta(id, meta);
|
|
225
|
+
}
|
|
226
|
+
return { id, project: summary(id, activeId()) };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function archive(id, on = true) {
|
|
230
|
+
mustExist(id);
|
|
231
|
+
if (on && id === activeId()) throw new Error("the open project can't be archived — open another project first");
|
|
232
|
+
writeMeta(id, { ...(readMeta(id) || { id }), archived: !!on });
|
|
233
|
+
return { id, project: summary(id, activeId()) };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/* Deleting is for archived projects only, so it always takes two steps. */
|
|
237
|
+
function remove(id) {
|
|
238
|
+
mustExist(id);
|
|
239
|
+
if (id === activeId()) throw new Error("the open project can't be deleted");
|
|
240
|
+
if (!readMeta(id)?.archived) throw new Error("archive the project first — only archived projects can be deleted");
|
|
241
|
+
fs.rmSync(folder(id), { recursive: true, force: true });
|
|
242
|
+
return { id, deleted: true };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/* A project file from elsewhere (an old backup, another machine). */
|
|
246
|
+
function importDoc(doc, { name, open: andOpen = false } = {}) {
|
|
247
|
+
if (!doc || typeof doc !== "object" || !Array.isArray(doc.clips) || !Array.isArray(doc.media))
|
|
248
|
+
throw new Error("not a FableCut project (it needs clips and media arrays)");
|
|
249
|
+
const id = add(structuredClone(doc), { name: cleanName(name) || doc.name });
|
|
250
|
+
return andOpen ? open(id) : { id, project: summary(id, activeId()) };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function templates() {
|
|
254
|
+
const out = BUILTIN_TEMPLATES.map((t) => ({ ...t, builtin: true, clips: 0 }));
|
|
255
|
+
let files = [];
|
|
256
|
+
try { files = fs.readdirSync(TEMPLATES).filter((f) => f.toLowerCase().endsWith(".json")).sort(); } catch { }
|
|
257
|
+
for (const f of files) {
|
|
258
|
+
try {
|
|
259
|
+
const t = readJSON(path.join(TEMPLATES, f));
|
|
260
|
+
const p = t.project || {};
|
|
261
|
+
out.push({ id: f.slice(0, -5), name: t.name || f.slice(0, -5), builtin: false, created: t.created || null,
|
|
262
|
+
width: p.width, height: p.height, fps: p.fps, clips: (p.clips || []).length, duration: +timelineEnd(p).toFixed(2) });
|
|
263
|
+
} catch { }
|
|
264
|
+
}
|
|
265
|
+
return out;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/* Save a project — its canvas, tracks, clips and media references — as a template. */
|
|
269
|
+
function saveTemplate(id, { name } = {}) {
|
|
270
|
+
mustExist(id);
|
|
271
|
+
const doc = structuredClone(readDoc(id));
|
|
272
|
+
const label = cleanName(name) || doc.name || "Template";
|
|
273
|
+
const tid = slug(label);
|
|
274
|
+
if (!tid) throw new Error("name the template (letters or digits)");
|
|
275
|
+
if (BUILTIN_TEMPLATES.some((t) => t.id === tid)) throw new Error(`"${label}" is a built-in template — pick another name`);
|
|
276
|
+
delete doc.revision;
|
|
277
|
+
writeJSON(path.join(TEMPLATES, tid + ".json"), { name: label, created: new Date().toISOString(), project: doc });
|
|
278
|
+
return { template: templates().find((t) => t.id === tid) };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function deleteTemplate(tid) {
|
|
282
|
+
if (BUILTIN_TEMPLATES.some((t) => t.id === tid)) throw new Error("built-in templates can't be deleted");
|
|
283
|
+
const file = path.join(TEMPLATES, slug(tid) + ".json");
|
|
284
|
+
if (!slug(tid) || !fs.existsSync(file)) throw new Error(`no saved template ${JSON.stringify(tid)}`);
|
|
285
|
+
fs.unlinkSync(file);
|
|
286
|
+
return { template: tid, deleted: true };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function setThumb(id, buf) {
|
|
290
|
+
mustExist(id);
|
|
291
|
+
if (!Buffer.isBuffer(buf) || buf.length < 4 || buf[0] !== 0xff || buf[1] !== 0xd8) throw new Error("thumbnail must be a JPEG");
|
|
292
|
+
if (buf.length > 1024 * 1024) throw new Error("thumbnail too large (1 MB max)");
|
|
293
|
+
const tmp = `${thumbFile(id)}.${crypto.randomUUID()}.tmp`;
|
|
294
|
+
fs.writeFileSync(tmp, buf);
|
|
295
|
+
fs.renameSync(tmp, thumbFile(id));
|
|
296
|
+
return { id, ok: true };
|
|
297
|
+
}
|
|
298
|
+
const thumbPath = (id) => (exists(id) && fs.existsSync(thumbFile(id)) ? thumbFile(id) : null);
|
|
299
|
+
|
|
300
|
+
/* One entry point for the REST API and the MCP tool. */
|
|
301
|
+
function act(a = {}) {
|
|
302
|
+
switch (a.action) {
|
|
303
|
+
case "list": return { ...list({ archived: a.archived }), templates: templates() };
|
|
304
|
+
case "open": return open(a.id);
|
|
305
|
+
case "new": return create(a);
|
|
306
|
+
case "duplicate": return duplicate(a.id, a);
|
|
307
|
+
case "update": case "rename": return update(a.id, a);
|
|
308
|
+
case "archive": return archive(a.id, true);
|
|
309
|
+
case "unarchive": return archive(a.id, false);
|
|
310
|
+
case "delete": return remove(a.id);
|
|
311
|
+
case "import": return importDoc(a.project, a);
|
|
312
|
+
case "templates": return { templates: templates() };
|
|
313
|
+
case "save_template": return saveTemplate(a.id, a);
|
|
314
|
+
case "delete_template": return deleteTemplate(a.template);
|
|
315
|
+
default:
|
|
316
|
+
throw new Error(`unknown action ${JSON.stringify(a.action)} (list|open|new|duplicate|update|archive|unarchive|delete|import|templates|save_template|delete_template)`);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
return { DIR, INDEX, TEMPLATES, activeId, peekActive, mustExist, readRoot, readDoc, writeDoc, list, open, create, duplicate, update, archive, remove, importDoc,
|
|
321
|
+
templates, saveTemplate, deleteTemplate, setThumb, thumbPath, act };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
module.exports = { createProjects, BUILTIN_TEMPLATES, FPS_CHOICES };
|
package/proxy.js
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/* Proxies: light copies of heavy footage (4K, HEVC, ProRes, long-GOP phone
|
|
2
|
+
video) that the editor plays while you cut. Export always reads the
|
|
3
|
+
original, so a proxy only ever changes how smoothly the preview runs.
|
|
4
|
+
|
|
5
|
+
A proxy is H.264 at 540p / 720p / 1080p (never larger than the source),
|
|
6
|
+
with a short GOP (a keyframe every 12 frames) so scrubbing seeks fast, the
|
|
7
|
+
source's own timestamps (no frames added or dropped) and its first audio
|
|
8
|
+
stream. It lives in analysis/proxies/ — a disposable cache, like the frame
|
|
9
|
+
grabs — named after the source file *and its size and mtime*: when the
|
|
10
|
+
original changes, its old proxy simply stops matching.
|
|
11
|
+
|
|
12
|
+
createProxies({dir, resolveSrc, probe, broadcast, ffmpeg?}) → { (probe: async, media-probe.js)
|
|
13
|
+
status(src) → Promise of {state:"ready", src:"/proxies/…", height, width?, size}
|
|
14
|
+
| {state:"queued"|"running", progress 0…1, height}
|
|
15
|
+
| {state:"failed", error} | {state:"none"} | null (no such file)
|
|
16
|
+
start(src, height?) → Promise of a status (queued, or ready when one exists at that height)
|
|
17
|
+
remove(src) → number of proxy files deleted (a running job is stopped)
|
|
18
|
+
file(name) → the path of a proxy file to serve, or null
|
|
19
|
+
}
|
|
20
|
+
Jobs run one at a time; each broadcasts SSE event "proxy" ({src, status})
|
|
21
|
+
as it starts, every ~0.5 s of progress, and when it ends. */
|
|
22
|
+
"use strict";
|
|
23
|
+
const crypto = require("crypto");
|
|
24
|
+
const fs = require("fs");
|
|
25
|
+
const path = require("path");
|
|
26
|
+
const { spawn } = require("child_process");
|
|
27
|
+
|
|
28
|
+
const HEIGHTS = [540, 720, 1080];
|
|
29
|
+
const DEFAULT_HEIGHT = 540;
|
|
30
|
+
|
|
31
|
+
/** "<stem>-<hash of path, size and mtime>" — every proxy of this version of the file starts with it. */
|
|
32
|
+
function baseName(file) {
|
|
33
|
+
const st = fs.statSync(file);
|
|
34
|
+
const h = crypto.createHash("sha1").update(path.resolve(file) + "|" + st.size + "|" + Math.round(st.mtimeMs)).digest("hex").slice(0, 10);
|
|
35
|
+
const stem = path.basename(file, path.extname(file)).replace(/[^\w\-]+/g, "_").slice(0, 40) || "media";
|
|
36
|
+
return `${stem}-${h}`;
|
|
37
|
+
}
|
|
38
|
+
/** Existing proxies of this version of the file in dir, best (largest) first: [{name, height}]. */
|
|
39
|
+
function findProxies(dir, file) {
|
|
40
|
+
let base;
|
|
41
|
+
try { base = baseName(file) + "-"; } catch { return []; }
|
|
42
|
+
let names = [];
|
|
43
|
+
try { names = fs.readdirSync(dir); } catch { }
|
|
44
|
+
return names.map((n) => { const m = n.startsWith(base) && /-(\d+)p\.mp4$/.exec(n); return m ? { name: n, height: +m[1] } : null; })
|
|
45
|
+
.filter(Boolean).sort((a, b) => b.height - a.height);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function createProxies({ dir, resolveSrc, probe, broadcast = () => { }, ffmpeg = "ffmpeg" }) {
|
|
49
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
50
|
+
const jobs = new Map(); // src → job {src, file, out, height, state, progress, error, proc}
|
|
51
|
+
const queue = [];
|
|
52
|
+
let running = null;
|
|
53
|
+
let fpsModeFlag = ["-fps_mode", "passthrough"]; // ffmpeg ≥ 5.1; older builds get -vsync 0
|
|
54
|
+
const existing = (file) => findProxies(dir, file);
|
|
55
|
+
async function readyStatus(e) {
|
|
56
|
+
const full = path.join(dir, e.name);
|
|
57
|
+
let size = 0; try { size = fs.statSync(full).size; } catch { }
|
|
58
|
+
const info = probe ? await probe(full) : null;
|
|
59
|
+
return { state: "ready", src: "/proxies/" + encodeURIComponent(e.name), height: (info && info.height) || e.height, width: info && info.width, size };
|
|
60
|
+
}
|
|
61
|
+
function jobStatus(j) {
|
|
62
|
+
if (j.state === "failed") return { state: "failed", error: j.error, height: j.height };
|
|
63
|
+
return { state: j.state, progress: Math.round((j.progress || 0) * 1000) / 1000, height: j.height };
|
|
64
|
+
}
|
|
65
|
+
async function status(src) {
|
|
66
|
+
const file = resolveSrc(src);
|
|
67
|
+
if (!file) return null;
|
|
68
|
+
const j = jobs.get(src);
|
|
69
|
+
if (j && j.file === file && (j.state === "queued" || j.state === "running" || j.state === "failed")) return jobStatus(j);
|
|
70
|
+
const e = existing(file)[0];
|
|
71
|
+
return e ? readyStatus(e) : { state: "none" };
|
|
72
|
+
}
|
|
73
|
+
async function tell(j) {
|
|
74
|
+
try { broadcast("proxy", JSON.stringify({ src: j.src, status: j.state === "done" ? await status(j.src) : jobStatus(j) })); } catch { }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function start(src, height = DEFAULT_HEIGHT) {
|
|
78
|
+
const file = resolveSrc(src);
|
|
79
|
+
if (!file) return null;
|
|
80
|
+
height = HEIGHTS.includes(+height) ? +height : DEFAULT_HEIGHT;
|
|
81
|
+
const have = existing(file).find((e) => e.height === height);
|
|
82
|
+
if (have) return readyStatus(have);
|
|
83
|
+
const cur = jobs.get(src);
|
|
84
|
+
if (cur && (cur.state === "queued" || cur.state === "running") && cur.height === height) return jobStatus(cur);
|
|
85
|
+
if (cur && (cur.state === "queued" || cur.state === "running")) cancel(src);
|
|
86
|
+
const j = { src, file, height, out: path.join(dir, `${baseName(file)}-${height}p.mp4`), state: "queued", progress: 0 };
|
|
87
|
+
jobs.set(src, j);
|
|
88
|
+
queue.push(j);
|
|
89
|
+
tell(j);
|
|
90
|
+
pump();
|
|
91
|
+
return jobStatus(j);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function args(j, part, fpsMode) {
|
|
95
|
+
return ["-y", "-hide_banner", "-v", "error", "-nostdin", "-i", j.file,
|
|
96
|
+
"-map", "0:v:0", "-map", "0:a:0?",
|
|
97
|
+
"-vf", `scale=-2:'min(ih,${j.height})':flags=bicubic`,
|
|
98
|
+
...fpsMode,
|
|
99
|
+
"-c:v", "libx264", "-preset", "veryfast", "-crf", "23", "-pix_fmt", "yuv420p",
|
|
100
|
+
"-g", "12", "-keyint_min", "12", "-sc_threshold", "0",
|
|
101
|
+
"-c:a", "aac", "-b:a", "160k",
|
|
102
|
+
"-movflags", "+faststart", "-map_metadata", "-1",
|
|
103
|
+
"-progress", "pipe:1", "-nostats", "-f", "mp4", part];
|
|
104
|
+
}
|
|
105
|
+
async function pump() {
|
|
106
|
+
if (running || !queue.length) return;
|
|
107
|
+
const j = queue.shift();
|
|
108
|
+
if (j.state !== "queued") return pump();
|
|
109
|
+
running = j;
|
|
110
|
+
j.state = "running";
|
|
111
|
+
const info = probe ? await probe(j.file) : null;
|
|
112
|
+
// cancelled (deleted, or asked again at another size) while the probe ran
|
|
113
|
+
if (j.state !== "running") { finish(); return; }
|
|
114
|
+
const dur = (info && info.duration) || 0;
|
|
115
|
+
const part = j.out + ".part";
|
|
116
|
+
let err = "", last = 0;
|
|
117
|
+
const run = (fpsMode, retried) => {
|
|
118
|
+
const proc = j.proc = spawn(ffmpeg, args(j, part, fpsMode), { windowsHide: true });
|
|
119
|
+
proc.stdout.on("data", (d) => {
|
|
120
|
+
const m = /out_time_(?:us|ms)=(\d+)/.exec(String(d).split("\n").reverse().join("\n"));
|
|
121
|
+
if (m && dur > 0) {
|
|
122
|
+
j.progress = Math.min(0.99, +m[1] / 1e6 / dur);
|
|
123
|
+
const now = Date.now();
|
|
124
|
+
if (now - last > 500) { last = now; tell(j); }
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
proc.stderr.on("data", (d) => { err = (err + d).slice(-2000); });
|
|
128
|
+
proc.on("error", (e) => { err = String(e.message || e); });
|
|
129
|
+
proc.on("close", (code) => {
|
|
130
|
+
j.proc = null;
|
|
131
|
+
if (j.state === "cancelled") { try { fs.unlinkSync(part); } catch { } finish(); return; }
|
|
132
|
+
if (code !== 0 && !retried && /fps_mode|Unrecognized option/i.test(err)) {
|
|
133
|
+
fpsModeFlag = ["-vsync", "0"]; err = "";
|
|
134
|
+
return run(fpsModeFlag, true);
|
|
135
|
+
}
|
|
136
|
+
if (code === 0) {
|
|
137
|
+
try { fs.renameSync(part, j.out); j.state = "done"; j.progress = 1; }
|
|
138
|
+
catch (e) { j.state = "failed"; j.error = String(e.message || e); }
|
|
139
|
+
} else {
|
|
140
|
+
try { fs.unlinkSync(part); } catch { }
|
|
141
|
+
j.state = "failed";
|
|
142
|
+
j.error = (err.trim().split("\n").pop() || `ffmpeg exited with ${code}`).slice(0, 300);
|
|
143
|
+
}
|
|
144
|
+
tell(j);
|
|
145
|
+
if (j.state === "done") jobs.delete(j.src);
|
|
146
|
+
finish();
|
|
147
|
+
});
|
|
148
|
+
};
|
|
149
|
+
tell(j);
|
|
150
|
+
run(fpsModeFlag, false);
|
|
151
|
+
}
|
|
152
|
+
function finish() { running = null; pump(); }
|
|
153
|
+
|
|
154
|
+
function cancel(src) {
|
|
155
|
+
const j = jobs.get(src);
|
|
156
|
+
if (!j) return;
|
|
157
|
+
if (j.state === "queued") { j.state = "cancelled"; jobs.delete(src); }
|
|
158
|
+
else if (j.state === "running") { j.state = "cancelled"; try { j.proc && j.proc.kill(); } catch { } jobs.delete(src); }
|
|
159
|
+
else jobs.delete(src);
|
|
160
|
+
}
|
|
161
|
+
function remove(src) {
|
|
162
|
+
cancel(src);
|
|
163
|
+
const file = resolveSrc(src);
|
|
164
|
+
if (!file) return 0;
|
|
165
|
+
let n = 0;
|
|
166
|
+
for (const e of existing(file)) { try { fs.unlinkSync(path.join(dir, e.name)); n++; } catch { } }
|
|
167
|
+
broadcast("proxy", JSON.stringify({ src, status: { state: "none" } }));
|
|
168
|
+
return n;
|
|
169
|
+
}
|
|
170
|
+
/** A proxy file to serve, by its name — only straight names inside dir. */
|
|
171
|
+
function file(name) {
|
|
172
|
+
if (!name || /[\\/]/.test(name) || name.startsWith(".") || !/\.mp4$/i.test(name)) return null;
|
|
173
|
+
const full = path.join(dir, name);
|
|
174
|
+
try { return fs.statSync(full).isFile() ? full : null; } catch { return null; }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
return { status, start, remove, cancel, file, HEIGHTS, DEFAULT_HEIGHT };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
module.exports = { createProxies, findProxies, HEIGHTS, DEFAULT_HEIGHT };
|