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/media-lib.js ADDED
@@ -0,0 +1,298 @@
1
+ /* FableCut media management — the Project bin's metadata, search, filters,
2
+ sorting, tags, collections and usage. Zero dependencies. Loaded by the
3
+ editor as a plain script (global `FableCutMedia`) and required by the
4
+ server, the MCP server and the tests.
5
+
6
+ A media entry may carry, beside id/name/kind/src/duration/width/height:
7
+ size bytes on disk
8
+ fps video frame rate (29.97, 30, 59.94 …)
9
+ codec video codec (h264, hevc, vp9, prores …) — or the image format
10
+ audioCodec aac, mp3, pcm_s16le, opus …
11
+ audioChannels channel count of the first audio stream, 0 = no audio
12
+ sampleRate Hz
13
+ bitrate bits per second (whole file)
14
+ favorite true = starred in the bin
15
+ tags ["interview", "b-roll"]
16
+ Metadata comes from ffprobe (parseProbe) — the server reads it, nobody
17
+ types it. Collections are project-level: project.collections =
18
+ [{id, name, media:[mediaId…]}], a media entry can be in any number of them. */
19
+ (function (root, factory) {
20
+ const node = typeof module === "object" && module.exports;
21
+ const api = factory();
22
+ if (node) module.exports = api;
23
+ else root.FableCutMedia = api;
24
+ })(typeof self !== "undefined" ? self : this, function () {
25
+ "use strict";
26
+
27
+ const KINDS = ["video", "audio", "image", "svg"];
28
+ /** Fields the server probes. Written back to the entry; never user-set. */
29
+ const INFO_KEYS = ["size", "fps", "codec", "audioCodec", "audioChannels", "sampleRate", "bitrate"];
30
+ const MAX_TAGS = 24, MAX_TAG_LEN = 32;
31
+ const SORT_KEYS = ["name", "kind", "duration", "resolution", "fps", "codec", "audio", "size", "usage"];
32
+
33
+ const ratio = (s) => {
34
+ const [a, b] = String(s || "").split("/").map(Number);
35
+ return b > 0 && a > 0 ? a / b : (a > 0 && !b && !String(s).includes("/") ? a : 0);
36
+ };
37
+ const round = (v, n) => Math.round(v * 10 ** n) / 10 ** n;
38
+
39
+ /** ffprobe -show_format -show_streams -of json output → the INFO_KEYS (+ duration,
40
+ * width, height). `size` falls back to the stat size the caller passes. */
41
+ function parseProbe(json, statSize) {
42
+ const out = {};
43
+ const streams = Array.isArray(json && json.streams) ? json.streams : [];
44
+ const fmt = (json && json.format) || {};
45
+ const v = streams.find((s) => s.codec_type === "video" && !(s.disposition && s.disposition.attached_pic));
46
+ const a = streams.find((s) => s.codec_type === "audio");
47
+ const size = Number(fmt.size) || Number(statSize) || 0;
48
+ if (size > 0) out.size = size;
49
+ const dur = Number(fmt.duration);
50
+ if (dur > 0) out.duration = round(dur, 3);
51
+ const br = Number(fmt.bit_rate);
52
+ if (br > 0) out.bitrate = Math.round(br);
53
+ // stills (png/jpg/webp, gif) report 25/1 — not a frame rate anyone shot at
54
+ const still = !!v && /^(png|mjpeg|jpeg|webp|bmp|tiff|gif)$/.test(String(v.codec_name || "")) && !(dur > 0 && Number(v.nb_frames) > 1);
55
+ if (v) {
56
+ if (v.codec_name) out.codec = String(v.codec_name);
57
+ let w = Number(v.width) || 0, h = Number(v.height) || 0;
58
+ const rot = Number(((v.side_data_list || []).find((d) => d.rotation != null) || {}).rotation ?? (v.tags && v.tags.rotate)) || 0;
59
+ if (Math.abs(rot) % 180 === 90) [w, h] = [h, w];
60
+ if (w > 0 && h > 0) { out.width = w; out.height = h; }
61
+ const fps = ratio(v.avg_frame_rate) || ratio(v.r_frame_rate);
62
+ if (!still && fps > 0 && fps < 1000) out.fps = round(fps, 3);
63
+ }
64
+ if (a) {
65
+ if (a.codec_name) out.audioCodec = String(a.codec_name);
66
+ const ch = Number(a.channels);
67
+ if (ch > 0) out.audioChannels = ch;
68
+ const sr = Number(a.sample_rate);
69
+ if (sr > 0) out.sampleRate = sr;
70
+ } else if (v && !still) out.audioChannels = 0; // a video without sound says so; a picture has no audio to speak of
71
+ return out;
72
+ }
73
+
74
+ /* ── formatting ── */
75
+ function fmtSize(b) {
76
+ if (!(b > 0)) return "";
77
+ const u = ["B", "KB", "MB", "GB", "TB"];
78
+ let i = 0, n = b;
79
+ while (n >= 1000 && i < u.length - 1) { n /= 1000; i++; }
80
+ return (i === 0 ? n : n < 10 ? n.toFixed(1) : Math.round(n)) + " " + u[i];
81
+ }
82
+ function fmtFps(f) {
83
+ if (!(f > 0)) return "";
84
+ return String(round(f, 2));
85
+ }
86
+ function fmtRes(m) { return m && m.width > 0 && m.height > 0 ? `${m.width}×${m.height}` : ""; }
87
+ function fmtAudio(m) {
88
+ if (!m || m.audioChannels == null) return "";
89
+ if (m.audioChannels === 0) return "no audio";
90
+ const ch = m.audioChannels === 1 ? "mono" : m.audioChannels === 2 ? "stereo" : m.audioChannels === 6 ? "5.1" : m.audioChannels === 8 ? "7.1" : m.audioChannels + " ch";
91
+ return ch + (m.sampleRate ? ` ${round(m.sampleRate / 1000, 1)} kHz` : "");
92
+ }
93
+ function fmtDur(t) {
94
+ if (!(t > 0)) return "";
95
+ const h = Math.floor(t / 3600), m = Math.floor((t % 3600) / 60), s = t % 60;
96
+ const ss = s.toFixed(2).padStart(5, "0");
97
+ return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`;
98
+ }
99
+ /** One-line summary: "1920×1080 · 29.97 fps · h264 · stereo 48 kHz · 45 MB". */
100
+ function describe(m) {
101
+ return [fmtRes(m), m.fps ? fmtFps(m.fps) + " fps" : "", m.codec || "", fmtAudio(m), fmtSize(m.size)]
102
+ .filter(Boolean).join(" · ");
103
+ }
104
+
105
+ /* ── tags and collections ── */
106
+ function normalizeTags(v) {
107
+ const list = Array.isArray(v) ? v : typeof v === "string" ? v.split(",") : [];
108
+ const out = [], seen = new Set();
109
+ for (const t of list) {
110
+ const s = String(t == null ? "" : t).replace(/^#+/, "").replace(/\s+/g, " ").trim().slice(0, MAX_TAG_LEN);
111
+ if (!s || seen.has(s.toLowerCase())) continue;
112
+ seen.add(s.toLowerCase());
113
+ out.push(s);
114
+ if (out.length >= MAX_TAGS) break;
115
+ }
116
+ return out;
117
+ }
118
+ /** Every tag used in the project, sorted, each once (first spelling wins). */
119
+ function allTags(media) {
120
+ const seen = new Map();
121
+ for (const m of media || []) for (const t of m.tags || []) if (!seen.has(t.toLowerCase())) seen.set(t.toLowerCase(), t);
122
+ return [...seen.values()].sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
123
+ }
124
+ function normalizeCollections(list, media) {
125
+ if (!Array.isArray(list)) return [];
126
+ const ids = media ? new Set(media.map((m) => m.id)) : null;
127
+ const out = [], seen = new Set();
128
+ for (const c of list) {
129
+ if (!c || !c.id || seen.has(String(c.id))) continue;
130
+ seen.add(String(c.id));
131
+ const mem = [...new Set((Array.isArray(c.media) ? c.media : []).map(String))].filter((id) => !ids || ids.has(id));
132
+ out.push({ id: String(c.id), name: String(c.name || "Collection").trim().slice(0, 80) || "Collection", media: mem });
133
+ }
134
+ return out;
135
+ }
136
+
137
+ /* ── usage ── */
138
+ /** Where a media entry is placed: one entry per placement (a video and its
139
+ * linked audio stems count once), on the main timeline (comp: null) and
140
+ * inside every composition. Sorted main timeline first, then by time. */
141
+ function placements(doc, mediaId) {
142
+ const out = [];
143
+ const scan = (clips, comp, seq) => {
144
+ const groups = new Map();
145
+ for (const c of clips || []) {
146
+ if (c.mediaId !== mediaId) continue;
147
+ const key = c.linkGroup ? "g:" + c.linkGroup : "c:" + c.id;
148
+ const prev = groups.get(key);
149
+ // the picture represents a placement; its stems fold into it
150
+ if (!prev || (prev.kind !== "video" && c.kind === "video")) groups.set(key, c);
151
+ }
152
+ for (const c of groups.values())
153
+ out.push({ clipId: c.id, comp: comp ? comp.id : null, compName: comp ? comp.name : null, track: c.track, start: +c.start || 0, duration: +c.duration || 0, kind: c.kind,
154
+ ...(seq ? { sequence: seq.id, sequenceName: seq.name || seq.id } : {}) });
155
+ };
156
+ scan(doc && doc.clips, null);
157
+ for (const comp of (doc && doc.comps) || []) scan(comp.clips, comp);
158
+ for (const seq of otherSequences(doc)) scan(seq.clips, null, seq);
159
+ const rank = (p) => (p.sequence ? 2 : p.comp ? 1 : 0);
160
+ return out.sort((a, b) => rank(a) - rank(b) || String(a.sequence || "").localeCompare(String(b.sequence || "")) ||
161
+ String(a.comp || "").localeCompare(String(b.comp || "")) || a.start - b.start);
162
+ }
163
+ /** The sequences that aren't open (see sequences.js): their clips use media too. */
164
+ function otherSequences(doc) {
165
+ const list = doc && Array.isArray(doc.sequences) ? doc.sequences : [];
166
+ const act = list.some((x) => x.id === doc.sequence) ? doc.sequence : list[0] && list[0].id;
167
+ return list.filter((x) => x && x.id !== act && Array.isArray(x.clips));
168
+ }
169
+ /** mediaId → number of placements (see placements()). */
170
+ function usageCounts(doc) {
171
+ const n = new Map();
172
+ for (const m of (doc && doc.media) || []) n.set(m.id, 0);
173
+ const scan = (clips) => {
174
+ const seen = new Set();
175
+ for (const c of clips || []) {
176
+ if (!c.mediaId) continue;
177
+ // per file: a denoised stem shares its video's linkGroup but plays another file
178
+ const key = (c.linkGroup ? "g:" + c.linkGroup : "c:" + c.id) + "|" + c.mediaId;
179
+ if (seen.has(key)) continue;
180
+ seen.add(key);
181
+ n.set(c.mediaId, (n.get(c.mediaId) || 0) + 1);
182
+ }
183
+ };
184
+ scan(doc && doc.clips);
185
+ for (const comp of (doc && doc.comps) || []) scan(comp.clips);
186
+ for (const seq of otherSequences(doc)) scan(seq.clips);
187
+ return n;
188
+ }
189
+
190
+ /* ── search, filter, sort ── */
191
+ const ext = (m) => (/\.([a-z0-9]+)$/i.exec(String(m.name || m.src || "")) || [])[1] || "";
192
+ /** Search text: every word must match the name, kind, extension, codecs,
193
+ * resolution or a tag; "#word" matches tags only. */
194
+ function matchesQuery(m, q) {
195
+ const words = String(q || "").toLowerCase().split(/\s+/).filter(Boolean);
196
+ if (!words.length) return true;
197
+ const tags = (m.tags || []).map((t) => t.toLowerCase());
198
+ const hay = [m.name, m.kind, ext(m), m.codec, m.audioCodec, fmtRes(m).replace("×", "x"), m.height ? m.height + "p" : ""]
199
+ .filter(Boolean).join(" ").toLowerCase();
200
+ return words.every((w) => w.startsWith("#")
201
+ ? tags.some((t) => t.includes(w.slice(1)))
202
+ : hay.includes(w) || tags.some((t) => t.includes(w)));
203
+ }
204
+ /** filter: "" | "fav" | "used" | "unused" | "kind:<kind>" | "tag:<tag>" | "col:<collectionId>". */
205
+ function matchesFilter(m, filter, ctx) {
206
+ const f = String(filter || "");
207
+ if (!f || f === "all") return true;
208
+ const uses = ctx && ctx.usage ? ctx.usage.get(m.id) || 0 : 0;
209
+ if (f === "fav") return m.favorite === true;
210
+ if (f === "used") return uses > 0;
211
+ if (f === "unused") return uses === 0;
212
+ if (f.startsWith("kind:")) return m.kind === f.slice(5);
213
+ if (f.startsWith("tag:")) { const t = f.slice(4).toLowerCase(); return (m.tags || []).some((x) => x.toLowerCase() === t); }
214
+ if (f.startsWith("col:")) {
215
+ const c = ((ctx && ctx.collections) || []).find((x) => x.id === f.slice(4));
216
+ return !!c && c.media.includes(m.id);
217
+ }
218
+ if (ctx && typeof ctx.extraFilter === "function") return ctx.extraFilter(m, f);
219
+ return true;
220
+ }
221
+ /** Sort value for a key; null sorts last whatever the direction. */
222
+ function sortValue(m, key, ctx) {
223
+ switch (key) {
224
+ case "kind": return KINDS.indexOf(m.kind);
225
+ case "duration": return m.duration > 0 ? m.duration : null;
226
+ case "resolution": return m.width > 0 && m.height > 0 ? m.width * m.height : null;
227
+ case "fps": return m.fps > 0 ? m.fps : null;
228
+ case "codec": return m.codec || null;
229
+ case "audio": return m.audioChannels != null ? m.audioChannels : null;
230
+ case "size": return m.size > 0 ? m.size : null;
231
+ case "usage": return ctx && ctx.usage ? ctx.usage.get(m.id) || 0 : 0;
232
+ default: return null;
233
+ }
234
+ }
235
+ function sortMedia(list, key, dir, ctx) {
236
+ const sign = dir === "desc" ? -1 : 1;
237
+ const byName = (a, b) => String(a.name).localeCompare(String(b.name), undefined, { sensitivity: "base", numeric: true });
238
+ return list.slice().sort((a, b) => {
239
+ if (!key || key === "name") return sign * byName(a, b);
240
+ const va = sortValue(a, key, ctx), vb = sortValue(b, key, ctx);
241
+ if (va == null || vb == null) return va == null && vb == null ? byName(a, b) : va == null ? 1 : -1;
242
+ const d = typeof va === "string" ? va.localeCompare(vb) : va - vb;
243
+ return d ? sign * d : byName(a, b);
244
+ });
245
+ }
246
+ /** search + filter + sort in one go. Favorites float to the top when asked. */
247
+ function query(media, opts, ctx) {
248
+ const o = opts || {};
249
+ const hit = (media || []).filter((m) => matchesQuery(m, o.q) && matchesFilter(m, o.filter, ctx));
250
+ return sortMedia(hit, o.sort || "name", o.dir || "asc", ctx);
251
+ }
252
+
253
+ const KIND_BY_EXT = {
254
+ mp4: "video", webm: "video", mov: "video", mkv: "video", m4v: "video", avi: "video",
255
+ mp3: "audio", wav: "audio", ogg: "audio", m4a: "audio", aac: "audio", flac: "audio", opus: "audio",
256
+ png: "image", jpg: "image", jpeg: "image", gif: "image", webp: "image", svg: "svg",
257
+ };
258
+ /** video | audio | image | svg from a file name or src, or null. */
259
+ function kindFromName(n) {
260
+ const ext = (/\.([a-z0-9]+)$/i.exec(String(n || "").split("?")[0]) || [])[1];
261
+ return (ext && KIND_BY_EXT[ext.toLowerCase()]) || null;
262
+ }
263
+
264
+ /* ── relink ── */
265
+ const stem = (n) => String(n || "").replace(/\.[a-z0-9]{1,5}$/i, "").toLowerCase();
266
+ /** Name of a /media/… or /library/… src, decoded. */
267
+ function srcName(src) {
268
+ const s = String(src || "").split("?")[0].split("/").pop() || "";
269
+ try { return decodeURIComponent(s); } catch { return s; }
270
+ }
271
+ /** How likely `file` ({name, size}) is the missing media `m` ({name, src, size}).
272
+ * → {score, why}; 0 = not a candidate. Same file name beats same name with
273
+ * another extension beats a name containing the other; a matching size adds.
274
+ * With m.kind, files of another kind never qualify. */
275
+ function relinkScore(m, file) {
276
+ // only files that can stand in for this kind (an audio entry may sit in a video container)
277
+ const fk = kindFromName(file.name);
278
+ if (m.kind && fk && fk !== m.kind && !(m.kind === "audio" && fk === "video")) return { score: 0, why: "" };
279
+ const names = [m.name, srcName(m.src)].filter(Boolean).map((n) => n.toLowerCase());
280
+ const fn = String(file.name || "").toLowerCase(), fs = stem(fn);
281
+ let score = 0, why = "";
282
+ if (names.includes(fn)) { score = 100; why = "same name"; }
283
+ else if (names.some((n) => stem(n) === fs && fs)) { score = 60; why = "same name, other type"; }
284
+ else if (names.some((n) => { const a = stem(n); return a.length >= 3 && fs.length >= 3 && (fs.includes(a) || a.includes(fs)); })) { score = 30; why = "similar name"; }
285
+ const sameSize = m.size > 0 && file.size > 0 && m.size === file.size;
286
+ if (sameSize) { score += score ? 50 : 40; why = why ? why + " and size" : "same size"; }
287
+ return { score, why };
288
+ }
289
+
290
+ return {
291
+ KINDS, INFO_KEYS, SORT_KEYS, MAX_TAGS,
292
+ srcName, relinkScore, kindFromName,
293
+ parseProbe, fmtSize, fmtFps, fmtRes, fmtAudio, fmtDur, describe,
294
+ normalizeTags, allTags, normalizeCollections,
295
+ placements, usageCounts,
296
+ matchesQuery, matchesFilter, sortValue, sortMedia, query,
297
+ };
298
+ });
package/media-probe.js ADDED
@@ -0,0 +1,88 @@
1
+ /* Read a media file's metadata with ffprobe (Node only — the server and the
2
+ MCP server). The parsing is media-lib.js's parseProbe, shared with the
3
+ tests; this file only runs ffprobe and caches the answer per file version.
4
+
5
+ probeFile(file) → Promise of {size, fps?, codec?, audioCodec?, audioChannels?,
6
+ sampleRate?, bitrate?, duration?, width?, height?, probe:"ffprobe"|"stat"}
7
+ or null when the file is not there.
8
+ Without ffprobe on PATH only `size` comes back (probe:"stat"). ffprobe runs
9
+ asynchronously, at most PROBE_CONCURRENCY at a time, so a project full of
10
+ unprobed files never stalls the server's other requests. */
11
+ "use strict";
12
+ const fs = require("fs");
13
+ const { execFile, spawnSync } = require("child_process");
14
+ const MediaLib = require("./media-lib");
15
+
16
+ const PROBE_CONCURRENCY = 4;
17
+
18
+ let hasProbe = null;
19
+ function ffprobeAvailable() {
20
+ if (hasProbe == null) {
21
+ try { hasProbe = spawnSync("ffprobe", ["-version"], { stdio: "ignore" }).status === 0; } catch { hasProbe = false; }
22
+ }
23
+ return hasProbe;
24
+ }
25
+
26
+ const cache = new Map(); // file → {key, info}
27
+ const inflight = new Map(); // file + key → Promise
28
+ const CACHE_MAX = 2000;
29
+ let active = 0;
30
+ const waiting = [];
31
+ function slot() {
32
+ if (active < PROBE_CONCURRENCY) { active++; return Promise.resolve(); }
33
+ return new Promise((r) => waiting.push(r));
34
+ }
35
+ function release() {
36
+ const next = waiting.shift();
37
+ if (next) next(); else active--;
38
+ }
39
+ function runProbe(file) {
40
+ return new Promise((resolve) => {
41
+ execFile("ffprobe", ["-v", "error", "-show_format", "-show_streams", "-of", "json", file],
42
+ { encoding: "utf8", timeout: 15_000, maxBuffer: 1 << 23, windowsHide: true },
43
+ (err, stdout) => {
44
+ if (err || !stdout) return resolve(null);
45
+ try { resolve(JSON.parse(stdout)); } catch { resolve(null); }
46
+ });
47
+ });
48
+ }
49
+
50
+ async function probeFile(file) {
51
+ let st;
52
+ try { st = await fs.promises.stat(file); } catch { return null; }
53
+ if (!st.isFile()) return null;
54
+ const key = st.size + ":" + st.mtimeMs;
55
+ const hit = cache.get(file);
56
+ if (hit && hit.key === key) return { ...hit.info };
57
+ const id = file + "\0" + key;
58
+ if (!inflight.has(id)) {
59
+ inflight.set(id, (async () => {
60
+ let info = { size: st.size, probe: "stat" };
61
+ if (ffprobeAvailable()) {
62
+ await slot();
63
+ try {
64
+ const json = await runProbe(file);
65
+ if (json) info = { ...MediaLib.parseProbe(json, st.size), probe: "ffprobe" };
66
+ } finally { release(); }
67
+ }
68
+ if (cache.size >= CACHE_MAX) cache.delete(cache.keys().next().value);
69
+ cache.set(file, { key, info });
70
+ return info;
71
+ })().finally(() => inflight.delete(id)));
72
+ }
73
+ return { ...(await inflight.get(id)) };
74
+ }
75
+
76
+ /** The INFO_KEYS of probeFile's answer, ready to merge into a media entry
77
+ * (duration / width / height only when the entry lacks them). */
78
+ function infoForEntry(info, entry) {
79
+ const out = {};
80
+ if (!info) return out;
81
+ for (const k of MediaLib.INFO_KEYS) if (info[k] != null) out[k] = info[k];
82
+ const kind = entry && entry.kind;
83
+ if (kind !== "image" && kind !== "svg" && info.duration > 0 && !(entry && entry.duration > 0)) out.duration = info.duration;
84
+ if (info.width > 0 && !(entry && entry.width > 0)) { out.width = info.width; out.height = info.height; }
85
+ return out;
86
+ }
87
+
88
+ module.exports = { probeFile, infoForEntry, ffprobeAvailable, PROBE_CONCURRENCY };
package/mp4-demux.js ADDED
@@ -0,0 +1,256 @@
1
+ /* FableCut MP4 demuxer — the sample table of an MP4 / MOV video track, so the
2
+ exporter can feed WebCodecs' VideoDecoder frame by frame instead of seeking a
3
+ <video> element and waiting for it to present each frame. Zero dependencies.
4
+ Loaded by the editor as a plain script (global `FableCutMp4`) and required by
5
+ the tests.
6
+
7
+ Only what decoding needs is read: the first video track's codec string and
8
+ decoder config (avcC / hvcC / vpcC / av1C), and per sample its byte range,
9
+ whether it is a sync sample, and its presentation time in seconds after the
10
+ track's edit list, which is the clock a <video> element shows. Fragmented
11
+ MP4 (moof) is not supported: findMoov / parseMovie return null and the
12
+ caller keeps the <video> path. */
13
+ (function (root, factory) {
14
+ const api = factory();
15
+ if (typeof module === "object" && module.exports) module.exports = api;
16
+ else root.FableCutMp4 = api;
17
+ })(typeof self !== "undefined" ? self : this, function () {
18
+ "use strict";
19
+
20
+ const CONTAINERS = new Set(["moov", "trak", "mdia", "minf", "stbl", "edts", "dinf"]);
21
+ const VIDEO_ENTRIES = new Set(["avc1", "avc3", "hvc1", "hev1", "vp09", "av01"]);
22
+
23
+ const u32 = (b, o) => ((b[o] << 24) | (b[o + 1] << 16) | (b[o + 2] << 8) | b[o + 3]) >>> 0;
24
+ const i32 = (b, o) => (b[o] << 24) | (b[o + 1] << 16) | (b[o + 2] << 8) | b[o + 3];
25
+ const u64 = (b, o) => u32(b, o) * 4294967296 + u32(b, o + 4);
26
+ const i64 = (b, o) => i32(b, o) * 4294967296 + u32(b, o + 4);
27
+ const fourcc = (b, o) => String.fromCharCode(b[o], b[o + 1], b[o + 2], b[o + 3]);
28
+ const hex2 = (n) => n.toString(16).padStart(2, "0").toUpperCase();
29
+
30
+ /** The boxes directly inside b[start, end): [{ type, start, body, end }]. */
31
+ function boxes(b, start = 0, end = b.length) {
32
+ const out = [];
33
+ let o = start;
34
+ while (o + 8 <= end) {
35
+ let size = u32(b, o), body = o + 8;
36
+ const type = fourcc(b, o + 4);
37
+ if (size === 1) { if (o + 16 > end) break; size = u64(b, o + 8); body = o + 16; }
38
+ else if (size === 0) size = end - o;
39
+ if (size < body - o || o + size > end) break;
40
+ out.push({ type, start: o, body, end: o + size });
41
+ o += size;
42
+ }
43
+ return out;
44
+ }
45
+ const child = (b, box, type) => boxes(b, box.body, box.end).find((x) => x.type === type) || null;
46
+ function path(b, box, ...types) {
47
+ let cur = box;
48
+ for (const t of types) { cur = cur && child(b, cur, t); if (!cur) return null; }
49
+ return cur;
50
+ }
51
+
52
+ /** Walk the top-level boxes through `read(start, end) → Promise<Uint8Array>`
53
+ * (an HTTP Range fetch) and return the moov box's bytes, or null (no moov,
54
+ * or a fragmented file). Faststart files answer from the first read. */
55
+ async function findMoov(read, fileSize) {
56
+ let o = 0, head = null, headAt = -1;
57
+ while (o + 8 <= fileSize) {
58
+ if (!head || o < headAt || o + 16 > headAt + head.length) {
59
+ headAt = o; head = await read(o, Math.min(fileSize, o + 65536));
60
+ }
61
+ const r = o - headAt;
62
+ let size = u32(head, r), hdr = 8;
63
+ const type = fourcc(head, r + 4);
64
+ if (size === 1) { size = u64(head, r + 8); hdr = 16; }
65
+ else if (size === 0) size = fileSize - o;
66
+ if (size < hdr) return null;
67
+ if (type === "moof") return null;
68
+ if (type === "moov") {
69
+ const have = head.length - r;
70
+ return have >= size ? head.subarray(r, r + size) : await read(o, o + size);
71
+ }
72
+ o += size;
73
+ }
74
+ return null;
75
+ }
76
+
77
+ /** Codec string for VideoDecoder.configure from the sample entry's config box. */
78
+ function codecString(entry, b, cfg) {
79
+ const d = b.subarray(cfg.body, cfg.end);
80
+ if (entry === "avc1" || entry === "avc3")
81
+ return `${entry}.${hex2(d[1])}${hex2(d[2])}${hex2(d[3])}`;
82
+ if (entry === "hvc1" || entry === "hev1") { // ISO/IEC 14496-15 Annex E
83
+ const space = ["", "A", "B", "C"][d[1] >> 6], tier = (d[1] >> 5) & 1 ? "H" : "L", idc = d[1] & 31;
84
+ let compat = u32(d, 2), rev = 0;
85
+ for (let i = 0; i < 32; i++) { rev = (rev << 1) | (compat & 1); compat >>>= 1; }
86
+ const cons = [];
87
+ for (let i = 6; i < 12; i++) cons.push(d[i]);
88
+ while (cons.length && cons[cons.length - 1] === 0) cons.pop();
89
+ return [entry, space + idc, (rev >>> 0).toString(16).toUpperCase(), tier + d[12], ...cons.map((x) => x.toString(16).toUpperCase())].join(".");
90
+ }
91
+ if (entry === "vp09") { // vpcC is a full box: version + flags first
92
+ const p = d.subarray(4);
93
+ const two = (n) => String(n).padStart(2, "0");
94
+ return `vp09.${two(p[0])}.${two(p[1])}.${two(p[2] >> 4)}`;
95
+ }
96
+ if (entry === "av01") {
97
+ const profile = d[1] >> 5, level = d[1] & 31, tier = d[2] >> 7 ? "H" : "M";
98
+ const bits = (d[2] >> 6) & 1 ? ((d[2] >> 5) & 1 ? 12 : 10) : 8;
99
+ return `av01.${profile}.${String(level).padStart(2, "0")}${tier}.${String(bits).padStart(2, "0")}`;
100
+ }
101
+ return null;
102
+ }
103
+
104
+ /** The first video track of a moov box: { codec, description, width, height,
105
+ * displayWidth, displayHeight (pasp applied), timescale, samples: [{ offset, size, key, pts, dur }] in decode order }.
106
+ * pts and dur are seconds on the presentation clock (edit list applied). */
107
+ function parseMovie(moov) {
108
+ const b = moov, root = { body: 0, end: b.length, type: "root" };
109
+ const moovBox = child(b, root, "moov") || (fourcc(b, 4) === "moov" ? boxes(b)[0] : null);
110
+ if (!moovBox) return null;
111
+ if (child(b, moovBox, "mvex")) return null; // fragmented: samples live in moof boxes
112
+ const mvhd = child(b, moovBox, "mvhd");
113
+ const movieScale = mvhd ? (b[mvhd.body] === 1 ? u32(b, mvhd.body + 20) : u32(b, mvhd.body + 12)) : 1000;
114
+ for (const trak of boxes(b, moovBox.body, moovBox.end).filter((x) => x.type === "trak")) {
115
+ const hdlr = path(b, trak, "mdia", "hdlr");
116
+ if (!hdlr || fourcc(b, hdlr.body + 8) !== "vide") continue;
117
+ const mdhd = path(b, trak, "mdia", "mdhd"), stbl = path(b, trak, "mdia", "minf", "stbl");
118
+ if (!mdhd || !stbl) continue;
119
+ // A rotated or mirrored track (phone footage) is turned by the player, not
120
+ // by the decoder: leave those to the <video> element.
121
+ const tkhd = child(b, trak, "tkhd");
122
+ if (tkhd) {
123
+ const m = tkhd.body + (b[tkhd.body] === 1 ? 52 : 40);
124
+ if (u32(b, m) !== 0x10000 || u32(b, m + 4) !== 0 || u32(b, m + 12) !== 0 || u32(b, m + 16) !== 0x10000) return null;
125
+ }
126
+ const v1 = b[mdhd.body] === 1;
127
+ const timescale = v1 ? u32(b, mdhd.body + 20) : u32(b, mdhd.body + 12);
128
+ const stsd = child(b, stbl, "stsd");
129
+ if (!stsd || !timescale) continue;
130
+ const entryBox = boxes(b, stsd.body + 8, stsd.end)[0];
131
+ if (!entryBox || !VIDEO_ENTRIES.has(entryBox.type)) continue;
132
+ const entry = entryBox.type;
133
+ const width = (b[entryBox.body + 24] << 8) | b[entryBox.body + 25];
134
+ const height = (b[entryBox.body + 26] << 8) | b[entryBox.body + 27];
135
+ const cfgType = { avc1: "avcC", avc3: "avcC", hvc1: "hvcC", hev1: "hvcC", vp09: "vpcC", av01: "av1C" }[entry];
136
+ const cfg = boxes(b, entryBox.body + 78, entryBox.end).find((x) => x.type === cfgType);
137
+ if (!cfg) continue;
138
+ const codec = codecString(entry, b, cfg);
139
+ if (!codec) continue;
140
+ // vpcC carries no decoder description; the others hand the box body over as is
141
+ const description = entry === "vp09" ? undefined : b.slice(cfg.body, cfg.end);
142
+ const samples = sampleTable(b, stbl, timescale);
143
+ if (!samples) continue;
144
+ applyEdits(b, trak, samples, timescale, movieScale);
145
+ // pasp: non-square pixels (anamorphic). Display width = coded width × h / v.
146
+ const pasp = boxes(b, entryBox.body + 78, entryBox.end).find((x) => x.type === "pasp");
147
+ const hs = pasp ? u32(b, pasp.body) : 0, vs = pasp ? u32(b, pasp.body + 4) : 0;
148
+ const displayWidth = hs && vs && hs !== vs ? Math.round(width * hs / vs) : width;
149
+ return { codec, description, width, height, displayWidth, displayHeight: height, timescale, samples };
150
+ }
151
+ return null;
152
+ }
153
+
154
+ function sampleTable(b, stbl, timescale) {
155
+ const box = (t) => child(b, stbl, t);
156
+ const stsz = box("stsz"), stz2 = box("stz2"), stsc = box("stsc"), stts = box("stts");
157
+ const stco = box("stco"), co64 = box("co64"), stss = box("stss"), ctts = box("ctts");
158
+ if (!(stsz || stz2) || !stsc || !stts || !(stco || co64)) return null;
159
+ // sizes
160
+ const sizes = [];
161
+ if (stsz) {
162
+ const fixed = u32(b, stsz.body + 4), n = u32(b, stsz.body + 8);
163
+ for (let i = 0; i < n; i++) sizes.push(fixed || u32(b, stsz.body + 12 + i * 4));
164
+ } else {
165
+ const field = b[stz2.body + 7], n = u32(b, stz2.body + 8), o = stz2.body + 12;
166
+ for (let i = 0; i < n; i++) {
167
+ if (field === 4) sizes.push(i & 1 ? b[o + (i >> 1)] & 15 : b[o + (i >> 1)] >> 4);
168
+ else if (field === 8) sizes.push(b[o + i]);
169
+ else sizes.push((b[o + i * 2] << 8) | b[o + i * 2 + 1]);
170
+ }
171
+ }
172
+ const n = sizes.length;
173
+ // chunk offsets → sample offsets via sample-to-chunk
174
+ const chunks = [];
175
+ if (stco) { const c = u32(b, stco.body + 4); for (let i = 0; i < c; i++) chunks.push(u32(b, stco.body + 8 + i * 4)); }
176
+ else { const c = u32(b, co64.body + 4); for (let i = 0; i < c; i++) chunks.push(u64(b, co64.body + 8 + i * 8)); }
177
+ const runs = [];
178
+ for (let i = 0, c = u32(b, stsc.body + 4); i < c; i++)
179
+ runs.push({ first: u32(b, stsc.body + 8 + i * 12) - 1, per: u32(b, stsc.body + 12 + i * 12) });
180
+ const offsets = new Array(n);
181
+ let s = 0;
182
+ for (let r = 0; r < runs.length && s < n; r++) {
183
+ const last = r + 1 < runs.length ? runs[r + 1].first : chunks.length;
184
+ for (let ch = runs[r].first; ch < last && s < n; ch++) {
185
+ let o = chunks[ch];
186
+ for (let k = 0; k < runs[r].per && s < n; k++) { offsets[s] = o; o += sizes[s]; s++; }
187
+ }
188
+ }
189
+ if (s < n) return null;
190
+ // decode times, composition offsets, sync samples
191
+ const dts = new Array(n), durs = new Array(n);
192
+ let t = 0, i = 0;
193
+ for (let e = 0, c = u32(b, stts.body + 4); e < c; e++) {
194
+ const count = u32(b, stts.body + 8 + e * 8), delta = u32(b, stts.body + 12 + e * 8);
195
+ for (let k = 0; k < count && i < n; k++, i++) { dts[i] = t; durs[i] = delta; t += delta; }
196
+ }
197
+ for (; i < n; i++) { dts[i] = t; durs[i] = 0; }
198
+ const cto = new Array(n).fill(0);
199
+ if (ctts) {
200
+ let j = 0;
201
+ for (let e = 0, c = u32(b, ctts.body + 4); e < c; e++) {
202
+ const count = u32(b, ctts.body + 8 + e * 8);
203
+ const off = i32(b, ctts.body + 12 + e * 8);
204
+ for (let k = 0; k < count && j < n; k++, j++) cto[j] = off;
205
+ }
206
+ }
207
+ const key = new Array(n).fill(!stss);
208
+ if (stss) for (let e = 0, c = u32(b, stss.body + 4); e < c; e++) {
209
+ const k = u32(b, stss.body + 8 + e * 4) - 1;
210
+ if (k >= 0 && k < n) key[k] = true;
211
+ }
212
+ const out = new Array(n);
213
+ for (let k = 0; k < n; k++)
214
+ out[k] = { offset: offsets[k], size: sizes[k], key: key[k], cts: dts[k] + cto[k], pts: (dts[k] + cto[k]) / timescale, dur: durs[k] / timescale };
215
+ return out;
216
+ }
217
+
218
+ /** Move pts onto the presentation clock, as a <video> element does: the first
219
+ * non-empty edit's media_time is presentation 0, after any leading empty
220
+ * edits (dwell, in movie-timescale units). */
221
+ function applyEdits(b, trak, samples, timescale, movieScale) {
222
+ const elst = path(b, trak, "edts", "elst");
223
+ if (!elst) return;
224
+ const v1 = b[elst.body] === 1, count = u32(b, elst.body + 4), size = v1 ? 20 : 12;
225
+ let empty = 0, mediaTime = null;
226
+ for (let e = 0; e < count; e++) {
227
+ const o = elst.body + 8 + e * size;
228
+ const dur = v1 ? u64(b, o) : u32(b, o), mt = v1 ? i64(b, o + 8) : i32(b, o + 4);
229
+ if (mt === -1) { empty += dur; continue; }
230
+ mediaTime = mt; break;
231
+ }
232
+ const shift = (empty / movieScale) - (mediaTime || 0) / timescale;
233
+ if (!shift) return;
234
+ for (const s of samples) s.pts = s.cts / timescale + shift;
235
+ }
236
+
237
+ /** Index (decode order) of the frame a player shows at presentation time t:
238
+ * the latest pts ≤ t (+ a microsecond for float noise); the first frame
239
+ * before the track starts. `order` is the decode indices sorted by pts. */
240
+ function frameAt(samples, order, t) {
241
+ let lo = 0, hi = order.length - 1, best = 0;
242
+ while (lo <= hi) {
243
+ const mid = (lo + hi) >> 1;
244
+ if (samples[order[mid]].pts <= t + 1e-6) { best = mid; lo = mid + 1; } else hi = mid - 1;
245
+ }
246
+ return order[best];
247
+ }
248
+ const presentationOrder = (samples) => samples.map((_, i) => i).sort((a, b) => samples[a].pts - samples[b].pts);
249
+ /** The sync sample at or before decode index k (where decoding must start). */
250
+ function syncBefore(samples, k) {
251
+ for (let i = k; i >= 0; i--) if (samples[i].key) return i;
252
+ return 0;
253
+ }
254
+
255
+ return { boxes, findMoov, parseMovie, codecString, frameAt, presentationOrder, syncBefore };
256
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fablecut",
3
- "version": "1.14.0",
3
+ "version": "1.16.0",
4
4
  "description": "Zero-dependency browser video editor that AI agents can drive — JSON timeline, MCP server, REST API, live-reloading UI.",
5
5
  "main": "server.js",
6
6
  "bin": {