fablecut 1.15.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/mcp-server.js CHANGED
@@ -28,12 +28,15 @@ const FX = require("./audio-fx");
28
28
  const EditOps = require("./edit-ops");
29
29
  const ProjectOps = require("./project-ops");
30
30
  const Denoise = require("./denoise");
31
+ const { createProjects } = require("./projects");
32
+ const { createHistory } = require("./history");
31
33
  const Color = require("./color");
32
34
  const FrameStats = require("./frame-stats");
33
35
  const Mask = require("./mask");
34
36
  const Tracker = require("./tracker");
35
37
  const Motion = require("./motion");
36
38
  const CompLib = require("./comp");
39
+ const SeqLib = require("./sequences");
37
40
  const Templates = require("./templates");
38
41
  const Delivery = require("./delivery");
39
42
  const { probeFile, infoForEntry } = require("./media-probe");
@@ -157,7 +160,7 @@ const TOOLS = [
157
160
  },
158
161
  {
159
162
  name: "fablecut_patch_project",
160
- description: "Apply targeted edits to the FableCut project WITHOUT round-tripping the whole document — PREFER THIS over get+set for every edit (it is ~10-100x cheaper in tokens and merge-safe by design: it re-reads the latest document from disk, applies your ops in order, bumps revision once, saves atomically). Ops: {op:'addClip', clip:{…}} (id auto-generated if omitted) · {op:'updateClip', id, set:{…}} · {op:'removeClip', id} · {op:'addMedia', media:{…}} · {op:'removeMedia', id} · MEDIA BIN: {op:'updateMedia', id | ids, set:{name?, favorite?:true|false, tags?:[…], folderId?}, addTags?:[…], removeTags?:[…]} (organize media; fps, codec, audio channels and size are probed from the file and read-only) · {op:'setCollection', id?, name?, media?:[…ids] (replaces), add?:[…], remove?:[…]} (a collection groups media across folders; a new id or name creates it) · {op:'removeCollection', id} · {op:'relinkMedia', id, src:'/media/…'} (the same footage found elsewhere — an OFFLINE file in the compact view; clips keep their In points) · {op:'replaceMedia', id, src, name?} (a different file behind the media — every clip using it switches, keeping its timing, trimmed to fit a shorter file; import the new file first with fablecut_import_media) · {op:'setProject', set:{name|width|height|fps|background|markers|disabledTracks|lockedTracks|untargetedTracks|encodeProfile|delivery|outputs|master}} (markers = the full list [{t, label?, color?}], color: gold|red|orange|green|cyan|blue|purple|pink; master = {gain}, the master fader in dB; delivery = a delivery preset id or spec — see fablecut_export — that exports use by default; outputs = the batch list, [preset id | spec, …] up to 16, exported together by fablecut_export {outputs:true}) · {op:'setTrack', id:'A1', set:{gain?, pan?, out?}} (audio-track fader in dB −60…+12, pan −1…1, out = a submix bus id or 'master'; null or 0 resets) · {op:'setBus', id:'B1', set:{name?, gain?, pan?, mute?}} (submix bus, created if missing; route tracks into it with setTrack out) · {op:'removeBus', id} · {op:'setFx', target:'clip'|'track'|'bus'|'master', id?, preset?:'podcast'|… OR fx:[{type,…params}], append?:true} (audio effects — validated; presets: clean-voice, podcast, radio, deep-voice, telephone, cinematic, wide, muffled; fx:null clears; on a clip it applies to its linked stems too) · {op:'setFxKeys', target, id?, index?|type?, param, keys:[{t, v, ease?}]|null} (automate one effect parameter: t is clip-local for a clip's effects, timeline seconds otherwise; see the 'Audio mix' docs section) · {op:'setGrade', id | ids:[…], grade:{exposure?, temp?, tint?, lift?, gamma?, gain?, offset?, contrast?, pivot?, blacks?, shadows?, midtones?, highlights?, whites?, lowSoft?, highSoft?, saturation?, curves?:{y?, r?, g?, b?}, hueHue?, hueSat?, hueLuma?, satLuma?, layers?:[…], on?}, replace?:true} (color grade on video / image / svg / adjust clips — wheels are [r, g, b, master]; curves are [[x, y], …] point lists on 0…1 and merge per channel; hue curves are [[hue°, value], …] — one point = a ±40° band; layers replaces the whole layer list; merges key by key, null resets a key, replace:true starts from neutral, grade:null clears; see the 'Color' docs section; measure the result with fablecut_scopes) · {op:'setGradeLayer', id | ids, layer: index | 'name', set:{name?, on?, qualifier?:{hue?:[centre°, width°, soft°], sat?:[lo, hi, soft], luma?:[lo, hi, soft], invert?}, mask?:{shape:'ellipse'|'rect'|'poly', x, y, w, h, rotation?, feather?, invert?, points?, keys?:[{t, x?, y?, …}]}, …any grade key}, replace?:true, remove?:true} (a secondary: a grade applied only where the qualifier × mask select; a new name or index = length adds a layer; qualifier and mask merge key by key; check what it selects with fablecut_scopes matte:{clip, layer}) · {op:'setMask', id | ids, mask?: index | 'name', set:{shape?:'rect'|'ellipse'|'bezier'|'freehand', mode?:'add'|'subtract'|'intersect'|'difference', invert?, opacity?, feather? (px), expand? (px, − shrinks), x?, y? (centre, 0…1 of the clip's picture), w?, h?, scale?, rotation?, points?:[[dx, dy, inX?, inY?, outX?, outY?], …] (bezier, around x, y), stroke?:[[u, v], …] (freehand: fitted into a bezier), keys?:[{t, ease?, x?, y?, w?, h?, scale?, rotation?, feather?, expand?, opacity?, points?}], name?, on?}, replace?:true, remove?:true} (clip masks on video / image / svg / text / adjust clips: the clip shows only where its masks combine to, bottom-up; mask left out, an unknown name or index = length adds one — a new mask needs shape; set merges key by key; masks follow the clip's transform; check with fablecut_scopes mask:{clip}) · {op:'removeMask', id, mask} · {op:'setMaskKeys', id, mask, keys:[…]|null} (animate a mask; t = seconds from the clip's start) · {op:'setMatte', id | ids, matte:'alpha'|'alpha-inverted'|'luma'|'luma-inverted'|null, track?:'V3'|null} (track matte: the picture on the video track directly above — or track — cuts the clip by its alpha or its brightness, inverted or not; that track stops drawing while it is a matte; null clears). · {op:'removeTrack', id, track: name | index} (delete a motion track stored by fablecut_track; what follows it keeps its keys). MOTION GRAPHICS: a shape layer is addClip {kind:'shape', track, start, duration, props:{shapes:[…]}} (no mediaId); a null is addClip {kind:'null', …} — invisible, a parent for other clips. {op:'setShape', id | ids, shape?: index | 'name' | '2.0' (path into a group), set:{type?:'rect'|'ellipse'|'polygon'|'star'|'line'|'path'|'group', name?, on?, x?, y? (px from the layer's origin), rotation?, scale?, opacity?, w?, h?, radius? (rect corners), sides?, inner? (star 0.05…1), points?:[[x, y, inX?, inY?, outX?, outY?], …] (line: 2, path: 2…128, px around x, y), closed? (path), fill?, stroke? ('#rrggbb' | '#rrggbbaa' | 'none'), strokeWidth?, lineCap?, lineJoin?, dash?:[on, off…], trimStart?, trimEnd? (0…100 — a draw-on), trimOffset?, items?:[…] (group), keys?:[{t, ease?, …any of x y rotation scale opacity w h radius inner strokeWidth trimStart trimEnd trimOffset fill stroke points}]}, replace?:true, remove?:true} (shape left out, an unknown name or index = length adds one — a new shape needs type; set merges key by key) · {op:'removeShape', id, shape} · {op:'setParent', id | ids, parent: clip id | null, keep?: true, at?} (the clip moves, turns and scales with its parent; keep:true — the default — keeps it where it is at time at, default its start; opacity and effects are not inherited). COMPOSITIONS (nested sequences): project.comps = [{id, name, width, height, duration, background?, tracks?, clips:[…]}]; a clip {kind:'comp', compId, start, in, duration} places one (draws like a picture of the comp's size — transform, masks, grade, blend, blur all apply — and its media plays and exports). {op:'addComp', comp:{id?, name, duration, width?, height?, background?, clips?:[…]}} · {op:'updateComp', id, set:{name?, width?, height?, duration?, background?, tracks?}} · {op:'removeComp', id} (refused while used) · {op:'precompose', ids:[…], name?, id?} (the clips move into a new comp; a comp clip takes their place) · {op:'inComp', comp, ops:[…]} (run clip and timeline ops on the comp's own clips — addClip, updateClip, setShape, split, …; nests). PRESETS AND TEMPLATES: {op:'applyPreset', id | ids, preset, length?, at?} keys a named animation onto visual clips, relative to where they sit (in: fade-in, pop-in, slide-up-in, slide-down-in, slide-left-in, slide-right-in, drop-in, zoom-in, spin-in, whip-in, rise-blur, draw-on · out: fade-out, pop-out, slide-up-out, slide-down-out, slide-left-out, slide-right-out, zoom-out, spin-out, whip-out, sink-blur, draw-off · at (an emphasis at timeline time at): pulse, shake, wobble, bounce, flash · loop (the whole clip): float, breathe, sway, spin, wiggle — or a saved one, or an inline {anchor:'in'|'out'|'at'|'whole', length, keys:{channel:[{t, v, ease?}]}} where scale / opacity multiply and the rest add). {op:'addTemplate', template, start?, track?, duration?, fields?:{key: value}, id?, compId?, name?} places a template as its own comp + a comp clip (lower-third-bar, lower-third-underline, lower-third-boxes [name, title, accent…] · logo-ring, logo-slam, logo-lines [logo = a media id, brand / tagline, accent] · social-story 1080x1920, social-quote 1080x1080, social-end-card [text fields, accent, background]); {op:'setTemplate', id: its clip or comp, fields?, duration?} changes the fields or the length (the exit keeps its timing). {op:'savePreset', id, name, anchor?} / {op:'saveTemplate', comp, name?, fields?} save to library/presets and library/templates for every project.MOTION PATHS: x and y keyed at the same time are a position key; curve handles pin / pout (px) on those x and y keys bend the path between keys ({op:'setMotionPath', id | ids, path:'smooth'|'straight', autoOrient?:bool} sets them for you; props.autoOrient turns the clip along its path). props.motionBlur = shutter angle 0…720 (180 = film look), props.motionBlurSamples 2…32. TEXT ON A PATH: {op:'setTextPath', id | ids, path:'line'|'arc'|'circle'|'wave'|{type:'path'|'line'|'ellipse'|'rect'|'polygon'|'star', …shape item geometry, keys?}|null, offset? (% along, keyable as pathOffset), align?:'start'|'center'|'end'} — the title runs along the path (more lines on parallel curves below it), every textAnim plays along it. Every visual clip also has props.anchorX / anchorY (px from its picture's centre: the point x / y place and rotation / scale turn around) and shape clips props.trimStart / trimEnd / trimOffset (trim every path in the layer) — all keyframable. props.blend: normal · multiply · screen · overlay · darken · lighten · color-dodge · color-burn · hard-light · soft-light · difference · exclusion · hue · saturation · color · luminosity · lighter. TIMELINE EDITS — the editor's own split / ripple / trim code, so linked stems, track targeting (untargetedTracks) and locks behave exactly as in the UI; times in seconds: {op:'split', at, ids?} (no ids: every targeted track) · {op:'rippleDelete', ids} (later clips close the hole) · {op:'closeGap', at} · {op:'lift'|'extract', from?, to?} (remove a range; extract closes it; default = project inPoint/outPoint, which then clear) · {op:'insert'|'overwrite', mediaId, at, in?, duration?} (three-point edit: insert pushes later clips right, overwrite replaces what is there; a video brings one audio stem per channel) · {op:'rippleTrim'|'roll', id, side:'in'|'out', delta} · {op:'slip'|'slide', id, delta} (clamped to the media; the note says what was applied) · {op:'crossfade', ids? | at, duration?} (constant-power audio crossfade, borrowing handles from both sides). Any of these takes tracks:[…] to target lanes for that op only. setProject also takes inPoint / outPoint. updateClip merge rules: top-level keys are replaced (keyframes/transitionIn/transitionOut wholesale), `props` merges key-by-key, and setting any key to null deletes it. LOCKS: the user can lock clips (`locked:true`) and tracks (`lockedTracks`); updateClip / removeClip on a locked clip — or on a clip linked to one — and addClip onto a locked track are refused. Leave locked material alone; only if the user asked you to change it, pass force:true on that op (or unlock first: updateClip set:{locked:null}, which is always allowed). All-or-nothing: an invalid op aborts the whole patch unsaved. Optional baseRevision: the revision your ops were planned against (from fablecut_get_project, fablecut_status or the previous patch result) — if the project has moved past it (e.g. the user edited in the UI meanwhile), the patch is refused with CONFLICT and the current revision, nothing saved; re-check the clips you touch, then retry with the new revision. Omit it to apply on top of whatever is latest.",
163
+ description: "Apply targeted edits to the FableCut project WITHOUT round-tripping the whole document — PREFER THIS over get+set for every edit (it is ~10-100x cheaper in tokens and merge-safe by design: it re-reads the latest document from disk, applies your ops in order, bumps revision once, saves atomically). Ops: {op:'addClip', clip:{…}} (id auto-generated if omitted) · {op:'updateClip', id, set:{…}} · {op:'removeClip', id} · {op:'addMedia', media:{…}} · {op:'removeMedia', id} · MEDIA BIN: {op:'updateMedia', id | ids, set:{name?, favorite?:true|false, tags?:[…], folderId?}, addTags?:[…], removeTags?:[…]} (organize media; fps, codec, audio channels and size are probed from the file and read-only) · {op:'setCollection', id?, name?, media?:[…ids] (replaces), add?:[…], remove?:[…]} (a collection groups media across folders; a new id or name creates it) · {op:'removeCollection', id} · {op:'relinkMedia', id, src:'/media/…'} (the same footage found elsewhere — an OFFLINE file in the compact view; clips keep their In points) · {op:'replaceMedia', id, src, name?} (a different file behind the media — every clip using it switches, keeping its timing, trimmed to fit a shorter file; import the new file first with fablecut_import_media) · {op:'setProject', set:{name|width|height|fps|background|markers|disabledTracks|lockedTracks|untargetedTracks|encodeProfile|delivery|outputs|master}} (markers = the full list [{t, label?, color?}], color: gold|red|orange|green|cyan|blue|purple|pink; master = {gain}, the master fader in dB; delivery = a delivery preset id or spec — see fablecut_export — that exports use by default; outputs = the batch list, [preset id | spec, …] up to 16, exported together by fablecut_export {outputs:true}) · {op:'setTrack', id:'A1', set:{gain?, pan?, out?}} (audio-track fader in dB −60…+12, pan −1…1, out = a submix bus id or 'master'; null or 0 resets) · {op:'setBus', id:'B1', set:{name?, gain?, pan?, mute?}} (submix bus, created if missing; route tracks into it with setTrack out) · {op:'removeBus', id} · {op:'setFx', target:'clip'|'track'|'bus'|'master', id?, preset?:'podcast'|… OR fx:[{type,…params}], append?:true} (audio effects — validated; presets: clean-voice, podcast, radio, deep-voice, telephone, cinematic, wide, muffled; fx:null clears; on a clip it applies to its linked stems too) · {op:'setFxKeys', target, id?, index?|type?, param, keys:[{t, v, ease?}]|null} (automate one effect parameter: t is clip-local for a clip's effects, timeline seconds otherwise; see the 'Audio mix' docs section) · {op:'setGrade', id | ids:[…], grade:{exposure?, temp?, tint?, lift?, gamma?, gain?, offset?, contrast?, pivot?, blacks?, shadows?, midtones?, highlights?, whites?, lowSoft?, highSoft?, saturation?, curves?:{y?, r?, g?, b?}, hueHue?, hueSat?, hueLuma?, satLuma?, layers?:[…], on?}, replace?:true} (color grade on video / image / svg / adjust clips — wheels are [r, g, b, master]; curves are [[x, y], …] point lists on 0…1 and merge per channel; hue curves are [[hue°, value], …] — one point = a ±40° band; layers replaces the whole layer list; merges key by key, null resets a key, replace:true starts from neutral, grade:null clears; see the 'Color' docs section; measure the result with fablecut_scopes) · {op:'setGradeLayer', id | ids, layer: index | 'name', set:{name?, on?, qualifier?:{hue?:[centre°, width°, soft°], sat?:[lo, hi, soft], luma?:[lo, hi, soft], invert?}, mask?:{shape:'ellipse'|'rect'|'poly', x, y, w, h, rotation?, feather?, invert?, points?, keys?:[{t, x?, y?, …}]}, …any grade key}, replace?:true, remove?:true} (a secondary: a grade applied only where the qualifier × mask select; a new name or index = length adds a layer; qualifier and mask merge key by key; check what it selects with fablecut_scopes matte:{clip, layer}) · {op:'setMask', id | ids, mask?: index | 'name', set:{shape?:'rect'|'ellipse'|'bezier'|'freehand', mode?:'add'|'subtract'|'intersect'|'difference', invert?, opacity?, feather? (px), expand? (px, − shrinks), x?, y? (centre, 0…1 of the clip's picture), w?, h?, scale?, rotation?, points?:[[dx, dy, inX?, inY?, outX?, outY?], …] (bezier, around x, y), stroke?:[[u, v], …] (freehand: fitted into a bezier), keys?:[{t, ease?, x?, y?, w?, h?, scale?, rotation?, feather?, expand?, opacity?, points?}], name?, on?}, replace?:true, remove?:true} (clip masks on video / image / svg / text / adjust clips: the clip shows only where its masks combine to, bottom-up; mask left out, an unknown name or index = length adds one — a new mask needs shape; set merges key by key; masks follow the clip's transform; check with fablecut_scopes mask:{clip}) · {op:'removeMask', id, mask} · {op:'setMaskKeys', id, mask, keys:[…]|null} (animate a mask; t = seconds from the clip's start) · {op:'setMatte', id | ids, matte:'alpha'|'alpha-inverted'|'luma'|'luma-inverted'|null, track?:'V3'|null} (track matte: the picture on the video track directly above — or track — cuts the clip by its alpha or its brightness, inverted or not; that track stops drawing while it is a matte; null clears). · {op:'removeTrack', id, track: name | index} (delete a motion track stored by fablecut_track; what follows it keeps its keys). MOTION GRAPHICS: a shape layer is addClip {kind:'shape', track, start, duration, props:{shapes:[…]}} (no mediaId); a null is addClip {kind:'null', …} — invisible, a parent for other clips. {op:'setShape', id | ids, shape?: index | 'name' | '2.0' (path into a group), set:{type?:'rect'|'ellipse'|'polygon'|'star'|'line'|'path'|'group', name?, on?, x?, y? (px from the layer's origin), rotation?, scale?, opacity?, w?, h?, radius? (rect corners), sides?, inner? (star 0.05…1), points?:[[x, y, inX?, inY?, outX?, outY?], …] (line: 2, path: 2…128, px around x, y), closed? (path), fill?, stroke? ('#rrggbb' | '#rrggbbaa' | 'none'), strokeWidth?, lineCap?, lineJoin?, dash?:[on, off…], trimStart?, trimEnd? (0…100 — a draw-on), trimOffset?, items?:[…] (group), keys?:[{t, ease?, …any of x y rotation scale opacity w h radius inner strokeWidth trimStart trimEnd trimOffset fill stroke points}]}, replace?:true, remove?:true} (shape left out, an unknown name or index = length adds one — a new shape needs type; set merges key by key) · {op:'removeShape', id, shape} · {op:'setParent', id | ids, parent: clip id | null, keep?: true, at?} (the clip moves, turns and scales with its parent; keep:true — the default — keeps it where it is at time at, default its start; opacity and effects are not inherited). COMPOSITIONS (nested sequences): project.comps = [{id, name, width, height, duration, background?, tracks?, clips:[…]}]; a clip {kind:'comp', compId, start, in, duration} places one (draws like a picture of the comp's size — transform, masks, grade, blend, blur all apply — and its media plays and exports). {op:'addComp', comp:{id?, name, duration, width?, height?, background?, clips?:[…]}} · {op:'updateComp', id, set:{name?, width?, height?, duration?, background?, tracks?}} · {op:'removeComp', id} (refused while used) · {op:'precompose', ids:[…], name?, id?} (the clips move into a new comp; a comp clip takes their place) · {op:'inComp', comp, ops:[…]} (run clip and timeline ops on the comp's own clips — addClip, updateClip, setShape, split, …; nests). SEQUENCES (several timelines in one project — e.g. a 16:9 cut and a 9:16 cut sharing the media and comps; the open one is the top level of the document, which every op, export and the compact view use): {op:'addSequence', name?, from?:'empty'|'open'|<sequence id> (empty takes the open one's canvas and frame rate; a copy takes its whole timeline), width?, height?, fps?, open?:true} · {op:'openSequence', id} (changes what the user's editor shows — only when asked, or to work on it) · {op:'updateSequence', id, set:{name?, index?}} · {op:'removeSequence', id} (only when the user asked) · {op:'inSequence', sequence, ops:[…]} (run any clip, timeline, track or setProject op on a sequence without opening it). PRESETS AND TEMPLATES: {op:'applyPreset', id | ids, preset, length?, at?} keys a named animation onto visual clips, relative to where they sit (in: fade-in, pop-in, slide-up-in, slide-down-in, slide-left-in, slide-right-in, drop-in, zoom-in, spin-in, whip-in, rise-blur, draw-on · out: fade-out, pop-out, slide-up-out, slide-down-out, slide-left-out, slide-right-out, zoom-out, spin-out, whip-out, sink-blur, draw-off · at (an emphasis at timeline time at): pulse, shake, wobble, bounce, flash · loop (the whole clip): float, breathe, sway, spin, wiggle — or a saved one, or an inline {anchor:'in'|'out'|'at'|'whole', length, keys:{channel:[{t, v, ease?}]}} where scale / opacity multiply and the rest add). {op:'addTemplate', template, start?, track?, duration?, fields?:{key: value}, id?, compId?, name?} places a template as its own comp + a comp clip (lower-third-bar, lower-third-underline, lower-third-boxes [name, title, accent…] · logo-ring, logo-slam, logo-lines [logo = a media id, brand / tagline, accent] · social-story 1080x1920, social-quote 1080x1080, social-end-card [text fields, accent, background]); {op:'setTemplate', id: its clip or comp, fields?, duration?} changes the fields or the length (the exit keeps its timing). {op:'savePreset', id, name, anchor?} / {op:'saveTemplate', comp, name?, fields?} save to library/presets and library/templates for every project.MOTION PATHS: x and y keyed at the same time are a position key; curve handles pin / pout (px) on those x and y keys bend the path between keys ({op:'setMotionPath', id | ids, path:'smooth'|'straight', autoOrient?:bool} sets them for you; props.autoOrient turns the clip along its path). props.motionBlur = shutter angle 0…720 (180 = film look), props.motionBlurSamples 2…32. TEXT ON A PATH: {op:'setTextPath', id | ids, path:'line'|'arc'|'circle'|'wave'|{type:'path'|'line'|'ellipse'|'rect'|'polygon'|'star', …shape item geometry, keys?}|null, offset? (% along, keyable as pathOffset), align?:'start'|'center'|'end'} — the title runs along the path (more lines on parallel curves below it), every textAnim plays along it. Every visual clip also has props.anchorX / anchorY (px from its picture's centre: the point x / y place and rotation / scale turn around) and shape clips props.trimStart / trimEnd / trimOffset (trim every path in the layer) — all keyframable. props.blend: normal · multiply · screen · overlay · darken · lighten · color-dodge · color-burn · hard-light · soft-light · difference · exclusion · hue · saturation · color · luminosity · lighter. TIMELINE EDITS — the editor's own split / ripple / trim code, so linked stems, track targeting (untargetedTracks) and locks behave exactly as in the UI; times in seconds: {op:'split', at, ids?} (no ids: every targeted track) · {op:'rippleDelete', ids} (later clips close the hole) · {op:'closeGap', at} · {op:'lift'|'extract', from?, to?} (remove a range; extract closes it; default = project inPoint/outPoint, which then clear) · {op:'insert'|'overwrite', mediaId, at, in?, duration?} (three-point edit: insert pushes later clips right, overwrite replaces what is there; a video brings one audio stem per channel) · {op:'rippleTrim'|'roll', id, side:'in'|'out', delta} · {op:'slip'|'slide', id, delta} (clamped to the media; the note says what was applied) · {op:'crossfade', ids? | at, duration?} (constant-power audio crossfade, borrowing handles from both sides). Any of these takes tracks:[…] to target lanes for that op only. setProject also takes inPoint / outPoint. updateClip merge rules: top-level keys are replaced (keyframes/transitionIn/transitionOut wholesale), `props` merges key-by-key, and setting any key to null deletes it. LOCKS: the user can lock clips (`locked:true`) and tracks (`lockedTracks`); updateClip / removeClip on a locked clip — or on a clip linked to one — and addClip onto a locked track are refused. Leave locked material alone; only if the user asked you to change it, pass force:true on that op (or unlock first: updateClip set:{locked:null}, which is always allowed). All-or-nothing: an invalid op aborts the whole patch unsaved. Optional baseRevision: the revision your ops were planned against (from fablecut_get_project, fablecut_status or the previous patch result) — if the project has moved past it (e.g. the user edited in the UI meanwhile), the patch is refused with CONFLICT and the current revision, nothing saved; re-check the clips you touch, then retry with the new revision. Omit it to apply on top of whatever is latest.",
161
164
  inputSchema: {
162
165
  type: "object",
163
166
  properties: {
@@ -284,6 +287,42 @@ const TOOLS = [
284
287
  required: ["clipIds"],
285
288
  },
286
289
  },
290
+ {
291
+ name: "fablecut_projects",
292
+ description: "Several projects in one FableCut: the projects dashboard. ./project.json (what every other tool reads and edits) is always the OPEN project; the others are stored beside it and share media/, exports/ and the library, so a duplicate or a template copies no footage. Actions: list (default; archived:'only'|'all' to see archived ones) · open {id} — switches the editor to that project (the open one is saved first; editor tabs reload; your next fablecut_get_project reads the new one) · new {name, template?, fps?, width?, height?, notes?, tags?, open?:true} — template is a built-in canvas (landscape-1080 default, vertical-1080, square-1080, portrait-1350, uhd-4k, landscape-720) or a saved template id · duplicate {id, name?, open?:false} · update {id, name?, notes?, tags?} · archive / unarchive {id} · delete {id} (archived projects only) · templates · save_template {id, name} (the project's canvas, tracks, clips and media references) · delete_template {template}. Opening another project changes what the user sees — only open, archive or delete when the user asked for it.",
293
+ inputSchema: {
294
+ type: "object",
295
+ properties: {
296
+ action: { type: "string", enum: ["list", "open", "new", "duplicate", "update", "archive", "unarchive", "delete", "templates", "save_template", "delete_template"], description: "What to do (default list)" },
297
+ id: { type: "string", description: "The project (p_…), from list" },
298
+ name: { type: "string", description: "new / duplicate / update: the project's name · save_template: the template's name" },
299
+ template: { type: "string", description: "new: the template to start from · delete_template: the saved template's id" },
300
+ fps: { type: "number", description: "new: frame rate (default: the template's)" },
301
+ width: { type: "integer", description: "new: canvas width (default: the template's)" },
302
+ height: { type: "integer", description: "new: canvas height (default: the template's)" },
303
+ notes: { type: "string", description: "new / update: free-text notes (brief, client, deadline …)" },
304
+ tags: { type: "array", items: { type: "string" }, description: "new / update: labels (replaces the list)" },
305
+ open: { type: "boolean", description: "new (default true) / duplicate (default false): open it afterwards" },
306
+ archived: { type: "string", enum: ["exclude", "only", "all"], description: "list: archived projects too, or only them" },
307
+ },
308
+ },
309
+ },
310
+ {
311
+ name: "fablecut_versions",
312
+ description: "A project's version history: saved copies you can go back to, never destructive. Actions: list (default) · save {name?, note?, final?} — keep the project as it is now (do this before big or risky edits, and when the user is happy with a cut) · diff {version, to?} — what changed from that version to now (or to another version): clips added / removed / changed, length, media, settings · restore {version} — put that version back; the current state is saved as a version first, so a restore can itself be undone · update {version, name?, note?, final?} — rename, annotate, or mark the one final cut · delete {version}. project defaults to the open one (fablecut_projects lists ids). Versions are also made on their own: every 10 minutes while the project changes, and before an agent's first edit of a session or a fablecut_set_project rewrite. Restoring changes what the user sees: only when they asked.",
313
+ inputSchema: {
314
+ type: "object",
315
+ properties: {
316
+ action: { type: "string", enum: ["list", "save", "diff", "restore", "update", "delete"], description: "What to do (default list)" },
317
+ project: { type: "string", description: "The project (p_…); default the open one" },
318
+ version: { description: "The version: its number (3) or \"v3\"", anyOf: [{ type: "integer" }, { type: "string" }] },
319
+ to: { description: "diff: compare to this version instead of the current project", anyOf: [{ type: "integer" }, { type: "string" }] },
320
+ name: { type: "string", description: "save / update: the version's name (default \"Version NN\")" },
321
+ note: { type: "string", description: "save / update: what this version is (\"client cut, shorter intro\")" },
322
+ final: { type: "boolean", description: "save / update: mark it the final cut (one per project)" },
323
+ },
324
+ },
325
+ },
287
326
  {
288
327
  name: "fablecut_proxy",
289
328
  description: "Proxies: light H.264 copies (540p by default, 720p or 1080p; never larger than the source) of heavy footage — 4K, HEVC, ProRes, long phone clips — that the editor plays while the user edits, so playback and scrubbing stay smooth. Export, fablecut_frame, fablecut_scopes and every measurement always read the original, so a proxy never changes the result. Without create or delete it reports each video's proxy (ready, being made with its progress, failed, none). create:true makes them (one at a time, in the background on the server) and waits until they are done unless wait:false; delete:true removes them. mediaIds defaults to every video in the project. The user turns proxy playback on or off with the monitor's Proxy button. Needs ffmpeg on PATH.",
@@ -567,6 +606,85 @@ function describeExportJob(j) {
567
606
  `Check again with fablecut_export {job:"${j.id}"}, or stop it with {cancel:"${j.id}"}.`;
568
607
  }
569
608
  /* fablecut_proxy: the server makes proxies (proxy.js); this asks it, and waits. */
609
+ /* fablecut_projects: through the editor server, so it is the only process that
610
+ switches ./project.json and its tabs hear about it at once. */
611
+ function describeProject(p) {
612
+ const dur = p.duration == null ? "?" : `${Math.floor(p.duration / 60)}:${String(Math.round(p.duration % 60)).padStart(2, "0")}`;
613
+ return `${p.id} "${p.name}"${p.active ? " (OPEN)" : ""}${p.archived ? " [archived]" : ""} — ` +
614
+ (p.unreadable ? "project file unreadable" : `${p.width}x${p.height}@${p.fps} ${dur}, ${p.clips} clip(s), ${p.media} media`) +
615
+ (p.modified ? `, modified ${p.modified.slice(0, 16).replace("T", " ")}` : "") +
616
+ (p.tags?.length ? " " + p.tags.map((t) => "#" + t).join(" ") : "") +
617
+ (p.notes ? `\n notes: ${p.notes.length > 300 ? p.notes.slice(0, 300) + "…" : p.notes}` : "");
618
+ }
619
+ const describeTemplate = (t) => `${t.id} "${t.name}" ${t.width}x${t.height}@${t.fps}${t.builtin ? " (built-in)" : ` — ${t.clips} clip(s)`}`;
620
+ async function projectsTool(args) {
621
+ if (!(await ensureUIServer())) throw new Error(`the editor server is not running and could not be started on port ${PORT}`);
622
+ const action = args.action || "list";
623
+ if (action === "list") {
624
+ const r = await apiJSON("GET", "/api/projects?archived=" + encodeURIComponent(args.archived || "exclude"));
625
+ if (r.status !== 200) throw new Error(r.body?.error || `projects request failed (${r.status})`);
626
+ const { projects, templates } = r.body;
627
+ return [`${projects.length} project(s):`, ...projects.map(describeProject),
628
+ `Templates (action:"new", template): ${templates.map((t) => t.id).join(", ")}`].join("\n");
629
+ }
630
+ const r = await apiJSON("POST", "/api/projects", { ...args, action });
631
+ if (r.status !== 200) throw new Error(r.body?.error || `projects request failed (${r.status})`);
632
+ const out = r.body;
633
+ if (action === "templates") return out.templates.map(describeTemplate).join("\n");
634
+ if (action === "save_template") return `Saved template ${describeTemplate(out.template)}. Start a project from it: {action:"new", template:"${out.template.id}", name}.`;
635
+ if (action === "delete_template") return `Deleted template ${out.template}.`;
636
+ if (action === "delete") return `Deleted project ${out.id} (its media stay in media/).`;
637
+ if (out.already) return `${describeProject(out.project)}\nAlready open.`;
638
+ if (out.from) return `Opened ${describeProject(out.project)}\nThe editor switched to it (${out.from} was saved first). Read it with fablecut_get_project {compact:true} before editing.`;
639
+ return describeProject(out.project);
640
+ }
641
+ /* fablecut_versions: through the editor server, like fablecut_projects. */
642
+ const KIND_LABEL = { manual: "", auto: " (auto)", agent: " (before agent edits)", restore: " (before a restore)" };
643
+ function describeVersion(e) {
644
+ const when = e.created ? e.created.slice(0, 16).replace("T", " ") : "?";
645
+ return `v${e.v}${e.final ? " FINAL" : ""} "${e.name}"${KIND_LABEL[e.kind] || ""} — ${when}, ${e.clips} clip(s), ` +
646
+ `${Math.floor(Math.round(e.duration) / 60)}:${String(Math.round(e.duration) % 60).padStart(2, "0")}, revision ${e.revision}` +
647
+ (e.note ? `\n note: ${e.note.length > 300 ? e.note.slice(0, 300) + "…" : e.note}` : "");
648
+ }
649
+ async function versionsTool(args) {
650
+ if (!(await ensureUIServer())) throw new Error(`the editor server is not running and could not be started on port ${PORT}`);
651
+ const action = args.action || "list";
652
+ const r = action === "list"
653
+ ? await apiJSON("GET", "/api/versions" + (args.project ? "?project=" + encodeURIComponent(args.project) : ""))
654
+ : await apiJSON("POST", "/api/versions", { ...args, action });
655
+ if (r.status !== 200) throw new Error(r.body?.error || `versions request failed (${r.status})`);
656
+ const out = r.body;
657
+ if (action === "list") return out.versions.length
658
+ ? [`${out.versions.length} version(s) of ${out.project}, newest first:`, ...out.versions.map(describeVersion)].join("\n")
659
+ : `No versions of ${out.project} yet. {action:"save", name, note} keeps one.`;
660
+ if (action === "save") return `Saved ${describeVersion(out.version)}`;
661
+ if (action === "update") return describeVersion(out.version);
662
+ if (action === "delete") return `Deleted v${out.deleted}.`;
663
+ if (action === "restore") return `Restored v${out.restored.v} "${out.restored.name}". What was there is kept as v${out.saved.v} "${out.saved.name}" (restore it to undo). ` +
664
+ (out.open === false
665
+ ? `${out.project} is not the open project, so the editor didn't change; open it (fablecut_projects {action:"open", id:"${out.project}"}) before reading or editing it.`
666
+ : `The editor reloaded; re-read the project (fablecut_get_project {compact:true}) before editing.`);
667
+ if (action === "diff") return out.same
668
+ ? `No difference between ${out.from === "current" ? "now" : "v" + String(out.from).replace(/^v/, "")} and ${out.to === "current" ? "now" : "v" + String(out.to).replace(/^v/, "")}.`
669
+ : [`From v${String(out.from).replace(/^v/, "")} to ${out.to === "current" ? "now" : "v" + String(out.to).replace(/^v/, "")}:`, ...out.lines.map((l) => "- " + l)].join("\n");
670
+ return JSON.stringify(out);
671
+ }
672
+ /* Before an agent changes the project: a version to go back to. Once per session start
673
+ (or after 10 quiet minutes), and before every whole-document rewrite. */
674
+ let lastAgentVersion = 0;
675
+ /** "" when the version was kept (or wasn't due), else a warning for the tool's answer:
676
+ * a version is a safety net, so the edit itself goes ahead either way. */
677
+ function versionBeforeAgent(rewrite) {
678
+ if (!rewrite && Date.now() - lastAgentVersion < 10 * 60_000) return "";
679
+ try {
680
+ const pj = createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR });
681
+ createHistory({ projects: pj }).beforeAgent(rewrite ? "Before an agent rewrote the project" : "Before agent edits");
682
+ lastAgentVersion = Date.now();
683
+ return "";
684
+ } catch (e) {
685
+ return ` Warning: no version was saved before this edit (${e.message}) — fablecut_versions {action:"save"} keeps one.`;
686
+ }
687
+ }
570
688
  async function proxyTool(args) {
571
689
  if (!(await ensureUIServer())) throw new Error(`the editor server is not running and could not be started on port ${PORT}`);
572
690
  const proj = readProject();
@@ -845,6 +963,10 @@ async function callTool(name, args, attempt = 0) {
845
963
  return denoiseTool(args);
846
964
  case "fablecut_proxy":
847
965
  return proxyTool(args);
966
+ case "fablecut_projects":
967
+ return projectsTool(args);
968
+ case "fablecut_versions":
969
+ return versionsTool(args);
848
970
  case "fablecut_status": {
849
971
  const up = await ensureUIServer();
850
972
  const proj = readProject();
@@ -889,6 +1011,7 @@ async function callTool(name, args, attempt = 0) {
889
1011
  return [
890
1012
  `Editor server: ${up ? "RUNNING — open " + BASE + " in a browser to watch edits live" : "FAILED TO START (check node / port " + PORT + ")"}`,
891
1013
  `Project: "${proj.name}" — ${proj.width}x${proj.height} @ ${proj.fps}fps, ${proj.clips.length} clip(s), ${dur.toFixed(2)}s, revision ${proj.revision}`,
1014
+ ...(SeqLib.entries(proj).length > 1 ? [`Sequences (${SeqLib.entries(proj).length}; the numbers above are the open one's): ${SeqLib.list(proj).map(SeqLib.describe).join(" · ")}`] : []),
892
1015
  encLine,
893
1016
  `Registered media: ${cap(proj.media.map((m) => `${m.id} (${m.kind}, ${m.name}${m.duration ? ", " + m.duration + "s" : ""})`), 25).join("; ") || "none"}`,
894
1017
  ...(() => {
@@ -897,6 +1020,15 @@ async function callTool(name, args, attempt = 0) {
897
1020
  })(),
898
1021
  `Files in media/: ${cap(files, 25).join(", ") || "none"}`,
899
1022
  `Library assets (./library): ${libSummary}`,
1023
+ ...(() => {
1024
+ try {
1025
+ const pj = createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR });
1026
+ if (!pj.peekActive()) return [];
1027
+ const { projects: all } = pj.list();
1028
+ const nv = createHistory({ projects: pj }).list(pj.peekActive()).versions.length;
1029
+ return [`Projects: ${all.length} (fablecut_projects lists, opens and creates them; this one is ${pj.peekActive()}, with ${nv} saved version(s): fablecut_versions)`];
1030
+ } catch { return []; }
1031
+ })(),
900
1032
  `Project file: ${PROJECT_FILE}`,
901
1033
  `Tips: fablecut_docs (use \`section\`) for the schema · fablecut_get_project {compact:true} to see the timeline · fablecut_patch_project for edits (cheapest) · fablecut_encode_profiles for export presets.`,
902
1034
  ].join("\n");
@@ -942,6 +1074,8 @@ async function callTool(name, args, attempt = 0) {
942
1074
  deliveryPresets: savedDeliveryPresets(),
943
1075
  mediaInfo: (src) => { const f = mediaFile(src); return f ? probeFile(f) : null; },
944
1076
  });
1077
+ // a version of the project as it was, kept before the last check so the write follows that check at once
1078
+ const verWarn = versionBeforeAgent(false);
945
1079
  // Someone else saved while the ops ran: writing now would drop their change.
946
1080
  // Without a baseRevision the ops just re-apply on the newer document.
947
1081
  let diskRev = readRev;
@@ -954,7 +1088,7 @@ async function callTool(name, args, attempt = 0) {
954
1088
  writeProject(proj);
955
1089
  lastReadRevision = proj.revision;
956
1090
  for (const [kind, item] of toSave) writeSaved(kind, item.id, item);
957
- return `Patched (revision ${proj.revision}): ${notes.join(" ")}. Now ${proj.clips.length} clip(s), ${proj.media.length} media. UI hot-reloaded.`;
1091
+ return `Patched (revision ${proj.revision}): ${notes.join(" ")}. Now ${proj.clips.length} clip(s), ${proj.media.length} media. UI hot-reloaded.${verWarn}`;
958
1092
  }
959
1093
  case "fablecut_set_project": {
960
1094
  const doc = args.project;
@@ -962,6 +1096,7 @@ async function callTool(name, args, attempt = 0) {
962
1096
  if (!Array.isArray(doc.clips) || !Array.isArray(doc.media))
963
1097
  throw new Error("project must contain `clips` and `media` arrays");
964
1098
  ProjectOps.checkProject(doc);
1099
+ const verWarn = versionBeforeAgent(true); // before the conflict check, so the write follows it at once
965
1100
  let cur = { revision: 0 };
966
1101
  try { cur = readProject(); } catch {}
967
1102
  const curRev = cur.revision || 0;
@@ -984,7 +1119,7 @@ async function callTool(name, args, attempt = 0) {
984
1119
  if (!(doc.panSchema >= 1) && (cur.panSchema >= 1)) doc.panSchema = 1;
985
1120
  writeProject(doc);
986
1121
  lastReadRevision = doc.revision;
987
- return `Saved (revision ${doc.revision}). ${doc.clips.length} clip(s). The editor UI (if open at ${BASE}) has hot-reloaded.`;
1122
+ return `Saved (revision ${doc.revision}). ${doc.clips.length} clip(s). The editor UI (if open at ${BASE}) has hot-reloaded.${verWarn}`;
988
1123
  }
989
1124
  case "fablecut_normalize_audio": {
990
1125
  const ids = Array.isArray(args.clipIds) ? args.clipIds.map(String) : [];
@@ -1246,7 +1381,7 @@ async function handle(msg) {
1246
1381
  result: {
1247
1382
  protocolVersion: negotiateProtocolVersion(params?.protocolVersion),
1248
1383
  capabilities: { tools: {} },
1249
- serverInfo: { name: "fablecut", version: "1.15.0" },
1384
+ serverInfo: { name: "fablecut", version: "1.16.0" },
1250
1385
  },
1251
1386
  });
1252
1387
  }
package/media-lib.js CHANGED
@@ -140,7 +140,7 @@
140
140
  * inside every composition. Sorted main timeline first, then by time. */
141
141
  function placements(doc, mediaId) {
142
142
  const out = [];
143
- const scan = (clips, comp) => {
143
+ const scan = (clips, comp, seq) => {
144
144
  const groups = new Map();
145
145
  for (const c of clips || []) {
146
146
  if (c.mediaId !== mediaId) continue;
@@ -150,11 +150,21 @@
150
150
  if (!prev || (prev.kind !== "video" && c.kind === "video")) groups.set(key, c);
151
151
  }
152
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 });
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 } : {}) });
154
155
  };
155
156
  scan(doc && doc.clips, null);
156
157
  for (const comp of (doc && doc.comps) || []) scan(comp.clips, comp);
157
- return out.sort((a, b) => (a.comp ? 1 : 0) - (b.comp ? 1 : 0) || String(a.comp || "").localeCompare(String(b.comp || "")) || a.start - b.start);
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));
158
168
  }
159
169
  /** mediaId → number of placements (see placements()). */
160
170
  function usageCounts(doc) {
@@ -173,6 +183,7 @@
173
183
  };
174
184
  scan(doc && doc.clips);
175
185
  for (const comp of (doc && doc.comps) || []) scan(comp.clips);
186
+ for (const seq of otherSequences(doc)) scan(seq.clips);
176
187
  return n;
177
188
  }
178
189
 
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.15.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": {