/* ═══════════════════════════════════════════════════════════════════════════ FableCut — a browser-based non-linear video editor Works standalone (open index.html) or connected to server.js, which adds persistent projects (project.json), a media library folder, and a REST API so external tools (e.g. Claude Code) can edit the timeline programmatically. ═══════════════════════════════════════════════════════════════════════════ */ "use strict"; /* ── Constants ─────────────────────────────────────────────────────────── */ const VIDEO_TRACK_COLORS = ["#4f8cff", "#7b6cff", "#ffd166", "#ff6b9d", "#45d9c2", "#f4a261", "#e76f51", "#a8dadc"]; const AUDIO_TRACK_COLORS = ["#7ec249", "#5a9e3a", "#4a8a2f", "#3a7226", "#2d5a1e", "#8fbc5a", "#6b9e3a", "#4d7a28"]; const MAX_TRACKS_PER_KIND = 16; // +V/+A and auto-grown A-tracks for multi-channel sources const DEFAULT_TRACK_DEFS = [ { id: "V3", kind: "video" }, { id: "V2", kind: "video" }, { id: "V1", kind: "video" }, { id: "A1", kind: "audio" }, { id: "A2", kind: "audio" }, { id: "A3", kind: "audio" }, { id: "A4", kind: "audio" }, ]; function makeTrack(id, kind) { const n = Math.max(1, parseInt(String(id).slice(1), 10) || 1); const colors = kind === "audio" ? AUDIO_TRACK_COLORS : VIDEO_TRACK_COLORS; return { id, kind, h: kind === "audio" ? 42 : 58, color: colors[(n - 1) % colors.length] }; } /** Live track list (top→bottom). Mutated by +V/+A; rebuilt from project.tracks on load. */ let TRACKS = DEFAULT_TRACK_DEFS.map((d) => makeTrack(d.id, d.kind)); /* Three timeline density presets. L matches the original track heights (with thumbs). S is compact solid-color rows; M is in between. */ const TRACK_SIZE_PRESETS = { s: { thumbs: false, hVideo: 26, hAudio: 22 }, m: { thumbs: true, hVideo: 44, hAudio: 32 }, l: { thumbs: true, hVideo: 58, hAudio: 42 }, }; const TRACK_SIZE_KEY = "fablecut-track-size"; const LAST_TRANS_KEY = { in: "fablecut-last-trans-in", out: "fablecut-last-trans-out" }; const DEFAULT_LAST_TRANS = { type: "fade", duration: 1 }; const RULER_H = 26; const SNAP_PX = 8; const MIN_DUR = 0.05; const ZOOM_MIN = 1; const ZOOM_MAX = 300; const TIMELINE_PAD_SEC = 15; // trailing empty seconds in the scrollable content const TIMELINE_FIT_FILL = 0.95; // ⇧Z / Fit — clip content fills this fraction of the viewport const DEFAULT_PROPS = { x: 0, y: 0, scale: 1, rotation: 0, opacity: 1, volume: 1, pan: 0, anchorX: 0, anchorY: 0, // anchor point, px from the picture's centre (motion.js) trimStart: 0, trimEnd: 100, trimOffset: 0, // shape layers: the part of every path that draws (%) autoOrient: false, // turn along the motion path pathOffset: 0, pathAlign: "start", // text on a path: where along it (%), which end sits there motionBlur: 0, motionBlurSamples: 8, // shutter angle (°, 0 = off) and sub-frame samples gain: 0, // clip gain, dB — applied before volume channelMode: "stereo", // stereo | mono | left | right | swap duck: 0, // ducking, dB (≤ 0) — keyframed by Auto-duck, multiplies volume speed: 1, // playback rate (video/audio) brightness: 100, contrast: 100, saturation: 100, hue: 0, blur: 0, grayscale: 0, sepia: 0, invert: 0, temperature: 0, tint: 0, vignette: 0, // color grade extensions filterPreset: "none", // named look, see FILTER_PRESETS fit: "contain", // contain | cover | stretch | none cropL: 0, cropT: 0, cropR: 0, cropB: 0, // % trimmed off each source edge flipH: false, flipV: false, cornerRadius: 0, // px, rounded corners (PiP look) blend: "normal", // canvas blend mode chromaKey: "", chromaTolerance: 26, chromaSoftness: 12, // green-screen key bgRemove: false, // AI person cut-out (MediaPipe) shake: 0, shakeSpeed: 8, // handheld/impact camera shake (px) rgbSplit: 0, // chromatic aberration (px) grain: 0, // film grain (%) text: "Title", fontSize: 72, color: "#ffffff", color2: "", font: "Segoe UI", bold: true, italic: false, weight: 0, align: "center", letterSpacing: 0, lineHeight: 1.2, uppercase: false, textShadow: 12, glow: 0, glowColor: "", // neon glow (glowColor defaults to fill) textAnim: "none", wordRate: 0.15, direction: "auto", highlightColor: "#ffd166", strokeWidth: 0, strokeColor: "#000000", bgColor: "#000000", bgOpacity: 0, boxW: 0, boxH: 0, // text box (px); 0 = hug content. Resize handles edit these. boxFit: false, // false = wrap at fixed fontSize; true = scale font to fit box vAlign: "middle", // top | middle | bottom — vertical align of the text block in the box }; const ANIMATABLE = ["x", "y", "scale", "rotation", "opacity", "volume", "pan", "duck", "speed", "brightness", "contrast", "saturation", "hue", "blur", "grayscale", "sepia", "invert", "temperature", "tint", "vignette", "cornerRadius", "shake", "rgbSplit", "grain", "fontSize", "letterSpacing", "glow", "anchorX", "anchorY", "trimStart", "trimEnd", "trimOffset", "pathOffset"]; const TRANSITIONS = ["none", "fade", "slide-left", "slide-right", "slide-up", "slide-down", "zoom", "wipe", "wipe-right", "wipe-up", "wipe-down", "iris", "spin", "blur", "whip", "glitch", "pop"]; const TEXT_ANIMS = ["none", "typewriter", "word-pop", "word-slide", "karaoke", "highlight", "letter-pop", "wave", "bounce", "shake", "clip-reveal", "zoom-in", "font-cut", "rise-mask"]; const BLEND_MODES = self.FableCutMask.BLENDS; // the canvas composite set, shared with the agent (mask.js) /* Named looks. % props multiply against the clip's own value, additive props add. */ const FILTER_PRESETS = { none: {}, cinematic: { contrast: 112, saturation: 118, temperature: -10, vignette: 28 }, "teal-orange": { contrast: 115, saturation: 125, temperature: -18, hue: -8, vignette: 22 }, noir: { grayscale: 100, contrast: 128, brightness: 96, vignette: 45 }, vintage: { sepia: 42, contrast: 92, brightness: 106, saturation: 88, temperature: 12, vignette: 30 }, faded: { contrast: 84, brightness: 110, saturation: 82 }, warm: { temperature: 28, brightness: 103, saturation: 108 }, cold: { temperature: -28, saturation: 104 }, pop: { saturation: 152, contrast: 116 }, dreamy: { brightness: 109, saturation: 112, blur: 0.6, temperature: 8 }, retro: { saturation: 130, hue: -6, contrast: 106, sepia: 15 }, "bw-soft": { grayscale: 100, contrast: 95, brightness: 108 }, cyberpunk: { saturation: 140, hue: 12, contrast: 118, temperature: -15, vignette: 25 }, sunset: { temperature: 24, tint: 6, brightness: 105, saturation: 116, contrast: 104, vignette: 20 }, midnight: { temperature: -24, brightness: 88, contrast: 122, saturation: 94, vignette: 38 }, }; const SYSTEM_FONTS = ["Segoe UI", "Arial", "Georgia", "Impact", "Courier New", "Trebuchet MS", "Verdana", "Times New Roman", "Comic Sans MS", "Consolas"]; /* Google fonts offered in the font picker, by look. Any other Google Font loads by name too. */ const GOOGLE_FONT_GROUPS = { Display: ["Anton", "Archivo Black", "Bebas Neue", "Bangers", "Bungee", "Oswald", "Teko", "Russo One", "Alfa Slab One", "Black Ops One", "Righteous", "Fjalla One", "Unbounded", "Syne"], Sans: ["Inter", "Montserrat", "Poppins", "Roboto", "Roboto Condensed", "Barlow", "Lato", "Open Sans", "Raleway", "Nunito", "Work Sans", "DM Sans", "Rubik", "Kanit", "Lexend", "Outfit", "Sora", "Space Grotesk", "Josefin Sans", "Fredoka"], Serif: ["Playfair Display", "Abril Fatface", "Cinzel", "Cormorant Garamond", "Lora", "Merriweather", "DM Serif Display", "Libre Baskerville", "Marcellus"], "Script & hand": ["Caveat", "Pacifico", "Lobster", "Permanent Marker", "Dancing Script", "Great Vibes", "Satisfy", "Shadows Into Light", "Kalam"], "Retro & mono": ["Monoton", "Press Start 2P", "Special Elite", "Space Mono", "VT323", "Courier Prime"], }; const GOOGLE_FONTS = Object.values(GOOGLE_FONT_GROUPS).flat(); /* ── Title styles: cohesive one-tap looks. Each bundles a DIFFERENT font, placement and animation, so titles vary instead of all looking basic. Agents can reproduce a look by writing the same props directly. ── */ const FONT_CUT_DEFAULT = ["Anton", "Bebas Neue", "Archivo Black", "Oswald", "Impact"]; const STYLE_RESET = { // decorative props a style owns; reset before applying color2: "", glow: 0, glowColor: "", strokeWidth: 0, bgColor: "#000000", bgOpacity: 0, rotation: 0, letterSpacing: 0, uppercase: false, italic: false, textShadow: 12, fontCutSet: undefined, align: "center", weight: 0, strokeColor: "#000000", highlightColor: "#ffd166", }; const TITLE_STYLES = { plain: { label: "Plain", place: "center", props: { font: "Segoe UI", fontSize: 72, bold: true, color: "#ffffff", textAnim: "none" } }, impact: { label: "Impact", place: "lower", props: { font: "Anton", fontSize: 96, bold: false, uppercase: true, color: "#ffffff", textShadow: 22, textAnim: "word-pop" } }, elegant: { label: "Elegant", place: "center", props: { font: "Playfair Display", fontSize: 88, bold: false, color: "#ffffff", color2: "#ffd166", letterSpacing: 2, textAnim: "clip-reveal" } }, kinetic: { label: "Kinetic cut", place: "center", props: { font: "Bebas Neue", fontSize: 120, bold: false, uppercase: true, color: "#ffd166", letterSpacing: 3, textAnim: "font-cut", fontCutSet: ["Anton", "Bebas Neue", "Archivo Black", "Oswald"] } }, neon: { label: "Neon", place: "center", props: { font: "Bebas Neue", fontSize: 104, bold: false, uppercase: true, color: "#ffffff", glow: 60, glowColor: "#22d3ee", textAnim: "wave" } }, handwritten: { label: "Handwritten", place: "lower-left", props: { font: "Caveat", fontSize: 92, bold: false, color: "#ffffff", rotation: -4, textAnim: "word-slide" } }, serifDrop: { label: "Serif drop", place: "center", props: { font: "Abril Fatface", fontSize: 96, bold: false, color: "#ffffff", textShadow: 18, textAnim: "zoom-in" } }, subtitle: { label: "Subtitle", place: "lower", props: { font: "Roboto", fontSize: 52, bold: false, color: "#ffffff", bgColor: "#000000", bgOpacity: 0.5, textAnim: "karaoke" } }, boldRise: { label: "Bold rise", place: "lower", props: { font: "Archivo Black", fontSize: 92, bold: false, uppercase: true, color: "#ffffff", textAnim: "rise-mask" } }, luxury: { label: "Luxury", place: "center", props: { font: "Cinzel", fontSize: 88, bold: false, uppercase: true, color: "#faf0dc", color2: "#c9a227", letterSpacing: 6, textAnim: "clip-reveal" } }, popOutline: { label: "Pop outline", place: "center", props: { font: "Montserrat", fontSize: 100, bold: false, weight: 900, uppercase: true, color: "#ffd166", strokeWidth: 6, strokeColor: "#111111", textShadow: 0, textAnim: "letter-pop" } }, boxed: { label: "Boxed", place: "lower", props: { font: "Inter", fontSize: 60, bold: false, weight: 800, color: "#111111", bgColor: "#ffffff", bgOpacity: 0.95, textShadow: 0, textAnim: "word-slide" } }, headline: { label: "Headline", place: "center", props: { font: "Montserrat", fontSize: 92, bold: false, weight: 900, uppercase: true, color: "#ffffff", highlightColor: "#ff4d6d", strokeWidth: 4, strokeColor: "#000000", textShadow: 0, textAnim: "highlight" } }, comic: { label: "Comic", place: "center", props: { font: "Bangers", fontSize: 112, bold: false, color: "#ffe14d", strokeWidth: 8, strokeColor: "#1a1a1a", rotation: -3, letterSpacing: 2, textShadow: 0, textAnim: "bounce" } }, typewriter: { label: "Typewriter", place: "lower-left", props: { font: "Special Elite", fontSize: 64, bold: false, color: "#f5f0e6", textShadow: 6, textAnim: "typewriter" } }, minimal: { label: "Minimal", place: "center", props: { font: "Inter", fontSize: 60, bold: false, weight: 300, uppercase: true, color: "#ffffff", letterSpacing: 12, textShadow: 0, textAnim: "rise-mask" } }, script: { label: "Script", place: "center", props: { font: "Great Vibes", fontSize: 120, bold: false, color: "#ffffff", color2: "#f9c5d1", textShadow: 10, textAnim: "clip-reveal" } }, retro: { label: "Retro", place: "center", props: { font: "Monoton", fontSize: 96, bold: false, uppercase: true, color: "#ff6ec7", glow: 40, glowColor: "#ff6ec7", textAnim: "letter-pop" } }, sticker: { label: "Sticker", place: "lower", props: { font: "Fredoka", fontSize: 80, bold: false, weight: 700, color: "#ffffff", bgColor: "#7b6cff", bgOpacity: 1, rotation: -2, textShadow: 0, textAnim: "word-pop" } }, glitch: { label: "Glitch", place: "center", props: { font: "Russo One", fontSize: 100, bold: false, uppercase: true, color: "#e8f9ff", glow: 30, glowColor: "#ff2e63", letterSpacing: 2, textAnim: "shake" } }, cinematic: { label: "Cinematic", place: "center", props: { font: "Cormorant Garamond", fontSize: 84, bold: false, weight: 500, uppercase: true, color: "#f2efe9", letterSpacing: 14, textShadow: 8, textAnim: "rise-mask" } }, }; const STYLE_CYCLE = ["impact", "elegant", "kinetic", "neon", "handwritten", "serifDrop", "boldRise", "luxury", "popOutline", "boxed", "comic", "typewriter", "script", "sticker", "cinematic"]; const AUDIO_EXT = /\.(mp3|wav|ogg|m4a|aac|flac|mpeg)$/i; const VIDEO_EXT = /\.(mp4|webm|mov|mkv|m4v)$/i; const IMAGE_EXT = /\.(png|jpe?g|gif|webp|avif)$/i; const ASPECT_PRESETS = [ { label: "16:9 · 1280×720", w: 1280, h: 720 }, { label: "16:9 · 1920×1080", w: 1920, h: 1080 }, { label: "9:16 · Reel 1080×1920", w: 1080, h: 1920 }, { label: "4:5 · IG 1080×1350", w: 1080, h: 1350 }, { label: "1:1 · 1080×1080", w: 1080, h: 1080 }, ]; const FPS_PRESETS = [24, 25, 30, 50, 60]; /** Delivery-aspect presets fitted inside the composition canvas (export crop). */ const EXPORT_FRAME_ASPECTS = [ { label: "Full canvas", w: 0, h: 0 }, { label: "9:16 Reel", w: 9, h: 16 }, { label: "16:9", w: 16, h: 9 }, { label: "4:5 IG", w: 4, h: 5 }, { label: "1:1 Square", w: 1, h: 1 }, ]; const WAVE_PEAKS_PER_SEC = 50; /* ── Mixer levels (dB). Clip gain is a trim before volume; track and master faders sit on the buses. A fader at its floor is silence, not −60 dB. ── */ const CLIP_GAIN_MIN = -60, CLIP_GAIN_MAX = 24; const FADER_DB_MIN = -60, FADER_DB_MAX = 12; const CHANNEL_MODES = ["stereo", "mono", "left", "right", "swap"]; function dbToGain(db) { db = +db; if (!Number.isFinite(db)) return 1; return db <= FADER_DB_MIN ? 0 : Math.pow(10, db / 20); } function clampFaderDb(db) { return clamp(+db || 0, FADER_DB_MIN, FADER_DB_MAX); } /** What a clip's evaluated props send to its vol stage: volume × duck. */ function clipAudioGain(p) { const vol = clamp(+p.volume || 0, 0, 4); return p.duck < 0 ? vol * dbToGain(p.duck) : vol; } function clipGainDb(c) { return clamp(+c?.props?.gain || 0, CLIP_GAIN_MIN, CLIP_GAIN_MAX); } function clipChannelMode(c) { const m = c?.props?.channelMode; return CHANNEL_MODES.includes(m) ? m : "stereo"; } function trackGainDb(id) { return clampFaderDb(TRACKS.find((t) => t.id === id)?.gain); } function trackPanValue(id) { return clipPan(TRACKS.find((t) => t.id === id)?.pan); } function masterGainDb() { return clampFaderDb(project.master?.gain); } /** project.master on disk: {gain?, fx?}, written only when off-default. */ function normalizeMaster(raw) { const gain = clampFaderDb(raw?.gain); const fx = normFx(raw?.fx); if (!gain && !fx) return null; const out = {}; if (gain) out.gain = gain; if (fx) out.fx = fx; return out; } /* Submix buses: project.buses = [{id:"B1", name?, gain?, pan?, mute?, fx?}]. An A-track routes into one with tracks[].out = "B1" (default: the master); a bus has its own effects, fader and pan and feeds the master. */ const BUS_MAX = 8; const BUS_COLOR = "#c58cff"; function normalizeBuses(raw) { if (!Array.isArray(raw)) return []; const seen = new Set(), out = []; for (const b of raw) { if (!b || !/^B\d+$/.test(String(b.id)) || seen.has(b.id) || out.length >= BUS_MAX) continue; seen.add(b.id); const d = { id: b.id }; if (typeof b.name === "string" && b.name.trim()) d.name = b.name.trim().slice(0, 40); const g = Math.round(clampFaderDb(b.gain) * 10) / 10; if (g) d.gain = g; const pn = clipPan(b.pan); if (pn) d.pan = pn; if (b.mute === true) d.mute = true; const fx = normFx(b.fx); if (fx) d.fx = fx; out.push(d); } return out.sort((a, b) => parseInt(a.id.slice(1), 10) - parseInt(b.id.slice(1), 10)); } function busById(id) { return (project.buses || []).find((b) => b.id === id) || null; } function busIdsNow() { return (project.buses || []).map((b) => b.id); } function busLabel(b) { return b?.name || b?.id || ""; } /** The bus an A-track feeds, or null for the master. */ function trackOut(id) { const o = TRACKS.find((t) => t.id === id)?.out; return o && busById(o) ? o : null; } const TRACK_IDS = new Set(TRACKS.map((t) => t.id)); function syncTrackIds() { TRACK_IDS.clear(); for (const t of TRACKS) TRACK_IDS.add(t.id); } function serializeTracks() { // Mixer settings are written only when off-default, so untouched projects // stay byte-identical. return TRACKS.map(({ id, kind, gain, pan, fx, out }) => { const d = { id, kind }; if (kind === "audio" && +gain) d.gain = +gain; if (kind === "audio" && +pan) d.pan = +pan; if (kind === "audio" && fx?.length) d.fx = fx; if (kind === "audio" && out && busById(out)) d.out = out; return d; }); } function sortTracksInPlace() { const vids = TRACKS.filter((t) => t.kind === "video") .sort((a, b) => (parseInt(b.id.slice(1), 10) || 0) - (parseInt(a.id.slice(1), 10) || 0)); const auds = TRACKS.filter((t) => t.kind === "audio") .sort((a, b) => (parseInt(a.id.slice(1), 10) || 0) - (parseInt(b.id.slice(1), 10) || 0)); TRACKS.length = 0; TRACKS.push(...vids, ...auds); syncTrackIds(); } function applyTracksFromProject(defs) { const raw = Array.isArray(defs) && defs.length ? defs.filter((d) => d && d.id && (d.kind === "video" || d.kind === "audio")) : DEFAULT_TRACK_DEFS; const seen = new Set(); const list = raw.filter((d) => { if (seen.has(d.id)) return false; seen.add(d.id); return true; }); TRACKS.length = 0; for (const d of list) { const t = makeTrack(d.id, d.kind === "audio" ? "audio" : "video"); if (t.kind === "audio") { if (+d.gain) t.gain = clampFaderDb(d.gain); if (+d.pan) t.pan = clipPan(d.pan); const fx = normFx(d.fx); if (fx) t.fx = fx; if (typeof d.out === "string" && /^B\d+$/.test(d.out)) t.out = d.out; } TRACKS.push(t); } sortTracksInPlace(); applyTrackHeights(); } /** Ensure every clip.track exists (agents may reference V4+ before the UI adds it). */ function ensureTracksCoverClips() { let added = false; for (const c of project.clips) { if (!c.track || TRACK_IDS.has(c.track)) continue; const kind = c.kind === "audio" || /^A\d+$/i.test(c.track) ? "audio" : "video"; TRACKS.push(makeTrack(c.track, kind)); TRACK_IDS.add(c.track); // mark present before later clips (avoids duplicate makeTrack) added = true; } if (added) { sortTracksInPlace(); applyTrackHeights(); } } function audioTrackIds() { return TRACKS.filter((t) => t.kind === "audio").map((t) => t.id); } function nextTrackId(kind) { const prefix = kind === "audio" ? "A" : "V"; let max = 0; for (const t of TRACKS) { if (t.kind !== kind) continue; const n = parseInt(t.id.slice(1), 10); if (n > max) max = n; } return prefix + (max + 1); } function addTimelineTrack(kind) { const existing = TRACKS.filter((t) => t.kind === kind).length; if (existing >= MAX_TRACKS_PER_KIND) { toast(`Maximum ${MAX_TRACKS_PER_KIND} ${kind} tracks`); return null; } const id = nextTrackId(kind); const t = makeTrack(id, kind); TRACKS.push(t); sortTracksInPlace(); applyTrackHeights(); project.tracks = serializeTracks(); if (state.soloId && state.soloId !== id) { state.disabledTracks.add(id); project.disabledTracks = [...state.disabledTracks].sort(); } if (kind === "audio") syncAudioGraphTracks(); buildTrackDOM(); syncAllTrackDisabledUI(); state.dirtyTimeline = true; rebuildClips(); const h = setTimelineHeight(Math.max( $("timelinePanel")?.getBoundingClientRect().height || 0, defaultTimelineHeight() )); localStorage.setItem(TL_H_KEY, String(h)); scheduleSave(); return t; } function trackHasClips(trackId) { return project.clips.some((c) => c.track === trackId); } function canRemoveTrack(trackId) { const t = TRACKS.find((x) => x.id === trackId); if (!t) return { ok: false, reason: "Unknown track" }; if (trackHasClips(trackId)) return { ok: false, reason: "Track has clips" }; if (TRACKS.filter((x) => x.kind === t.kind).length <= 1) return { ok: false, reason: `Keep at least one ${t.kind} track` }; return { ok: true, reason: "" }; } function removeTimelineTrack(trackId) { const check = canRemoveTrack(trackId); if (!check.ok) { toast(check.reason); return false; } const wasAudio = TRACKS.find((t) => t.id === trackId)?.kind === "audio"; const idx = TRACKS.findIndex((t) => t.id === trackId); if (idx < 0) return false; if (state.soloId === trackId) clearTrackSolo({ restore: true }); TRACKS.splice(idx, 1); syncTrackIds(); if (state.disabledTracks.has(trackId)) { state.disabledTracks.delete(trackId); project.disabledTracks = [...state.disabledTracks].sort(); } state.lockedTracks.delete(trackId); state.untargetedTracks.delete(trackId); project.lockedTracks = [...state.lockedTracks].sort(); project.untargetedTracks = [...state.untargetedTracks].sort(); if (Array.isArray(state.soloRestore)) { state.soloRestore = state.soloRestore.filter((id) => id !== trackId); } project.tracks = serializeTracks(); if (wasAudio) syncAudioGraphTracks(); buildTrackDOM(); syncAllTrackDisabledUI(); state.dirtyTimeline = true; rebuildClips(); scheduleSave(); return true; } /* Lightweight right-click menu for track headers. */ let trackCtxMenu = null; function hideTrackCtxMenu() { if (trackCtxMenu) { trackCtxMenu.remove(); trackCtxMenu = null; } } function showTrackCtxMenu(clientX, clientY, track) { hideTrackCtxMenu(); const check = canRemoveTrack(track.id); const menu = document.createElement("div"); menu.className = "ctx-menu"; menu.id = "trackCtxMenu"; const btn = document.createElement("button"); btn.type = "button"; btn.className = "ctx-item"; btn.textContent = "Remove track"; if (!check.ok) { btn.disabled = true; btn.title = check.reason; } else { btn.addEventListener("click", () => { hideTrackCtxMenu(); removeTimelineTrack(track.id); }); } menu.appendChild(btn); document.body.appendChild(menu); trackCtxMenu = menu; const pad = 6; const w = menu.offsetWidth, h = menu.offsetHeight; let x = clientX, y = clientY; if (x + w + pad > window.innerWidth) x = window.innerWidth - w - pad; if (y + h + pad > window.innerHeight) y = window.innerHeight - h - pad; menu.style.left = Math.max(pad, x) + "px"; menu.style.top = Math.max(pad, y) + "px"; btn.focus(); } /* Clip right-click menu: enable / lock / link for the clip's selection. */ function showClipCtxMenu(clientX, clientY, c) { hideTrackCtxMenu(); if (!state.selIds.has(c.id)) selectClip(c.id); const group = withLinked(selectedClips()); const menu = document.createElement("div"); menu.className = "ctx-menu"; menu.id = "trackCtxMenu"; const item = (label, keys, run, disabledReason) => { const btn = document.createElement("button"); btn.type = "button"; btn.className = "ctx-item"; btn.innerHTML = `${escapeHtml(label)}` + (keys ? `${escapeHtml(keys)}` : ""); if (disabledReason) { btn.disabled = true; btn.title = disabledReason; } else btn.addEventListener("click", () => { hideTrackCtxMenu(); run(); }); menu.appendChild(btn); return btn; }; const anyEnabled = group.some((x) => x.disabled !== true); const anyUnlocked = group.some((x) => x.locked !== true); const locked = group.some(isClipLocked); item(anyEnabled ? "Disable clip" : "Enable clip", "Shift+E", toggleClipsDisabled, locked ? "Locked — unlock to change" : null); item(anyUnlocked ? "Lock clip" : "Unlock clip", "", toggleClipsLocked); if (group.some((x) => x.kind === "audio")) { item("Crossfade with neighbours", "Shift+D", () => crossfadeSelected(), locked ? "Locked — unlock to change" : null); item("Auto-duck under other tracks", "", () => autoDuckClips(selectedClips()), locked ? "Locked — unlock to change" : null); } if (group.some((x) => x.kind === "audio" || x.kind === "video")) item("Find silences", "", () => findSilences(selectedClips())); if (selectedClips().some((x) => isVisualClip(x) && x.kind !== "null")) item("Parent to a new null", "", parentSelectionToNull, locked ? "Locked — unlock to change" : null); item("Precompose", "", precomposeSelection, locked ? "Locked — unlock to change" : null); if (c.kind === "comp") item("Open composition", "", () => enterComp(c.compId, c)); if (c.mediaId || c.kind === "comp") item("Reveal in project", "", () => revealInProject(c)); const linked = selectedClips().some((x) => x.linkGroup || x.linkedId); if (linked) item("Unlink audio / video", "Ctrl+L", toggleLinkSelected, locked ? "Locked — unlock to change" : null); else if (c.kind === "video" || c.kind === "audio") { const why = linkRefusal(selectedClips()); item("Link audio / video", "Ctrl+L", toggleLinkSelected, why); } document.body.appendChild(menu); trackCtxMenu = menu; const pad = 6; const w = menu.offsetWidth, h = menu.offsetHeight; let x = clientX, y = clientY; if (x + w + pad > window.innerWidth) x = window.innerWidth - w - pad; if (y + h + pad > window.innerHeight) y = window.innerHeight - h - pad; menu.style.left = Math.max(pad, x) + "px"; menu.style.top = Math.max(pad, y) + "px"; menu.querySelector(".ctx-item:not(:disabled)")?.focus(); } document.addEventListener("pointerdown", (e) => { if (trackCtxMenu && !trackCtxMenu.contains(e.target)) hideTrackCtxMenu(); }, true); document.addEventListener("keydown", (e) => { if (e.key === "Escape") hideTrackCtxMenu(); }, true); /* ── User settings (localStorage; optional behavior toggles) ── */ const SETTINGS_KEY = "fablecut-settings"; const DEFAULT_SETTINGS = { linkSelect: false, // timeline ↔ project bin selection sync encodeProfile: null, // null = server default from encoding-profiles.json exportKind: null, // "delivery" | "profile" — what the Export dialog last used delivery: null, // last delivery spec used in the Export dialog (delivery.js) // WebCodecs has no CRF — bitrate (Mbps) + constant|variable mode webCodecsBitrateMbps: null, // null = auto from canvas size webCodecsBitrateMode: "variable", // "variable" | "constant" snapTargets: { clips: true, playhead: true, markers: true, inout: true, keyframes: false, frames: true }, useProxies: true, // play proxies (when a file has one) while editing; export always reads the original exportAsk: true, // Export opens its dialog (name + settings) first; false = render straight away exportEngine: null, // "fast" | "second" — what the last export used ("Don't ask again" reuses it) exportChoice: null, // the Export dialog's preset / profile last used ("d:" | "p:"), reused with it }; let settings = { ...DEFAULT_SETTINGS }; function loadSettings() { try { const raw = JSON.parse(localStorage.getItem(SETTINGS_KEY) || "null"); if (!raw || typeof raw !== "object") { settings = { ...DEFAULT_SETTINGS }; return; } const next = { ...DEFAULT_SETTINGS }; for (const k of Object.keys(DEFAULT_SETTINGS)) { if (Object.hasOwn(raw, k)) next[k] = raw[k]; } // coerce WebCodecs bitrate settings const mbps = next.webCodecsBitrateMbps; if (mbps != null) { const n = Number(mbps); next.webCodecsBitrateMbps = (Number.isFinite(n) && n > 0) ? n : null; } if (next.webCodecsBitrateMode !== "constant" && next.webCodecsBitrateMode !== "variable") { next.webCodecsBitrateMode = "variable"; } const st = next.snapTargets; next.snapTargets = { ...DEFAULT_SETTINGS.snapTargets }; if (st && typeof st === "object") { for (const k of Object.keys(next.snapTargets)) if (typeof st[k] === "boolean") next.snapTargets[k] = st[k]; } settings = next; } catch { settings = { ...DEFAULT_SETTINGS }; } } function saveSettings() { try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings)); } catch { } } function getSetting(key) { return settings[key]; } function setSetting(key, value) { if (!Object.hasOwn(DEFAULT_SETTINGS, key)) return; settings[key] = value; saveSettings(); } /* ── State ─────────────────────────────────────────────────────────────── */ const project = { name: "Untitled Project", width: 1280, height: 720, fps: 30, // overwritten by project.json / applyProject background: "#000000", revision: 0, folders: [], // {id, name, parentId:null|string, open:true} — Project-bin tree (virtual) media: [], // {id, name, kind, src, duration, width?, height?, folderId?} clips: [], // {id, mediaId, kind, track, start, in, duration, name, props:{}} markers: [], // {t, label?} — beat/cue markers on the ruler; snap targets inPoint: null, // timeline work-area IN (seconds), or null outPoint: null, // timeline work-area OUT (seconds), or null disabledTracks: [], // track ids (V4…A3) hidden from preview/export when listed lockedTracks: [], // track ids no edit may change (UI and MCP patch) untargetedTracks: [], // track ids edits skip (split, insert, ripple, close gap…) exportFrame: null, // optional {x,y,w,h} delivery crop inside width×height canvas encodeProfile: null, // optional fast-export profile id (overrides browser setting) delivery: null, // optional delivery spec (delivery.js) — the default for exports, agents' included outputs: null, // optional batch outputs: [{id, on, …delivery spec}] — one render, several files tracks: null, // optional [{id, kind, gain?, pan?}] — null means default V3…V1 + A1…A4 master: null, // optional {gain} — master bus fader (dB) buses: [], // submix buses [{id:"B1", name?, gain?, pan?, mute?, fx?}]; tracks[].out routes into one panSchema: 1, // 1 = pan-aware; gates one-time L/R stem migration on load }; /** Sole runtime FPS source — always the loaded project’s `fps`. */ function projectFps() { const n = Number(project.fps); return (Number.isFinite(n) && n > 0) ? n : 1; } const state = { time: 0, playing: false, pps: 60, snap: true, previewRate: 1, // playback speed for PREVIEW only — never affects export selId: null, // primary selection (drives the inspector) selIds: new Set(), // full multi-selection (includes selId) silence: null, // silences found (Inspector → Silence): {ids, spans, sig}, shown on the timeline until cut or cleared silenceBusy: false, // a Find is listening (the Inspector offers Cancel) beats: null, // the beat Find beats heard (Inspector → Beats): {clipId, sig, a, grid, bpm, drop}, ticks on the timeline beatsBusy: false, // Find beats is listening trackSize: "l", // s | m | l — timeline track density preset connected: false, exporting: false, rendering: false, // fast (server/ffmpeg) export in progress guides: false, // safe-area overlay on the monitor exportFrameView: true, // export frame overlay (border + overscan dim) exportFrameCrop: false, // clip preview to the export frame (hide overscan) viewZoom: 1, // program-monitor display zoom (1 = fit stage) monitorMode: "program", // "source" | "program" — single-viewer Avid-style toggle source: { // Source monitor (media-local; not timeline) mediaId: null, time: 0, playing: false, in: null, // media-time mark, or null out: null, fromClipId: null, // set when loaded from a timeline clip (informational) }, audioHold: false, // while paused, loop one frame of audio at the playhead ffmpeg: false, // server reports ffmpeg available webCodecs: false, // VideoEncoder + Annex-B H.264 supported dirtyTimeline: true, gesture: false, workAreaPlay: false, // when true, play + Home/End stay inside IN/OUT binTab: "project", // project | elements | sfx | svg | shapes disabledTracks: new Set(), // mirror of project.disabledTracks for fast lookup lockedTracks: new Set(), // mirror of project.lockedTracks untargetedTracks: new Set(), // mirror of project.untargetedTracks tool: "select", // timeline edit tool: select | ripple | roll | slip | slide soloId: null, // track id when solo is active, else null soloRestore: null, // disabledTracks snapshot taken when solo engaged transFocus: null, // "in" | "out" — inspector transition row highlighted kfGraphs: new Set(), // animatable prop keys with open monitor graphs }; function normalizeDisabledTracks(raw) { if (raw == null) return []; const arr = Array.isArray(raw) ? raw : []; return [...new Set(arr.filter((id) => TRACK_IDS.has(id)))].sort(); } function isTrackEnabled(id) { return !state.disabledTracks.has(id); } /* ── Track targeting, locks and clip enable ── Three independent switches, Premiere-style: • enabled (eye) — output only: hidden from preview, audio and export. • targeted — which lanes an edit touches: split, insert, ripple delete, close gap, T / ⇧T, jump-to-cut, Source placement. • locked — nothing may change it: not the mouse, not the keyboard, not a ripple (locked lanes stay put while others shift). A clip can also be locked or disabled on its own. A linked A/V group with any locked member counts as locked as a whole, so sync lock never splits it. */ function isTrackTargeted(id) { return !state.untargetedTracks.has(id); } function isTrackLocked(id) { return state.lockedTracks.has(id); } /* Timeline edit ops (split, ripple, insert, trims, crossfade…) live in edit-ops.js, shared with the MCP server so an agent's patch op and the editor's shortcut run the same code. The wrappers below add undo, selection, toasts and saving. */ const EDIT = FableCutEdit.create({ doc: () => project, tracks: () => TRACKS, trackLocked: (id) => isTrackLocked(id), trackTargeted: (id) => isTrackTargeted(id), uid: () => uid(), mediaTimeAt: (c, t) => mediaTimeAt(c, t), onRemove: (c) => releaseClipEl(c.id), onPlace: (m, c) => { if (m.kind === "video" || m.kind === "audio") ensureWave(m); if (m.kind === "video" && c) reconcileAudioChannels(c, true); }, defaultProps: () => DEFAULT_PROPS, }); const { isEditTarget, isClipLocked, isGroupLocked, withoutLocked, editTargetTracks, withLinked, relinkClips, splitClipAt, relinkSplitRights, sourceEditTracks, placeSourceWindowClips, punchTrackRange, listAlignedGaps, adjacentClip, rippleTrim, rollEdit, slipClip, slideClip, crossfadeCuts, crossfadeCut, } = EDIT; /** Does this clip reach the picture / the mix? Track output and clip enable. */ function clipRenders(c) { // comp audio plays through the main timeline's track of the same id, so that track's switch applies too if (c._comp) return c._on !== false && (c.kind !== "audio" || isTrackEnabled(c.track)); return isTrackEnabled(c.track) && c.disabled !== true; } function toastLocked(partial = false) { toast(partial ? "Locked clips were left untouched — unlock them to edit" : "Locked — unlock the clip or its track to edit"); } function syncTrackDisabledUI(id) { const on = isTrackEnabled(id); const solo = state.soloId === id; const head = els.trackHeaders.querySelector(`.track-head[data-track="${id}"]`); const row = els.tracks.querySelector(`.track[data-track="${id}"]`); if (head) { head.classList.toggle("disabled", !on); head.classList.toggle("solo", solo); const btn = head.querySelector(".track-toggle"); if (btn) { btn.setAttribute("aria-pressed", on ? "true" : "false"); btn.title = on ? "Disable track" : "Enable track"; } const sBtn = head.querySelector(".track-solo"); if (sBtn) { sBtn.setAttribute("aria-pressed", solo ? "true" : "false"); sBtn.classList.toggle("on", solo); sBtn.title = solo ? "Unsolo track" : "Solo track (mute all others)"; } } const locked = isTrackLocked(id), targeted = isTrackTargeted(id); if (head) { head.classList.toggle("locked", locked); head.classList.toggle("untargeted", !targeted); const tBtn = head.querySelector(".track-id"); if (tBtn) { tBtn.setAttribute("aria-pressed", targeted ? "true" : "false"); tBtn.title = targeted ? "Targeted — edits (split, insert, ripple, close gap) touch this track. Click to untarget" : "Not targeted — edits skip this track. Click to target"; } const lBtn = head.querySelector(".track-lock"); if (lBtn) { lBtn.setAttribute("aria-pressed", locked ? "true" : "false"); lBtn.classList.toggle("on", locked); lBtn.title = locked ? "Unlock track" : "Lock track — nothing on it can be edited or moved"; } } if (row) { row.classList.toggle("disabled", !on); row.classList.toggle("solo", solo); row.classList.toggle("locked", locked); } syncMixerStrip(id); } function syncAllTrackDisabledUI() { for (const t of TRACKS) syncTrackDisabledUI(t.id); } function clearTrackSolo({ restore = false } = {}) { if (!state.soloId) return; if (restore && Array.isArray(state.soloRestore)) { state.disabledTracks = new Set(state.soloRestore.filter((id) => TRACK_IDS.has(id))); project.disabledTracks = [...state.disabledTracks].sort(); } state.soloId = null; state.soloRestore = null; } function toggleTrackSolo(id) { if (!TRACK_IDS.has(id)) return; if (state.soloId === id) { clearTrackSolo({ restore: true }); } else { if (!state.soloId) state.soloRestore = [...state.disabledTracks]; state.soloId = id; state.disabledTracks = new Set(TRACKS.filter((t) => t.id !== id).map((t) => t.id)); project.disabledTracks = [...state.disabledTracks].sort(); } syncAllTrackDisabledUI(); scheduleSave(); } function toggleTrackEnabled(id) { if (!TRACK_IDS.has(id)) return; // Manual mute exits solo without restoring the pre-solo snapshot if (state.soloId) clearTrackSolo({ restore: false }); if (state.disabledTracks.has(id)) state.disabledTracks.delete(id); else state.disabledTracks.add(id); project.disabledTracks = [...state.disabledTracks].sort(); syncAllTrackDisabledUI(); scheduleSave(); } function toggleTrackLocked(id) { if (!TRACK_IDS.has(id)) return; if (state.lockedTracks.has(id)) state.lockedTracks.delete(id); else state.lockedTracks.add(id); project.lockedTracks = [...state.lockedTracks].sort(); syncAllTrackDisabledUI(); state.dirtyTimeline = true; // clips on the lane redraw with the lock hatch renderInspector(); scheduleSave(); } function toggleTrackTargeted(id) { if (!TRACK_IDS.has(id)) return; if (state.untargetedTracks.has(id)) state.untargetedTracks.delete(id); else state.untargetedTracks.add(id); project.untargetedTracks = [...state.untargetedTracks].sort(); syncAllTrackDisabledUI(); scheduleSave(); } const runtime = { clipEls: new Map(), // clipId -> HTMLMediaElement clipGain: new Map(), // clipId -> GainNode mediaAux: new Map(), // mediaId -> {img?, thumb?, svgText?, svgAnimated?} audioBufs: new Map(), // media src -> Promise (waveforms + export mix); by file, so a relinked entry decodes its new one wavePeaks: new Map(), // mediaId -> {src, channels: Float32Array[], max: Float32Array} | Float32Array (legacy) | {src, pending} library: {}, // dir -> [{name, rel, src, size}] cached /api/library results customFonts: [], // family names loaded from /library/fonts libraryFontReq: new Set(), // library families claimed by a load pass googleLoaded: new Set(), // loaded from Google Fonts (the font picker lists them) fontReq: new Map(), // font name -> Promise (ensureFont) undo: [], redo: [], seqUndo: new Map(), // sequence id -> {undo, redo, time, sel}: each sequence keeps its own undo history this session seqOpen: null, // the open sequence's id, to notice another one being opened audio: null, // {ctx, master (sum), masterOut (fader), trackBus, recDest, meter?, meterReady?} saveTimer: null, pendingSync: false, sfxPreview: null, //