fablecut 1.14.0 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/app.js CHANGED
@@ -438,6 +438,7 @@ function showClipCtxMenu(clientX, clientY, c) {
438
438
  item("Parent to a new null", "", parentSelectionToNull, locked ? "Locked — unlock to change" : null);
439
439
  item("Precompose", "", precomposeSelection, locked ? "Locked — unlock to change" : null);
440
440
  if (c.kind === "comp") item("Open composition", "", () => enterComp(c.compId, c));
441
+ if (c.mediaId || c.kind === "comp") item("Reveal in project", "", () => revealInProject(c));
441
442
  const linked = selectedClips().some((x) => x.linkGroup || x.linkedId);
442
443
  if (linked) item("Unlink audio / video", "Ctrl+L", toggleLinkSelected, locked ? "Locked — unlock to change" : null);
443
444
  else if (c.kind === "video" || c.kind === "audio") {
@@ -467,10 +468,13 @@ const SETTINGS_KEY = "fablecut-settings";
467
468
  const DEFAULT_SETTINGS = {
468
469
  linkSelect: false, // timeline ↔ project bin selection sync
469
470
  encodeProfile: null, // null = server default from encoding-profiles.json
471
+ exportKind: null, // "delivery" | "profile" — what the Export dialog last used
472
+ delivery: null, // last delivery spec used in the Export dialog (delivery.js)
470
473
  // WebCodecs has no CRF — bitrate (Mbps) + constant|variable mode
471
474
  webCodecsBitrateMbps: null, // null = auto from canvas size
472
475
  webCodecsBitrateMode: "variable", // "variable" | "constant"
473
476
  snapTargets: { clips: true, playhead: true, markers: true, inout: true, keyframes: false, frames: true },
477
+ useProxies: true, // play proxies (when a file has one) while editing; export always reads the original
474
478
  };
475
479
  let settings = { ...DEFAULT_SETTINGS };
476
480
  function loadSettings() {
@@ -529,6 +533,8 @@ const project = {
529
533
  untargetedTracks: [], // track ids edits skip (split, insert, ripple, close gap…)
530
534
  exportFrame: null, // optional {x,y,w,h} delivery crop inside width×height canvas
531
535
  encodeProfile: null, // optional fast-export profile id (overrides browser setting)
536
+ delivery: null, // optional delivery spec (delivery.js) — the default for exports, agents' included
537
+ outputs: null, // optional batch outputs: [{id, on, …delivery spec}] — one render, several files
532
538
  tracks: null, // optional [{id, kind, gain?, pan?}] — null means default V3…V1 + A1…A4
533
539
  master: null, // optional {gain} — master bus fader (dB)
534
540
  buses: [], // submix buses [{id:"B1", name?, gain?, pan?, mute?, fx?}]; tracks[].out routes into one
@@ -729,14 +735,16 @@ const runtime = {
729
735
  clipEls: new Map(), // clipId -> HTMLMediaElement
730
736
  clipGain: new Map(), // clipId -> GainNode
731
737
  mediaAux: new Map(), // mediaId -> {img?, thumb?, svgText?, svgAnimated?}
732
- audioBufs: new Map(), // mediaId -> Promise<AudioBuffer> (waveforms + export mix)
733
- wavePeaks: new Map(), // mediaId -> {channels: Float32Array[], max: Float32Array} | Float32Array (legacy) | null (pending)
738
+ audioBufs: new Map(), // media src -> Promise<AudioBuffer> (waveforms + export mix); by file, so a relinked entry decodes its new one
739
+ wavePeaks: new Map(), // mediaId -> {src, channels: Float32Array[], max: Float32Array} | Float32Array (legacy) | {src, pending}
734
740
  library: {}, // dir -> [{name, rel, src, size}] cached /api/library results
735
741
  customFonts: [], // family names loaded from /library/fonts
736
742
  libraryFontReq: new Set(), // library families claimed by a load pass
737
743
  googleLoaded: new Set(), // loaded from Google Fonts (the font picker lists them)
738
744
  fontReq: new Map(), // font name -> Promise<boolean> (ensureFont)
739
745
  undo: [], redo: [],
746
+ seqUndo: new Map(), // sequence id -> {undo, redo, time, sel}: each sequence keeps its own undo history this session
747
+ seqOpen: null, // the open sequence's id, to notice another one being opened
740
748
  audio: null, // {ctx, master (sum), masterOut (fader), trackBus, recDest, meter?, meterReady?}
741
749
  saveTimer: null, pendingSync: false,
742
750
  sfxPreview: null, // <audio> element for library sound previews
@@ -757,6 +765,8 @@ const $ = (id) => document.getElementById(id);
757
765
  const els = {
758
766
  binList: $("binList"), binEmpty: $("binEmpty"), fileInput: $("fileInput"),
759
767
  binTabs: $("binTabs"), libList: $("libList"), toast: $("toast"),
768
+ binTools: $("binTools"), binSearch: $("binSearch"), binFilter: $("binFilter"), binSort: $("binSort"),
769
+ binSortDir: $("binSortDir"), binViewBtn: $("binViewBtn"), btnProxy: $("btnProxy"),
760
770
  preview: $("preview"), tcCurrent: $("tcCurrent"), tcTotal: $("tcTotal"),
761
771
  tcIo: $("tcIo"), tcIn: $("tcIn"), tcOut: $("tcOut"), tcDur: $("tcDur"),
762
772
  btnPlay: $("btnPlay"), inspector: $("inspector"),
@@ -1187,6 +1197,8 @@ async function connectServer() {
1187
1197
  applyProject(data);
1188
1198
  state.connected = true;
1189
1199
  els.projectName.textContent = project.name + " · 🟢 connected";
1200
+ runtime.projectId = res.headers.get("X-FableCut-Project");
1201
+ if (res.headers.get("X-FableCut-Projects")) initProjectsUi();
1190
1202
  listenSSE();
1191
1203
  fetch("/api/export/ffmpeg").then((r) => r.json())
1192
1204
  .then((j) => { state.ffmpeg = !!j.available; }).catch(() => { });
@@ -1196,6 +1208,7 @@ async function connectServer() {
1196
1208
  state.connected = false;
1197
1209
  els.projectName.textContent = project.name + " · ⚪ local session";
1198
1210
  }
1211
+ initSequencesUi();
1199
1212
  await probeMissingMeta();
1200
1213
  }
1201
1214
  /* Main-profile AVC level by canvas height; Annex-B is required so ffmpeg
@@ -1238,6 +1251,23 @@ function normalizeWorkArea(i, o, t0 = TIMELINE_START_TIME) {
1238
1251
  }
1239
1252
  return { inPoint, outPoint };
1240
1253
  }
1254
+ /* Project-bin media management: metadata, search / filter / sort, tags,
1255
+ collections and usage live in media-lib.js (shared with the agent ops). */
1256
+ const MediaLib = self.FableCutMedia;
1257
+ const BIN_PREFS_KEY = "fablecut.binPrefs";
1258
+ const binView = (() => {
1259
+ let saved = {};
1260
+ try { saved = JSON.parse(localStorage.getItem(BIN_PREFS_KEY) || "{}") || {}; } catch { }
1261
+ return {
1262
+ q: "", filter: "", // per session: search text and the "Show" filter
1263
+ sort: MediaLib.SORT_KEYS.includes(saved.sort) ? saved.sort : "name",
1264
+ dir: saved.dir === "desc" ? "desc" : "asc",
1265
+ list: saved.list === true, // list view: metadata columns
1266
+ };
1267
+ })();
1268
+ function saveBinPrefs() {
1269
+ try { localStorage.setItem(BIN_PREFS_KEY, JSON.stringify({ sort: binView.sort, dir: binView.dir, list: binView.list })); } catch { }
1270
+ }
1241
1271
  function getFolder(id) {
1242
1272
  return id ? project.folders.find((f) => f.id === id) : null;
1243
1273
  }
@@ -1261,17 +1291,20 @@ function normalizeFolders(list) {
1261
1291
  }
1262
1292
  function normalizeMediaEntry(m) {
1263
1293
  if (!m || typeof m !== "object") return m;
1264
- return { ...m, folderId: m.folderId || null };
1294
+ const out = { ...m, folderId: m.folderId || null };
1295
+ const tags = MediaLib.normalizeTags(m.tags);
1296
+ if (tags.length) out.tags = tags; else delete out.tags;
1297
+ if (out.favorite !== true) delete out.favorite;
1298
+ return out;
1265
1299
  }
1266
1300
  function folderChildren(parentId) {
1267
1301
  return project.folders
1268
1302
  .filter((f) => (f.parentId || null) === (parentId || null))
1269
1303
  .sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: "base" }));
1270
1304
  }
1271
- function mediaInFolder(folderId) {
1272
- return project.media
1273
- .filter((m) => (m.folderId || null) === (folderId || null))
1274
- .sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: "base" }));
1305
+ function mediaInFolder(folderId, ctx) {
1306
+ return MediaLib.sortMedia(project.media.filter((m) => (m.folderId || null) === (folderId || null)),
1307
+ binView.sort, binView.dir, ctx);
1275
1308
  }
1276
1309
  /* True if ancestorId is the same as nodeId or an ancestor of nodeId. */
1277
1310
  function isSelfOrFolderAncestor(ancestorId, nodeId) {
@@ -1418,6 +1451,14 @@ function syncExportFrameSel() {
1418
1451
  els.exportFrameSel.innerHTML = html;
1419
1452
  }
1420
1453
  function applyProject(data, opts = {}) {
1454
+ if (state.compCtx && !opts.ctx && SeqLib.activeId(data) !== SeqLib.activeId(state.compCtx.root)) {
1455
+ // another sequence was opened (an agent, another tab): the comp was opened from the old one
1456
+ state.compCtx = null;
1457
+ runtime.undo.length = 0; runtime.redo.length = 0;
1458
+ applyProject(data, { ctx: true });
1459
+ syncCompCrumb();
1460
+ return;
1461
+ }
1421
1462
  if (state.compCtx && !opts.ctx) { // the root changed on disk (an agent, another tab): keep the open comp open
1422
1463
  const x = state.compCtx;
1423
1464
  x.root = data;
@@ -1430,6 +1471,7 @@ function applyProject(data, opts = {}) {
1430
1471
  syncCompCrumb();
1431
1472
  return;
1432
1473
  }
1474
+ if (!state.compCtx) noteOpenSequence(data);
1433
1475
  const wa = normalizeWorkArea(data.inPoint, data.outPoint);
1434
1476
  Object.assign(project, {
1435
1477
  name: data.name || "Untitled Project",
@@ -1439,14 +1481,20 @@ function applyProject(data, opts = {}) {
1439
1481
  revision: data.revision || 0,
1440
1482
  folders: normalizeFolders(data.folders),
1441
1483
  media: (data.media || []).map(normalizeMediaEntry),
1484
+ collections: MediaLib.normalizeCollections(data.collections, data.media || []),
1442
1485
  clips: data.clips || [],
1443
1486
  markers: normalizeMarkers(data.markers),
1444
1487
  inPoint: wa.inPoint,
1445
1488
  outPoint: wa.outPoint,
1446
1489
  exportFrame: normalizeExportFrame(data.exportFrame, data.width || 1280, data.height || 720),
1447
1490
  encodeProfile: data.encodeProfile || null,
1491
+ delivery: data.delivery && typeof data.delivery === "object" ? data.delivery : null,
1492
+ outputs: Array.isArray(data.outputs) ? data.outputs.filter((o) => o && typeof o === "object") : null,
1448
1493
  master: normalizeMaster(data.master),
1449
1494
  buses: normalizeBuses(data.buses),
1495
+ // the sequences that aren't open, kept as they are (see sequences.js); the open one is this document
1496
+ sequences: Array.isArray(data.sequences) && data.sequences.length ? data.sequences : null,
1497
+ sequence: Array.isArray(data.sequences) && data.sequences.length ? SeqLib.activeId(data) : null,
1450
1498
  comps: (Array.isArray(data.comps) ? data.comps : []).filter((cp) => cp && cp.id).map((cp) => ({
1451
1499
  ...cp, clips: (cp.clips || []).map((x) => {
1452
1500
  if (x.keyframes) for (const arr of Object.values(x.keyframes)) if (Array.isArray(arr)) arr.sort((a, b) => a.t - b.t);
@@ -1525,19 +1573,38 @@ function scheduleSave() {
1525
1573
  state.dirtyTimeline = true;
1526
1574
  if (!state.connected) return;
1527
1575
  clearTimeout(runtime.saveTimer);
1528
- runtime.saveTimer = setTimeout(async () => {
1529
- runtime.saveTimer = null;
1530
- project.revision++;
1531
- const body = JSON.stringify(projectJSON(), null, 2);
1532
- try {
1533
- const res = await fetch("/api/project", { method: "PUT", headers: { "Content-Type": "application/json" }, body });
1534
- if (res.status === 409) {
1535
- // an external tool saved a newer revision while this change was pending
1536
- await syncFromServer(true);
1537
- toast("Project was updated externally — your last change may need redoing.");
1538
- }
1539
- } catch { }
1540
- }, 400);
1576
+ runtime.saveTimer = setTimeout(() => { runtime.saveTimer = null; runtime.saving = saveNow(); }, 400);
1577
+ }
1578
+ async function saveNow() {
1579
+ project.revision++;
1580
+ const body = JSON.stringify(projectJSON(), null, 2);
1581
+ try {
1582
+ const headers = { "Content-Type": "application/json" };
1583
+ if (runtime.projectId) headers["X-FableCut-Project"] = runtime.projectId; // the project this edit belongs to
1584
+ const res = await fetch("/api/project", { method: "PUT", headers, body });
1585
+ if (res.status === 409) {
1586
+ // an external tool saved a newer revision while this change was pending
1587
+ const loaded = await syncFromServer(true);
1588
+ toast("Project was updated externally — your last change may need redoing.");
1589
+ runtime.saveFailed = loaded !== true;
1590
+ return loaded === true; // the newer document on disk is now what this tab shows
1591
+ }
1592
+ runtime.saveFailed = !res.ok;
1593
+ return res.ok;
1594
+ } catch { runtime.saveFailed = true; return false; }
1595
+ }
1596
+ /** Write a pending edit now (and wait for one in flight), e.g. before switching projects.
1597
+ * False when that save did not land. */
1598
+ async function flushSave() {
1599
+ try { await runtime.saving; } catch { }
1600
+ // a pending edit, or one whose last save did not land: send it (again) now
1601
+ if (runtime.saveTimer || runtime.saveFailed) { clearTimeout(runtime.saveTimer); runtime.saveTimer = null; runtime.saving = saveNow(); }
1602
+ try { return (await runtime.saving) !== false; } catch { return false; }
1603
+ }
1604
+ async function flushSaveBeforeSwitch() {
1605
+ if (await flushSave()) return true;
1606
+ toast("Your last change couldn't be saved, so the project stays open. Try again in a moment.");
1607
+ return false;
1541
1608
  }
1542
1609
  /** One clip as saved: only the fields the editor knows (unknown runtime fields stay out). */
1543
1610
  function serializeClip({ id, mediaId, kind, compId, track, start, in: inn, duration, name, props, keyframes, transitionIn, transitionOut, linkedId, linkGroup, locked, disabled, unlinked, fx, parent }) {
@@ -1561,15 +1628,19 @@ function projectJSON() {
1561
1628
  }
1562
1629
  /** The project as it is loaded right now (an open comp's stand-in project, or the root). */
1563
1630
  function projectJSONHere() {
1564
- const { name, width, height, fps, background, revision, folders, media, clips, markers, inPoint, outPoint, disabledTracks, encodeProfile } = project;
1631
+ const { name, width, height, fps, background, revision, folders, media, clips, markers, inPoint, outPoint, disabledTracks, encodeProfile, delivery, outputs } = project;
1565
1632
  const out = {
1566
1633
  name, width, height, fps, background, revision,
1567
1634
  panSchema: 1,
1568
1635
  folders: (folders || []).map(({ id, name, parentId, open }) =>
1569
1636
  ({ id, name, parentId: parentId || null, open: open !== false })),
1570
1637
  tracks: serializeTracks(),
1571
- media: media.filter((m) => !m.transient).map(({ id, name, kind, src, duration, width, height, folderId, derivedFrom, denoise }) => {
1638
+ media: media.filter((m) => !m.transient).map((m) => {
1639
+ const { id, name, kind, src, duration, width, height, folderId, derivedFrom, denoise } = m;
1572
1640
  const mo = { id, name, kind, src, duration, width, height, folderId: folderId || null };
1641
+ for (const k of MediaLib.INFO_KEYS) if (m[k] != null) mo[k] = m[k];
1642
+ if (m.favorite === true) mo.favorite = true;
1643
+ if (m.tags && m.tags.length) mo.tags = m.tags.slice();
1573
1644
  if (derivedFrom) { mo.derivedFrom = derivedFrom; if (denoise) mo.denoise = denoise; }
1574
1645
  return mo;
1575
1646
  }),
@@ -1579,6 +1650,8 @@ function projectJSONHere() {
1579
1650
  outPoint: outPoint == null ? null : outPoint,
1580
1651
  disabledTracks: normalizeDisabledTracks(disabledTracks),
1581
1652
  };
1653
+ const collections = MediaLib.normalizeCollections(project.collections, out.media);
1654
+ if (collections.length) out.collections = collections;
1582
1655
  const locked = normalizeDisabledTracks(project.lockedTracks);
1583
1656
  const untargeted = normalizeDisabledTracks(project.untargetedTracks);
1584
1657
  if (locked.length) out.lockedTracks = locked;
@@ -1586,20 +1659,54 @@ function projectJSONHere() {
1586
1659
  const ef = getExportFrame();
1587
1660
  if (ef) out.exportFrame = ef;
1588
1661
  if (encodeProfile) out.encodeProfile = encodeProfile;
1662
+ if (delivery) out.delivery = delivery;
1663
+ if (outputs && outputs.length) out.outputs = outputs;
1589
1664
  const master = normalizeMaster(project.master);
1590
1665
  if (master) out.master = master;
1591
1666
  const buses = normalizeBuses(project.buses);
1592
1667
  if (buses.length) out.buses = buses;
1593
1668
  if (project.comps && project.comps.length) out.comps = project.comps.map((cp) => ({ ...cp, clips: (cp.clips || []).map(serializeClip) }));
1669
+ if (project.sequences) {
1670
+ out.sequences = project.sequences.map((sq) => (sq.id === project.sequence ? { id: sq.id, name: sq.name } : sq));
1671
+ out.sequence = project.sequence;
1672
+ }
1594
1673
  return out;
1595
1674
  }
1596
1675
  function listenSSE() {
1597
1676
  const es = new EventSource("/api/events");
1598
1677
  // Named events: "change" = project/media/library; "profiles" = encoding-profiles.json only
1599
- es.addEventListener("change", () => syncFromServer());
1678
+ es.addEventListener("change", () => { noteActivity(); syncFromServer(); scheduleOfflineCheck(); });
1679
+ es.addEventListener("proxy", (e) => onProxyEvent(e.data));
1680
+ es.addEventListener("versions", (e) => {
1681
+ let d = {};
1682
+ try { d = JSON.parse(e.data); } catch { }
1683
+ if (!(projectsOpen() && pj.verOf && d.project === pj.verOf)) return;
1684
+ if (pj.busy) { pj.verPending = true; return; } // pjVersionAction refreshes when it is done
1685
+ if (document.querySelector(".ver-rename")) return; // a rename is being typed: it refreshes the list when it ends
1686
+ pjDropDiffs(); // a comparison made before this change no longer holds
1687
+ pjLoadVersions();
1688
+ });
1689
+ es.addEventListener("projects", (e) => {
1690
+ let d = {};
1691
+ try { d = JSON.parse(e.data); } catch { }
1692
+ if (d.active && runtime.projectId && d.active !== runtime.projectId) syncFromServer(true);
1693
+ else if (projectsOpen() && !pj.busy) pjLoad();
1694
+ });
1600
1695
  es.addEventListener("export", (e) => {
1696
+ noteActivity();
1601
1697
  try { runExportJob(JSON.parse(e.data)); } catch { }
1602
1698
  });
1699
+ es.addEventListener("delivery-presets", () => {
1700
+ fetchDeliveryInfo().then(() => {
1701
+ if (els.exportSetup && !els.exportSetup.classList.contains("hidden")) {
1702
+ const keep = els.exportProfileSel.value;
1703
+ populateExportProfileSelect();
1704
+ els.exportProfileSel.value = keep;
1705
+ if (els.exportProfileSel.value !== keep) els.exportProfileSel.value = "d:" + Delivery.DEFAULT_PRESET;
1706
+ syncExportChoiceUi(dlvSource);
1707
+ }
1708
+ });
1709
+ });
1603
1710
  es.addEventListener("profiles", () => {
1604
1711
  fetchEncodeProfiles().then(() => {
1605
1712
  if (els.exportSetup && !els.exportSetup.classList.contains("hidden"))
@@ -1607,25 +1714,46 @@ function listenSSE() {
1607
1714
  });
1608
1715
  });
1609
1716
  // Legacy default "message" events (old servers that emit bare `data:`)
1610
- es.onmessage = () => syncFromServer();
1717
+ es.onmessage = () => { noteActivity(); syncFromServer(); };
1611
1718
  }
1612
1719
  /* Pull the server's project if it moved past our revision (an external tool —
1613
1720
  e.g. Claude — wrote it). Our own saves land at our exact local revision, so
1614
1721
  they compare equal and are skipped without any timing heuristics. Deferred
1615
1722
  during gestures/exports and re-run when they end (runtime.pendingSync). */
1723
+ /** True when the server's document was loaded (a later caller may rely on it). */
1616
1724
  async function syncFromServer(force) {
1617
- if (state.gesture || state.exporting) { runtime.pendingSync = true; return; }
1725
+ if (state.gesture || state.exporting) { runtime.pendingSync = true; return false; }
1618
1726
  runtime.pendingSync = false;
1619
1727
  if (state.binTab === "templates") fetchSaved("templates").then(() => { if (state.binTab === "templates") renderTemplatesTab(); });
1620
1728
  else if (state.binTab !== "project" && state.binTab !== "shapes") fetchLibrary(state.binTab).then(renderLibrary);
1621
1729
  fetchSaved("presets");
1622
1730
  loadLibraryFonts();
1623
1731
  fetchEncodeProfiles();
1732
+ const seq = runtime.syncSeq = (runtime.syncSeq || 0) + 1;
1624
1733
  try {
1625
1734
  const res = await fetch("/api/project", { cache: "no-store" });
1626
1735
  if (!res.ok) return;
1627
1736
  const data = await res.json();
1737
+ if (seq !== runtime.syncSeq) return; // a newer reload is on its way: this answer may be older than it
1628
1738
  if (!data || !Array.isArray(data.clips)) return;
1739
+ // another project was opened (the dashboard, another tab, an agent)
1740
+ const pid = res.headers.get("X-FableCut-Project");
1741
+ const switched = !!(pid && runtime.projectId && pid !== runtime.projectId);
1742
+ if (pid) runtime.projectId = pid;
1743
+ if (switched) {
1744
+ onProjectSwitched();
1745
+ applyProject(data);
1746
+ { // decoded audio is by file: keep what this project uses, free the rest
1747
+ const srcs = new Set(project.media.map((m) => m.src));
1748
+ for (const src of [...runtime.audioBufs.keys()]) if (!srcs.has(src)) runtime.audioBufs.delete(src);
1749
+ }
1750
+ setTime(0);
1751
+ syncCompCrumb();
1752
+ if (!pj.selfSwitch) toast(`Switched to “${project.name}”`);
1753
+ if (projectsOpen()) pjLoad();
1754
+ await probeMissingMeta();
1755
+ return true;
1756
+ }
1629
1757
  if (!force && (data.revision || 0) === (project.revision || 0)) return; // our own save
1630
1758
  if (runtime.saveTimer) { // unsaved local edit vs. external write: external wins, tell the user
1631
1759
  clearTimeout(runtime.saveTimer); runtime.saveTimer = null;
@@ -1634,8 +1762,14 @@ async function syncFromServer(force) {
1634
1762
  toast("Project was updated externally — your last change may need redoing.");
1635
1763
  }
1636
1764
  applyProject(data);
1765
+ syncCompCrumb(); // the top bar shows the project's name
1766
+ // "Compare with now" was against the document before this change
1767
+ // (always: a comparison still on its way was made against the old document too)
1768
+ if (pj.verOf === runtime.projectId) { const had = pj.verDiff.size; pjDropDiffs(); if (had && projectsOpen()) renderProjectGrid(); }
1637
1769
  await probeMissingMeta();
1770
+ return true;
1638
1771
  } catch { }
1772
+ return false;
1639
1773
  }
1640
1774
  /** Populate a media entry's duration/dimensions (and cache preview assets) by
1641
1775
  * dispatching on kind: svg loads its markup, image loads for width/height,
@@ -1645,8 +1779,10 @@ async function syncFromServer(force) {
1645
1779
  async function loadMediaMetadata(m) {
1646
1780
  if (m.kind === "svg") { await loadSvgMedia(m); return; }
1647
1781
  if (m.kind === "image") {
1782
+ const gen = runtime.projectGen;
1648
1783
  const img = await loadImage(m.src);
1649
- runtime.mediaAux.set(m.id, { ...(runtime.mediaAux.get(m.id) || {}), img });
1784
+ if (gen !== runtime.projectGen) return; // another project was opened meanwhile
1785
+ runtime.mediaAux.set(m.id, { ...(runtime.mediaAux.get(m.id) || {}), img, imgSrc: m.src });
1650
1786
  m.width = img.naturalWidth; m.height = img.naturalHeight;
1651
1787
  return;
1652
1788
  }
@@ -1673,6 +1809,9 @@ async function probeMissingMeta() {
1673
1809
  }
1674
1810
  if (changed) { renderBin(); scheduleSave(); }
1675
1811
  state.dirtyTimeline = true;
1812
+ refreshMediaInfo();
1813
+ scheduleOfflineCheck(0);
1814
+ syncProxyButton();
1676
1815
  }
1677
1816
  function probeAV(src, kind) {
1678
1817
  return new Promise((resolve, reject) => {
@@ -1697,6 +1836,7 @@ function loadImage(src) {
1697
1836
  });
1698
1837
  }
1699
1838
  async function grabThumb(m) {
1839
+ const gen = runtime.projectGen;
1700
1840
  const v = document.createElement("video");
1701
1841
  v.muted = true; v.preload = "auto";
1702
1842
  if (isCrossOriginSrc(m.src)) v.crossOrigin = "anonymous";
@@ -1707,6 +1847,7 @@ async function grabThumb(m) {
1707
1847
  const c = document.createElement("canvas");
1708
1848
  c.width = 160; c.height = 90;
1709
1849
  c.getContext("2d").drawImage(v, 0, 0, 160, 90);
1850
+ if (gen !== runtime.projectGen) { v.src = ""; return; }
1710
1851
  runtime.mediaAux.set(m.id, { ...(runtime.mediaAux.get(m.id) || {}), thumb: c.toDataURL("image/jpeg", 0.6) });
1711
1852
  v.src = "";
1712
1853
  renderBin(); state.dirtyTimeline = true;
@@ -1718,20 +1859,24 @@ function getDecodeCtx() {
1718
1859
  return decodeCtx || (decodeCtx = new (window.AudioContext || window.webkitAudioContext)());
1719
1860
  }
1720
1861
  function getAudioBuffer(m) {
1721
- let p = runtime.audioBufs.get(m.id);
1862
+ const src = m.src;
1863
+ let p = runtime.audioBufs.get(src);
1722
1864
  if (!p) {
1723
- p = fetch(m.src).then((r) => r.arrayBuffer())
1865
+ p = fetch(src).then((r) => r.arrayBuffer())
1724
1866
  .then((ab) => getDecodeCtx().decodeAudioData(ab));
1725
- runtime.audioBufs.set(m.id, p);
1726
- p.catch(() => runtime.audioBufs.delete(m.id));
1867
+ runtime.audioBufs.set(src, p);
1868
+ p.catch(() => runtime.audioBufs.delete(src));
1727
1869
  }
1728
1870
  return p;
1729
1871
  }
1730
1872
  function ensureWave(m) {
1731
1873
  // Also decode peaks from video files when their audio is placed on an A track
1732
- if ((m.kind !== "audio" && m.kind !== "video") || runtime.wavePeaks.has(m.id)) return;
1733
- runtime.wavePeaks.set(m.id, null); // pending
1874
+ if (m.kind !== "audio" && m.kind !== "video") return;
1875
+ const have = runtime.wavePeaks.get(m.id), src = m.src;
1876
+ if (have && (have instanceof Float32Array || have.src === src)) return;
1877
+ runtime.wavePeaks.set(m.id, { src, pending: true });
1734
1878
  getAudioBuffer(m).then((buf) => {
1879
+ if (runtime.wavePeaks.get(m.id)?.src !== src) return; // the entry points at another file now (relink, another project)
1735
1880
  const n = Math.max(1, Math.ceil(buf.duration * WAVE_PEAKS_PER_SEC));
1736
1881
  const step = buf.length / n;
1737
1882
  const channels = [];
@@ -1753,10 +1898,10 @@ function ensureWave(m) {
1753
1898
  for (const p of channels) if (p[i] > mx) mx = p[i];
1754
1899
  max[i] = mx;
1755
1900
  }
1756
- runtime.wavePeaks.set(m.id, { channels, max });
1901
+ runtime.wavePeaks.set(m.id, { src, channels, max });
1757
1902
  if (m.channels == null) m.channels = buf.numberOfChannels;
1758
1903
  state.dirtyTimeline = true;
1759
- }).catch(() => runtime.wavePeaks.delete(m.id));
1904
+ }).catch(() => { if (runtime.wavePeaks.get(m.id)?.src === src) runtime.wavePeaks.delete(m.id); });
1760
1905
  }
1761
1906
  function wavePeaksFor(c) {
1762
1907
  const w = runtime.wavePeaks.get(c.mediaId);
@@ -1791,7 +1936,7 @@ async function importFiles(fileList) {
1791
1936
  ? runtime.importFolderId : null;
1792
1937
  runtime.importFolderId = null;
1793
1938
  let added = 0, skipped = 0;
1794
- const addedMedia = [];
1939
+ const addedMedia = [], gen = runtime.projectGen;
1795
1940
  for (const file of files) {
1796
1941
  const kind = mediaKindFromFile(file);
1797
1942
  if (!kind) { skipped++; continue; }
@@ -1811,11 +1956,13 @@ async function importFiles(fileList) {
1811
1956
  if (kind === "video") grabThumb(m).catch(() => { });
1812
1957
  ensureWave(m);
1813
1958
  } catch { skipped++; continue; }
1959
+ if (gen !== runtime.projectGen) { toast("Import stopped: another project was opened. The uploaded files are in media/"); break; }
1814
1960
  project.media.push(m);
1815
1961
  addedMedia.push(m);
1816
1962
  added++;
1817
1963
  }
1818
1964
  renderBin(); scheduleSave();
1965
+ refreshMediaInfo(addedMedia);
1819
1966
  if (!added && skipped)
1820
1967
  toast("Couldn't import — unsupported or unreadable file type");
1821
1968
  else if (skipped)
@@ -1860,6 +2007,7 @@ async function importFromUrl(url) {
1860
2007
  if (!state.connected) { toast("Import from URL needs the editor server"); return; }
1861
2008
  runtime.importUrlAbort = new AbortController();
1862
2009
  setImportUrlBusy(true);
2010
+ const gen = runtime.projectGen;
1863
2011
  try {
1864
2012
  const res = await fetch("/api/import-url", {
1865
2013
  method: "POST",
@@ -1880,6 +2028,7 @@ async function importFromUrl(url) {
1880
2028
  if (kind === "video") grabThumb(m).catch(() => { });
1881
2029
  ensureWave(m);
1882
2030
  } catch { /* browser will retry via probeMissingMeta */ }
2031
+ if (gen !== runtime.projectGen) throw new Error("another project was opened — the file is in media/");
1883
2032
  project.media.push(m);
1884
2033
  renderBin(); scheduleSave();
1885
2034
  closeImportUrl();
@@ -1894,12 +2043,24 @@ async function importFromUrl(url) {
1894
2043
  }
1895
2044
 
1896
2045
  function renderBin() {
1897
- els.binList.querySelectorAll(".bin-item, .bin-folder, .bin-drop-root, .comp-item").forEach((n) => n.remove());
2046
+ els.binList.querySelectorAll(".bin-item, .bin-folder, .bin-drop-root, .comp-item, .bin-filterbar, .bin-colhead, .bin-noresult").forEach((n) => n.remove());
2047
+ syncBinTools();
1898
2048
  const comps = project.comps || [];
1899
2049
  const empty = !project.media.length && !project.folders.length && !comps.length;
1900
2050
  els.binEmpty.style.display = empty ? "" : "none";
2051
+ els.binList.classList.toggle("list-view", binView.list && !empty);
1901
2052
  if (empty) return;
1902
- for (const comp of comps) els.binList.appendChild(makeCompItem(comp));
2053
+ const ctx = binCtx();
2054
+ const flat = !!(binView.q.trim() || binView.filter); // searching / filtering → one flat list of hits
2055
+ if (mediaOffline.size && binView.filter !== "offline") {
2056
+ const warn = document.createElement("div");
2057
+ warn.className = "bin-filterbar bin-offline-bar";
2058
+ warn.innerHTML = `<span>⚠ ${mediaOffline.size} file${mediaOffline.size === 1 ? " is" : "s are"} offline</span>
2059
+ <button type="button" class="btn tiny" data-show>Show</button><button type="button" class="btn tiny accent" data-relink>Relink…</button>`;
2060
+ warn.querySelector("[data-show]").addEventListener("click", () => setBinFilter("offline"));
2061
+ warn.querySelector("[data-relink]").addEventListener("click", () => openRelinkDialog());
2062
+ els.binList.appendChild(warn);
2063
+ }
1903
2064
 
1904
2065
  const clearBinDropHints = () => {
1905
2066
  els.binList.querySelectorAll(".bin-drop-over").forEach((n) => n.classList.remove("bin-drop-over"));
@@ -1956,26 +2117,46 @@ function renderBin() {
1956
2117
 
1957
2118
  const makeMediaItem = (m, depth) => {
1958
2119
  const item = document.createElement("div");
1959
- item.className = "bin-item";
2120
+ const offline = isMediaOffline(m.id);
2121
+ item.className = "bin-item" + (binView.list ? " bin-row" : "") + (offline ? " offline" : "");
1960
2122
  item.draggable = true;
1961
2123
  item.dataset.mediaId = m.id;
1962
- item.style.setProperty("--bin-depth", depth);
2124
+ item.style.setProperty("--bin-depth", flat ? 0 : depth);
1963
2125
  const aux = runtime.mediaAux.get(m.id) || {};
1964
2126
  const icon = mediaKindIcon(m.kind, "🎞");
1965
2127
  const thumbSrc = aux.thumb || (m.kind === "image" || m.kind === "svg" ? m.src : null);
1966
- item.innerHTML = `
1967
- <div class="bin-thumb"></div>
1968
- <div class="bin-meta">
1969
- <div class="bin-name"></div>
1970
- <div class="bin-sub">${m.kind}${m.duration ? " · " + fmt(m.duration) : ""}</div>
1971
- </div>
1972
- <span class="bin-del" title="Remove (and its clips)">✕</span>`;
2128
+ const uses = ctx.usage.get(m.id) || 0;
2129
+ const folder = flat && m.folderId ? getFolder(m.folderId) : null;
2130
+ const usesHtml = `<button type="button" class="bin-uses${uses ? "" : " none"}" title="${uses ? `Used ${uses}× — click to find every instance` : "Not used on the timeline"}">${uses}</button>`;
2131
+ const favHtml = `<button type="button" class="bin-fav${m.favorite ? " on" : ""}" title="${m.favorite ? "Favorite — click to unstar" : "Mark as favorite"}" aria-pressed="${!!m.favorite}">${m.favorite ? "★" : "☆"}</button>`;
2132
+ if (binView.list) {
2133
+ const cell = (v, cls = "") => `<span class="bin-cell${cls}">${escapeHtml(v || "—")}</span>`;
2134
+ item.innerHTML = `
2135
+ <span class="bin-cell bin-cell-name">${favHtml}<span class="bin-thumb sm"></span>${offline ? `<span class="bin-offline" title="The file is missing — right-click → Relink…">OFFLINE</span>` : ""}<span class="bin-name"></span></span>
2136
+ ${cell(MediaLib.fmtDur(m.duration), " num c-duration")}${cell(MediaLib.fmtRes(m), " num c-resolution")}${cell(MediaLib.fmtFps(m.fps), " num c-fps")}
2137
+ ${cell(m.codec, " c-codec")}${cell(MediaLib.fmtAudio(m), " c-audio")}${cell(MediaLib.fmtSize(m.size), " num c-size")}
2138
+ <span class="bin-cell c-proxy">${proxyBadgeHtml(m) || escapeHtml(m.kind === "video" ? "—" : "")}</span>
2139
+ <span class="bin-cell num c-usage">${usesHtml}</span>
2140
+ <span class="bin-del" title="Remove (and its clips)">✕</span>`;
2141
+ } else {
2142
+ const sub = [folder ? "📁 " + folder.name : "", m.kind, m.duration ? fmt(m.duration) : "", MediaLib.fmtRes(m), m.fps ? MediaLib.fmtFps(m.fps) + " fps" : ""]
2143
+ .filter(Boolean).join(" · ");
2144
+ item.innerHTML = `
2145
+ <div class="bin-thumb"></div>
2146
+ <div class="bin-meta">
2147
+ <div class="bin-name"></div>
2148
+ <div class="bin-sub">${offline ? `<span class="bin-offline" title="The file is missing — right-click → Relink…">OFFLINE</span> ` : ""}${escapeHtml(sub)}</div>
2149
+ ${m.tags && m.tags.length ? `<div class="bin-tags">${m.tags.map((t) => `<span class="bin-tag">#${escapeHtml(t)}</span>`).join("")}</div>` : ""}
2150
+ </div>
2151
+ <div class="bin-side">${favHtml}${usesHtml}${proxyBadgeHtml(m)}</div>
2152
+ <span class="bin-del" title="Remove (and its clips)">✕</span>`;
2153
+ }
1973
2154
  const thumbEl = item.querySelector(".bin-thumb");
1974
2155
  if (thumbSrc) thumbEl.style.backgroundImage = `url(${JSON.stringify(thumbSrc)})`;
1975
2156
  else thumbEl.textContent = icon;
1976
2157
  const nameEl = item.querySelector(".bin-name");
1977
2158
  nameEl.textContent = m.name;
1978
- nameEl.title = m.name;
2159
+ item.title = [m.name, offline ? "⚠ Offline: " + decodeURIComponent(String(m.src).split("?")[0]) + " is missing — right-click → Relink…" : "", MediaLib.describe(m), m.tags && m.tags.length ? m.tags.map((t) => "#" + t).join(" ") : ""].filter(Boolean).join("\n");
1979
2160
  item.addEventListener("dragstart", (e) => {
1980
2161
  runtime.binDragFolderId = null;
1981
2162
  e.dataTransfer.setData("text/fablecut-media", m.id);
@@ -1990,13 +2171,14 @@ function renderBin() {
1990
2171
  // Don't bubble to the root drop zone while hovering a media row
1991
2172
  item.addEventListener("dragover", (e) => e.stopPropagation());
1992
2173
  item.addEventListener("click", (e) => {
1993
- if (e.target.closest(".bin-del")) return;
2174
+ if (e.target.closest(".bin-del, .bin-fav, .bin-uses")) return;
1994
2175
  if (e.ctrlKey || e.metaKey) return; // reserved for import
1995
2176
  if (!getSetting("linkSelect")) return;
1996
2177
  e.preventDefault();
1997
2178
  selectClipsByMediaId(m.id);
1998
2179
  });
1999
- item.addEventListener("dblclick", () => {
2180
+ item.addEventListener("dblclick", (e) => {
2181
+ if (e.target.closest(".bin-del, .bin-fav, .bin-uses")) return;
2000
2182
  // Double-click loads Source (single-click only selects when link-select is on).
2001
2183
  if (state.source.mediaId === m.id) {
2002
2184
  setMonitorMode("source");
@@ -2005,17 +2187,16 @@ function renderBin() {
2005
2187
  }
2006
2188
  if (getSetting("linkSelect")) flashMonitorAttention();
2007
2189
  });
2190
+ item.addEventListener("contextmenu", (e) => { e.preventDefault(); e.stopPropagation(); showMediaMenu(e.clientX, e.clientY, m); });
2191
+ item.querySelector(".bin-fav").addEventListener("click", (e) => { e.stopPropagation(); setMediaFavorite([m.id], !m.favorite); });
2192
+ item.querySelector(".bin-uses").addEventListener("click", (e) => {
2193
+ e.stopPropagation();
2194
+ const r = e.currentTarget.getBoundingClientRect();
2195
+ showMediaInstances(m, r.left, r.bottom + 4);
2196
+ });
2008
2197
  item.querySelector(".bin-del").addEventListener("click", (e) => {
2009
2198
  e.stopPropagation();
2010
- if (state.compCtx && (state.compCtx.root.clips || []).some((c) => c.mediaId === m.id)) { toast("It's used on the main timeline — go back to Main to delete it"); return; }
2011
- pushUndo(JSON.stringify({ clips: project.clips, markers: project.markers || [], comps: project.comps || [], media: project.media })); // undo brings the media back too
2012
- project.media = project.media.filter((x) => x.id !== m.id);
2013
- project.clips = project.clips.filter((c) => c.mediaId !== m.id);
2014
- // and its clips inside comps (and on the main timeline while a comp is open)
2015
- project.comps = (project.comps || []).map((cp) => ({ ...cp, clips: (cp.clips || []).filter((c) => c.mediaId !== m.id) }));
2016
- runtime.compGen = (runtime.compGen || 0) + 1;
2017
- if (state.source.mediaId === m.id) clearSource();
2018
- renderBin(); scheduleSave(); renderInspector();
2199
+ removeMediaFromBin(m);
2019
2200
  });
2020
2201
  return item;
2021
2202
  };
@@ -2074,20 +2255,789 @@ function renderBin() {
2074
2255
  els.binList.appendChild(row);
2075
2256
  if (f.open) renderLevel(f.id, depth + 1);
2076
2257
  }
2077
- for (const m of mediaInFolder(parentId)) els.binList.appendChild(makeMediaItem(m, depth));
2258
+ for (const m of mediaInFolder(parentId, ctx)) els.binList.appendChild(makeMediaItem(m, depth));
2078
2259
  };
2079
2260
 
2080
- renderLevel(null, 0);
2081
-
2082
- // Root drop zone at the bottom so items can be moved out of folders
2083
- const root = document.createElement("div");
2084
- root.className = "bin-drop-root";
2085
- root.textContent = "Drop here to move to root";
2086
- bindFolderDropTarget(root, null);
2087
- els.binList.appendChild(root);
2261
+ if (flat) {
2262
+ const hits = MediaLib.query(project.media, binView, ctx);
2263
+ els.binList.appendChild(makeFilterBar(hits.length));
2264
+ if (binView.list) els.binList.appendChild(makeColumnHead());
2265
+ const q = binView.q.trim().toLowerCase();
2266
+ if (!binView.filter) for (const comp of comps) if (q && String(comp.name).toLowerCase().includes(q)) els.binList.appendChild(makeCompItem(comp));
2267
+ for (const m of hits) els.binList.appendChild(makeMediaItem(m, 0));
2268
+ if (!hits.length) {
2269
+ const none = document.createElement("div");
2270
+ none.className = "bin-noresult";
2271
+ none.textContent = "No media matches.";
2272
+ els.binList.appendChild(none);
2273
+ }
2274
+ } else {
2275
+ if (binView.list) els.binList.appendChild(makeColumnHead());
2276
+ for (const comp of comps) els.binList.appendChild(makeCompItem(comp));
2277
+ renderLevel(null, 0);
2278
+ // Root drop zone at the bottom so items can be moved out of folders
2279
+ const root = document.createElement("div");
2280
+ root.className = "bin-drop-root";
2281
+ root.textContent = "Drop here to move to root";
2282
+ bindFolderDropTarget(root, null);
2283
+ els.binList.appendChild(root);
2284
+ }
2088
2285
  syncBinSelectionFromTimeline();
2089
2286
  }
2090
2287
 
2288
+ /* ── Project bin: media management ──
2289
+ Search, the Show filter, sort, list view, favorites, tags, collections,
2290
+ usage counts, find instances, reveal in project, server-probed metadata. */
2291
+ /** The whole document as it stands now — with an open comp's live clips written into it. */
2292
+ function usageDoc() {
2293
+ if (!state.compCtx) return project;
2294
+ const id = compCtxId();
2295
+ return {
2296
+ media: project.media,
2297
+ clips: state.compCtx.root.clips || [],
2298
+ sequences: state.compCtx.root.sequences, sequence: state.compCtx.root.sequence,
2299
+ comps: (project.comps || []).map((c) => (c.id === id ? { ...c, clips: project.clips } : c)),
2300
+ };
2301
+ }
2302
+ function binCtx() {
2303
+ return {
2304
+ usage: MediaLib.usageCounts(usageDoc()), collections: project.collections || [],
2305
+ extraFilter: (m, f) => (f === "offline" ? isMediaOffline(m.id)
2306
+ : f === "proxy" ? !!proxyOf(m) : f === "noproxy" ? m.kind === "video" && !proxyOf(m) : true),
2307
+ };
2308
+ }
2309
+ function getCollection(id) { return (project.collections || []).find((c) => c.id === id) || null; }
2310
+
2311
+ /* Fill the Show / Sort controls from the project (tags and collections change). */
2312
+ function syncBinTools() {
2313
+ const tools = els.binTools;
2314
+ if (!tools) return;
2315
+ const tags = MediaLib.allTags(project.media);
2316
+ const cols = project.collections || [];
2317
+ // a filter whose tag / collection is gone falls back to everything
2318
+ const f = binView.filter;
2319
+ if ((f.startsWith("tag:") && !tags.some((t) => t.toLowerCase() === f.slice(4).toLowerCase())) ||
2320
+ (f.startsWith("col:") && !getCollection(f.slice(4)))) binView.filter = "";
2321
+ const opt = (v, label) => `<option value="${escapeHtml(v)}"${v === binView.filter ? " selected" : ""}>${escapeHtml(label)}</option>`;
2322
+ const html = opt("", "All media") + opt("fav", "★ Favorites") + opt("used", "Used in the edit") + opt("unused", "Unused") +
2323
+ (mediaOffline.size || binView.filter === "offline" ? opt("offline", `⚠ Offline (${mediaOffline.size})`) : "") +
2324
+ (project.media.some((m) => m.kind === "video") ? opt("proxy", "Has a proxy") + opt("noproxy", "Video without a proxy") : "") +
2325
+ `<optgroup label="Kind">${MediaLib.KINDS.map((k) => opt("kind:" + k, k[0].toUpperCase() + k.slice(1))).join("")}</optgroup>` +
2326
+ (cols.length ? `<optgroup label="Collections">${cols.map((c) => opt("col:" + c.id, c.name + ` (${c.media.length})`)).join("")}</optgroup>` : "") +
2327
+ (tags.length ? `<optgroup label="Tags">${tags.map((t) => opt("tag:" + t, "#" + t)).join("")}</optgroup>` : "");
2328
+ if (els.binFilter.innerHTML !== html) els.binFilter.innerHTML = html;
2329
+ els.binFilter.value = binView.filter;
2330
+ els.binFilter.classList.toggle("on", !!binView.filter);
2331
+ els.binSort.value = binView.sort;
2332
+ els.binSortDir.textContent = binView.dir === "desc" ? "↓" : "↑";
2333
+ els.binSortDir.title = binView.dir === "desc" ? "Descending — click for ascending" : "Ascending — click for descending";
2334
+ els.binViewBtn.classList.toggle("on", binView.list);
2335
+ els.binViewBtn.title = binView.list ? "Thumbnail view" : "List view: metadata columns";
2336
+ if (els.binSearch.value !== binView.q && document.activeElement !== els.binSearch) els.binSearch.value = binView.q;
2337
+ }
2338
+ function setBinFilter(filter) {
2339
+ binView.filter = filter || "";
2340
+ renderBin();
2341
+ }
2342
+ /* The strip above search / filter results: how many, the active collection's actions, Clear. */
2343
+ function makeFilterBar(n) {
2344
+ const bar = document.createElement("div");
2345
+ bar.className = "bin-filterbar";
2346
+ const col = binView.filter.startsWith("col:") ? getCollection(binView.filter.slice(4)) : null;
2347
+ bar.innerHTML = `<span class="bin-filter-count">${n} of ${project.media.length}</span>` +
2348
+ (col ? `<span class="bin-filter-name" title="Collection">▣ ${escapeHtml(col.name)}</span>
2349
+ <button type="button" class="btn tiny" data-col-rename>Rename</button>
2350
+ <button type="button" class="btn tiny" data-col-delete title="Delete the collection (keeps the media)">Delete</button>` : "") +
2351
+ (binView.filter === "offline" && mediaOffline.size ? `<button type="button" class="btn tiny accent" data-relink-all>Relink…</button>` : "") +
2352
+ `<button type="button" class="btn tiny" data-clear title="Show everything (Esc in the search box)">Clear</button>`;
2353
+ bar.querySelector("[data-relink-all]")?.addEventListener("click", () => openRelinkDialog());
2354
+ bar.querySelector("[data-clear]").addEventListener("click", () => { binView.q = ""; els.binSearch.value = ""; setBinFilter(""); });
2355
+ if (col) {
2356
+ bar.querySelector("[data-col-rename]").addEventListener("click", (e) => {
2357
+ const r = e.currentTarget.getBoundingClientRect();
2358
+ promptBinText(r.left, r.bottom + 4, "Collection name", col.name, (name) => { col.name = name.slice(0, 80); scheduleSave(); renderBin(); });
2359
+ });
2360
+ bar.querySelector("[data-col-delete]").addEventListener("click", () => {
2361
+ project.collections = (project.collections || []).filter((c) => c.id !== col.id);
2362
+ binView.filter = "";
2363
+ scheduleSave(); renderBin();
2364
+ toast(`Deleted the collection “${col.name}” — its media stay in the bin`);
2365
+ });
2366
+ }
2367
+ return bar;
2368
+ }
2369
+ /* List view header: click a column to sort by it (again to flip the direction). */
2370
+ const BIN_COLUMNS = [["name", "Name"], ["duration", "Duration"], ["resolution", "Resolution"], ["fps", "FPS"],
2371
+ ["codec", "Codec"], ["audio", "Audio"], ["size", "Size"], ["proxy", "Proxy"], ["usage", "Uses"]];
2372
+ function makeColumnHead() {
2373
+ const head = document.createElement("div");
2374
+ head.className = "bin-colhead bin-row";
2375
+ for (const [key, label] of BIN_COLUMNS) {
2376
+ if (key === "proxy") { const sp = document.createElement("span"); sp.className = "bin-cell c-proxy"; sp.textContent = label; head.appendChild(sp); continue; }
2377
+ const b = document.createElement("button");
2378
+ b.type = "button";
2379
+ b.className = "bin-cell c-" + key + (key === "name" ? " bin-cell-name" : "") + (["duration", "resolution", "fps", "size", "usage"].includes(key) ? " num" : "") + (binView.sort === key ? " on" : "");
2380
+ b.textContent = label + (binView.sort === key ? (binView.dir === "desc" ? " ↓" : " ↑") : "");
2381
+ b.addEventListener("click", () => {
2382
+ if (binView.sort === key) binView.dir = binView.dir === "desc" ? "asc" : "desc";
2383
+ else { binView.sort = key; binView.dir = key === "name" || key === "codec" ? "asc" : "desc"; }
2384
+ saveBinPrefs(); renderBin();
2385
+ });
2386
+ head.appendChild(b);
2387
+ }
2388
+ head.appendChild(document.createElement("span"));
2389
+ return head;
2390
+ }
2391
+
2392
+ /* Server-probed metadata (fps, codecs, channels, sample rate, size) for media
2393
+ that has none yet. Without ffprobe the server still answers the size. */
2394
+ let mediaInfoBusy = false, mediaInfoAgain = false;
2395
+ async function refreshMediaInfo(list) {
2396
+ if (!state.connected) return;
2397
+ if (mediaInfoBusy) { mediaInfoAgain = true; return; } // run once more when this one ends
2398
+ // blob: srcs are files a hosted editor reads from a folder (a local session's own blobs are transient)
2399
+ const todo = (list || project.media).filter((m) => !m.transient && m.size == null && (isLocalSrc(m.src) || /^blob:/.test(m.src || "")));
2400
+ if (!todo.length) return;
2401
+ mediaInfoBusy = true;
2402
+ try {
2403
+ const res = await fetch("/api/media-info", {
2404
+ method: "POST", headers: { "Content-Type": "application/json" },
2405
+ body: JSON.stringify({ srcs: [...new Set(todo.map((m) => m.src))] }),
2406
+ });
2407
+ if (!res.ok) return;
2408
+ const { info } = await res.json();
2409
+ let changed = false;
2410
+ for (const m of project.media) {
2411
+ const i = info && info[m.src];
2412
+ if (!i) continue;
2413
+ for (const k of MediaLib.INFO_KEYS) if (i[k] != null && m[k] !== i[k]) { m[k] = i[k]; changed = true; }
2414
+ if (!(m.width > 0) && i.width > 0) { m.width = i.width; m.height = i.height; changed = true; }
2415
+ }
2416
+ if (changed) { renderBin(); scheduleSave(); if (state.selId) renderInspector(); }
2417
+ } catch { } finally {
2418
+ mediaInfoBusy = false;
2419
+ // files imported (or a Media info opened) meanwhile: everything still without details
2420
+ if (mediaInfoAgain) { mediaInfoAgain = false; refreshMediaInfo(); }
2421
+ }
2422
+ }
2423
+
2424
+ function setMediaFavorite(ids, on) {
2425
+ for (const id of ids) {
2426
+ const m = getMedia(id);
2427
+ if (!m) continue;
2428
+ if (on) m.favorite = true; else delete m.favorite;
2429
+ }
2430
+ scheduleSave(); renderBin();
2431
+ }
2432
+ function setMediaTags(m, tags) {
2433
+ const t = MediaLib.normalizeTags(tags);
2434
+ if (t.length) m.tags = t; else delete m.tags;
2435
+ scheduleSave(); renderBin();
2436
+ }
2437
+ function addToCollection(colId, mediaId, on = true) {
2438
+ const col = getCollection(colId);
2439
+ if (!col) return;
2440
+ if (on && !col.media.includes(mediaId)) col.media.push(mediaId);
2441
+ if (!on) col.media = col.media.filter((id) => id !== mediaId);
2442
+ scheduleSave(); renderBin();
2443
+ }
2444
+ function newCollection(name, mediaIds) {
2445
+ const col = { id: "col_" + uid(), name: String(name).trim().slice(0, 80) || "Collection", media: [...new Set(mediaIds || [])] };
2446
+ project.collections = [...(project.collections || []), col];
2447
+ scheduleSave(); renderBin();
2448
+ return col;
2449
+ }
2450
+ function removeMediaFromBin(m) {
2451
+ if (state.compCtx && (state.compCtx.root.clips || []).some((c) => c.mediaId === m.id)) { toast(`It's used on the timeline of “${openSequenceName()}” — go back to it to delete it`); return; }
2452
+ const elsewhere = SeqLib.others(seqRoot()).find((sq) => (sq.clips || []).some((c) => c.mediaId === m.id));
2453
+ if (elsewhere) { toast(`It's used in the sequence “${elsewhere.name}” — remove its clips there first`); return; }
2454
+ pushUndo(JSON.stringify({ clips: project.clips, markers: project.markers || [], comps: project.comps || [], media: project.media })); // undo brings the media back too
2455
+ project.media = project.media.filter((x) => x.id !== m.id);
2456
+ project.clips = project.clips.filter((c) => c.mediaId !== m.id);
2457
+ // and its clips inside comps (and on the main timeline while a comp is open)
2458
+ project.comps = (project.comps || []).map((cp) => ({ ...cp, clips: (cp.clips || []).filter((c) => c.mediaId !== m.id) }));
2459
+ runtime.compGen = (runtime.compGen || 0) + 1;
2460
+ if (state.source.mediaId === m.id) clearSource();
2461
+ renderBin(); scheduleSave(); renderInspector();
2462
+ }
2463
+
2464
+ /* A one-line text prompt as a popover (Enter saves, Esc cancels). */
2465
+ function promptBinText(x, y, label, value, onOk, opts = {}) {
2466
+ const pop = document.createElement("div");
2467
+ pop.className = "ctx-menu bin-pop";
2468
+ pop.innerHTML = `<label class="bin-pop-label">${escapeHtml(label)}</label>
2469
+ <input type="text" class="bin-pop-input" maxlength="${opts.max || 80}" spellcheck="false">
2470
+ ${opts.hint ? `<div class="bin-pop-hint">${escapeHtml(opts.hint)}</div>` : ""}
2471
+ <div class="bin-pop-chips"></div>
2472
+ <div class="bin-pop-btns"><button type="button" class="btn tiny" data-cancel>Cancel</button><button type="button" class="btn tiny accent" data-ok>${escapeHtml(opts.ok || "OK")}</button></div>`;
2473
+ const input = pop.querySelector("input");
2474
+ input.value = value || "";
2475
+ if (opts.placeholder) input.placeholder = opts.placeholder;
2476
+ const chips = pop.querySelector(".bin-pop-chips");
2477
+ for (const c of opts.chips || []) {
2478
+ const b = document.createElement("button");
2479
+ b.type = "button"; b.className = "bin-tag chip"; b.textContent = "#" + c;
2480
+ b.title = "Add or remove this tag";
2481
+ b.addEventListener("click", () => {
2482
+ const cur = MediaLib.normalizeTags(input.value);
2483
+ const has = cur.some((t) => t.toLowerCase() === c.toLowerCase());
2484
+ input.value = (has ? cur.filter((t) => t.toLowerCase() !== c.toLowerCase()) : [...cur, c]).join(", ");
2485
+ input.focus();
2486
+ });
2487
+ chips.appendChild(b);
2488
+ }
2489
+ if (!chips.children.length) chips.remove();
2490
+ const ok = () => {
2491
+ const v = input.value.trim();
2492
+ if (!v && !opts.allowEmpty) { input.focus(); return; }
2493
+ hideTrackCtxMenu();
2494
+ onOk(v);
2495
+ };
2496
+ pop.querySelector("[data-ok]").addEventListener("click", ok);
2497
+ pop.querySelector("[data-cancel]").addEventListener("click", () => hideTrackCtxMenu());
2498
+ input.addEventListener("keydown", (e) => {
2499
+ if (e.key === "Enter") { e.preventDefault(); ok(); }
2500
+ else if (e.key === "Escape") { e.preventDefault(); hideTrackCtxMenu(); }
2501
+ e.stopPropagation();
2502
+ });
2503
+ showPopover(pop, x, y);
2504
+ input.focus(); input.select();
2505
+ }
2506
+
2507
+ /* Right-click a media item in the Project bin. */
2508
+ function showMediaMenu(x, y, m) {
2509
+ hideTrackCtxMenu();
2510
+ closeBinCtxMenu();
2511
+ const menu = document.createElement("div");
2512
+ menu.className = "ctx-menu";
2513
+ const uses = MediaLib.placements(usageDoc(), m.id).length;
2514
+ const item = (label, run, why, keys) => {
2515
+ const b = document.createElement("button");
2516
+ b.type = "button"; b.className = "ctx-item";
2517
+ b.innerHTML = `<span>${escapeHtml(label)}</span>` + (keys ? `<kbd>${escapeHtml(keys)}</kbd>` : "");
2518
+ if (why) { b.disabled = true; b.title = why; } else b.addEventListener("click", () => { hideTrackCtxMenu(); run(); });
2519
+ menu.appendChild(b);
2520
+ return b;
2521
+ };
2522
+ const sep = () => { const d = document.createElement("div"); d.className = "ctx-sep"; menu.appendChild(d); };
2523
+ item("Open in Source", () => loadSourceFromMedia(m));
2524
+ item(`Find timeline instances (${uses})`, () => showMediaInstances(m, x, y), uses ? null : "Not used on the timeline");
2525
+ item("Media info…", () => showMediaInfo(m, x, y));
2526
+ item(isMediaOffline(m.id) ? "Relink…" : "Relink to another copy…", () => openRelinkDialog([m]), state.connected ? null : "Needs the FableCut server");
2527
+ item("Replace file…", () => replaceMediaFile(m), state.connected ? null : "Needs the FableCut server");
2528
+ if (m.kind === "video") {
2529
+ const ps = proxyStatus.get(m.id);
2530
+ const why = !state.connected ? "Needs the FableCut server" : !state.ffmpeg ? "Needs ffmpeg on the server's PATH" : isMediaOffline(m.id) ? "The file is offline" : null;
2531
+ if (ps && (ps.state === "ready" || ps.state === "running" || ps.state === "queued")) item(ps.state === "ready" ? "Delete proxy" : "Stop making the proxy", () => deleteProxies([m]));
2532
+ else {
2533
+ item("Create proxy (540p)", () => createProxies([m], 540), why);
2534
+ item("Create proxy (720p)", () => createProxies([m], 720), why);
2535
+ }
2536
+ }
2537
+ sep();
2538
+ item(m.favorite ? "Remove from favorites" : "Add to favorites", () => setMediaFavorite([m.id], !m.favorite));
2539
+ item("Tags…", () => promptBinText(x, y, `Tags for ${m.name}`, (m.tags || []).join(", "), (v) => setMediaTags(m, v),
2540
+ { allowEmpty: true, max: 400, ok: "Save", placeholder: "interview, b-roll, day 1", hint: "Comma-separated. Search #tag to find them.",
2541
+ chips: MediaLib.allTags(project.media) }));
2542
+ for (const col of project.collections || []) {
2543
+ const inIt = col.media.includes(m.id);
2544
+ item(inIt ? `Remove from “${col.name}”` : `Add to “${col.name}”`, () => addToCollection(col.id, m.id, !inIt));
2545
+ }
2546
+ item("New collection…", () => promptBinText(x, y, "New collection", "", (name) => {
2547
+ const col = newCollection(name, [m.id]);
2548
+ toast(`Added ${m.name} to the collection “${col.name}”`);
2549
+ }, { placeholder: "Selects, Interviews…", ok: "Create" }));
2550
+ sep();
2551
+ item("Remove from project", () => removeMediaFromBin(m));
2552
+ document.body.appendChild(menu);
2553
+ menu.id = "trackCtxMenu";
2554
+ trackCtxMenu = menu;
2555
+ menu.style.left = Math.max(6, Math.min(x, innerWidth - menu.offsetWidth - 6)) + "px";
2556
+ menu.style.top = Math.max(6, Math.min(y, innerHeight - menu.offsetHeight - 6)) + "px";
2557
+ }
2558
+
2559
+ /* Media info: everything the bin knows about one file. */
2560
+ function showMediaInfo(m, x, y) {
2561
+ const doc = usageDoc();
2562
+ const uses = MediaLib.placements(doc, m.id);
2563
+ const folder = m.folderId ? getFolder(m.folderId) : null;
2564
+ const cols = (project.collections || []).filter((c) => c.media.includes(m.id)).map((c) => c.name);
2565
+ const audio = m.audioChannels == null ? "" : m.audioChannels === 0 ? "none" :
2566
+ [m.audioCodec, MediaLib.fmtAudio(m)].filter(Boolean).join(" · ");
2567
+ const rows = [
2568
+ ["Kind", m.kind], ["File", decodeURIComponent(String(m.src || "").split("?")[0]) + (isMediaOffline(m.id) ? " — MISSING (offline)" : "")],
2569
+ ["Duration", m.duration > 0 ? MediaLib.fmtDur(m.duration) + ` (${(+m.duration).toFixed(3)} s)` : ""],
2570
+ ["Resolution", MediaLib.fmtRes(m)], ["Frame rate", m.fps ? MediaLib.fmtFps(m.fps) + " fps" : ""],
2571
+ ["Video codec", m.kind === "video" ? m.codec : ""], ["Format", m.kind !== "video" && m.codec ? m.codec : ""],
2572
+ ["Audio", audio], ["Bitrate", m.bitrate ? (m.bitrate >= 1e6 ? (m.bitrate / 1e6).toFixed(1) + " Mb/s" : Math.round(m.bitrate / 1000) + " kb/s") : ""],
2573
+ ["Size", MediaLib.fmtSize(m.size)], ["Used", uses.length ? uses.length + "×" : "not used"],
2574
+ ["Proxy", m.kind !== "video" ? "" : (() => {
2575
+ const ps = proxyStatus.get(m.id);
2576
+ if (!ps) return "none";
2577
+ if (ps.state === "ready") return `${ps.width ? ps.width + "×" : ""}${ps.height} · ${MediaLib.fmtSize(ps.size)}${proxiesOn() ? " · playing it" : " · Proxy button off"}`;
2578
+ return ps.state === "running" ? `making it — ${Math.round((ps.progress || 0) * 100)}%` : ps.state + (ps.error ? ": " + ps.error : "");
2579
+ })()],
2580
+ ["Folder", folder ? folder.name : ""], ["Tags", (m.tags || []).map((t) => "#" + t).join(" ")],
2581
+ ["Collections", cols.join(", ")], ["Favorite", m.favorite ? "★ yes" : ""],
2582
+ ].filter(([, v]) => v);
2583
+ const pop = document.createElement("div");
2584
+ pop.className = "ctx-menu bin-pop bin-info";
2585
+ pop.innerHTML = `<div class="bin-pop-title"></div><table>${rows.map(([k, v]) => `<tr><th>${escapeHtml(k)}</th><td>${escapeHtml(v)}</td></tr>`).join("")}</table>` +
2586
+ (m.size == null && state.connected ? `<div class="bin-pop-hint">Reading the file's details…</div>` : "");
2587
+ pop.querySelector(".bin-pop-title").textContent = m.name;
2588
+ showPopover(pop, x, y);
2589
+ if (m.size == null) refreshMediaInfo([m]);
2590
+ }
2591
+
2592
+ /* Find all timeline instances: every placement (main timeline and inside comps); click one to go there. */
2593
+ function showMediaInstances(m, x, y) {
2594
+ const list = MediaLib.placements(usageDoc(), m.id);
2595
+ if (!list.length) { toast(`${m.name} isn't used on the timeline`); return; }
2596
+ // select the instances on the timeline that is open now
2597
+ const here = compCtxId();
2598
+ const local = list.filter((p) => p.comp === here).map((p) => p.clipId);
2599
+ if (local.length) selectClipsByMediaId(m.id);
2600
+ const pop = document.createElement("div");
2601
+ pop.className = "ctx-menu bin-pop bin-instances";
2602
+ pop.innerHTML = `<div class="bin-pop-title"></div><div class="bin-pop-hint">${list.length} instance${list.length === 1 ? "" : "s"} — click one to jump to it</div>`;
2603
+ pop.querySelector(".bin-pop-title").textContent = m.name;
2604
+ for (const p of list) {
2605
+ const b = document.createElement("button");
2606
+ b.type = "button"; b.className = "ctx-item";
2607
+ b.innerHTML = `<span>${escapeHtml(p.sequence ? `▤ ${p.sequenceName}` : p.comp ? `▣ ${p.compName}` : openSequenceName())} · ${escapeHtml(p.track)}</span><kbd>${fmt(p.start)} → ${fmt(p.start + p.duration)}</kbd>`;
2608
+ b.addEventListener("click", () => { goToPlacement(p); });
2609
+ pop.appendChild(b);
2610
+ }
2611
+ showPopover(pop, x, y);
2612
+ }
2613
+ function goToPlacement(p) {
2614
+ if (p.sequence && !openSequence(p.sequence)) return;
2615
+ const here = compCtxId();
2616
+ if (p.comp !== here) {
2617
+ if (state.compCtx) exitComp(state.compCtx.path.length);
2618
+ if (p.comp) enterComp(p.comp);
2619
+ }
2620
+ const c = getClip(p.clipId);
2621
+ if (!c) return;
2622
+ if (isSourceMode()) setMonitorMode("program");
2623
+ setSelection([...withLinked([c])].map((x) => x.id), c.id);
2624
+ setTime(c.start);
2625
+ revealTime(c.start);
2626
+ }
2627
+
2628
+ /* Reveal in project: show a clip's media (or comp) in the Project bin. */
2629
+ function revealInProject(c) {
2630
+ const id = c.kind === "comp" ? null : c.mediaId;
2631
+ if (state.binTab !== "project") setBinTab("project");
2632
+ let sel;
2633
+ if (id) {
2634
+ const m = getMedia(id);
2635
+ if (!m) { toast("Its media is no longer in the project"); return; }
2636
+ if ((binView.q || binView.filter) && !MediaLib.query([m], binView, binCtx()).length) { binView.q = ""; binView.filter = ""; }
2637
+ for (let f = getFolder(m.folderId); f; f = getFolder(f.parentId)) f.open = true;
2638
+ renderBin();
2639
+ sel = `.bin-item[data-media-id="${CSS.escape(id)}"]`;
2640
+ } else if (c.compId) {
2641
+ binView.q = ""; binView.filter = "";
2642
+ renderBin();
2643
+ sel = `.comp-item[data-comp-id="${CSS.escape(c.compId)}"]`;
2644
+ }
2645
+ const el = sel && els.binList.querySelector(sel);
2646
+ if (!el) return;
2647
+ el.scrollIntoView({ block: "nearest" });
2648
+ el.classList.remove("bin-flash");
2649
+ void el.offsetWidth;
2650
+ el.classList.add("bin-flash");
2651
+ }
2652
+
2653
+ /* ── Offline media, relink and replace ──
2654
+ A file is offline when its src names nothing under media/ or library/ (it was
2655
+ moved, renamed or deleted). Its clips stay on the timeline and draw a "Media
2656
+ offline" slate until it is relinked: pointed at the same footage somewhere
2657
+ else (clips keep their In points). Replace puts a different file behind the
2658
+ media entry (a new render): clips keep their timing, trimmed to fit. */
2659
+ const mediaOffline = new Set(); // media ids whose file is missing (runtime only, re-checked on every change)
2660
+ function isMediaOffline(id) { return !!id && mediaOffline.has(id); }
2661
+ const isLocalSrc = (src) => /^\/(media|library)\//.test(String(src || ""));
2662
+ let offlineCheckTimer = null, offlineChecking = false;
2663
+ function scheduleOfflineCheck(delay = 300) {
2664
+ clearTimeout(offlineCheckTimer);
2665
+ offlineCheckTimer = setTimeout(() => { checkOffline(); refreshProxyStatus(); }, delay);
2666
+ }
2667
+ async function checkOffline() {
2668
+ if (!state.connected || offlineChecking) return;
2669
+ const list = project.media.filter((m) => !m.transient && (isLocalSrc(m.src) || /^blob:/.test(m.src || "")));
2670
+ offlineChecking = true;
2671
+ try {
2672
+ const res = await fetch("/api/media-info", {
2673
+ method: "POST", headers: { "Content-Type": "application/json" },
2674
+ body: JSON.stringify({ srcs: [...new Set(list.map((m) => m.src))], stat: true }),
2675
+ });
2676
+ if (!res.ok) return;
2677
+ const { info } = await res.json();
2678
+ const was = new Set(mediaOffline);
2679
+ mediaOffline.clear();
2680
+ for (const m of list) if (info && info[m.src] === null) mediaOffline.add(m.id);
2681
+ // a file that came back (put back, or relinked by an agent): reload what was cached from it
2682
+ for (const id of was) if (!mediaOffline.has(id)) { const m = getMedia(id); if (m) reloadMediaSource(m); }
2683
+ const changed = was.size !== mediaOffline.size || [...was].some((id) => !mediaOffline.has(id));
2684
+ if (changed) {
2685
+ renderBin(); state.dirtyTimeline = true;
2686
+ const fresh = [...mediaOffline].filter((id) => !was.has(id));
2687
+ if (fresh.length) toast(`${fresh.length === 1 ? `“${getMedia(fresh[0])?.name}” is` : fresh.length + " files are"} offline — right-click it in the bin → Relink…`);
2688
+ }
2689
+ } catch { } finally { offlineChecking = false; }
2690
+ }
2691
+ /* Everything cached from a media file (players, picture, waveform, thumbnail) is dropped and read again. */
2692
+ function reloadMediaSource(m, oldSrc) {
2693
+ // a proxy belongs to a file, not to the entry: the old file's must not stand in for the new one
2694
+ const proxySrc = proxyStatus.get(m.id)?.src;
2695
+ proxyStatus.delete(m.id);
2696
+ for (const [id, el] of runtime.clipEls)
2697
+ if (el._fcSrc === m.src || (oldSrc && el._fcSrc === oldSrc) || (proxySrc && el._fcSrc === proxySrc)) releaseClipEl(id);
2698
+ runtime.mediaAux.delete(m.id);
2699
+ runtime.wavePeaks.delete(m.id);
2700
+ if (state.source.mediaId === m.id) { const sm = m; clearSource(); loadSourceFromMedia(sm); }
2701
+ seekMediaWhilePaused(); // fresh players start at 0 — park them on the playhead
2702
+ loadMediaMetadata(m).then(() => {
2703
+ if (m.kind === "video") grabThumb(m).catch(() => { });
2704
+ ensureWave(m);
2705
+ seekMediaWhilePaused();
2706
+ renderBin(); state.dirtyTimeline = true;
2707
+ }).catch(() => { });
2708
+ if (m.kind === "video") refreshProxyStatus(); // the new file may have a proxy of its own
2709
+ }
2710
+
2711
+ /** Point a media entry at another file. mode "relink" (same footage) or "replace" (a new file). */
2712
+ async function setMediaSource(m, src, mode, name) {
2713
+ const oldSrc = m.src, oldDur = m.duration;
2714
+ pushUndo(JSON.stringify({ clips: project.clips, markers: project.markers || [], comps: project.comps || [], media: project.media, seqClips: otherSequenceClips() }));
2715
+ m.src = src;
2716
+ for (const k of MediaLib.INFO_KEYS) delete m[k];
2717
+ if (mode === "replace") {
2718
+ m.name = name || MediaLib.srcName(src);
2719
+ delete m.duration; delete m.width; delete m.height;
2720
+ }
2721
+ mediaOffline.delete(m.id);
2722
+ reloadMediaSource(m, oldSrc);
2723
+ try { await loadMediaMetadata(m); } catch { }
2724
+ let msg = mode === "replace" ? `Replaced ${m.name}` : `Relinked ${m.name}`;
2725
+ if (mode === "relink" && oldDur > 0 && m.duration > 0 && Math.abs(oldDur - m.duration) > 0.1)
2726
+ msg += ` — but it is ${fmt(m.duration)} long, the original was ${fmt(oldDur)}: is it the same footage?`;
2727
+ if (mode === "replace" && m.duration > 0) {
2728
+ let trimmed = 0;
2729
+ const fit = (clips) => {
2730
+ for (const c of clips || []) {
2731
+ if (c.mediaId !== m.id || c.kind === "image" || c.kind === "svg") continue;
2732
+ const speed = c.props?.speed || 1;
2733
+ const maxIn = Math.max(0, m.duration - 0.001);
2734
+ if (c.in > maxIn) { c.in = maxIn; trimmed++; }
2735
+ const maxDur = Math.max(0.05, (m.duration - c.in) / speed);
2736
+ if (c.duration > maxDur + 1e-6) { c.duration = maxDur; trimmed++; }
2737
+ }
2738
+ };
2739
+ fit(project.clips);
2740
+ for (const comp of project.comps || []) fit(comp.clips);
2741
+ if (state.compCtx) fit(state.compCtx.root.clips);
2742
+ for (const sq of SeqLib.others(seqRoot())) fit(sq.clips);
2743
+ runtime.compGen = (runtime.compGen || 0) + 1;
2744
+ if (trimmed) msg += ` — ${trimmed} clip edge${trimmed === 1 ? "" : "s"} trimmed to fit`;
2745
+ if (m.kind === "video") for (const c of project.clips) if (c.mediaId === m.id && c.kind === "video") reconcileAudioChannels(c);
2746
+ }
2747
+ state.dirtyTimeline = true;
2748
+ renderBin(); scheduleSave(); renderInspector();
2749
+ refreshMediaInfo([m]);
2750
+ toast(msg);
2751
+ }
2752
+
2753
+ /* Upload local files into media/ (like import, without adding bin entries) → [{file, src}]. */
2754
+ async function uploadForRelink(files, onProgress) {
2755
+ const out = [];
2756
+ for (const file of files) {
2757
+ onProgress?.(file);
2758
+ try {
2759
+ const res = await fetch("/api/upload?name=" + encodeURIComponent(file.name), { method: "POST", body: file });
2760
+ if (!res.ok) throw new Error("upload " + res.status);
2761
+ out.push({ file, src: (await res.json()).src });
2762
+ } catch { out.push({ file, src: null }); }
2763
+ }
2764
+ return out;
2765
+ }
2766
+ let relinkPicker = null;
2767
+ /** A file input of our own for relink / replace (never the shared #fileInput). */
2768
+ function pickFilesForRelink({ folder = false, accept = els.fileInput.accept } = {}) {
2769
+ return new Promise((resolve) => {
2770
+ relinkPicker?.remove();
2771
+ const input = relinkPicker = document.createElement("input");
2772
+ input.type = "file"; input.className = "sr-only";
2773
+ if (folder) { input.webkitdirectory = true; input.multiple = true; } else input.accept = accept;
2774
+ document.body.appendChild(input);
2775
+ input.addEventListener("change", () => { resolve([...input.files]); input.remove(); }, { once: true });
2776
+ input.addEventListener("cancel", () => { resolve([]); input.remove(); }, { once: true });
2777
+ input.click();
2778
+ });
2779
+ }
2780
+
2781
+ /* Replace file…: a different file behind this media entry, for every clip that uses it. */
2782
+ async function replaceMediaFile(m) {
2783
+ const files = await pickFilesForRelink({ accept: m.kind === "audio" ? "audio/*,.mp3,.wav,.m4a,.flac,.ogg" : els.fileInput.accept });
2784
+ const file = files[0];
2785
+ if (!file) return;
2786
+ const kind = mediaKindFromFile(file);
2787
+ if (kind !== m.kind && !(m.kind === "audio" && kind === "video")) { toast(`That is ${kind ? (kind === "audio" || kind === "image" ? "an " : "a ") + kind : "an unsupported"} file — ${m.name} is ${m.kind}`); return; }
2788
+ toast(`Copying ${file.name} into the project…`);
2789
+ const [up] = await uploadForRelink([file]);
2790
+ if (!up || !up.src) { toast("Couldn't copy the file into media/"); return; }
2791
+ await setMediaSource(m, up.src, "replace", file.name);
2792
+ }
2793
+
2794
+ /* The Relink dialog: one row per file, each with candidates found on disk
2795
+ (same name, same name with another extension, similar name, same size),
2796
+ Browse… for one file and Choose folder… to match a whole folder by name. */
2797
+ async function openRelinkDialog(list) {
2798
+ list = (list || project.media.filter((m) => isMediaOffline(m.id))).filter(Boolean);
2799
+ if (!list.length) { toast("Nothing is offline"); return; }
2800
+ document.getElementById("relinkOverlay")?.remove();
2801
+ const overlay = document.createElement("div");
2802
+ overlay.className = "overlay";
2803
+ overlay.id = "relinkOverlay";
2804
+ overlay.innerHTML = `<div class="dialog relink" role="dialog" aria-modal="true" aria-labelledby="relinkTitle" tabindex="-1">
2805
+ <h2 id="relinkTitle">Relink media</h2>
2806
+ <p class="dim">Point ${list.length === 1 ? "this file" : `these ${list.length} files`} at the footage where it is now. Clips keep their In points and edits.</p>
2807
+ <div class="relink-tools">
2808
+ <button type="button" class="btn tiny" data-folder title="Pick the folder the files are in now — they are matched by name and copied into the project">Choose folder…</button>
2809
+ <span class="relink-status dim"></span>
2810
+ </div>
2811
+ <div class="relink-rows"></div>
2812
+ <div class="dialog-actions"><button type="button" class="btn" data-cancel>Cancel</button><button type="button" class="btn primary" data-apply>Relink</button></div>
2813
+ </div>`;
2814
+ document.body.appendChild(overlay);
2815
+ const dialog = overlay.querySelector(".dialog");
2816
+ const rowsEl = overlay.querySelector(".relink-rows"), status = overlay.querySelector(".relink-status");
2817
+ const pick = new Map(); // media id → {src, label} | null
2818
+ const cands = new Map(); // media id → [{src, name, size, why}]
2819
+ const close = () => { overlay.remove(); };
2820
+ const render = () => {
2821
+ rowsEl.innerHTML = "";
2822
+ for (const m of list) {
2823
+ const row = document.createElement("div");
2824
+ row.className = "relink-row";
2825
+ const cur = pick.get(m.id);
2826
+ const options = (cands.get(m.id) || []);
2827
+ row.innerHTML = `<div class="relink-name"><b></b><span class="dim relink-was"></span></div>
2828
+ <div class="relink-pick">
2829
+ <select aria-label="New location"></select>
2830
+ <button type="button" class="btn tiny" data-browse title="Pick the file (it is copied into the project)">Browse…</button>
2831
+ </div>`;
2832
+ row.querySelector("b").textContent = (isMediaOffline(m.id) ? "⚠ " : "") + m.name;
2833
+ row.querySelector(".relink-was").textContent = "was " + decodeURIComponent(String(m.src).split("?")[0]) + (m.duration ? " · " + fmt(m.duration) : "") + (m.size ? " · " + MediaLib.fmtSize(m.size) : "");
2834
+ const sel = row.querySelector("select");
2835
+ const opt = (v, label) => { const o = document.createElement("option"); o.value = v; o.textContent = label; sel.appendChild(o); };
2836
+ opt("", options.length || cur ? "— leave it —" : "— not found: Browse… or Choose folder… —");
2837
+ if (cur && !options.some((o) => o.src === cur.src)) opt(cur.src, cur.label);
2838
+ for (const o of options) opt(o.src, `${decodeURIComponent(o.path || o.src)} · ${MediaLib.fmtSize(o.size)} (${o.why})`);
2839
+ sel.value = cur ? cur.src : "";
2840
+ sel.addEventListener("change", () => {
2841
+ const o = options.find((x) => x.src === sel.value);
2842
+ pick.set(m.id, sel.value ? { src: sel.value, label: o ? o.name : sel.value } : null);
2843
+ syncApply();
2844
+ });
2845
+ row.querySelector("[data-browse]").addEventListener("click", async () => {
2846
+ const [file] = await pickFilesForRelink({});
2847
+ if (!file) return;
2848
+ status.textContent = `Copying ${file.name}…`;
2849
+ const [up] = await uploadForRelink([file]);
2850
+ status.textContent = up?.src ? "" : "Couldn't copy " + file.name;
2851
+ if (up?.src) { pick.set(m.id, { src: up.src, label: `${file.name} (chosen)` }); render(); }
2852
+ });
2853
+ rowsEl.appendChild(row);
2854
+ }
2855
+ syncApply();
2856
+ };
2857
+ const syncApply = () => {
2858
+ const n = list.filter((m) => pick.get(m.id)).length;
2859
+ const b = overlay.querySelector("[data-apply]");
2860
+ b.disabled = !n;
2861
+ b.textContent = n ? `Relink ${n}` : "Relink";
2862
+ };
2863
+ overlay.querySelector("[data-cancel]").addEventListener("click", close);
2864
+ overlay.addEventListener("click", (e) => { if (e.target === overlay) close(); });
2865
+ overlay.addEventListener("keydown", (e) => { if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); close(); } });
2866
+ overlay.querySelector("[data-folder]").addEventListener("click", async () => {
2867
+ const files = await pickFilesForRelink({ folder: true });
2868
+ if (!files.length) return;
2869
+ // match each row by file name (then by size), copy only the matches
2870
+ const want = [];
2871
+ for (const m of list) {
2872
+ let best = null, bestScore = 0;
2873
+ for (const f of files) {
2874
+ const { score } = MediaLib.relinkScore(m, { name: f.name, size: f.size });
2875
+ if (score > bestScore && score >= 60) { best = f; bestScore = score; }
2876
+ }
2877
+ if (best) want.push([m, best]);
2878
+ }
2879
+ if (!want.length) { status.textContent = `None of the ${files.length} files in that folder match by name.`; return; }
2880
+ let i = 0;
2881
+ const ups = await uploadForRelink(want.map(([, f]) => f), (f) => { status.textContent = `Copying ${++i}/${want.length}: ${f.name}…`; });
2882
+ want.forEach(([m, f], k) => { if (ups[k].src) pick.set(m.id, { src: ups[k].src, label: `${f.name} (from the folder)` }); });
2883
+ status.textContent = `Matched ${ups.filter((u) => u.src).length} of ${list.length} by name.`;
2884
+ render();
2885
+ });
2886
+ overlay.querySelector("[data-apply]").addEventListener("click", async () => {
2887
+ const todo = list.filter((m) => pick.get(m.id));
2888
+ close();
2889
+ for (const m of todo) await setMediaSource(m, pick.get(m.id).src, "relink");
2890
+ scheduleOfflineCheck(0);
2891
+ });
2892
+ render();
2893
+ dialog.focus();
2894
+ // candidates found on disk (same name, other extension, similar name, same size)
2895
+ if (state.connected) {
2896
+ status.textContent = "Looking for the files…";
2897
+ try {
2898
+ const res = await fetch("/api/relink/candidates", {
2899
+ method: "POST", headers: { "Content-Type": "application/json" },
2900
+ body: JSON.stringify({ media: list.map((m) => ({ id: m.id, name: m.name, src: m.src, size: m.size, kind: m.kind })) }),
2901
+ });
2902
+ const { candidates } = await res.json();
2903
+ const used = new Set(project.media.map((x) => x.src));
2904
+ let found = 0;
2905
+ for (const m of list) {
2906
+ const opts = (candidates[m.id] || []).filter((o) => o.src !== m.src && (!used.has(o.src) || !isMediaOffline(m.id)));
2907
+ cands.set(m.id, opts);
2908
+ // a confident match is picked for you (same name, or same name with a matching size)
2909
+ if (opts[0] && opts[0].score >= 100 && !pick.get(m.id)) { pick.set(m.id, { src: opts[0].src, label: opts[0].name }); found++; }
2910
+ }
2911
+ status.textContent = found ? `Found ${found} of ${list.length} in the project folders.` : "";
2912
+ if (overlay.isConnected) render();
2913
+ } catch { status.textContent = ""; }
2914
+ }
2915
+ }
2916
+
2917
+ /* ── Proxies ──
2918
+ The server makes light H.264 copies of heavy footage (proxy.js). With the
2919
+ monitor's Proxy button on, video clips and the Source monitor play the
2920
+ proxy; export, still renders for agents and scopes always switch back to
2921
+ the original — so a proxy changes how smoothly you edit, never the result. */
2922
+ const proxyStatus = new Map(); // media id → {state, src?, height, width?, size?, progress?, error?}
2923
+ function proxyOf(m) { const s = m && proxyStatus.get(m.id); return s && s.state === "ready" ? s : null; }
2924
+ function proxiesOn() { return getSetting("useProxies") !== false; }
2925
+ /** The file a player should load for this media now: the proxy while editing, the original for output. */
2926
+ function mediaPlaySrc(m) {
2927
+ if (!m || m.kind !== "video" || state.exporting || runtime.forceOriginals || !proxiesOn()) return m && m.src;
2928
+ const p = proxyOf(m);
2929
+ return p ? p.src : m.src;
2930
+ }
2931
+ /** Switch every player to the original files and wait until they can draw (export, still renders). */
2932
+ async function useOriginalPlayers() {
2933
+ runtime.forceOriginals = true;
2934
+ const waits = [];
2935
+ for (const c of mediaClips()) {
2936
+ if (c.kind !== "video" || !clipRenders(c)) continue;
2937
+ const el = getClipEl(c);
2938
+ if (el) waits.push(waitMediaEl(el));
2939
+ }
2940
+ await Promise.all(waits);
2941
+ }
2942
+ function releaseOriginalPlayers() {
2943
+ if (!runtime.forceOriginals) return;
2944
+ runtime.forceOriginals = false;
2945
+ state.dirtyTimeline = true;
2946
+ seekMediaWhilePaused();
2947
+ }
2948
+ async function refreshProxyStatus() {
2949
+ if (!state.connected) return;
2950
+ const vids = project.media.filter((m) => m.kind === "video" && !m.transient && isLocalSrc(m.src));
2951
+ if (!vids.length) { if (proxyStatus.size) { proxyStatus.clear(); renderBin(); } return; }
2952
+ try {
2953
+ const res = await fetch("/api/proxy/status", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ srcs: [...new Set(vids.map((m) => m.src))] }) });
2954
+ if (!res.ok) return;
2955
+ const { status } = await res.json();
2956
+ const before = JSON.stringify([...proxyStatus]);
2957
+ proxyStatus.clear();
2958
+ for (const m of vids) { const s = status[m.src]; if (s && s.state !== "none") proxyStatus.set(m.id, s); }
2959
+ if (JSON.stringify([...proxyStatus]) !== before) onProxiesChanged();
2960
+ } catch { }
2961
+ }
2962
+ /** SSE "proxy": one file's proxy moved on (queued, progress, ready, failed, deleted). */
2963
+ function onProxyEvent(data) {
2964
+ let ev; try { ev = JSON.parse(data); } catch { return; }
2965
+ let hit = false;
2966
+ for (const m of project.media) {
2967
+ if (m.src !== ev.src) continue;
2968
+ hit = true;
2969
+ const s = ev.status || { state: "none" };
2970
+ if (s.state === "none") proxyStatus.delete(m.id); else proxyStatus.set(m.id, s);
2971
+ if (s.state === "ready" && runtime.proxyAsked?.has(m.id)) { runtime.proxyAsked.delete(m.id); toast(`Proxy ready: ${m.name}`); }
2972
+ if (s.state === "failed" && runtime.proxyAsked?.has(m.id)) { runtime.proxyAsked.delete(m.id); toast(`Couldn't make a proxy of ${m.name}: ${s.error}`); }
2973
+ }
2974
+ if (!hit) return;
2975
+ if (ev.status && ev.status.state === "running") { renderBinProxyBadges(); return; } // progress: just the badges
2976
+ onProxiesChanged();
2977
+ }
2978
+ function onProxiesChanged() {
2979
+ renderBin();
2980
+ syncProxyButton();
2981
+ state.dirtyTimeline = true;
2982
+ seekMediaWhilePaused(); // players switch file on the next frame; park the new ones on the playhead
2983
+ }
2984
+ /* Progress ticks repaint only the badges, not the whole bin. */
2985
+ function renderBinProxyBadges() {
2986
+ for (const el of els.binList.querySelectorAll(".bin-item[data-media-id] .bin-proxy")) {
2987
+ const s = proxyStatus.get(el.closest(".bin-item").dataset.mediaId);
2988
+ if (s && s.state === "running") el.textContent = `P ${Math.round((s.progress || 0) * 100)}%`;
2989
+ }
2990
+ }
2991
+ function proxyBadgeHtml(m) {
2992
+ const s = proxyStatus.get(m.id);
2993
+ if (!s || m.kind !== "video") return "";
2994
+ if (s.state === "ready") return `<span class="bin-proxy ready${proxiesOn() ? " on" : ""}" title="Proxy ready (${s.width ? s.width + "×" : ""}${s.height}p, ${MediaLib.fmtSize(s.size)})${proxiesOn() ? " — playing it while you edit" : " — the Proxy button is off"}">P</span>`;
2995
+ if (s.state === "running" || s.state === "queued") return `<span class="bin-proxy busy" title="Making a ${s.height}p proxy">P ${s.state === "running" ? Math.round((s.progress || 0) * 100) + "%" : "…"}</span>`;
2996
+ if (s.state === "failed") return `<span class="bin-proxy failed" title="Proxy failed: ${escapeHtml(s.error || "")}">P ✕</span>`;
2997
+ return "";
2998
+ }
2999
+ function proxyLabel(m) {
3000
+ const s = proxyStatus.get(m.id);
3001
+ if (m.kind !== "video") return "";
3002
+ if (!s) return "none";
3003
+ if (s.state === "ready") return `${s.height}p`;
3004
+ if (s.state === "running") return Math.round((s.progress || 0) * 100) + "%";
3005
+ return s.state;
3006
+ }
3007
+ async function createProxies(list, height) {
3008
+ list = list.filter((m) => m.kind === "video" && !m.transient && isLocalSrc(m.src) && !isMediaOffline(m.id));
3009
+ if (!list.length) { toast("No video to make proxies of"); return; }
3010
+ if (!state.ffmpeg) { toast("Proxies need ffmpeg on the server's PATH"); return; }
3011
+ (runtime.proxyAsked ||= new Set());
3012
+ for (const m of list) runtime.proxyAsked.add(m.id);
3013
+ try {
3014
+ const res = await fetch("/api/proxy", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ srcs: [...new Set(list.map((m) => m.src))], height }) });
3015
+ const body = await res.json();
3016
+ if (!res.ok) throw new Error(body.error || res.status);
3017
+ for (const m of list) { const s = body.status[m.src]; if (s) proxyStatus.set(m.id, s); if (s && s.state === "ready") runtime.proxyAsked.delete(m.id); }
3018
+ onProxiesChanged();
3019
+ const queued = list.filter((m) => proxyStatus.get(m.id)?.state !== "ready").length;
3020
+ toast(queued ? `Making ${queued} prox${queued === 1 ? "y" : "ies"} in the background — the bin shows the progress` : "Already has a proxy");
3021
+ } catch (e) { toast("Couldn't start the proxies: " + (e.message || e)); }
3022
+ }
3023
+ async function deleteProxies(list) {
3024
+ try {
3025
+ await fetch("/api/proxy/delete", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ srcs: list.map((m) => m.src) }) });
3026
+ } catch { }
3027
+ for (const m of list) proxyStatus.delete(m.id);
3028
+ onProxiesChanged();
3029
+ }
3030
+ function syncProxyButton() {
3031
+ const b = els.btnProxy;
3032
+ if (!b) return;
3033
+ const n = project.media.filter((m) => proxyOf(m)).length;
3034
+ b.classList.toggle("on", proxiesOn());
3035
+ b.classList.toggle("has", n > 0);
3036
+ b.title = (proxiesOn() ? "Proxies on: " : "Proxies off: ") +
3037
+ (n ? `${n} file${n === 1 ? " has a proxy" : "s have proxies"}` : "no proxies yet (right-click a video in the bin → Create proxy)") +
3038
+ ". Export always uses the originals.";
3039
+ }
3040
+
2091
3041
  /* Open the native file dialog. Windows anchors it to the <input>'s screen
2092
3042
  position — park the input under the cursor and open after the mouse
2093
3043
  gesture finishes so the dialog doesn't appear then jump. */
@@ -2101,6 +3051,23 @@ function openFileImport(clientX, clientY) {
2101
3051
  setTimeout(() => input.click(), 0);
2102
3052
  }
2103
3053
 
3054
+ /* Bin search / Show / Sort / view controls. */
3055
+ els.binSearch.addEventListener("input", () => { binView.q = els.binSearch.value; renderBin(); });
3056
+ els.binSearch.addEventListener("keydown", (e) => {
3057
+ if (e.key === "Escape") { e.preventDefault(); binView.q = ""; els.binSearch.value = ""; renderBin(); els.binSearch.blur(); }
3058
+ e.stopPropagation();
3059
+ });
3060
+ els.binFilter.addEventListener("change", () => setBinFilter(els.binFilter.value));
3061
+ els.binSort.addEventListener("change", () => { binView.sort = els.binSort.value; saveBinPrefs(); renderBin(); });
3062
+ els.binSortDir.addEventListener("click", () => { binView.dir = binView.dir === "desc" ? "asc" : "desc"; saveBinPrefs(); renderBin(); });
3063
+ els.binViewBtn.addEventListener("click", () => { binView.list = !binView.list; saveBinPrefs(); renderBin(); });
3064
+
3065
+ els.btnProxy?.addEventListener("click", () => {
3066
+ setSetting("useProxies", !proxiesOn());
3067
+ onProxiesChanged();
3068
+ toast(proxiesOn() ? "Proxies on — files with a proxy play it while you edit" : "Proxies off — every clip plays its original");
3069
+ });
3070
+
2104
3071
  /* Ctrl/Cmd+click in the Project bin opens the file importer. */
2105
3072
  els.binList.addEventListener("click", (e) => {
2106
3073
  if (!(e.ctrlKey || e.metaKey) || e.button !== 0) return;
@@ -2144,7 +3111,7 @@ function mediaForLibraryItem(f) {
2144
3111
  return m;
2145
3112
  }
2146
3113
  async function addLibraryItem(f, trackId, at) {
2147
- const m = mediaForLibraryItem(f);
3114
+ const m = mediaForLibraryItem(f), gen = runtime.projectGen;
2148
3115
  if (!m) { toast("Unsupported file type: " + f.name); return; }
2149
3116
  if ((m.kind === "audio" || m.kind === "video") && (m.duration == null || isNaN(m.duration))) {
2150
3117
  try { await loadMediaMetadata(m); } catch { }
@@ -2157,6 +3124,7 @@ async function addLibraryItem(f, trackId, at) {
2157
3124
  if (m.kind === "image" && !runtime.mediaAux.get(m.id)?.img) {
2158
3125
  try { await loadMediaMetadata(m); } catch { }
2159
3126
  }
3127
+ if (gen !== runtime.projectGen) return; // another project was opened meanwhile
2160
3128
  addClipFromMedia(m, trackId, at);
2161
3129
  }
2162
3130
  function toggleSfxPreview(f, btn) {
@@ -2228,11 +3196,606 @@ function setBinTab(tab) {
2228
3196
  const isProj = tab === "project";
2229
3197
  els.binList.classList.toggle("hidden", !isProj);
2230
3198
  els.libList.classList.toggle("hidden", isProj);
3199
+ if (els.binTools) els.binTools.classList.toggle("hidden", !isProj);
2231
3200
  if (tab === "shapes") renderShapesTab();
2232
3201
  else if (tab === "templates") { renderTemplatesTab(); fetchSaved("templates").then(() => { if (state.binTab === "templates") renderTemplatesTab(); }); }
2233
3202
  else if (!isProj) fetchLibrary(tab).then(renderLibrary);
2234
3203
  }
2235
3204
 
3205
+ /* ═══════════════════════════ PROJECTS (dashboard) ═══════════════════════════ */
3206
+ /* Several projects in one data folder (projects.js on the server). The open one
3207
+ is always ./project.json, so everything else in the editor is unchanged; the
3208
+ dashboard lists the others and switches between them. A switch shows up in
3209
+ syncFromServer as a new X-FableCut-Project id, wherever it came from (this
3210
+ tab, another tab, an agent): undo, the open comp and the Source monitor
3211
+ belong to the old project and are reset there. */
3212
+ const pj = {
3213
+ view: "active", // active | archived
3214
+ mode: "detail", // detail | new
3215
+ sel: null, list: [], templates: [], tpl: "landscape-1080",
3216
+ sort: "opened", search: "", busy: false, selfSwitch: false,
3217
+ verOf: null, versions: [], verDiff: new Map(), // the versions view: whose, its list, open comparisons
3218
+ verDiffGen: 0, verPending: false, // bumped when comparisons are dropped · a list refresh waiting for a busy action
3219
+ };
3220
+ const pjFmtDur = (s) => {
3221
+ if (!(s > 0)) return "0:00";
3222
+ const m = Math.floor(s / 60), r = Math.floor(s % 60);
3223
+ return m >= 60 ? `${Math.floor(m / 60)}:${String(m % 60).padStart(2, "0")}:${String(r).padStart(2, "0")}` : `${m}:${String(r).padStart(2, "0")}`;
3224
+ };
3225
+ function pjAgo(iso) {
3226
+ if (!iso) return "never";
3227
+ const s = (Date.now() - new Date(iso).getTime()) / 1000;
3228
+ if (!(s >= 0)) return new Date(iso).toLocaleDateString();
3229
+ if (s < 60) return "just now";
3230
+ if (s < 3600) return `${Math.floor(s / 60)} min ago`;
3231
+ if (s < 86400) return `${Math.floor(s / 3600)} h ago`;
3232
+ if (s < 86400 * 7) return `${Math.floor(s / 86400)} d ago`;
3233
+ return new Date(iso).toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });
3234
+ }
3235
+ const pjFps = (f) => (f ? `${+(+f).toFixed(3)} fps` : "");
3236
+ async function pjPost(body) {
3237
+ try {
3238
+ const res = await fetch("/api/projects", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
3239
+ const out = await res.json().catch(() => ({}));
3240
+ if (!res.ok) { toast(out.error || `Projects: request failed (${res.status})`); return null; }
3241
+ return out;
3242
+ } catch { toast("Projects: the editor server did not answer"); return null; }
3243
+ }
3244
+ /* The program monitor's picture, small, as the open project's card thumbnail. */
3245
+ async function pjSnapThumb() {
3246
+ const id = runtime.projectId, cv = els.preview;
3247
+ if (!id || !cv || !cv.width || !cv.height) return;
3248
+ try {
3249
+ const w = 360, h = Math.max(1, Math.round(w * cv.height / cv.width));
3250
+ const c = document.createElement("canvas");
3251
+ c.width = w; c.height = h;
3252
+ c.getContext("2d").drawImage(cv, 0, 0, w, h);
3253
+ const blob = await new Promise((r) => c.toBlob(r, "image/jpeg", 0.74));
3254
+ if (blob) await fetch("/api/projects/thumb?id=" + encodeURIComponent(id), { method: "PUT", body: blob });
3255
+ } catch { }
3256
+ }
3257
+ async function pjLoad() {
3258
+ try {
3259
+ const res = await fetch("/api/projects?archived=" + (pj.view === "archived" ? "only" : "exclude"), { cache: "no-store" });
3260
+ if (!res.ok) throw new Error();
3261
+ const data = await res.json();
3262
+ pj.list = data.projects || [];
3263
+ pj.templates = data.templates || [];
3264
+ // syncFromServer owns runtime.projectId: it resets undo, comp and Source on a switch.
3265
+ // On first use the list has just given the shown project.json its id: adopt it, if
3266
+ // project.json is still the document this tab shows.
3267
+ if (data.active && !runtime.projectId) {
3268
+ const r = await fetch("/api/project", { cache: "no-store" }).catch(() => null);
3269
+ const doc = r && r.ok ? await r.json().catch(() => null) : null;
3270
+ const ids = (d) => JSON.stringify([d.name, d.revision || 0, (d.clips || []).map((c) => c.id), (d.media || []).map((m) => m.id)]);
3271
+ const shown = projectJSON();
3272
+ if (doc && r.headers.get("X-FableCut-Project") === data.active && ids(doc) === ids(shown)) runtime.projectId = data.active;
3273
+ else { runtime.projectId = "?"; syncFromServer(true); } // not what this tab shows: load it as a switch
3274
+ } else if (data.active && data.active !== runtime.projectId) syncFromServer(true);
3275
+ if (!pj.list.some((p) => p.id === pj.sel)) pj.sel = (pj.list.find((p) => p.active) || pj.list[0] || {}).id || null;
3276
+ } catch { pj.list = []; toast("Projects: couldn't read the project list"); }
3277
+ renderProjects();
3278
+ }
3279
+ async function openProjects() {
3280
+ const ov = $("projectsOverlay");
3281
+ if (!ov || !state.connected) return;
3282
+ pj.mode = "detail"; pj.view = "active"; pj.sel = runtime.projectId;
3283
+ pj.verOf = null; pjDropDiffs(); // a versions list left open last time may be out of date
3284
+ ov.classList.remove("hidden");
3285
+ $("projectsDialog")?.focus();
3286
+ renderProjects(); // the shell at once; cards once the list is in
3287
+ await flushSave();
3288
+ await pjSnapThumb();
3289
+ await pjLoad();
3290
+ }
3291
+ function closeProjects() {
3292
+ $("projectsOverlay")?.classList.add("hidden");
3293
+ $("btnProjectsDash")?.focus();
3294
+ }
3295
+ const projectsOpen = () => !!$("projectsOverlay") && !$("projectsOverlay").classList.contains("hidden");
3296
+ function pjVisible() {
3297
+ const q = pj.search.trim().toLowerCase();
3298
+ const words = q ? q.split(/\s+/) : [];
3299
+ const hit = (p, w) => w.startsWith("#")
3300
+ ? (p.tags || []).some((t) => t.toLowerCase().includes(w.slice(1)))
3301
+ : [p.name, p.notes, ...(p.tags || [])].some((s) => String(s || "").toLowerCase().includes(w));
3302
+ const out = pj.list.filter((p) => words.every((w) => hit(p, w)));
3303
+ const key = { opened: (p) => p.opened || p.modified || "", modified: (p) => p.modified || "", created: (p) => p.created || "" }[pj.sort];
3304
+ if (key) out.sort((a, b) => String(key(b)).localeCompare(String(key(a))));
3305
+ else out.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" }));
3306
+ return out;
3307
+ }
3308
+ function pjThumbHtml(p, big) {
3309
+ const ar = p.width > 0 && p.height > 0 ? `${p.width} / ${p.height}` : "16 / 9";
3310
+ const inner = p.thumb
3311
+ ? `<img src="/api/projects/thumb?id=${encodeURIComponent(p.id)}&v=${p.thumb}" alt="" loading="lazy" draggable="false">`
3312
+ : `<span>${p.width ? `${p.width}×${p.height}` : "?"}</span>`;
3313
+ return `<div class="pj-thumb${big ? " big" : ""}"><div class="pj-frame" style="aspect-ratio:${ar}">${inner}</div></div>`;
3314
+ }
3315
+ function renderProjects() {
3316
+ renderProjectGrid();
3317
+ renderProjectSide();
3318
+ }
3319
+ function renderProjectSide() {
3320
+ const side = $("pjSide");
3321
+ if (side) side.innerHTML = pj.mode === "new" ? pjNewHtml() : pjDetailHtml(pj.list.find((p) => p.id === pj.sel));
3322
+ $("pjNewBtn")?.classList.toggle("on", pj.mode === "new");
3323
+ }
3324
+ function renderProjectGrid() {
3325
+ const grid = $("pjGrid");
3326
+ if (!grid) return;
3327
+ for (const b of document.querySelectorAll("[data-pj-view]")) b.classList.toggle("on", b.dataset.pjView === pj.view);
3328
+ grid.classList.toggle("versions", !!pj.verOf);
3329
+ if (pj.verOf) { grid.innerHTML = pjVersionsHtml(); return; }
3330
+ const rows = pjVisible();
3331
+ grid.innerHTML = rows.length ? rows.map((p) => `
3332
+ <button type="button" class="pj-card${p.id === pj.sel && pj.mode === "detail" ? " sel" : ""}${p.active ? " open" : ""}" data-pj="${escapeHtml(p.id)}" title="${p.active ? "Currently open" : "Double-click to open"}">
3333
+ ${pjThumbHtml(p)}
3334
+ <span class="pj-card-name">${escapeHtml(p.name)}${p.active ? ` <span class="pj-badge">Open</span>` : ""}</span>
3335
+ <span class="pj-card-meta">${p.unreadable ? "file unreadable" : `${p.width}×${p.height} · ${pjFps(p.fps)} · ${pjFmtDur(p.duration)}`}</span>
3336
+ <span class="pj-card-when dim">${pj.sort === "created" ? "Created " + pjAgo(p.created) : pj.sort === "modified" || !p.opened ? "Modified " + pjAgo(p.modified) : "Opened " + pjAgo(p.opened)}</span>
3337
+ </button>`).join("")
3338
+ : `<div class="pj-empty dim">${pj.list.length ? "No project matches the search." : pj.view === "archived" ? "Nothing archived. Archive a project to keep it out of the list without deleting it." : "Loading…"}</div>`;
3339
+ }
3340
+ function pjDetailHtml(p) {
3341
+ if (!p) return `<p class="dim">Pick a project to see its details.</p>`;
3342
+ const fact = (k, v) => `<dt>${k}</dt><dd>${v}</dd>`;
3343
+ const tpl = p.template && pj.templates.find((t) => t.id === p.template);
3344
+ return `${pjThumbHtml(p, true)}
3345
+ <label class="pj-field"><span>Name</span><input type="text" id="pjName" value="${escapeHtml(p.name)}" maxlength="120" spellcheck="false"></label>
3346
+ <dl class="pj-facts">
3347
+ ${fact("Canvas", p.unreadable ? "—" : `${p.width}×${p.height} · ${pjFps(p.fps)}`)}
3348
+ ${fact("Length", `${pjFmtDur(p.duration)} · ${p.clips} clip${p.clips === 1 ? "" : "s"} · ${p.media} media`)}
3349
+ ${fact("Modified", pjAgo(p.modified))}
3350
+ ${fact("Opened", p.active ? "open now" : pjAgo(p.opened))}
3351
+ ${fact("Created", pjAgo(p.created))}
3352
+ ${tpl ? fact("Template", escapeHtml(tpl.name)) : ""}
3353
+ </dl>
3354
+ <label class="pj-field"><span>Notes</span><textarea id="pjNotes" rows="4" maxlength="4000" placeholder="Brief, client, deadline, what's left to do…">${escapeHtml(p.notes || "")}</textarea></label>
3355
+ <label class="pj-field"><span>Tags</span><input type="text" id="pjTags" value="${escapeHtml((p.tags || []).join(", "))}" placeholder="client, reel, draft" spellcheck="false"></label>
3356
+ <div class="pj-actions">
3357
+ ${p.archived
3358
+ ? `<button type="button" class="btn primary" data-pj-act="unarchive">Unarchive</button>
3359
+ <button type="button" class="btn danger-ghost" data-pj-act="delete" title="Deletes the project file. Its media stay in media/.">Delete…</button>`
3360
+ : `<button type="button" class="btn primary" data-pj-act="open"${p.active ? " disabled" : ""}>${p.active ? "Currently open" : "Open"}</button>
3361
+ <button type="button" class="btn" data-pj-act="duplicate" title="A copy of the whole project (the footage is shared, not copied)">Duplicate</button>
3362
+ <button type="button" class="btn" data-pj-act="template" title="Start new projects from this one: its canvas, tracks, clips and media">Save as template</button>
3363
+ <button type="button" class="btn" data-pj-act="archive"${p.active ? ` disabled title="Open another project first"` : ` title="Hide it from the list; nothing is deleted"`}>Archive</button>`}
3364
+ </div>
3365
+ <div class="pj-actions">
3366
+ <button type="button" class="btn" data-pj-act="versions" title="Saved versions of this project: compare, restore, mark the final cut">Versions…</button>
3367
+ <a class="btn" href="/api/projects/backup?id=${encodeURIComponent(p.id)}" download${p.active ? " data-pj-backup" : ""} title="The project and all its versions as one file. Import… restores it">Download backup</a>
3368
+ </div>
3369
+ <div class="pj-inline hidden" id="pjTplRow">
3370
+ <input type="text" id="pjTplName" value="${escapeHtml(p.name)}" maxlength="120" aria-label="Template name" spellcheck="false">
3371
+ <button type="button" class="btn primary" data-pj-act="template-save">Save template</button>
3372
+ </div>`;
3373
+ }
3374
+ function pjNewHtml() {
3375
+ const tpls = pj.templates;
3376
+ if (!tpls.some((t) => t.id === pj.tpl)) pj.tpl = "landscape-1080";
3377
+ const t = tpls.find((x) => x.id === pj.tpl) || { fps: 30 };
3378
+ const shape = (x) => {
3379
+ const k = 22 / Math.max(x.width || 16, x.height || 9);
3380
+ return `<i class="pj-shape" style="width:${Math.round((x.width || 16) * k)}px;height:${Math.round((x.height || 9) * k)}px"></i>`;
3381
+ };
3382
+ const row = (x) => `<button type="button" class="pj-tpl${x.id === pj.tpl ? " on" : ""}" data-pj-tpl="${escapeHtml(x.id)}">
3383
+ ${shape(x)}<span class="pj-tpl-name">${escapeHtml(x.name)}</span>
3384
+ <span class="pj-tpl-meta dim">${x.width}×${x.height}${x.builtin ? "" : ` · ${x.clips} clip${x.clips === 1 ? "" : "s"}`}</span>
3385
+ ${x.builtin ? "" : `<span class="pj-tpl-del" data-pj-tpldel="${escapeHtml(x.id)}" role="button" tabindex="0" title="Delete this template">✕</span>`}
3386
+ </button>`;
3387
+ const saved = tpls.filter((x) => !x.builtin);
3388
+ return `<h3>New project</h3>
3389
+ <label class="pj-field"><span>Name</span><input type="text" id="pjNewName" value="Untitled Project" maxlength="120" spellcheck="false"></label>
3390
+ <div class="pj-field"><span>Start from</span>
3391
+ <div class="pj-tpls">${tpls.filter((x) => x.builtin).map(row).join("")}</div>
3392
+ ${saved.length ? `<span class="pj-sub">Saved templates</span><div class="pj-tpls">${saved.map(row).join("")}</div>` : ""}
3393
+ </div>
3394
+ <label class="pj-field"><span>Frame rate</span><select id="pjNewFps">
3395
+ <option value="">${t.fps ? `${+(+t.fps).toFixed(3)} fps (template)` : "Template's"}</option>
3396
+ ${[23.976, 24, 25, 29.97, 30, 50, 59.94, 60].map((f) => `<option value="${f}">${f} fps</option>`).join("")}
3397
+ </select></label>
3398
+ <div class="pj-actions">
3399
+ <button type="button" class="btn" data-pj-act="new-cancel">Cancel</button>
3400
+ <button type="button" class="btn primary" data-pj-act="new-create">Create and open</button>
3401
+ </div>`;
3402
+ }
3403
+ async function pjOpenProject(id) {
3404
+ const p = pj.list.find((x) => x.id === id);
3405
+ if (!p || p.active || pj.busy) return;
3406
+ if (state.exporting) { toast("Wait for the export to finish before switching projects"); return; }
3407
+ pj.busy = true;
3408
+ try {
3409
+ if (!(await flushSaveBeforeSwitch())) return;
3410
+ await pjSnapThumb();
3411
+ pj.selfSwitch = true;
3412
+ const out = await pjPost({ action: "open", id });
3413
+ if (!out) return;
3414
+ closeProjects();
3415
+ if (await syncFromServer(true)) toast(`Opened “${out.project?.name || p.name}”`);
3416
+ else toast(`“${out.project?.name || p.name}” is open, but this tab couldn't load it yet. It will reload when the editor server answers.`);
3417
+ } finally { pj.busy = false; pj.selfSwitch = false; }
3418
+ }
3419
+ async function pjBusy(fn) {
3420
+ pj.busy = true;
3421
+ try { return await fn(); } finally { pj.busy = false; }
3422
+ }
3423
+ async function pjAction(act, btn) {
3424
+ const p = pj.list.find((x) => x.id === pj.sel);
3425
+ if (act === "new-cancel") { pj.mode = "detail"; renderProjects(); return; }
3426
+ if (act === "new-create") {
3427
+ if (pj.busy) return;
3428
+ if (state.exporting) { toast("Wait for the export to finish before switching projects"); return; }
3429
+ const name = ($("pjNewName")?.value || "").trim() || "Untitled Project";
3430
+ const fps = $("pjNewFps")?.value;
3431
+ pj.busy = true;
3432
+ try {
3433
+ if (!(await flushSaveBeforeSwitch())) return;
3434
+ await pjSnapThumb();
3435
+ pj.selfSwitch = true;
3436
+ const out = await pjPost({ action: "new", name, template: pj.tpl, fps: fps ? +fps : undefined, open: true });
3437
+ if (!out) return;
3438
+ closeProjects();
3439
+ if (await syncFromServer(true)) toast(`Created “${name}”`);
3440
+ else toast(`“${name}” was created and opened, but this tab couldn't load it yet. It will reload when the editor server answers.`);
3441
+ } finally { pj.busy = false; pj.selfSwitch = false; }
3442
+ return;
3443
+ }
3444
+ if (!p) return;
3445
+ if (act === "open") { pjOpenProject(p.id); return; }
3446
+ if (act === "template") { $("pjTplRow")?.classList.toggle("hidden"); $("pjTplName")?.select(); return; }
3447
+ if (act === "versions") { pj.verOf = p.id; pj.versions = []; pjDropDiffs(); renderProjectGrid(); pjLoadVersions(); return; }
3448
+ if (pj.busy) return; // one request at a time: a second click must not duplicate twice
3449
+ if (act === "template-save") {
3450
+ const out = await pjBusy(() => pjPost({ action: "save_template", id: p.id, name: $("pjTplName")?.value || p.name }));
3451
+ if (out) { toast(`Saved template “${out.template.name}” — pick it under + New project`); await pjLoad(); }
3452
+ return;
3453
+ }
3454
+ if (act === "delete") {
3455
+ if (btn.dataset.armed !== "1") {
3456
+ btn.dataset.armed = "1"; btn.textContent = "Click again to delete";
3457
+ setTimeout(() => { if (btn.isConnected) { btn.dataset.armed = ""; btn.textContent = "Delete…"; } }, 3000);
3458
+ return;
3459
+ }
3460
+ const out = await pjBusy(() => pjPost({ action: "delete", id: p.id }));
3461
+ if (out) { toast(`Deleted “${p.name}”`); pj.sel = null; await pjLoad(); }
3462
+ return;
3463
+ }
3464
+ const out = await pjBusy(() => pjPost({ action: act, id: p.id }));
3465
+ if (!out) return;
3466
+ if (act === "duplicate") { pj.sel = out.id; toast(`Duplicated as “${out.project.name}”`); }
3467
+ if (act === "archive") toast(`Archived “${p.name}” — it's under Archived`);
3468
+ if (act === "unarchive") toast(`“${p.name}” is back in Projects`);
3469
+ await pjLoad();
3470
+ }
3471
+ async function pjSaveField(field) {
3472
+ const p = pj.list.find((x) => x.id === pj.sel);
3473
+ if (!p) return;
3474
+ const el = $({ name: "pjName", notes: "pjNotes", tags: "pjTags" }[field]);
3475
+ if (!el) return;
3476
+ const v = el.value;
3477
+ if (field === "name" && (!v.trim() || v.trim() === p.name)) { if (!v.trim()) el.value = p.name; return; }
3478
+ if (field === "notes" && v === (p.notes || "")) return;
3479
+ if (field === "tags" && v === (p.tags || []).join(", ")) return;
3480
+ const out = await pjPost({ action: "update", id: p.id, [field]: field === "name" ? v.trim() : v });
3481
+ if (!out) return;
3482
+ Object.assign(p, out.project);
3483
+ if (field === "tags") el.value = (out.project.tags || []).join(", ");
3484
+ if (field === "name") renderProjectGrid();
3485
+ }
3486
+ async function pjImport(file) {
3487
+ let doc;
3488
+ try { doc = JSON.parse((await file.text()).replace(/^/, "")); }
3489
+ catch { toast(`${file.name} isn't JSON`); return; }
3490
+ const name = doc && doc.name && doc.name !== "Untitled Project" ? doc.name : file.name.replace(/\.json$/i, "");
3491
+ const out = await pjPost({ action: "import", project: doc, name });
3492
+ if (!out) return;
3493
+ pj.view = "active"; pj.mode = "detail"; pj.sel = out.id;
3494
+ toast(`Imported “${out.project.name}” — its media must be in media/ (Relink finds moved files)`);
3495
+ await pjLoad();
3496
+ }
3497
+ /* Versions of one project (history.js on the server), shown in the dashboard's
3498
+ main area in place of the cards. Restoring never loses anything: the server
3499
+ saves what was there as a version first. */
3500
+ const VER_KIND = { manual: "", auto: "Auto", agent: "Agent", restore: "Before restore" };
3501
+ /** Drop the open comparisons, and any still on their way: they were against an older state. */
3502
+ function pjDropDiffs() { pj.verDiff.clear(); pj.verDiffGen++; }
3503
+ async function pjLoadVersions() {
3504
+ const id = pj.verOf;
3505
+ if (!id) return;
3506
+ const seq = pj.verSeq = (pj.verSeq || 0) + 1;
3507
+ // only the newest request for the project still shown may change the list
3508
+ const current = () => seq === pj.verSeq && pj.verOf === id;
3509
+ try {
3510
+ const res = await fetch("/api/versions?project=" + encodeURIComponent(id), { cache: "no-store" });
3511
+ const data = await res.json();
3512
+ if (!res.ok) throw new Error(data.error);
3513
+ if (!current()) return;
3514
+ pj.versions = data.versions || [];
3515
+ } catch (e) {
3516
+ if (!current()) return;
3517
+ pj.versions = []; toast("Versions: " + (e.message || "couldn't read them"));
3518
+ }
3519
+ // what is being typed in Save version survives the repaint
3520
+ const draft = { name: $("verName")?.value, note: $("verNote")?.value, focus: document.activeElement?.id };
3521
+ renderProjectGrid();
3522
+ if (draft.name != null && $("verName")) $("verName").value = draft.name;
3523
+ if (draft.note != null && $("verNote")) $("verNote").value = draft.note;
3524
+ if ((draft.focus === "verName" || draft.focus === "verNote") && $(draft.focus)) $(draft.focus).focus();
3525
+ }
3526
+ function pjVersionsHtml() {
3527
+ const p = pj.list.find((x) => x.id === pj.verOf) || { name: "Project" };
3528
+ const rows = pj.versions.map((v) => {
3529
+ const diff = pj.verDiff.get(v.v);
3530
+ return `<div class="ver-row${v.final ? " final" : ""}" data-ver="${v.v}">
3531
+ <div class="ver-main">
3532
+ <span class="ver-num">v${v.v}</span>
3533
+ <span class="ver-name" title="${escapeHtml(v.name)}">${escapeHtml(v.name)}</span>
3534
+ ${v.final ? `<span class="ver-badge final">Final</span>` : ""}
3535
+ ${VER_KIND[v.kind] ? `<span class="ver-badge">${VER_KIND[v.kind]}</span>` : ""}
3536
+ <span class="ver-meta dim">${pjAgo(v.created)} · ${pjFmtDur(v.duration)} · ${v.clips} clip${v.clips === 1 ? "" : "s"}</span>
3537
+ </div>
3538
+ ${v.note ? `<div class="ver-note">${escapeHtml(v.note)}</div>` : ""}
3539
+ ${diff ? `<ul class="ver-diff">${diff.length ? diff.map((l) => `<li>${escapeHtml(l)}</li>`).join("") : "<li>Same as now.</li>"}</ul>` : ""}
3540
+ <div class="ver-actions">
3541
+ <button type="button" class="btn tiny" data-ver-act="diff">${diff ? "Hide changes" : "Compare with now"}</button>
3542
+ <button type="button" class="btn tiny" data-ver-act="restore" title="Put this version back. What is there now is saved as a version first.">Restore…</button>
3543
+ <button type="button" class="btn tiny" data-ver-act="final">${v.final ? "Unmark final" : "Mark final"}</button>
3544
+ <button type="button" class="btn tiny" data-ver-act="rename">Rename</button>
3545
+ <a class="btn tiny" href="/api/versions/file?project=${encodeURIComponent(pj.verOf)}&version=${v.v}" download>Download</a>
3546
+ <button type="button" class="btn tiny danger-ghost" data-ver-act="delete"${v.final ? ` disabled title="Unmark it as final first"` : ""}>Delete…</button>
3547
+ </div>
3548
+ </div>`;
3549
+ }).join("");
3550
+ return `<div class="ver-view">
3551
+ <div class="ver-head">
3552
+ <button type="button" class="btn tiny" data-ver-act="back">← All projects</button>
3553
+ <h3>Versions of ${escapeHtml(p.name)}</h3>
3554
+ </div>
3555
+ <div class="ver-save">
3556
+ <input type="text" id="verName" maxlength="120" placeholder="Name (optional), e.g. Client cut" spellcheck="false" aria-label="Version name">
3557
+ <input type="text" id="verNote" maxlength="2000" placeholder="Note (optional)" aria-label="Version note">
3558
+ <button type="button" class="btn primary" data-ver-act="save">Save version</button>
3559
+ </div>
3560
+ <p class="dim ver-hint">Versions are also saved on their own every 10 minutes while the project changes, and before an agent edits it.${p.active ? " Ctrl/Cmd+S saves one from anywhere in the editor." : ""}</p>
3561
+ ${rows || `<div class="pj-empty dim">No versions yet. Save one to have a point to come back to.</div>`}
3562
+ </div>`;
3563
+ }
3564
+ async function pjVersionAction(act, btn) {
3565
+ if (act === "back") { pj.verOf = null; pjDropDiffs(); renderProjects(); return; }
3566
+ if (pj.busy) return;
3567
+ // busy from before the first await, so a second click can't start the same action again
3568
+ if (act === "rename") return pjVersionRun(act, btn);
3569
+ pj.verPending = false;
3570
+ await pjBusy(() => pjVersionRun(act, btn));
3571
+ if (pj.verPending && pj.verOf) { pj.verPending = false; pjDropDiffs(); pjLoadVersions(); } // changed elsewhere meanwhile
3572
+ }
3573
+ async function pjVersionRun(act, btn) {
3574
+ const p = pj.list.find((x) => x.id === pj.verOf);
3575
+ if (!p) return;
3576
+ const row = btn.closest("[data-ver]"), v = row ? +row.dataset.ver : null;
3577
+ const post = (body) => fetch("/api/versions", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ project: p.id, ...body }) })
3578
+ .then(async (r) => { const out = await r.json().catch(() => ({})); if (!r.ok) { toast(out.error || "Versions: request failed"); return null; } return out; })
3579
+ .catch(() => { toast("Versions: the editor server did not answer"); return null; });
3580
+ if (act === "save") {
3581
+ if (p.active && !(await flushSaveForVersion("no version was made"))) return;
3582
+ const out = await post({ action: "save", name: $("verName")?.value, note: $("verNote")?.value });
3583
+ if (out) {
3584
+ toast(`Saved v${out.version.v} “${out.version.name}”`);
3585
+ for (const id of ["verName", "verNote"]) if ($(id)) $(id).value = ""; // saved: not a draft any more
3586
+ await pjLoadVersions();
3587
+ }
3588
+ return;
3589
+ }
3590
+ if (act === "diff") {
3591
+ if (pj.verDiff.has(v)) { pj.verDiff.delete(v); renderProjectGrid(); return; }
3592
+ // compare with what is on screen, or not at all
3593
+ if (p.active && !(await flushSaveForVersion("the comparison would miss it"))) return;
3594
+ const gen = pj.verDiffGen, of = pj.verOf;
3595
+ const out = await post({ action: "diff", version: v });
3596
+ if (out && gen === pj.verDiffGen && of === pj.verOf) { pj.verDiff.set(v, out.lines); renderProjectGrid(); }
3597
+ return;
3598
+ }
3599
+ if (act === "restore") {
3600
+ if (btn.dataset.armed !== "1") {
3601
+ btn.dataset.armed = "1"; btn.textContent = "Click again to restore";
3602
+ setTimeout(() => { if (btn.isConnected) { btn.dataset.armed = ""; btn.textContent = "Restore…"; } }, 3000);
3603
+ return;
3604
+ }
3605
+ if (p.active && state.exporting) { toast("Wait for the export to finish before restoring"); return; }
3606
+ if (p.active && !(await flushSaveForVersion("nothing was restored"))) return;
3607
+ const out = await post({ action: "restore", version: v });
3608
+ if (!out) return;
3609
+ if (p.active) {
3610
+ // the undo steps describe the document before the restore
3611
+ runtime.undo.length = 0; runtime.redo.length = 0;
3612
+ await syncFromServer(true);
3613
+ }
3614
+ pjDropDiffs();
3615
+ toast(`Restored v${out.restored.v}. What was there is kept as v${out.saved.v}`);
3616
+ await pjLoad(); // the card and details show the restored project
3617
+ await pjLoadVersions();
3618
+ return;
3619
+ }
3620
+ if (act === "final") {
3621
+ const e = pj.versions.find((x) => x.v === v);
3622
+ const out = await post({ action: "update", version: v, final: !e?.final });
3623
+ if (out) await pjLoadVersions();
3624
+ return;
3625
+ }
3626
+ if (act === "rename") {
3627
+ const name = row.querySelector(".ver-name");
3628
+ if (!name || name.querySelector("input")) return;
3629
+ const e = pj.versions.find((x) => x.v === v);
3630
+ name.innerHTML = `<input type="text" class="ver-rename" maxlength="120" value="${escapeHtml(e?.name || "")}" spellcheck="false" aria-label="Version name">`;
3631
+ const inp = name.querySelector("input");
3632
+ inp.focus(); inp.select();
3633
+ const done = async (keep) => {
3634
+ if (inp.dataset.done) return;
3635
+ inp.dataset.done = "1";
3636
+ const val = inp.value.trim();
3637
+ if (keep && val && val !== e?.name) await post({ action: "update", version: v, name: val });
3638
+ await pjLoadVersions();
3639
+ };
3640
+ // Enter / Esc reach it through the dashboard's key handler (initProjectsUi): they blur it
3641
+ inp.addEventListener("blur", () => done(!inp.dataset.cancel));
3642
+ return;
3643
+ }
3644
+ if (act === "delete") {
3645
+ if (btn.dataset.armed !== "1") {
3646
+ btn.dataset.armed = "1"; btn.textContent = "Click again to delete";
3647
+ setTimeout(() => { if (btn.isConnected) { btn.dataset.armed = ""; btn.textContent = "Delete…"; } }, 3000);
3648
+ return;
3649
+ }
3650
+ const out = await post({ action: "delete", version: v });
3651
+ if (out) { pj.verDiff.delete(v); await pjLoadVersions(); }
3652
+ }
3653
+ }
3654
+ /* Ctrl/Cmd+S: keep the open project as it is now. */
3655
+ let versionSaving = false;
3656
+ async function saveVersionNow() {
3657
+ if (versionSaving) return; // one at a time
3658
+ versionSaving = true;
3659
+ try {
3660
+ const project = runtime.projectId; // another tab may open another project meanwhile
3661
+ if (!(await flushSaveForVersion("no version was made"))) return;
3662
+ const res = await fetch("/api/versions", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "save", ...(project && project !== "?" ? { project } : {}) }) });
3663
+ const out = await res.json().catch(() => ({}));
3664
+ if (!res.ok) { toast(out.error || "Couldn't save a version"); return; }
3665
+ toast(`Saved v${out.version.v} “${out.version.name}” · Projects → Versions to go back to it`);
3666
+ } catch { toast("Couldn't save a version: the editor server did not answer"); }
3667
+ finally { versionSaving = false; }
3668
+ }
3669
+ /** Write the open project's pending edit before a version action; false (with a toast) when it didn't land. */
3670
+ async function flushSaveForVersion(skipped) {
3671
+ if (await flushSave()) return true;
3672
+ toast(`Your last change couldn't be saved, so ${skipped}. Try again in a moment.`);
3673
+ return false;
3674
+ }
3675
+ /* Called by syncFromServer when ./project.json is now another project. */
3676
+ function onProjectSwitched() {
3677
+ runtime.projectGen = (runtime.projectGen || 0) + 1; // loads started before now no longer write the caches
3678
+ // queued exports carry the old project's settings and names: they don't render this one
3679
+ const queued = exportQueue.length;
3680
+ for (let i = exportQueue.length - 1; i >= 0; i--)
3681
+ if (["pending", "failed", "cancelled"].includes(exportQueue[i].status)) exportQueue.splice(i, 1); // Retry would render this project
3682
+ if (exportQueue.length !== queued) { renderQueue(); toast("Queued exports of the previous project were removed"); }
3683
+ if (runtime.saveTimer) { clearTimeout(runtime.saveTimer); runtime.saveTimer = null; } // an edit of the old project
3684
+ runtime.saveFailed = false;
3685
+ runtime.undo.length = 0; runtime.redo.length = 0;
3686
+ runtime.seqUndo.clear(); runtime.seqOpen = null;
3687
+ state.compCtx = null;
3688
+ clearSource();
3689
+ setSelection([]);
3690
+ // players, pictures, waveforms and proxy states are keyed by media / clip id, which a
3691
+ // duplicate or a template shares with a different file: rebuild them for this project
3692
+ pause();
3693
+ for (const id of [...runtime.clipEls.keys()]) releaseClipEl(id);
3694
+ runtime.mediaAux.clear();
3695
+ runtime.wavePeaks.clear();
3696
+ proxyStatus.clear();
3697
+ }
3698
+ function initProjectsUi() {
3699
+ const ov = $("projectsOverlay"), btn = $("btnProjectsDash");
3700
+ if (!ov || !btn || ov.dataset.wired) return;
3701
+ ov.dataset.wired = "1";
3702
+ btn.classList.remove("hidden");
3703
+ btn.addEventListener("click", openProjects);
3704
+ els.projectName?.classList.add("clickable");
3705
+ els.projectName?.setAttribute("title", "Projects");
3706
+ els.projectName?.addEventListener("click", openProjects);
3707
+ $("pjClose").addEventListener("click", closeProjects);
3708
+ ov.addEventListener("click", (e) => { if (e.target === ov) closeProjects(); });
3709
+ // capture on window: wherever focus is while the dashboard is up, the editor's shortcuts stay out of it
3710
+ window.addEventListener("keydown", (e) => {
3711
+ if (!projectsOpen()) return;
3712
+ e.stopPropagation();
3713
+ if ((e.ctrlKey || e.metaKey) && (e.key === "o" || e.key === "O")) {
3714
+ e.preventDefault(); closeProjects(); // not the browser's Open File dialog
3715
+ } else if ((e.ctrlKey || e.metaKey) && (e.key === "s" || e.key === "S")) {
3716
+ e.preventDefault(); // not the browser's Save Page dialog
3717
+ if (!e.repeat) saveVersionNow().then(() => { if (pj.verOf) pjLoadVersions(); }); // holding the keys makes one
3718
+ } else if (e.target.classList?.contains("ver-rename") && (e.key === "Enter" || e.key === "Escape")) {
3719
+ e.preventDefault();
3720
+ if (e.key === "Escape") e.target.dataset.cancel = "1";
3721
+ e.target.blur();
3722
+ } else if (e.key === "Enter" && (e.target.id === "verName" || e.target.id === "verNote")) {
3723
+ e.preventDefault(); pjVersionAction("save", e.target);
3724
+ } else if (e.key === "Escape") {
3725
+ e.preventDefault();
3726
+ if (pj.mode === "new") { pj.mode = "detail"; renderProjects(); }
3727
+ else if (pj.verOf) { pj.verOf = null; pjDropDiffs(); renderProjects(); }
3728
+ else closeProjects();
3729
+ } else if ((e.key === "Enter" || e.key === " ") && e.target.dataset?.pjTpldel) {
3730
+ e.preventDefault(); e.target.click();
3731
+ } else if (e.key === "Enter" && e.target.dataset?.pj) {
3732
+ e.preventDefault(); pjOpenProject(e.target.dataset.pj);
3733
+ } else if (e.key === "Enter" && e.target.id === "pjNewName") {
3734
+ e.preventDefault(); pjAction("new-create");
3735
+ } else if (e.key === "Enter" && (e.target.id === "pjName" || e.target.id === "pjTags")) {
3736
+ e.preventDefault(); e.target.blur();
3737
+ } else if (e.key === "Enter" && e.target.id === "pjTplName") {
3738
+ e.preventDefault(); pjAction("template-save");
3739
+ }
3740
+ }, true);
3741
+ for (const b of ov.querySelectorAll("[data-pj-view]")) b.addEventListener("click", () => {
3742
+ if (pj.view === b.dataset.pjView && pj.mode === "detail") return;
3743
+ pj.view = b.dataset.pjView; pj.mode = "detail"; pj.verOf = null; pj.list = []; renderProjects(); pjLoad();
3744
+ });
3745
+ $("pjNewBtn").addEventListener("click", () => {
3746
+ pj.mode = pj.mode === "new" ? "detail" : "new";
3747
+ renderProjects();
3748
+ if (pj.mode === "new") $("pjNewName")?.select();
3749
+ });
3750
+ $("pjSearch").addEventListener("input", (e) => { pj.search = e.target.value; renderProjectGrid(); });
3751
+ $("pjSort").addEventListener("change", (e) => { pj.sort = e.target.value; renderProjectGrid(); });
3752
+ $("pjImportFile").addEventListener("change", (e) => { const f = e.target.files?.[0]; e.target.value = ""; if (f) pjImport(f); });
3753
+ $("pjGrid").addEventListener("click", (e) => {
3754
+ const vact = e.target.closest("[data-ver-act]");
3755
+ if (vact) { if (!vact.disabled) pjVersionAction(vact.dataset.verAct, vact); return; }
3756
+ const card = e.target.closest("[data-pj]");
3757
+ if (!card) return;
3758
+ // only the selection changes: re-rendering the cards would swallow a double-click
3759
+ pj.sel = card.dataset.pj; pj.mode = "detail";
3760
+ for (const c of $("pjGrid").querySelectorAll(".pj-card")) c.classList.toggle("sel", c === card);
3761
+ renderProjectSide();
3762
+ });
3763
+ $("pjGrid").addEventListener("dblclick", (e) => { const card = e.target.closest("[data-pj]"); if (card && pj.view === "active") pjOpenProject(card.dataset.pj); });
3764
+ const side = $("pjSide");
3765
+ side.addEventListener("click", async (e) => {
3766
+ const bk = e.target.closest("[data-pj-backup]");
3767
+ if (bk && !bk.dataset.flushed) {
3768
+ // the open project: write its pending edit, then download
3769
+ e.preventDefault();
3770
+ if (!(await flushSaveForVersion("the backup would miss it"))) return;
3771
+ bk.dataset.flushed = "1"; bk.click(); delete bk.dataset.flushed;
3772
+ return;
3773
+ }
3774
+ const del = e.target.closest("[data-pj-tpldel]");
3775
+ if (del) {
3776
+ e.stopPropagation();
3777
+ if (del.dataset.armed !== "1") { del.dataset.armed = "1"; del.textContent = "Delete?"; setTimeout(() => { if (del.isConnected) { del.dataset.armed = ""; del.textContent = "✕"; } }, 3000); return; }
3778
+ const out = await pjPost({ action: "delete_template", template: del.dataset.pjTpldel });
3779
+ if (out) { if (pj.tpl === del.dataset.pjTpldel) pj.tpl = "landscape-1080"; await pjLoad(); }
3780
+ return;
3781
+ }
3782
+ const tpl = e.target.closest("[data-pj-tpl]");
3783
+ if (tpl) {
3784
+ const keepName = $("pjNewName")?.value;
3785
+ pj.tpl = tpl.dataset.pjTpl; renderProjects();
3786
+ if (keepName != null && $("pjNewName")) $("pjNewName").value = keepName;
3787
+ return;
3788
+ }
3789
+ const act = e.target.closest("[data-pj-act]");
3790
+ if (act && !act.disabled) pjAction(act.dataset.pjAct, act);
3791
+ });
3792
+ side.addEventListener("focusout", (e) => {
3793
+ if (e.target.id === "pjName") pjSaveField("name");
3794
+ else if (e.target.id === "pjNotes") pjSaveField("notes");
3795
+ else if (e.target.id === "pjTags") pjSaveField("tags");
3796
+ });
3797
+ }
3798
+
2236
3799
  /* ═══════════════════════════ EDIT OPERATIONS ═══════════════════════════ */
2237
3800
  /* Undo entries are {clips, markers} snapshots. Drag gestures still push a bare
2238
3801
  clips array (taken at pointerdown) — restoring one leaves markers alone. */
@@ -2246,23 +3809,53 @@ function pushUndo(snap = undoSnapshot()) {
2246
3809
  if (runtime.undo.length > 100) runtime.undo.shift();
2247
3810
  runtime.redo.length = 0;
2248
3811
  }
3812
+ /** Does this undo step hold other sequences' clips (a top-level seqClips)? Parsed only when the text could say so. */
3813
+ function hasSeqClips(json) {
3814
+ if (typeof json !== "string" || !json.includes('"seqClips":')) return false;
3815
+ try { const snap = JSON.parse(json); return !!snap && typeof snap === "object" && !Array.isArray(snap) && Object.hasOwn(snap, "seqClips"); }
3816
+ catch { return false; }
3817
+ }
3818
+ /** The clips of the sequences that aren't open, by id — for the undo of an edit that reaches into them. */
3819
+ function otherSequenceClips() { return Object.fromEntries(SeqLib.others(seqRoot()).map((sq) => [sq.id, sq.clips || []])); }
2249
3820
  function restoreSnapshot(json) {
2250
3821
  const snap = JSON.parse(json);
3822
+ if (snap && snap.seqClips) {
3823
+ const open = SeqLib.activeId(seqRoot());
3824
+ for (const [id, clips] of Object.entries(snap.seqClips)) { const sq = SeqLib.find(seqRoot(), id); if (sq && id !== open) sq.clips = clips; }
3825
+ }
2251
3826
  if (Array.isArray(snap)) project.clips = snap;
2252
- else { project.clips = snap.clips; project.markers = snap.markers; if (snap.comps) project.comps = snap.comps; if (snap.media) { project.media = snap.media; renderBin(); } }
3827
+ else {
3828
+ project.clips = snap.clips; project.markers = snap.markers; if (snap.comps) project.comps = snap.comps;
3829
+ if (snap.media) {
3830
+ const before = new Map(project.media.map((m) => [m.id, m.src]));
3831
+ project.media = snap.media;
3832
+ // a relink / replace undone or redone: the players and pictures follow the src
3833
+ for (const m of project.media) if (before.has(m.id) && before.get(m.id) !== m.src) reloadMediaSource(m, before.get(m.id));
3834
+ renderBin(); scheduleOfflineCheck(0);
3835
+ }
3836
+ }
2253
3837
  runtime.compGen = (runtime.compGen || 0) + 1;
2254
3838
  }
3839
+ /** The current state to step back to, carrying the media list when `snap` does
3840
+ * (removing, relinking or replacing media), so redo puts it back too. */
3841
+ function counterSnapshot(snap) {
3842
+ if (!snap.includes('"media":')) return undoSnapshot();
3843
+ return JSON.stringify({ clips: project.clips, markers: project.markers || [], comps: project.comps || [], media: project.media,
3844
+ ...(hasSeqClips(snap) ? { seqClips: otherSequenceClips() } : {}) });
3845
+ }
2255
3846
  function undo() {
2256
3847
  if (!runtime.undo.length) return;
2257
- runtime.redo.push(undoSnapshot());
2258
- restoreSnapshot(runtime.undo.pop());
3848
+ const snap = runtime.undo.pop();
3849
+ runtime.redo.push(counterSnapshot(snap));
3850
+ restoreSnapshot(snap);
2259
3851
  pruneSelection();
2260
3852
  scheduleSave(); renderInspector();
2261
3853
  }
2262
3854
  function redo() {
2263
3855
  if (!runtime.redo.length) return;
2264
- runtime.undo.push(undoSnapshot());
2265
- restoreSnapshot(runtime.redo.pop());
3856
+ const snap = runtime.redo.pop();
3857
+ runtime.undo.push(counterSnapshot(snap));
3858
+ restoreSnapshot(snap);
2266
3859
  pruneSelection();
2267
3860
  scheduleSave(); renderInspector();
2268
3861
  }
@@ -3077,8 +4670,9 @@ function exportRangeMode() {
3077
4670
  if (v === "in-out" && !hasWorkArea()) return "entire";
3078
4671
  return v;
3079
4672
  }
3080
- function exportRange() {
3081
- const fps = projectFps();
4673
+ /** fps: the output's frame rate when it differs from the project's (delivery). */
4674
+ function exportRange(fpsOverride) {
4675
+ const fps = fpsOverride || projectFps();
3082
4676
  const span = Math.max(projDur(), 0);
3083
4677
  let start = 0, end = span;
3084
4678
  if (exportRangeMode() === "in-out") {
@@ -3352,7 +4946,8 @@ function rebuildClips() {
3352
4946
  div.className = `clip c-${c.kind}` +
3353
4947
  (state.selIds.has(c.id) ? " selected" : "") + (c.id === state.selId ? " primary" : "") +
3354
4948
  (isClipLocked(c) ? " locked" : "") + (c.disabled === true ? " disabled" : "") +
3355
- (c.unlinked === true ? " unlinked" : "") + (c.kind !== "audio" && isMatte(c) ? " matte-src" : "");
4949
+ (c.unlinked === true ? " unlinked" : "") + (c.kind !== "audio" && isMatte(c) ? " matte-src" : "") +
4950
+ (isMediaOffline(c.mediaId) ? " offline" : "");
3356
4951
  div.dataset.id = c.id;
3357
4952
  div.style.left = c.start * state.pps + "px";
3358
4953
  div.style.width = Math.max(8, c.duration * state.pps) + "px";
@@ -3363,7 +4958,7 @@ function rebuildClips() {
3363
4958
  }
3364
4959
  const hasWave = c.kind === "audio" && !!wavePeaksFor(c);
3365
4960
  if (hasWave) body += `<canvas class="wave"></canvas>`;
3366
- const badge = (c.keyframes && Object.keys(c.keyframes).length ? "◆ " : "") +
4961
+ const badge = (isMediaOffline(c.mediaId) ? "⚠ Offline · " : "") + (c.keyframes && Object.keys(c.keyframes).length ? "◆ " : "") +
3367
4962
  (c.transitionIn || c.transitionOut ? "⇄ " : "") +
3368
4963
  (clipMatte(c) ? "◐ " : "");
3369
4964
  const chTag = (() => {
@@ -5746,13 +7341,18 @@ function ensureSourceEl(m) {
5746
7341
  });
5747
7342
  runtime.sourceEl = el;
5748
7343
  }
5749
- if (el.dataset.src !== m.src) {
5750
- el.src = m.src;
5751
- el.dataset.src = m.src;
7344
+ const want = mediaPlaySrc(m);
7345
+ if (el.dataset.src !== want) {
7346
+ el.src = want;
7347
+ el.dataset.src = want;
5752
7348
  runtime.sourceHold = null;
5753
7349
  runtime.sourceHoldOk = false;
5754
7350
  runtime.sourceSeekPending = null;
5755
7351
  runtime.sourceSeekBusy = false;
7352
+ // a new file (proxy ↔ original) loads at 0 — put it back on the Source playhead
7353
+ el.addEventListener("loadedmetadata", () => {
7354
+ if (runtime.sourceEl === el && el.dataset.src === want && !state.source.playing) seekSourceEl(state.source.time);
7355
+ }, { once: true });
5756
7356
  }
5757
7357
  return el;
5758
7358
  }
@@ -5945,6 +7545,7 @@ async function playSource() {
5945
7545
  audio.ctx.resume();
5946
7546
  state.source.playing = true;
5947
7547
  syncPlayButton();
7548
+ noteActivity();
5948
7549
  }
5949
7550
  function toggleTransportPlay() {
5950
7551
  // Space always resumes forward — drop a reverse / crawl rate left by J or K+L
@@ -6316,13 +7917,17 @@ function drawSourceFrame() {
6316
7917
  function getClipEl(c) {
6317
7918
  let el = runtime.clipEls.get(c.id);
6318
7919
  const m = getMedia(c.mediaId);
6319
- // The clip now plays another file (noise reduction, or undoing it): rebuild.
6320
- if (el && m && el._fcSrc !== m.src) { releaseClipEl(c.id); el = null; }
7920
+ // video plays its proxy while editing (never during export); audio always the original
7921
+ const src = c.kind === "video" ? mediaPlaySrc(m) : m && m.src;
7922
+ // The clip now plays another file (noise reduction or undoing it, a relink, proxies on / off): rebuild.
7923
+ if (el && m && el._fcSrc !== src) { releaseClipEl(c.id); el = null; }
6321
7924
  if (el) return el;
6322
7925
  if (!m) return null;
6323
7926
  el = document.createElement(c.kind === "audio" ? "audio" : "video");
6324
- el.preload = "auto"; el.src = m.src; el.playsInline = true;
6325
- el._fcSrc = m.src;
7927
+ el.preload = "auto"; el.src = src; el.playsInline = true;
7928
+ el._fcSrc = src;
7929
+ // a proxy is smaller than the original: fit "none" (native pixels) scales it back up
7930
+ el._fcScale = src !== m.src && m.height > 0 ? (proxyOf(m)?.height || m.height) / m.height : 1;
6326
7931
  runtime.clipEls.set(c.id, el);
6327
7932
  hookAudio(c, el);
6328
7933
  return el;
@@ -8058,6 +9663,7 @@ function play() {
8058
9663
  }
8059
9664
  state.playing = true;
8060
9665
  syncPlayButton();
9666
+ noteActivity();
8061
9667
  syncMedia(); // start active seeks + cut lookahead without waiting a RAF
8062
9668
  }
8063
9669
  function pause() {
@@ -8455,7 +10061,9 @@ function parseSvgSize(txt) {
8455
10061
  return { width: w || 800, height: h || 600 };
8456
10062
  }
8457
10063
  async function loadSvgMedia(m) {
10064
+ const gen = runtime.projectGen;
8458
10065
  const txt = await (await fetch(m.src)).text();
10066
+ if (gen !== runtime.projectGen) return; // another project was opened meanwhile
8459
10067
  const { width, height } = parseSvgSize(txt);
8460
10068
  m.width = width; m.height = height;
8461
10069
  const aux = runtime.mediaAux.get(m.id) || {};
@@ -8464,7 +10072,7 @@ async function loadSvgMedia(m) {
8464
10072
  aux.svgFrames = new Map(); // quantized t -> HTMLImageElement (small LRU)
8465
10073
  aux.svgPending = null;
8466
10074
  runtime.mediaAux.set(m.id, aux);
8467
- if (!aux.svgAnimated) aux.img = await rasterizeSvgMarkup(txt);
10075
+ if (!aux.svgAnimated) { const img = await rasterizeSvgMarkup(txt); if (gen === runtime.projectGen) aux.img = img; }
8468
10076
  state.dirtyTimeline = true;
8469
10077
  }
8470
10078
  function svgMarkupAt(aux, t) {
@@ -8676,9 +10284,161 @@ function hexToRgb(hex) {
8676
10284
  const n = parseInt(String(hex).replace("#", ""), 16) || 0;
8677
10285
  return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
8678
10286
  }
10287
+ /* The same pixel loop as a WebGL2 shader: no getImageData read-back and no
10288
+ per-pixel JS, so a keyed or tinted 1080p layer costs a draw call, not ~20 ms
10289
+ of main thread. The input is staged through a 2D canvas exactly as the CPU
10290
+ path draws it (same resize, same cut-out mask, unpremultiplied on upload
10291
+ like getImageData), so both paths see the same pixels; the CPU loop below
10292
+ stays as the fallback when WebGL2 is unavailable. */
10293
+ const pixGL = { tried: false, gl: null, canvas: null, loc: null, stage: null, stageCtx: null, outs: new Map() };
10294
+ const PIX_VERT = `#version 300 es
10295
+ in vec2 aPos;
10296
+ void main() { gl_Position = vec4(aPos, 0.0, 1.0); }`;
10297
+ const PIX_FRAG = `#version 300 es
10298
+ precision highp float;
10299
+ uniform sampler2D uTex;
10300
+ uniform ivec2 uSize; // picture size: the buffers only grow, so it sits in their top-left corner
10301
+ uniform int uSplit; // RGB split in pixels (R from x+split, B from x−split)
10302
+ uniform int uKey;
10303
+ uniform vec2 uKeyC; // key colour Cb, Cr (0…255)
10304
+ uniform vec2 uKeyT; // tolerance t0, t1 (CbCr distance)
10305
+ uniform vec2 uShift; // temperature (R+, B−), tint (G+), in 0…255 units
10306
+ out vec4 o;
10307
+ void main() {
10308
+ ivec2 sz = uSize;
10309
+ ivec2 q = ivec2(int(gl_FragCoord.x), sz.y - 1 - int(gl_FragCoord.y)); // texture row 0 = top
10310
+ vec4 c = texelFetch(uTex, q, 0);
10311
+ vec3 rgb = c.rgb * 255.0;
10312
+ float a = c.a;
10313
+ if (uSplit > 0) {
10314
+ rgb.r = texelFetch(uTex, ivec2(min(sz.x - 1, q.x + uSplit), q.y), 0).r * 255.0;
10315
+ rgb.b = texelFetch(uTex, ivec2(max(0, q.x - uSplit), q.y), 0).b * 255.0;
10316
+ }
10317
+ if (uKey == 1) {
10318
+ float cb = 128.0 - 0.168736 * rgb.r - 0.331264 * rgb.g + 0.5 * rgb.b;
10319
+ float cr = 128.0 + 0.5 * rgb.r - 0.418688 * rgb.g - 0.081312 * rgb.b;
10320
+ float dist = distance(vec2(cb, cr), uKeyC);
10321
+ if (dist < uKeyT.x) { o = vec4(0.0); return; }
10322
+ if (dist < uKeyT.y) {
10323
+ float k = (dist - uKeyT.x) / (uKeyT.y - uKeyT.x);
10324
+ a *= k;
10325
+ float avg = (rgb.r + rgb.b) * 0.5; // spill suppression
10326
+ if (rgb.g > avg) rgb.g = rgb.g * k + avg * (1.0 - k);
10327
+ }
10328
+ }
10329
+ rgb += vec3(uShift.x, uShift.y, -uShift.x);
10330
+ rgb = clamp(rgb, 0.0, 255.0) / 255.0;
10331
+ o = vec4(rgb * a, a);
10332
+ }`;
10333
+ function initPixGL() {
10334
+ if (pixGL.tried) return pixGL.gl;
10335
+ pixGL.tried = true;
10336
+ try {
10337
+ const cv = document.createElement("canvas");
10338
+ const gl = cv.getContext("webgl2", { premultipliedAlpha: true, preserveDrawingBuffer: true, antialias: false, alpha: true });
10339
+ if (!gl) return null;
10340
+ // A software rasterizer (SwiftShader in headless Chrome, llvmpipe) runs the
10341
+ // shader on the CPU anyway, no faster than the loop: keep the loop there.
10342
+ const info = gl.getExtension("WEBGL_debug_renderer_info");
10343
+ if (info && /swiftshader|llvmpipe|softpipe|software/i.test(gl.getParameter(info.UNMASKED_RENDERER_WEBGL))) return null;
10344
+ const sh = (type, src) => {
10345
+ const s = gl.createShader(type);
10346
+ gl.shaderSource(s, src); gl.compileShader(s);
10347
+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));
10348
+ return s;
10349
+ };
10350
+ const prog = gl.createProgram();
10351
+ gl.attachShader(prog, sh(gl.VERTEX_SHADER, PIX_VERT));
10352
+ gl.attachShader(prog, sh(gl.FRAGMENT_SHADER, PIX_FRAG));
10353
+ gl.linkProgram(prog);
10354
+ if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(prog));
10355
+ gl.useProgram(prog);
10356
+ gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
10357
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);
10358
+ const aPos = gl.getAttribLocation(prog, "aPos");
10359
+ gl.enableVertexAttribArray(aPos);
10360
+ gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);
10361
+ gl.bindTexture(gl.TEXTURE_2D, gl.createTexture());
10362
+ for (const [k, v] of [[gl.TEXTURE_MIN_FILTER, gl.NEAREST], [gl.TEXTURE_MAG_FILTER, gl.NEAREST],
10363
+ [gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE], [gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE]]) gl.texParameteri(gl.TEXTURE_2D, k, v);
10364
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
10365
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); // straight alpha, as getImageData returns it
10366
+ const loc = {};
10367
+ for (const n of ["uTex", "uSize", "uSplit", "uKey", "uKeyC", "uKeyT", "uShift"]) loc[n] = gl.getUniformLocation(prog, n);
10368
+ gl.uniform1i(loc.uTex, 0);
10369
+ cv.addEventListener("webglcontextlost", (e) => { e.preventDefault(); pixGL.gl = null; });
10370
+ cv.addEventListener("webglcontextrestored", () => { pixGL.tried = false; });
10371
+ const stage = document.createElement("canvas"); // GPU-backed: no willReadFrequently
10372
+ Object.assign(pixGL, { gl, canvas: cv, loc, stage, stageCtx: stage.getContext("2d") });
10373
+ return gl;
10374
+ } catch (err) {
10375
+ console.warn("[FableCut] WebGL2 pixel pass unavailable, using the CPU path:", err && err.message);
10376
+ return null;
10377
+ }
10378
+ }
10379
+ /** pixelPass on the GPU; null when WebGL2 isn't usable (the caller falls back). */
10380
+ function pixelPassGL(c, p, src, sx, sy, sw, sh, w, h, dw) {
10381
+ const gl = initPixGL();
10382
+ if (!gl) return null;
10383
+ const { stage, stageCtx: g, canvas: cv, loc } = pixGL;
10384
+ // Resizing a canvas reallocates it, and the layers of one frame differ in
10385
+ // size, so the stage and the GL buffer only grow; each clip gets its own
10386
+ // output canvas at its own size, which keeps its size from frame to frame.
10387
+ if (stage.width < w) stage.width = w;
10388
+ if (stage.height < h) stage.height = h;
10389
+ g.clearRect(0, 0, w, h);
10390
+ g.drawImage(src, sx, sy, sw, sh, 0, 0, w, h);
10391
+ const mask = p.bgRemove ? bgSeg.masks.get(c.id) : null;
10392
+ if (mask && mask.width) {
10393
+ g.globalCompositeOperation = "destination-in";
10394
+ g.drawImage(mask, 0, 0, w, h);
10395
+ g.globalCompositeOperation = "source-over";
10396
+ }
10397
+ const doKey = !!p.chromaKey, temp = +p.temperature || 0, tint = +p.tint || 0;
10398
+ const split = Math.round(clamp(+p.rgbSplit || 0, 0, 60) * (w / Math.max(1, dw)));
10399
+ const run = doKey || temp || tint || split > 0;
10400
+ let out = pixGL.outs.get(c.id);
10401
+ if (!out) {
10402
+ if (pixGL.outs.size >= 32) pixGL.outs.delete(pixGL.outs.keys().next().value);
10403
+ out = document.createElement("canvas");
10404
+ pixGL.outs.set(c.id, out);
10405
+ }
10406
+ if (out.width !== w) out.width = w;
10407
+ if (out.height !== h) out.height = h;
10408
+ const o = out.getContext("2d");
10409
+ o.clearRect(0, 0, w, h);
10410
+ if (!run) { o.drawImage(stage, 0, 0, w, h, 0, 0, w, h); return out; }
10411
+ try {
10412
+ if (cv.width < w) cv.width = w;
10413
+ if (cv.height < h) cv.height = h;
10414
+ gl.viewport(0, 0, w, h);
10415
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, stage);
10416
+ gl.uniform2i(loc.uSize, w, h);
10417
+ gl.uniform1i(loc.uSplit, split);
10418
+ gl.uniform1i(loc.uKey, doKey ? 1 : 0);
10419
+ if (doKey) {
10420
+ const [kr, kg, kb] = hexToRgb(p.chromaKey);
10421
+ const t0 = clamp(+p.chromaTolerance || 0, 0, 100) * 1.2;
10422
+ gl.uniform2f(loc.uKeyC, 128 - 0.168736 * kr - 0.331264 * kg + 0.5 * kb, 128 + 0.5 * kr - 0.418688 * kg - 0.081312 * kb);
10423
+ gl.uniform2f(loc.uKeyT, t0, t0 + Math.max(1, clamp(+p.chromaSoftness || 0, 0, 100) * 1.2));
10424
+ }
10425
+ gl.uniform2f(loc.uShift, temp * 0.6, tint * 0.5);
10426
+ gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT);
10427
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
10428
+ o.drawImage(cv, 0, cv.height - h, w, h, 0, 0, w, h); // the viewport is the buffer's bottom-left
10429
+ return out;
10430
+ } catch (err) {
10431
+ if (err && err.name === "SecurityError") throw err; // tainted source: same as getImageData on the CPU path
10432
+ console.warn("[FableCut] pixel pass failed, using the CPU path:", err && err.message);
10433
+ pixGL.gl = null;
10434
+ return null;
10435
+ }
10436
+ }
8679
10437
  function pixelPass(c, p, src, sx, sy, sw, sh, dw, dh) {
8680
10438
  const w = Math.max(2, Math.min(Math.round(dw), 1920));
8681
10439
  const h = Math.max(2, Math.min(Math.round(dh), 1920));
10440
+ const viaGL = pixelPassGL(c, p, src, sx, sy, sw, sh, w, h, dw);
10441
+ if (viaGL) return viaGL;
8682
10442
  if (scratch.width !== w) scratch.width = w;
8683
10443
  if (scratch.height !== h) scratch.height = h;
8684
10444
  scratchCtx.clearRect(0, 0, w, h);
@@ -9133,7 +10893,7 @@ function commitCompCtx() {
9133
10893
  const comps = (cur.comps || []).map((c) => (c.id === id
9134
10894
  ? { ...c, clips: cur.clips, tracks: cur.tracks, disabledTracks: cur.disabledTracks && cur.disabledTracks.length ? cur.disabledTracks : undefined, markers: cur.markers && cur.markers.length ? cur.markers : undefined, background: c.background }
9135
10895
  : c));
9136
- x.root = { ...x.root, media: cur.media, folders: cur.folders, fps: cur.fps, master: cur.master, buses: cur.buses, revision: cur.revision, comps };
10896
+ x.root = { ...x.root, media: cur.media, folders: cur.folders, collections: cur.collections, fps: cur.fps, master: cur.master, buses: cur.buses, revision: cur.revision, comps };
9137
10897
  return x.root;
9138
10898
  }
9139
10899
  function enterComp(compId, viaClip) {
@@ -9170,6 +10930,7 @@ function exitComp(levels = 1) {
9170
10930
  scheduleSave();
9171
10931
  }
9172
10932
  function syncCompCrumb() {
10933
+ syncSequenceButton();
9173
10934
  if (els.projectName) els.projectName.textContent = project.name + (state.connected ? " · 🟢 connected" : " · ⚪ local session");
9174
10935
  const el = document.getElementById("compCrumb");
9175
10936
  if (!el) return;
@@ -9177,13 +10938,203 @@ function syncCompCrumb() {
9177
10938
  el.classList.toggle("hidden", !x);
9178
10939
  if (!x) { el.innerHTML = ""; return; }
9179
10940
  const names = x.path.map((id) => (CompLib.getComp(x.root, id) || { name: id }).name);
9180
- el.innerHTML = `<button type="button" class="btn tiny" data-crumb="${x.path.length}" title="Back to the main timeline">◀ Main</button>` +
10941
+ el.innerHTML = `<button type="button" class="btn tiny" data-crumb="${x.path.length}" title="Back to the timeline">◀ ${escapeHtml(openSequenceName())}</button>` +
9181
10942
  names.map((n, i) => `<span class="crumb-sep">›</span>` + (i < names.length - 1
9182
10943
  ? `<button type="button" class="btn tiny" data-crumb="${x.path.length - 1 - i}">${escapeHtml(n)}</button>`
9183
- : `<b title="You are editing this composition — Esc or ◀ Main goes back">${escapeHtml(n)}</b>`)).join("");
10944
+ : `<b title="You are editing this composition — Esc or ◀ goes back">${escapeHtml(n)}</b>`)).join("");
9184
10945
  for (const b of el.querySelectorAll("[data-crumb]")) b.addEventListener("click", () => exitComp(+b.dataset.crumb));
9185
10946
  }
9186
10947
 
10948
+ /* ═══════════════════════════ SEQUENCES ═══════════════════════════
10949
+ Several timelines in one project (sequences.js). The open one is `project`
10950
+ itself — clips, tracks, canvas, frame rate, mix, delivery — and the others
10951
+ wait in project.sequences. Opening one parks this timeline in its entry and
10952
+ loads the other, like a reload. For the session each sequence keeps its own
10953
+ undo history, playhead and selection. */
10954
+ const SeqLib = self.FableCutSeq;
10955
+ /** The document that holds the sequences (the root while a comp is open). */
10956
+ function seqRoot() { return state.compCtx ? state.compCtx.root : project; }
10957
+ function openSequenceName() { const r = seqRoot(); return (SeqLib.find(r, SeqLib.activeId(r)) || SeqLib.MAIN).name; }
10958
+ /** A document is about to be shown: when it opens another sequence, the undo steps,
10959
+ * playhead and selection go with the one that was open, and the other's come back. */
10960
+ function noteOpenSequence(data) {
10961
+ const next = SeqLib.activeId(data), prev = runtime.seqOpen;
10962
+ runtime.seqOpen = next;
10963
+ runtime.seqBack = null;
10964
+ if (!prev || prev === next) return;
10965
+ // the steps only fit the state they were taken on: its timeline, and the comps and media every sequence
10966
+ // shares (undo puts those back too). An agent or the other sequence may change them meanwhile.
10967
+ // A relink / replace step also holds the other sequences' clips: then those must be as they were too.
10968
+ const here = projectJSONHere();
10969
+ const withOthers = [...runtime.undo, ...runtime.redo].some(hasSeqClips);
10970
+ runtime.seqUndo.set(prev, { undo: runtime.undo.slice(), redo: runtime.redo.slice(), time: state.time, sel: state.selId,
10971
+ fp: seqUndoPrint(here, withOthers), withOthers });
10972
+ const back = runtime.seqUndo.get(next);
10973
+ const fits = back && back.fp === seqUndoPrint(data, back.withOthers);
10974
+ runtime.undo.splice(0, runtime.undo.length, ...(fits ? back.undo : []));
10975
+ runtime.redo.splice(0, runtime.redo.length, ...(fits ? back.redo : []));
10976
+ runtime.seqBack = back || null;
10977
+ }
10978
+ /** What a sequence's undo steps rely on: its timeline, the shared comps and media, and (for relink /
10979
+ * replace steps) the clips of the other sequences — in the saved form, so both sides compare alike. */
10980
+ function seqUndoPrint(d, withOthers) {
10981
+ return JSON.stringify([d.clips || [], d.comps || [], (d.media || []).filter((m) => !m.transient),
10982
+ ...(withOthers ? [SeqLib.others(d).map((sq) => [sq.id, sq.clips || []])] : [])]);
10983
+ }
10984
+ /** Open sequence `id` in the editor. False when it can't be opened now. */
10985
+ function openSequence(id) {
10986
+ if (state.exporting) { toast("Wait for the export to finish before opening another sequence"); return false; }
10987
+ if (state.gesture) return false;
10988
+ if (state.compCtx) exitComp(state.compCtx.path.length);
10989
+ if (SeqLib.activeId(project) === id) return true;
10990
+ if (state.playing) pause();
10991
+ const doc = projectJSONHere();
10992
+ try { SeqLib.open(doc, id); } catch (e) { toast(e.message); return false; }
10993
+ applyProject(doc);
10994
+ const back = runtime.seqBack;
10995
+ runtime.seqBack = null;
10996
+ const sel = back && back.sel && getClip(back.sel);
10997
+ setSelection(sel ? [...withLinked([sel])].map((c) => c.id) : []);
10998
+ setTime(back ? back.time : 0);
10999
+ syncCompCrumb();
11000
+ scheduleSave();
11001
+ return true;
11002
+ }
11003
+ /** Add a sequence ({name?, from?, width?, height?}) and open it. */
11004
+ function newSequence(opts) {
11005
+ if (state.exporting) { toast("Wait for the export to finish"); return; }
11006
+ if (state.compCtx) exitComp(state.compCtx.path.length);
11007
+ const doc = projectJSONHere();
11008
+ let s;
11009
+ try { s = SeqLib.add(doc, opts); } catch (e) { toast(e.message); return; }
11010
+ project.sequences = doc.sequences; project.sequence = doc.sequence;
11011
+ if (openSequence(s.id)) toast(`New sequence “${s.name}” · ${s.width}×${s.height}`);
11012
+ else { scheduleSave(); syncCompCrumb(); toast(`New sequence “${s.name}” added — open it from the sequence menu`); }
11013
+ }
11014
+ function renameSequence(id, name) {
11015
+ const r = seqRoot();
11016
+ try { SeqLib.rename(r, id, name); } catch (e) { toast(e.message); return; }
11017
+ if (!r.sequences) { r.sequences = null; r.sequence = null; }
11018
+ syncCompCrumb(); scheduleSave();
11019
+ }
11020
+ /** Delete a sequence — after keeping the project as it is now as a version, when the server is there. */
11021
+ async function deleteSequence(id) {
11022
+ const r = seqRoot(), s = SeqLib.find(r, id);
11023
+ if (!s || SeqLib.entries(r).length < 2) return;
11024
+ if (state.exporting) { toast("Wait for the export to finish"); return; }
11025
+ if (state.compCtx) exitComp(state.compCtx.path.length);
11026
+ let kept = null;
11027
+ if (state.connected) {
11028
+ const projectId = runtime.projectId; // the version is of this project, whatever another tab opens meanwhile
11029
+ if (!(await flushSaveForVersion("the sequence was not deleted"))) return;
11030
+ try {
11031
+ const res = await fetch("/api/versions", { method: "POST", headers: { "Content-Type": "application/json" },
11032
+ body: JSON.stringify({ action: "save", name: `Before deleting the sequence “${s.name}”`.slice(0, 120), ...(projectId && projectId !== "?" ? { project: projectId } : {}) }) });
11033
+ if (res.ok) kept = (await res.json()).version;
11034
+ } catch { }
11035
+ // the delete has no undo: without that version it doesn't happen
11036
+ if (!kept) { toast(`Couldn't keep a version of the project, so “${s.name}” was not deleted. Try again in a moment.`); return; }
11037
+ }
11038
+ // the editor may have moved on while the version was saved
11039
+ if (state.exporting) { toast("Wait for the export to finish"); return; }
11040
+ if (state.compCtx) exitComp(state.compCtx.path.length);
11041
+ if (!SeqLib.find(project, id) || SeqLib.entries(project).length < 2) return; // deleted or changed meanwhile (another tab, an agent)
11042
+ const wasOpen = SeqLib.activeId(project) === id;
11043
+ const doc = projectJSONHere();
11044
+ try { SeqLib.remove(doc, id); } catch (e) { toast(e.message); return; }
11045
+ if (wasOpen) {
11046
+ applyProject(doc);
11047
+ const back = runtime.seqBack;
11048
+ runtime.seqBack = null;
11049
+ setSelection([]);
11050
+ setTime(back ? back.time : 0);
11051
+ } else { project.sequences = doc.sequences || null; project.sequence = doc.sequence || null; }
11052
+ runtime.seqUndo.delete(id);
11053
+ syncCompCrumb(); scheduleSave();
11054
+ toast(`Deleted the sequence “${s.name}”` + (kept ? ` · it is kept in version v${kept.v} (Projects → Versions)` : ""));
11055
+ }
11056
+ function syncSequenceButton() {
11057
+ const b = $("btnSequences");
11058
+ if (!b) return;
11059
+ const n = SeqLib.entries(seqRoot()).length;
11060
+ b.querySelector(".seq-name").textContent = openSequenceName();
11061
+ b.querySelector(".seq-count").textContent = n > 1 ? String(n) : "";
11062
+ b.title = `Sequence: ${openSequenceName()}${n > 1 ? ` (one of ${n})` : ""} — open another one, or add, duplicate, rename`;
11063
+ }
11064
+ /** The sequence menu: the project's sequences (click one to open it), then what to do with them. */
11065
+ function showSequenceMenu(x, y) {
11066
+ hideTrackCtxMenu();
11067
+ const menu = document.createElement("div");
11068
+ menu.className = "ctx-menu seq-menu";
11069
+ const r = seqRoot(), openId = SeqLib.activeId(r);
11070
+ const rows = SeqLib.list(r), open = rows.find((row) => row.active);
11071
+ const item = (html, run, why, keepOpen) => {
11072
+ const b = document.createElement("button");
11073
+ b.type = "button"; b.className = "ctx-item"; b.innerHTML = html;
11074
+ if (why) { b.disabled = true; b.title = why; } else b.addEventListener("click", () => { if (!keepOpen) hideTrackCtxMenu(); run(b); });
11075
+ menu.appendChild(b);
11076
+ return b;
11077
+ };
11078
+ const sep = () => { const d = document.createElement("div"); d.className = "ctx-sep"; menu.appendChild(d); };
11079
+ for (const row of rows) {
11080
+ // the open one's live numbers are on the timeline (or the root, while a comp is open)
11081
+ const w = row.active ? r.width : row.width, h = row.active ? r.height : row.height;
11082
+ const len = row.active ? (state.compCtx ? row.duration : projDur()) : row.duration;
11083
+ const b = item(`<span class="seq-check">${row.active ? "✓" : ""}</span><span class="seq-row-name">${escapeHtml(row.name)}</span><kbd>${w}×${h} · ${fmt(len)}</kbd>`,
11084
+ () => openSequence(row.id));
11085
+ if (row.active) b.classList.add("on");
11086
+ }
11087
+ sep();
11088
+ item(`<span>New sequence…</span>`, () => promptNewSequence(x, y));
11089
+ item(`<span>Duplicate “${escapeHtml(open.name)}”</span>`, () => newSequence({ from: "open" }));
11090
+ item(`<span>Rename “${escapeHtml(open.name)}”…</span>`, () => promptBinText(x, y, "Sequence name", open.name, (v) => renameSequence(openId, v), { max: 120, ok: "Rename" }));
11091
+ item(`<span>Delete “${escapeHtml(open.name)}”…</span>`, (b) => {
11092
+ if (b.dataset.armed !== "1") { b.dataset.armed = "1"; b.querySelector("span").textContent = "Click again to delete it"; return; }
11093
+ hideTrackCtxMenu();
11094
+ deleteSequence(openId);
11095
+ }, rows.length < 2 ? "A project keeps at least one sequence" : null, true);
11096
+ showPopover(menu, x, y);
11097
+ }
11098
+ /** New sequence: a name, a canvas, and whether it starts empty or as a copy of the open one. */
11099
+ function promptNewSequence(x, y) {
11100
+ const pop = document.createElement("div");
11101
+ pop.className = "ctx-menu bin-pop seq-new";
11102
+ const n = SeqLib.entries(seqRoot()).length + 1;
11103
+ const sizes = [{ label: `Same as “${openSequenceName()}” · ${project.width}×${project.height}`, w: 0, h: 0 }, ...ASPECT_PRESETS];
11104
+ pop.innerHTML = `<label class="bin-pop-label" for="seqNewName">New sequence</label>
11105
+ <input type="text" class="bin-pop-input" id="seqNewName" maxlength="120" spellcheck="false">
11106
+ <label class="bin-pop-label" for="seqNewSize">Canvas</label>
11107
+ <select id="seqNewSize" class="bin-pop-input">${sizes.map((s, i) => `<option value="${i}">${escapeHtml(s.label)}</option>`).join("")}</select>
11108
+ <label class="seq-new-copy"><input type="checkbox" id="seqNewCopy"> Start from a copy of “${escapeHtml(openSequenceName())}”</label>
11109
+ <div class="bin-pop-hint">Media and compositions are shared by every sequence. Each has its own timeline, canvas, frame rate, mix and delivery settings.</div>
11110
+ <div class="bin-pop-btns"><button type="button" class="btn tiny" data-cancel>Cancel</button><button type="button" class="btn tiny accent" data-ok>Create</button></div>`;
11111
+ pop.querySelector("#seqNewName").value = `Sequence ${n}`;
11112
+ const ok = () => {
11113
+ const name = pop.querySelector("#seqNewName").value.trim();
11114
+ const size = sizes[+pop.querySelector("#seqNewSize").value] || sizes[0];
11115
+ const copy = pop.querySelector("#seqNewCopy").checked;
11116
+ hideTrackCtxMenu();
11117
+ newSequence({ name: name || undefined, from: copy ? "open" : "empty", ...(size.w ? { width: size.w, height: size.h } : {}) });
11118
+ };
11119
+ pop.querySelector("[data-ok]").addEventListener("click", ok);
11120
+ pop.querySelector("[data-cancel]").addEventListener("click", () => hideTrackCtxMenu());
11121
+ pop.addEventListener("keydown", (e) => {
11122
+ if (e.key === "Enter" && e.target.tagName !== "SELECT") { e.preventDefault(); ok(); }
11123
+ else if (e.key === "Escape") { e.preventDefault(); hideTrackCtxMenu(); }
11124
+ e.stopPropagation();
11125
+ });
11126
+ showPopover(pop, x, y);
11127
+ const input = pop.querySelector("#seqNewName");
11128
+ input.focus(); input.select();
11129
+ }
11130
+ function initSequencesUi() {
11131
+ const b = $("btnSequences");
11132
+ if (!b || b.dataset.wired) return;
11133
+ b.dataset.wired = "1";
11134
+ b.addEventListener("click", () => { const rc = b.getBoundingClientRect(); showSequenceMenu(rc.left, rc.bottom + 4); });
11135
+ syncSequenceButton();
11136
+ }
11137
+
9187
11138
  /* ── Making comps ── */
9188
11139
  function newCompId() { let id; do id = "comp_" + uid(); while (getComp(id)); return id; }
9189
11140
  /** Precompose the selection: the clips move into a new comp, a comp clip takes their place. */
@@ -9227,6 +11178,7 @@ function addCompClip(comp, trackId, at) {
9227
11178
  function makeCompItem(comp) {
9228
11179
  const item = document.createElement("div");
9229
11180
  item.className = "bin-item comp-item";
11181
+ item.dataset.compId = comp.id;
9230
11182
  item.draggable = true;
9231
11183
  const used = CompLib.usages(state.compCtx ? state.compCtx.root : project, comp.id).length;
9232
11184
  item.innerHTML = `<div class="bin-thumb comp-thumb">▣</div>
@@ -9865,6 +11817,28 @@ function shapeKeyed(c) {
9865
11817
  const any = (list) => (list || []).some((it) => (it.keys && it.keys.length) || (it.type === "group" && any(it.items)));
9866
11818
  return any(c.props.shapes);
9867
11819
  }
11820
+ /** A missing file's picture: the box it would fill, marked "Media offline" (preview and export). */
11821
+ function drawOfflineSlate(c, p, W, H) {
11822
+ const m = getMedia(c.mediaId);
11823
+ const mw = m && m.width > 0 ? m.width : W, mh = m && m.height > 0 ? m.height : H, sc = p.scale || 1;
11824
+ let dw, dh;
11825
+ if (p.fit === "cover") { const f = Math.max(W / mw, H / mh) * sc; dw = mw * f; dh = mh * f; }
11826
+ else if (p.fit === "stretch") { dw = W * sc; dh = H * sc; }
11827
+ else if (p.fit === "none") { dw = mw * sc; dh = mh * sc; }
11828
+ else { const f = Math.min(W / mw, H / mh) * sc; dw = mw * f; dh = mh * f; }
11829
+ ctx2d.fillStyle = "#3a0d10";
11830
+ ctx2d.fillRect(-dw / 2, -dh / 2, dw, dh);
11831
+ ctx2d.strokeStyle = "#e5484d"; ctx2d.lineWidth = Math.max(2, dh / 120);
11832
+ ctx2d.strokeRect(-dw / 2, -dh / 2, dw, dh);
11833
+ const fs = Math.max(9, Math.min(dw / 20, dh / 9));
11834
+ ctx2d.fillStyle = "#ff8a8d";
11835
+ ctx2d.textAlign = "center"; ctx2d.textBaseline = "middle";
11836
+ ctx2d.font = `700 ${fs}px "Segoe UI", system-ui, sans-serif`;
11837
+ ctx2d.fillText("Media offline", 0, -fs * 0.35, dw * 0.9);
11838
+ ctx2d.font = `400 ${fs * 0.42}px "Segoe UI", system-ui, sans-serif`;
11839
+ ctx2d.fillStyle = "#f2c4c5";
11840
+ ctx2d.fillText(m ? m.name : "", 0, fs * 0.55, dw * 0.9);
11841
+ }
9868
11842
  /** Draw one clip. `layered`: into a mask layer — opacity and blend wait for
9869
11843
  * the composite. Returns { p, geom } — geom = where the clip's picture landed
9870
11844
  * (canvas transform + its box), the space its masks live in. */
@@ -9929,18 +11903,23 @@ function drawClipPicture(c, W, H, t, layered) {
9929
11903
  }
9930
11904
  let src = null, sw = 0, sh = 0;
9931
11905
  if (c.kind === "image") {
9932
- src = runtime.mediaAux.get(c.mediaId)?.img;
11906
+ const aux = runtime.mediaAux.get(c.mediaId), im = aux?.imgSrc && getMedia(c.mediaId);
11907
+ if (im && aux.imgSrc !== im.src && !aux.reloading) { aux.reloading = true; reloadMediaSource(im); } // relinked / undone
11908
+ src = aux?.img;
9933
11909
  if (src) { sw = src.naturalWidth; sh = src.naturalHeight; }
9934
11910
  } else if (c.kind === "svg") {
9935
11911
  src = getSvgImage(c, t);
9936
11912
  if (src) { sw = src.naturalWidth || src.width; sh = src.naturalHeight || src.height; }
9937
11913
  } else if (c.kind === "video") {
9938
- src = getClipEl(c);
9939
- if (src) { sw = src.videoWidth; sh = src.videoHeight; }
11914
+ const frame = runtime.exportFrames && runtime.exportFrames.get(c.id);
11915
+ src = frame || getClipEl(c);
11916
+ if (frame) { sw = frame.displayWidth; sh = frame.displayHeight; }
11917
+ else if (src) { sw = src.videoWidth; sh = src.videoHeight; }
9940
11918
  } else if (c.kind === "comp") {
9941
11919
  src = renderComp(c, t);
9942
11920
  if (src) { sw = src.width; sh = src.height; }
9943
11921
  }
11922
+ if ((!src || !sw || !sh) && isMediaOffline(c.mediaId)) drawOfflineSlate(c, p, W, H);
9944
11923
  if (src && sw && sh) {
9945
11924
  // source crop (percent per edge)
9946
11925
  const sx = sw * clamp(+p.cropL || 0, 0, 95) / 100;
@@ -9952,7 +11931,7 @@ function drawClipPicture(c, W, H, t, layered) {
9952
11931
  let dw, dh;
9953
11932
  if (p.fit === "cover") { const f = Math.max(W / cw, H / ch) * sc; dw = cw * f; dh = ch * f; }
9954
11933
  else if (p.fit === "stretch") { dw = W * sc; dh = H * sc; }
9955
- else if (p.fit === "none") { dw = cw * sc; dh = ch * sc; }
11934
+ else if (p.fit === "none") { const k = src._fcScale || 1; dw = cw * sc / k; dh = ch * sc / k; }
9956
11935
  else { const f = Math.min(W / cw, H / ch) * sc; dw = cw * f; dh = ch * f; }
9957
11936
  if (p.flipH || p.flipV) ctx2d.scale(p.flipH ? -1 : 1, p.flipV ? -1 : 1);
9958
11937
  if (p.cornerRadius > 0) {
@@ -10375,7 +12354,7 @@ function pictureRect(c, p) {
10375
12354
  let dw, dh;
10376
12355
  if (p.fit === "cover") { const f = Math.max(W / cw, H / ch) * sc; dw = cw * f; dh = ch * f; }
10377
12356
  else if (p.fit === "stretch") { dw = W * sc; dh = H * sc; }
10378
- else if (p.fit === "none") { dw = cw * sc; dh = ch * sc; }
12357
+ else if (p.fit === "none") { const ps = el._fcScale || 1; dw = cw * sc / ps; dh = ch * sc / ps; } // a proxy is drawn at the original's size
10379
12358
  else { const f = Math.min(W / cw, H / ch) * sc; dw = cw * f; dh = ch * f; }
10380
12359
  return { cx: W / 2 + (+p.x || 0), cy: H / 2 + (+p.y || 0), dw, dh, rot: (p.rotation || 0) * Math.PI / 180, fx: p.flipH ? -1 : 1, fy: p.flipV ? -1 : 1 };
10381
12360
  }
@@ -12703,6 +14682,52 @@ async function loadProjectFonts() {
12703
14682
  let lastTs = null;
12704
14683
  let exportWindow = null;
12705
14684
  let playheadPx = -1;
14685
+ /* The loop runs at the display's refresh rate (240 Hz on some laptops), but
14686
+ the picture only changes once per project frame. Redraw the program
14687
+ monitor and the playhead-driven panels when the playhead reaches a new
14688
+ frame; while paused, at the project rate for a moment after any input
14689
+ (sliders, drags, hover handles) and at 4 fps otherwise, which still picks
14690
+ up late seeks, font loads and agent edits. */
14691
+ let lastDrawKey = null, lastDrawAt = 0, lastActivity = 0, lastRulerKey = "";
14692
+ /* An idle editor doesn't need a callback per display refresh either: even an
14693
+ empty requestAnimationFrame loop keeps the compositor ticking at 240 Hz.
14694
+ When nothing moves the loop sleeps on a 4 fps timer, and any input or
14695
+ server event wakes it at once. */
14696
+ let loopSleep = 0;
14697
+ const IDLE_MS = 250, ACTIVE_MS = 1500, AUDIO_IDLE_MS = 3000;
14698
+ function noteActivity() {
14699
+ lastActivity = performance.now();
14700
+ if (loopSleep) { clearTimeout(loopSleep); loopSleep = 0; lastTs = null; requestAnimationFrame(loop); }
14701
+ }
14702
+ function loopBusy(now) {
14703
+ return state.playing || state.source.playing || state.exporting || state.rendering || state.audioHold ||
14704
+ state.gesture || state.dirtyTimeline || now - lastActivity < ACTIVE_MS;
14705
+ }
14706
+ /* The audio graph (fx worklets, meter, convolvers) renders silence for as long
14707
+ as its context runs, which costs a realtime thread a quarter of a core.
14708
+ Suspend it a few seconds after the last sound — reverb and delay tails
14709
+ finish first — and let every play path resume it as it already does. */
14710
+ let audioIdleSince = 0;
14711
+ function idleAudio(now) {
14712
+ const au = runtime.audio;
14713
+ if (!au || au.ctx.state !== "running") { audioIdleSince = 0; return; }
14714
+ let sounding = state.playing || state.source.playing || state.exporting || state.rendering || state.audioHold;
14715
+ if (!sounding) for (const el of runtime.clipEls.values()) if (!el.paused) { sounding = true; break; }
14716
+ if (sounding) { audioIdleSince = 0; return; }
14717
+ if (!audioIdleSince) audioIdleSince = now;
14718
+ else if (now - audioIdleSince > AUDIO_IDLE_MS) { audioIdleSince = 0; au.ctx.suspend().catch(() => { }); }
14719
+ }
14720
+ for (const ev of ["pointerdown", "pointermove", "pointerup", "wheel", "keydown", "keyup", "input", "change", "dragover", "drop", "resize"])
14721
+ window.addEventListener(ev, noteActivity, { capture: true, passive: true });
14722
+ function frameDue(now) {
14723
+ if (state.exporting) return true;
14724
+ const src = isSourceMode(), fps = projectFps();
14725
+ const key = (src ? "s" : "p") + Math.floor((src ? state.source.time : state.time) * fps + 1e-6);
14726
+ const gap = now - lastActivity < ACTIVE_MS ? 1000 / fps : IDLE_MS;
14727
+ if (key === lastDrawKey && now - lastDrawAt < gap - 1) return false;
14728
+ lastDrawKey = key; lastDrawAt = now;
14729
+ return true;
14730
+ }
12706
14731
  function loop(ts) {
12707
14732
  if (lastTs == null) lastTs = ts;
12708
14733
  const dt = Math.min(0.1, (ts - lastTs) / 1000);
@@ -12755,13 +14780,14 @@ function loop(ts) {
12755
14780
  if (px < sc.scrollLeft || px > sc.scrollLeft + sc.clientWidth - 40)
12756
14781
  sc.scrollLeft = Math.max(0, px - 60);
12757
14782
  }
14783
+ const draw = frameDue(ts);
12758
14784
  if (!state.rendering) { // fast export owns media seeking + the canvas
12759
14785
  if (isSourceMode()) {
12760
14786
  syncSourceMedia();
12761
- drawSourceFrame();
14787
+ if (draw) drawSourceFrame();
12762
14788
  } else {
12763
14789
  syncMedia();
12764
- drawFrame();
14790
+ if (draw) drawFrame();
12765
14791
  }
12766
14792
  }
12767
14793
  if (state.dirtyTimeline) rebuildClips();
@@ -12770,14 +14796,17 @@ function loop(ts) {
12770
14796
  playheadPx = phX;
12771
14797
  els.playhead.style.left = phX + "px";
12772
14798
  }
12773
- drawRuler();
12774
- if (!isSourceMode()) updateSafeOverlay();
12775
- updateKfGraphs();
12776
- syncInspectorPlayhead();
12777
- syncFxEditors();
12778
- syncColorPlayhead();
14799
+ const rulerKey = `${els.timelineScroll.scrollLeft} ${els.timelineScroll.clientWidth} ${state.pps}`;
14800
+ if (draw || rulerKey !== lastRulerKey) { lastRulerKey = rulerKey; drawRuler(); }
14801
+ if (draw) {
14802
+ if (!isSourceMode()) updateSafeOverlay();
14803
+ updateKfGraphs();
14804
+ syncInspectorPlayhead();
14805
+ syncFxEditors();
14806
+ syncColorPlayhead();
14807
+ updateTimecode(dur);
14808
+ }
12779
14809
  updateMeterUI(dt);
12780
- updateTimecode(dur);
12781
14810
  if (isSourceMode()) updateSourceScrub();
12782
14811
  if (state.exporting && !state.rendering) {
12783
14812
  const w = exportWindow;
@@ -12787,7 +14816,9 @@ function loop(ts) {
12787
14816
  els.exportProgress.style.width = pct.toFixed(1) + "%";
12788
14817
  els.exportTitle.textContent = `Exporting… ${pct.toFixed(0)}%`;
12789
14818
  }
12790
- requestAnimationFrame(loop);
14819
+ idleAudio(ts);
14820
+ if (loopBusy(ts)) requestAnimationFrame(loop);
14821
+ else loopSleep = setTimeout(() => { loopSleep = 0; lastTs = null; requestAnimationFrame(loop); }, IDLE_MS); // a nap is not playback time
12791
14822
  }
12792
14823
 
12793
14824
  /* ═══════════════════════════ EXPORT ═══════════════════════════ */
@@ -12855,28 +14886,308 @@ function updateExportProfileNote(id) {
12855
14886
  } else if (getSetting("encodeProfile")) {
12856
14887
  els.exportProfileHint.textContent = "Browser default — saved when you change this dropdown.";
12857
14888
  } else {
12858
- els.exportProfileHint.textContent = "Using server default from encoding-profiles.json.";
14889
+ els.exportProfileHint.textContent = "Raw ffmpeg arguments from encoding-profiles.json.";
12859
14890
  }
12860
14891
  }
12861
14892
  }
14893
+
14894
+ /* ── Delivery presets (delivery.js) ──
14895
+ The Preset dropdown lists the delivery presets (YouTube, Reels, Broadcast…,
14896
+ saved ones, Custom) and, last, the raw encoding profiles. A delivery preset
14897
+ fills the controls below it; any change makes it "modified" and is kept as
14898
+ the browser's last settings. Values: "d:<preset id>" / "p:<profile id>". */
14899
+ const Delivery = window.FableCutDelivery;
14900
+ let deliveryInfo = { encoders: null, saved: {} };
14901
+ let dlvSpec = null;
14902
+ let dlvNotes = [];
14903
+ async function fetchDeliveryInfo() {
14904
+ if (!state.connected) return;
14905
+ try {
14906
+ const r = await fetch("/api/export/presets", { cache: "no-store" });
14907
+ if (!r.ok) return;
14908
+ const d = await r.json();
14909
+ deliveryInfo = { encoders: Array.isArray(d.encoders) ? d.encoders : null, saved: d.saved && typeof d.saved === "object" ? d.saved : {} };
14910
+ } catch { }
14911
+ }
14912
+ function deliveryOpts() {
14913
+ return { available: deliveryInfo.encoders ? new Set(deliveryInfo.encoders) : null, presets: deliveryInfo.saved };
14914
+ }
14915
+ function normalizeDelivery(input) { return Delivery.normalize(input, deliveryOpts()); }
14916
+ /** What an export uses when nobody picks: the project's pin, else this browser's last choice. */
14917
+ function exportChoice() {
14918
+ if (project.delivery) return { kind: "delivery", spec: project.delivery, source: "project" };
14919
+ if (project.encodeProfile) return { kind: "profile", id: project.encodeProfile, source: "project" };
14920
+ const kind = getSetting("exportKind") || (getSetting("encodeProfile") ? "profile" : "delivery");
14921
+ if (kind === "profile") return { kind, id: effectiveEncodeProfileId(), source: "browser" };
14922
+ const last = getSetting("delivery");
14923
+ return { kind: "delivery", spec: last && typeof last === "object" ? last : Delivery.DEFAULT_PRESET, source: last ? "browser" : "default" };
14924
+ }
14925
+ function selectedExportChoice() {
14926
+ const v = els.exportProfileSel?.value || "";
14927
+ return v.startsWith("p:") ? { kind: "profile", id: v.slice(2) } : { kind: "delivery", id: v.slice(2) || Delivery.DEFAULT_PRESET };
14928
+ }
12862
14929
  function populateExportProfileSelect() {
12863
- if (!els.exportProfileSel) return;
14930
+ const sel = els.exportProfileSel;
14931
+ if (!sel) return;
14932
+ const choice = exportChoice();
14933
+ let cur;
14934
+ if (choice.kind === "delivery") {
14935
+ const n = normalizeDelivery(choice.spec);
14936
+ dlvSpec = n.spec; dlvNotes = n.notes;
14937
+ cur = "d:" + dlvSpec.preset;
14938
+ } else cur = "p:" + choice.id;
14939
+ const opt = (v, label) => `<option value="${escapeHtml(v)}">${escapeHtml(label)}</option>`;
14940
+ let html = Delivery.presetGroups(deliveryInfo.saved).map((g) =>
14941
+ `<optgroup label="${escapeHtml(g.group)}">${g.items.map((it) => opt("d:" + it.id, it.label)).join("")}</optgroup>`).join("");
12864
14942
  const ids = Object.keys(encodeProfiles.profiles);
12865
- const cur = effectiveEncodeProfileId();
12866
14943
  // a project/browser default naming a deleted profile must stay visible rather
12867
14944
  // than silently falling through to whichever option happens to be first
12868
- if (cur && !ids.includes(cur)) ids.unshift(cur);
12869
- els.exportProfileSel.innerHTML = ids.map((id) => {
14945
+ if (choice.kind === "profile" && !ids.includes(choice.id)) ids.unshift(choice.id);
14946
+ html += `<optgroup label="Encoding profiles (encoding-profiles.json)">${ids.map((id) => {
12870
14947
  const p = encodeProfiles.profiles[id];
12871
- const sel = id === cur ? " selected" : "";
12872
- const label = p ? (p.label || id) : `${id} (not defined on the server)`;
12873
- return `<option value="${escapeHtml(id)}"${sel}>${escapeHtml(label)}</option>`;
12874
- }).join("");
12875
- updateExportProfileNote(els.exportProfileSel.value || cur || "delivery");
14948
+ return opt("p:" + id, p ? (p.label || id) : `${id} (not defined on the server)`);
14949
+ }).join("")}</optgroup>`;
14950
+ sel.innerHTML = html;
14951
+ sel.value = cur;
14952
+ if (sel.value !== cur) sel.value = "d:" + Delivery.DEFAULT_PRESET;
14953
+ syncExportChoiceUi(choice.source);
14954
+ }
14955
+ /** source: where the current settings came from, for the hint line. */
14956
+ function syncExportChoiceUi(source) {
14957
+ const c = selectedExportChoice();
14958
+ const isD = c.kind === "delivery";
14959
+ $("dlvBody")?.classList.toggle("hidden", !isD);
14960
+ $("dlvSaveBtn")?.classList.toggle("hidden", !isD);
14961
+ $("dlvDeleteBtn")?.classList.toggle("hidden", !(isD && deliveryInfo.saved[c.id]));
14962
+ $("dlvSaveRow")?.classList.add("hidden");
14963
+ if (!isD) {
14964
+ updateExportProfileNote(c.id);
14965
+ const w = $("dlvWarn"); if (w) { w.textContent = ""; w.classList.add("hidden"); }
14966
+ return;
14967
+ }
14968
+ if (!dlvSpec || dlvSpec.preset !== c.id) {
14969
+ const n = normalizeDelivery(c.id);
14970
+ dlvSpec = n.spec; dlvNotes = n.notes;
14971
+ source = "preset";
14972
+ }
14973
+ dlvSource = source || dlvSource;
14974
+ fillDeliveryControls();
14975
+ refreshDeliveryNotes();
14976
+ }
14977
+ let dlvSource = "default";
14978
+ function deliveryCanvas() {
14979
+ return { w: els.preview?.width || project.width, h: els.preview?.height || project.height, region: getExportFrame() };
14980
+ }
14981
+ function deliveryFrame(spec) {
14982
+ const cv = deliveryCanvas();
14983
+ return Delivery.reframe(spec, cv.w, cv.h, cv.region);
14984
+ }
14985
+ function deliveryFileName(spec, fps) {
14986
+ const fr = deliveryFrame(spec);
14987
+ return Delivery.renderFilename(spec.filename, spec, {
14988
+ project: project.name.replace(/[^\w\- ]+/g, "").trim() || "export",
14989
+ width: fr.outW, height: fr.outH, fps: fps || spec.fps || projectFps(), range: exportRangeMode(),
14990
+ });
14991
+ }
14992
+ const dlvVal = (id) => $(id)?.value ?? "";
14993
+ function setOptions(sel, items, value) {
14994
+ if (!sel) return;
14995
+ sel.innerHTML = items.map(([v, label, disabled]) =>
14996
+ `<option value="${escapeHtml(String(v))}"${disabled ? " disabled" : ""}>${escapeHtml(label)}</option>`).join("");
14997
+ sel.value = String(value);
14998
+ }
14999
+ function showField(id, on) { $(id)?.classList.toggle("hidden", !on); }
15000
+ function fillDeliveryControls() {
15001
+ const sp = dlvSpec, v = sp.video, a = sp.audio, C = Delivery.CODECS[v.codec];
15002
+ const fr = deliveryFrame({ ...sp, width: null, height: null });
15003
+ const avail = deliveryOpts().available;
15004
+ // resolution
15005
+ const res = [["", `Picture size (${fr.outW} × ${fr.outH})`]];
15006
+ for (const [w, h, label] of Delivery.RESOLUTIONS) res.push([`${w}x${h}`, `${w} × ${h} · ${label}`]);
15007
+ res.push(["custom", "Custom…"]);
15008
+ let rv = sp.width ? `${sp.width}x${sp.height}` : "";
15009
+ if (rv && !res.some((r) => r[0] === rv)) rv = "custom";
15010
+ if (dlvCustomRes && sp.width) rv = "custom";
15011
+ setOptions($("dlvRes"), res, rv);
15012
+ showField("dlvWhField", rv === "custom");
15013
+ if (rv === "custom") { $("dlvW").value = sp.width; $("dlvH").value = sp.height; }
15014
+ showField("dlvReframeField", !!sp.width);
15015
+ $("dlvReframe").value = sp.reframe;
15016
+ setOptions($("dlvFps"), [["", `Project (${projectFps()} fps)`], ...Delivery.FPS_CHOICES.map((f) => [f, `${f} fps`])], sp.fps ?? "");
15017
+ setOptions($("dlvCodec"), Object.entries(Delivery.CODECS).map(([k, c]) => {
15018
+ const none = avail && !Delivery.encodersFor(k, avail).length;
15019
+ return [k, c.label + (none ? " — not in this ffmpeg" : ""), none && k !== v.codec];
15020
+ }), v.codec);
15021
+ const encs = Delivery.encodersFor(v.codec, avail);
15022
+ setOptions($("dlvEncoder"), (encs.length ? encs : [v.encoder]).map((e) => [e, Delivery.ENCODERS[e]?.label || e]), v.encoder);
15023
+ showField("dlvEncoderField", encs.length > 1);
15024
+ showField("dlvProfileField", !!C.profiles);
15025
+ if (C.profiles) setOptions($("dlvProfile"), Object.entries(C.profiles), v.profile);
15026
+ const fixed = v.rate === "fixed";
15027
+ showField("dlvRateField", !fixed);
15028
+ if (!fixed) setOptions($("dlvRate"), C.rate.map((r) => [r, { crf: "CRF (constant quality)", vbr: "VBR (variable bitrate)", cbr: "CBR (constant bitrate)" }[r]]), v.rate);
15029
+ showField("dlvCrfField", v.rate === "crf");
15030
+ showField("dlvBitrateField", v.rate === "vbr" || v.rate === "cbr");
15031
+ showField("dlvMaxrateField", v.rate === "crf" || v.rate === "vbr");
15032
+ for (const f of ["dlvKeyintField", "dlvSpeedField"]) showField(f, !fixed);
15033
+ if (!fixed) {
15034
+ const crf = $("dlvCrf"); crf.min = C.crf[0]; crf.max = C.crf[1];
15035
+ if (document.activeElement !== crf) crf.value = v.crf;
15036
+ if (document.activeElement !== $("dlvBitrate")) $("dlvBitrate").value = +(v.bitrate / 1000).toFixed(2);
15037
+ if (document.activeElement !== $("dlvMaxrate")) $("dlvMaxrate").value = v.maxrate ? +(v.maxrate / 1000).toFixed(2) : "";
15038
+ if (document.activeElement !== $("dlvKeyint")) $("dlvKeyint").value = v.keyint;
15039
+ $("dlvSpeed").value = v.speed;
15040
+ }
15041
+ const E = Delivery.ENCODERS[v.encoder] || {};
15042
+ const pix = C.pixFmts.filter((f) => !E.pix || E.pix.includes(f));
15043
+ const PIX = { yuv420p: "4:2:0 8-bit", yuv422p: "4:2:2 8-bit", yuv444p: "4:4:4 8-bit", yuv420p10le: "4:2:0 10-bit", yuv422p10le: "4:2:2 10-bit", yuv444p10le: "4:4:4 10-bit" };
15044
+ setOptions($("dlvPixFmt"), (pix.includes(v.pixFmt) ? pix : [v.pixFmt, ...pix]).map((f) => [f, `${PIX[f] || f} (${f})`]), v.pixFmt);
15045
+ $("dlvPixFmt").disabled = v.codec === "prores" || v.codec === "dnxhr" || pix.length < 2;
15046
+ setOptions($("dlvColor"), Object.entries(Delivery.COLORS).map(([k, c]) => [k, c.label]), sp.color);
15047
+ setOptions($("dlvContainer"), C.containers.map((k) => [k, Delivery.CONTAINERS[k].label]), sp.container);
15048
+ // audio
15049
+ setOptions($("dlvACodec"), Object.entries(Delivery.AUDIO).filter(([, A]) => A.containers.includes(sp.container)).map(([k, A]) => [k, A.label]), a.codec);
15050
+ const A = Delivery.AUDIO[a.codec];
15051
+ showField("dlvABitrateField", !!A.bitrate);
15052
+ if (A.bitrate) {
15053
+ const steps = [64, 96, 128, 160, 192, 256, 320, 384, 448, 512].filter((k) => k >= A.bitrate[0] && k <= A.bitrate[1]);
15054
+ if (!steps.includes(a.bitrate)) steps.push(a.bitrate), steps.sort((x, y) => x - y);
15055
+ setOptions($("dlvABitrate"), steps.map((k) => [k, `${k} kb/s`]), a.bitrate);
15056
+ }
15057
+ showField("dlvARateField", a.codec !== "none" && a.codec !== "opus");
15058
+ showField("dlvAChField", a.codec !== "none");
15059
+ if (a.codec !== "none") { $("dlvARate").value = a.sampleRate; $("dlvACh").value = a.channels; }
15060
+ showField("dlvLoudField", a.codec !== "none");
15061
+ showField("dlvTpField", a.codec !== "none" && a.loudness != null);
15062
+ if (a.codec !== "none") {
15063
+ const opts = [["off", "Off — as mixed"], ...Delivery.LOUDNESS_TARGETS];
15064
+ if (a.loudness != null && !opts.some((o) => +o[0] === a.loudness)) opts.push([a.loudness, `${a.loudness} LUFS`]);
15065
+ setOptions($("dlvLoud"), opts, a.loudness == null ? "off" : a.loudness);
15066
+ if (a.loudness != null && document.activeElement !== $("dlvTp")) $("dlvTp").value = a.truePeak;
15067
+ }
15068
+ // file name + metadata (left alone while typing)
15069
+ const fn = $("dlvFilename");
15070
+ if (document.activeElement !== fn) fn.value = sp.filename;
15071
+ for (const k of Delivery.META_KEYS) {
15072
+ const el = $("dlvMeta" + k[0].toUpperCase() + k.slice(1));
15073
+ if (el && document.activeElement !== el) el.value = sp.metadata[k] || "";
15074
+ }
15075
+ $("dlvTokens").textContent = "Tokens: " + Delivery.FILENAME_TOKENS.map((t) => `{${t}}`).join(" ");
15076
+ }
15077
+ let dlvCustomRes = false;
15078
+ /** The controls → a spec. `changed`: the control the user touched. */
15079
+ function readDeliveryControls(changed) {
15080
+ const sp = dlvSpec;
15081
+ const raw = { preset: sp.preset, video: { ...sp.video }, audio: { ...sp.audio }, metadata: {} };
15082
+ const r = dlvVal("dlvRes");
15083
+ dlvCustomRes = r === "custom";
15084
+ if (r === "") { raw.width = null; raw.height = null; }
15085
+ else if (r === "custom") {
15086
+ if (changed === "dlvRes") { const fr = deliveryFrame(sp); raw.width = fr.outW; raw.height = fr.outH; }
15087
+ else { raw.width = +dlvVal("dlvW") || null; raw.height = +dlvVal("dlvH") || null; }
15088
+ } else { const [w, h] = r.split("x").map(Number); raw.width = w; raw.height = h; }
15089
+ raw.reframe = dlvVal("dlvReframe");
15090
+ raw.fps = dlvVal("dlvFps") === "" ? null : +dlvVal("dlvFps");
15091
+ raw.container = dlvVal("dlvContainer");
15092
+ raw.color = dlvVal("dlvColor");
15093
+ if (changed === "dlvCodec") raw.video = { codec: dlvVal("dlvCodec"), speed: sp.video.speed, keyint: sp.video.keyint, maxrate: sp.video.maxrate, bitrate: sp.video.bitrate };
15094
+ else {
15095
+ const v = raw.video;
15096
+ v.encoder = dlvVal("dlvEncoder") || v.encoder;
15097
+ if (!$("dlvProfileField").classList.contains("hidden")) v.profile = dlvVal("dlvProfile");
15098
+ if (v.rate !== "fixed") {
15099
+ v.rate = dlvVal("dlvRate") || v.rate;
15100
+ v.crf = +dlvVal("dlvCrf");
15101
+ v.bitrate = Math.round(+dlvVal("dlvBitrate") * 1000) || v.bitrate;
15102
+ v.maxrate = dlvVal("dlvMaxrate") === "" ? null : Math.round(+dlvVal("dlvMaxrate") * 1000);
15103
+ v.keyint = +dlvVal("dlvKeyint");
15104
+ v.speed = dlvVal("dlvSpeed");
15105
+ }
15106
+ v.pixFmt = dlvVal("dlvPixFmt");
15107
+ }
15108
+ const a = raw.audio;
15109
+ a.codec = dlvVal("dlvACodec") || a.codec;
15110
+ if (changed !== "dlvACodec") {
15111
+ if (!$("dlvABitrateField").classList.contains("hidden")) a.bitrate = +dlvVal("dlvABitrate");
15112
+ a.sampleRate = +dlvVal("dlvARate") || a.sampleRate;
15113
+ a.channels = +dlvVal("dlvACh") || a.channels;
15114
+ a.loudness = dlvVal("dlvLoud") === "off" || dlvVal("dlvLoud") === "" ? null : +dlvVal("dlvLoud");
15115
+ if (dlvVal("dlvTp") !== "") a.truePeak = +dlvVal("dlvTp");
15116
+ } else delete a.bitrate;
15117
+ raw.filename = dlvVal("dlvFilename");
15118
+ for (const k of Delivery.META_KEYS) raw.metadata[k] = dlvVal("dlvMeta" + k[0].toUpperCase() + k.slice(1));
15119
+ return raw;
15120
+ }
15121
+ function onDeliveryControl(e) {
15122
+ const id = e.target?.id || "";
15123
+ if (!id.startsWith("dlv") || id === "dlvSaveName") return;
15124
+ const n = normalizeDelivery(readDeliveryControls(id));
15125
+ dlvSpec = n.spec; dlvNotes = n.notes;
15126
+ dlvSource = "edited";
15127
+ // text fields refresh the preview only; everything else may move other controls
15128
+ if (e.type === "change") fillDeliveryControls();
15129
+ refreshDeliveryNotes();
15130
+ }
15131
+ function deliveryModified() {
15132
+ if (!dlvSpec) return false;
15133
+ const base = normalizeDelivery(dlvSpec.preset).spec;
15134
+ const strip = (x) => JSON.stringify({ ...x, metadata: null });
15135
+ return strip(base) !== strip(dlvSpec);
15136
+ }
15137
+ function refreshDeliveryNotes() {
15138
+ if (!dlvSpec) return;
15139
+ const sp = dlvSpec, fr = deliveryFrame(sp), fps = sp.fps || projectFps();
15140
+ const preset = Delivery.PRESETS[sp.preset] || deliveryInfo.saved[sp.preset];
15141
+ const modified = deliveryModified();
15142
+ if (els.exportProfileNote) els.exportProfileNote.textContent = preset?.note || "";
15143
+ if (els.exportProfileHint) {
15144
+ els.exportProfileHint.textContent = dlvSource === "project"
15145
+ ? "Project default (delivery in project.json) — agents export with it too."
15146
+ : modified ? `${preset?.label || "Preset"} · modified — Save preset… keeps these settings for every project.`
15147
+ : dlvSource === "browser" ? "Your last settings in this browser." : "";
15148
+ }
15149
+ const range = exportRange(fps);
15150
+ const size = Delivery.estimateSize(sp, { duration: range.dur, width: fr.outW, height: fr.outH, fps });
15151
+ $("dlvSummary").textContent = `${Delivery.describe(sp, { width: fr.outW, height: fr.outH, fps })}` +
15152
+ (size ? ` · about ${Delivery.fmtBytes(size)}` : "");
15153
+ $("dlvFilePreview").textContent = "→ exports/" + deliveryFileName(sp, fps) + Delivery.CONTAINERS[sp.container].ext;
15154
+ const cv = deliveryCanvas();
15155
+ const warn = [...dlvNotes.map((n) => n[0].toUpperCase() + n.slice(1)),
15156
+ ...Delivery.checks(sp, { duration: range.dur, fps, canvasW: cv.w, canvasH: cv.h, region: cv.region })];
15157
+ const w = $("dlvWarn");
15158
+ if (w) { w.textContent = warn.join(" · "); w.classList.toggle("hidden", !warn.length); }
15159
+ }
15160
+ async function saveDeliveryPreset() {
15161
+ const name = $("dlvSaveName").value.trim();
15162
+ if (!name) { $("dlvSaveName").focus(); return; }
15163
+ const r = await fetch("/api/export/presets", { method: "POST", body: JSON.stringify({ name, spec: dlvSpec }) })
15164
+ .then((x) => x.json()).catch((e) => ({ error: String(e) }));
15165
+ if (!r.ok) { alert("Could not save the preset: " + (r.error || "unknown error")); return; }
15166
+ await fetchDeliveryInfo();
15167
+ setSetting("exportKind", "delivery");
15168
+ setSetting("delivery", { ...dlvSpec, preset: r.id });
15169
+ if (!project.delivery) populateExportProfileSelect();
15170
+ else { els.exportProfileSel.value = "d:" + r.id; dlvSpec = null; syncExportChoiceUi("preset"); }
15171
+ }
15172
+ async function deleteDeliveryPreset() {
15173
+ const c = selectedExportChoice();
15174
+ if (c.kind !== "delivery" || !deliveryInfo.saved[c.id]) return;
15175
+ const r = await fetch("/api/export/presets/delete", { method: "POST", body: JSON.stringify({ id: c.id }) }).then((x) => x.json()).catch(() => ({}));
15176
+ if (!r.ok) { alert("Could not delete the preset: " + (r.error || "unknown error")); return; }
15177
+ await fetchDeliveryInfo();
15178
+ els.exportProfileSel.value = "d:" + Delivery.DEFAULT_PRESET;
15179
+ dlvSpec = null;
15180
+ populateExportProfileSelect();
15181
+ els.exportProfileSel.value = "d:" + Delivery.DEFAULT_PRESET;
15182
+ syncExportChoiceUi("preset");
12876
15183
  }
12877
15184
  function syncExportProfileVisibility() {
12878
15185
  const show = els.engineFast.checked && !els.engineFast.disabled;
12879
15186
  els.exportProfileRow?.classList.toggle("hidden", !show);
15187
+ // the batch list and the queue are Fast export (ffmpeg) only
15188
+ for (const id of ["dlvBatch", "btnQueueExport", "btnBatchExport"]) $(id)?.classList.toggle("hidden", !show);
15189
+ if (!show) { const w = $("dlvWarn"); if (w) w.classList.add("hidden"); }
15190
+ else if (selectedExportChoice().kind === "delivery") refreshDeliveryNotes();
12880
15191
  }
12881
15192
 
12882
15193
  function syncExportWcOpts() {
@@ -12975,14 +15286,30 @@ async function openExportSetup() {
12975
15286
  warn.textContent = "";
12976
15287
  warn.classList.add("hidden");
12977
15288
  }
15289
+ // missing files export as their "Media offline" slate — say so before the render
15290
+ const offUsed = project.media.filter((m) => isMediaOffline(m.id) && MediaLib.placements(usageDoc(), m.id).length);
15291
+ if (offUsed.length && warn) {
15292
+ warn.textContent = (warn.textContent ? warn.textContent + " " : "") +
15293
+ `${offUsed.length === 1 ? `“${offUsed[0].name}” is` : offUsed.length + " files are"} offline and will export as “Media offline” — relink first (right-click in the bin → Relink…).`;
15294
+ warn.classList.remove("hidden");
15295
+ }
12978
15296
  fillExportRangeSelect();
12979
15297
  syncExportRangeUi();
12980
15298
  syncExportProfileVisibility();
12981
- fetchEncodeProfiles().then(() => {
15299
+ Promise.all([fetchEncodeProfiles(), fetchDeliveryInfo()]).then(() => {
12982
15300
  populateExportProfileSelect();
15301
+ syncExportProfileVisibility();
15302
+ renderBatchList();
15303
+ renderQueue();
12983
15304
  els.exportSetup.classList.remove("hidden");
15305
+ // aria-modal hides what is behind — focus has to come inside
15306
+ if (!els.exportSetup.contains(document.activeElement)) $("exportRangeSel")?.focus();
12984
15307
  });
12985
15308
  }
15309
+ function closeExportSetup() {
15310
+ els.exportSetup.classList.add("hidden");
15311
+ $("btnExport")?.focus();
15312
+ }
12986
15313
  function startChosenExport() {
12987
15314
  persistExportWcOpts();
12988
15315
  const useFast = els.engineFast.checked && !els.engineFast.disabled;
@@ -13000,8 +15327,15 @@ function startChosenExport() {
13000
15327
  alert("Export range is empty — IN/OUT is at or past the end of the timeline. Choose Entire timeline, or move the markers.");
13001
15328
  return;
13002
15329
  }
13003
- els.exportSetup.classList.add("hidden");
13004
- if (useFast) fastExport();
15330
+ closeExportSetup();
15331
+ if (useFast) {
15332
+ const c = selectedExportChoice();
15333
+ setSetting("exportKind", c.kind);
15334
+ if (c.kind === "delivery") {
15335
+ setSetting("delivery", dlvSpec);
15336
+ fastExport({ delivery: dlvSpec });
15337
+ } else fastExport({ profile: c.id });
15338
+ }
13005
15339
  else if (useSecond && state.connected && state.ffmpeg && state.webCodecs && !getExportFrame()) webCodecsExport();
13006
15340
  else startExport();
13007
15341
  }
@@ -13043,8 +15377,8 @@ function syncExportRangeUi() {
13043
15377
  /* ── Fast export ── */
13044
15378
  let renderCancelled = false;
13045
15379
  let exportAbort = null;
13046
- function beginExportWindow() {
13047
- exportWindow = exportRange();
15380
+ function beginExportWindow(fps) {
15381
+ exportWindow = exportRange(fps);
13048
15382
  return exportWindow;
13049
15383
  }
13050
15384
  function endExportWindow() {
@@ -13052,6 +15386,9 @@ function endExportWindow() {
13052
15386
  }
13053
15387
  let exportCropCanvas = null;
13054
15388
  let exportCropCtx = null;
15389
+ /* A delivery export sends the whole canvas; ffmpeg crops the export frame
15390
+ (and reframes) itself, so one stream can feed any output shape. */
15391
+ let exportFullCanvas = false;
13055
15392
  function canvasTaintError(e) {
13056
15393
  const tainted = e && (e.name === "SecurityError" || /taint/i.test(String(e.message || e)));
13057
15394
  return tainted
@@ -13060,7 +15397,7 @@ function canvasTaintError(e) {
13060
15397
  }
13061
15398
  function exportSourceCanvas() {
13062
15399
  const ef = getExportFrame();
13063
- if (!ef) return els.preview;
15400
+ if (!ef || exportFullCanvas) return els.preview;
13064
15401
  if (!exportCropCanvas) exportCropCanvas = document.createElement("canvas");
13065
15402
  if (exportCropCanvas.width !== ef.w) exportCropCanvas.width = ef.w;
13066
15403
  if (exportCropCanvas.height !== ef.h) exportCropCanvas.height = ef.h;
@@ -13087,6 +15424,22 @@ function snapshotExportFrame() {
13087
15424
  return { kind: "rgba", data: img.data, w: src.width, h: src.height };
13088
15425
  } catch (e) { throw canvasTaintError(e); }
13089
15426
  }
15427
+ let exportRgbaOff = null, exportRgbaCtx = null;
15428
+ /** Raw RGBA of the frame, for outputs that keep more than JPEG's 4:2:0 8-bit
15429
+ * (ProRes, DNxHR, FFV1, 10-bit, 4:2:2 / 4:4:4). */
15430
+ function snapshotExportRgba() {
15431
+ const src = exportSourceCanvas();
15432
+ try {
15433
+ if (!exportRgbaOff || exportRgbaOff.width !== src.width || exportRgbaOff.height !== src.height) {
15434
+ exportRgbaOff = typeof OffscreenCanvas === "function" ? new OffscreenCanvas(src.width, src.height)
15435
+ : Object.assign(document.createElement("canvas"), { width: src.width, height: src.height });
15436
+ exportRgbaCtx = exportRgbaOff.getContext("2d", { alpha: false, willReadFrequently: true });
15437
+ }
15438
+ exportRgbaCtx.drawImage(src, 0, 0);
15439
+ const img = exportRgbaCtx.getImageData(0, 0, src.width, src.height);
15440
+ return new Uint8Array(img.data.buffer, img.data.byteOffset, img.data.byteLength);
15441
+ } catch (e) { throw canvasTaintError(e); }
15442
+ }
13090
15443
  const JPEG_WORKER_SRC = `"use strict";
13091
15444
  self.onmessage = async (e) => {
13092
15445
  const { id, bmp, quality } = e.data;
@@ -13171,6 +15524,8 @@ function resetExportCanvases() {
13171
15524
  }
13172
15525
  adjScratch.width = adjScratch.width;
13173
15526
  scratch.width = scratch.width;
15527
+ if (pixGL.stage) pixGL.stage.width = pixGL.stage.width; // the GPU pixel pass keeps these between frames
15528
+ pixGL.outs.clear();
13174
15529
  exportSnapOff = null;
13175
15530
  exportSnapCtx = null;
13176
15531
  }
@@ -13546,6 +15901,141 @@ function prefetchExportVideos(t) {
13546
15901
  } catch { }
13547
15902
  }
13548
15903
  }
15904
+ /* ── Export decode: frames straight from WebCodecs ──
15905
+ Seeking <video> per frame is slow and not frame-exact, so export decodes
15906
+ MP4 / MOV clips itself (mp4-demux.js + VideoDecoder). Clips it can't take
15907
+ stay on the <video> path. */
15908
+ const Mp4 = self.FableCutMp4;
15909
+ class ExportFrameSource {
15910
+ static async open(src) {
15911
+ if (typeof VideoDecoder !== "function" || !Mp4) return null;
15912
+ try {
15913
+ const probe = await fetch(src, { headers: { Range: "bytes=0-0" } });
15914
+ if (probe.status !== 206) { try { await probe.body?.cancel(); } catch { } return null; }
15915
+ const size = Number((probe.headers.get("content-range") || "").split("/")[1]);
15916
+ await probe.arrayBuffer();
15917
+ if (!(size > 0)) return null;
15918
+ const read = async (a, b) => {
15919
+ const r = await fetch(src, { headers: { Range: `bytes=${a}-${b - 1}` } });
15920
+ if (r.status !== 206) throw new Error("range request refused");
15921
+ return new Uint8Array(await r.arrayBuffer());
15922
+ };
15923
+ const moov = await Mp4.findMoov(read, size);
15924
+ const mv = moov && Mp4.parseMovie(moov);
15925
+ if (!mv || !mv.samples.length) return null;
15926
+ const cfg = { codec: mv.codec, codedWidth: mv.width, codedHeight: mv.height };
15927
+ if (mv.description) cfg.description = mv.description;
15928
+ if (mv.displayWidth !== mv.width) Object.assign(cfg, { displayAspectWidth: mv.displayWidth, displayAspectHeight: mv.displayHeight });
15929
+ const ok = await VideoDecoder.isConfigSupported(cfg).catch(() => null);
15930
+ return ok && ok.supported ? new ExportFrameSource(read, size, mv, cfg) : null;
15931
+ } catch { return null; }
15932
+ }
15933
+ constructor(read, size, mv, cfg) {
15934
+ Object.assign(this, { read, size, cfg, samples: mv.samples, order: Mp4.presentationOrder(mv.samples) });
15935
+ this.dec = null; this.pos = 0; this.out = []; this.cur = null; this.win = null; this.err = null; this.wake = null;
15936
+ }
15937
+ restart(from) {
15938
+ this.dropQueue();
15939
+ if (this.dec && this.dec.state !== "closed") this.dec.close();
15940
+ this.err = null;
15941
+ this.dec = new VideoDecoder({
15942
+ output: (f) => { this.out.push(f); this.poke(); },
15943
+ error: (e) => { this.err = e; this.poke(); },
15944
+ });
15945
+ this.dec.ondequeue = () => this.poke();
15946
+ this.dec.configure(this.cfg);
15947
+ this.pos = from;
15948
+ }
15949
+ poke() { const w = this.wake; this.wake = null; if (w) w(); }
15950
+ dropQueue() { for (const f of this.out) f.close(); this.out = []; }
15951
+ /** The bytes of one sample, read through a 4 MB window (samples are mostly
15952
+ * contiguous, so one range request covers many frames). */
15953
+ async bytes(s) {
15954
+ const w = this.win;
15955
+ if (!w || s.offset < w.at || s.offset + s.size > w.at + w.data.length) {
15956
+ const end = Math.min(this.size, s.offset + Math.max(s.size, 4 << 20));
15957
+ this.win = { at: s.offset, data: await this.read(s.offset, end) };
15958
+ }
15959
+ const o = s.offset - this.win.at;
15960
+ return this.win.data.subarray(o, o + s.size);
15961
+ }
15962
+ /** The frame a player shows at media time t (a VideoFrame owned by this
15963
+ * source: valid until the next call or close()). */
15964
+ async frameAt(t) {
15965
+ const k = Mp4.frameAt(this.samples, this.order, t), ts = Math.round(this.samples[k].pts * 1e6);
15966
+ if (this.cur && this.cur.timestamp === ts) return this.cur;
15967
+ const sync = Mp4.syncBefore(this.samples, k);
15968
+ const passed = this.out.length > 0 && this.out[0].timestamp > ts;
15969
+ if (!this.dec || this.dec.state === "closed" || (this.cur && this.cur.timestamp > ts)
15970
+ || (k < this.pos && passed) || sync > this.pos) this.restart(sync);
15971
+ const n = this.samples.length;
15972
+ for (;;) {
15973
+ while (this.out.length && this.out[0].timestamp < ts) this.out.shift().close();
15974
+ if (this.out.length) { // the target, or (a frame the decoder dropped) the next one
15975
+ if (this.cur) this.cur.close();
15976
+ this.cur = this.out.shift();
15977
+ return this.cur;
15978
+ }
15979
+ if (this.err) throw this.err;
15980
+ let fed = false;
15981
+ while (this.pos < n && this.dec.decodeQueueSize < 8 && this.out.length < 3) {
15982
+ const s = this.samples[this.pos++];
15983
+ this.dec.decode(new EncodedVideoChunk({
15984
+ type: s.key ? "key" : "delta", timestamp: Math.round(s.pts * 1e6),
15985
+ duration: Math.round(s.dur * 1e6), data: await this.bytes(s),
15986
+ }));
15987
+ fed = true;
15988
+ }
15989
+ if (!fed && this.pos >= n && this.dec.decodeQueueSize === 0) {
15990
+ await this.dec.flush().catch((e) => { this.err = this.err || e; });
15991
+ this.pos = n + 1; // after a flush the decoder needs a sync sample again
15992
+ if (!this.out.length) { if (this.err) throw this.err; return this.cur; }
15993
+ continue;
15994
+ }
15995
+ await new Promise((res) => { this.wake = res; setTimeout(res, 50); });
15996
+ }
15997
+ }
15998
+ close() {
15999
+ this.dropQueue();
16000
+ if (this.cur) { this.cur.close(); this.cur = null; }
16001
+ if (this.dec && this.dec.state !== "closed") this.dec.close();
16002
+ this.dec = null; this.win = null;
16003
+ }
16004
+ }
16005
+ /** Export-time decode state: clip id → source (or null: use the element). */
16006
+ function exportDecodeBegin() {
16007
+ runtime.exportDecode = runtime.noExportDecode ? null : { sources: new Map(), opening: new Map() };
16008
+ runtime.exportFrames = new Map();
16009
+ }
16010
+ function exportDecodeEnd() {
16011
+ const d = runtime.exportDecode;
16012
+ if (d) for (const s of d.sources.values()) s?.close();
16013
+ runtime.exportDecode = null;
16014
+ runtime.exportFrames = null;
16015
+ }
16016
+ /** Decode the frame of video clip c for timeline time t; false when the clip
16017
+ * stays on the <video> path. Frames go to runtime.exportFrames for drawing. */
16018
+ async function exportDecodeFrame(c, t) {
16019
+ const d = runtime.exportDecode;
16020
+ if (!d || c.kind !== "video" || evalProps(c, t).bgRemove) return false;
16021
+ let src = d.sources.get(c.id);
16022
+ if (src === undefined) {
16023
+ const m = getMedia(c.mediaId);
16024
+ if (!m || !m.src) { d.sources.set(c.id, null); return false; }
16025
+ if (!d.opening.has(c.id)) d.opening.set(c.id, ExportFrameSource.open(m.src));
16026
+ src = await d.opening.get(c.id);
16027
+ d.sources.set(c.id, src);
16028
+ }
16029
+ if (!src) return false;
16030
+ try {
16031
+ runtime.exportFrames.set(c.id, await src.frameAt(mediaTimeAt(c, t)));
16032
+ return true;
16033
+ } catch (e) { // a decode error: this clip falls back to its element for the rest of the export
16034
+ console.warn("[FableCut] export decode failed, using the video element:", e && e.message);
16035
+ src.close(); d.sources.set(c.id, null); runtime.exportFrames.delete(c.id);
16036
+ return false;
16037
+ }
16038
+ }
13549
16039
  async function seekVideosTo(t, { queueBusy } = {}) {
13550
16040
  const fps = projectFps();
13551
16041
  const frameMs = 1000 / fps;
@@ -13557,9 +16047,26 @@ async function seekVideosTo(t, { queueBusy } = {}) {
13557
16047
  const keepPlaying = fast && !behind && !queueBusy;
13558
16048
  const waits = [];
13559
16049
  const restoreGain = [];
16050
+ const decoded = new Set();
16051
+ const dec = runtime.exportDecode;
16052
+ if (dec) {
16053
+ const jobs = [];
16054
+ for (const c of mediaClips()) {
16055
+ if (c.kind !== "video" || !clipRenders(c)) continue;
16056
+ if (!activeAt(c, t)) { // export runs forward: past its end, free the clip's decoder
16057
+ const s = dec.sources.get(c.id);
16058
+ if (s && t > c.start + c.duration) { s.close(); dec.sources.delete(c.id); dec.opening.delete(c.id); }
16059
+ runtime.exportFrames.delete(c.id);
16060
+ continue;
16061
+ }
16062
+ jobs.push(exportDecodeFrame(c, t).then((ok) => { if (ok) decoded.add(c.id); }));
16063
+ }
16064
+ await Promise.all(jobs);
16065
+ }
13560
16066
  for (const c of mediaClips()) {
13561
16067
  if (c.kind !== "video") continue;
13562
16068
  if (!clipRenders(c)) continue;
16069
+ if (decoded.has(c.id)) continue;
13563
16070
  const el = getClipEl(c); if (!el) continue;
13564
16071
  if (!activeAt(c, t)) {
13565
16072
  if (!el.paused) el.pause();
@@ -13731,20 +16238,27 @@ async function prepareFrameAssets(t) {
13731
16238
  }
13732
16239
  /** opts.job: an agent's export job id — progress and the result go back to
13733
16240
  * the server instead of an alert / download (nobody may be watching).
13734
- * opts.profile: encoding profile id for this run. */
16241
+ * opts.profile: encoding profile id for this run.
16242
+ * opts.delivery: a delivery spec (delivery.js) instead of a profile.
16243
+ * opts.deliveries: [{delivery, name?}] — several files from one render (same fps).
16244
+ * opts.silent: no overlay, alert or download (the export queue shows it);
16245
+ * opts.onProgress(0…1). Resolves {outputs:[{file, ok, src?, error?}]} or {error, cancelled}. */
13735
16246
  async function fastExport(opts = {}) {
13736
- if (state.exporting) return;
16247
+ if (state.exporting) return { error: "an export is already running" };
13737
16248
  const job = opts.job || null;
13738
16249
  pause();
13739
16250
  state.exporting = true; state.rendering = true; renderCancelled = false;
13740
16251
  exportAbort = new AbortController();
13741
16252
  const signal = exportAbort.signal;
13742
- els.exportOverlay.classList.remove("hidden");
16253
+ if (!opts.silent) els.exportOverlay.classList.remove("hidden");
13743
16254
  els.exportProgress.style.width = "0%";
13744
16255
  els.exportNote.textContent = "Rendering frames → ffmpeg. You can switch tabs; export continues.";
13745
16256
  restoreExportVideoState();
13746
- const { start: t0, end: t1, frames } = beginExportWindow();
13747
- const fps = projectFps();
16257
+ const deliveries = opts.deliveries || (opts.delivery ? [{ delivery: opts.delivery }] : null);
16258
+ const delivery = deliveries ? deliveries[0].delivery : null;
16259
+ const fps = (delivery && delivery.fps) || projectFps();
16260
+ let result = null;
16261
+ const { start: t0, end: t1, frames } = beginExportWindow(fps);
13748
16262
  let sessId = null;
13749
16263
  let uploadError = null;
13750
16264
  const setError = (err) => { if (!uploadError) uploadError = err; };
@@ -13752,12 +16266,15 @@ async function fastExport(opts = {}) {
13752
16266
  els.exportTitle.textContent = "Mixing audio…";
13753
16267
  const wav = await renderAudioMix(t0, t1);
13754
16268
  if (renderCancelled) throw new Error("cancelled");
13755
- const profileId = job ? (opts.profile || effectiveEncodeProfileId())
13756
- : els.exportProfileSel?.value || effectiveEncodeProfileId();
13757
- const jpegQ = exportProfileMeta(profileId).jpegQuality ?? 0.95;
16269
+ const profileId = opts.profile || effectiveEncodeProfileId();
16270
+ const cv = deliveryCanvas();
13758
16271
  const begin = await fetch("/api/export/begin", {
13759
16272
  method: "POST",
13760
- body: JSON.stringify({
16273
+ body: JSON.stringify(delivery ? {
16274
+ fps, duration: frames / fps,
16275
+ deliveries: deliveries.map((d) => ({ delivery: d.delivery, name: d.name || deliveryFileName(d.delivery, fps) })),
16276
+ canvasW: cv.w, canvasH: cv.h, region: cv.region, hasAudio: !!wav,
16277
+ } : {
13761
16278
  fps,
13762
16279
  name: project.name.replace(/[^\w\- ]+/g, "") || "export",
13763
16280
  profile: profileId,
@@ -13767,6 +16284,9 @@ async function fastExport(opts = {}) {
13767
16284
  }).then((r) => r.json());
13768
16285
  if (!begin.id) throw new Error(begin.error || "export begin failed");
13769
16286
  sessId = begin.id;
16287
+ const jpegQ = delivery ? begin.jpegQuality ?? 0.95 : exportProfileMeta(profileId).jpegQuality ?? 0.95;
16288
+ const rgba = begin.input === "rgba";
16289
+ exportFullCanvas = !!delivery;
13770
16290
  if (wav) {
13771
16291
  const r = await fetch("/api/export/audio?id=" + sessId, { method: "POST", body: wav, signal });
13772
16292
  if (!r.ok) throw new Error("audio upload failed");
@@ -13774,6 +16294,8 @@ async function fastExport(opts = {}) {
13774
16294
  await loadProjectFonts();
13775
16295
  resetExportCanvases();
13776
16296
  await armExportCors();
16297
+ await useOriginalPlayers(); // proxies are for editing — export reads the originals
16298
+ exportDecodeBegin();
13777
16299
  // JPEG off the compositor thread: snapshot is sync, encode/upload run ahead
13778
16300
  // under backpressure. Awaiting toBlob every frame was slower than ffmpeg.
13779
16301
  const up = createExportUploader(sessId, {
@@ -13807,10 +16329,11 @@ async function fastExport(opts = {}) {
13807
16329
  await seekVideosTo(t, { queueBusy });
13808
16330
  await prepareFrameAssets(t);
13809
16331
  drawFrame(t);
13810
- const snap = snapshotExportFrame();
16332
+ const snap = rgba ? { kind: "raw", px: snapshotExportRgba() } : snapshotExportFrame();
13811
16333
  pixelsInflight++;
13812
16334
  let jpegP;
13813
- if (snap.kind === "bmp") {
16335
+ if (snap.kind === "raw") jpegP = Promise.resolve(snap.px);
16336
+ else if (snap.kind === "bmp") {
13814
16337
  jpegP = workers ? workers.encode(snap.bmp, jpegQ) : jpegFromBitmap(snap.bmp, jpegQ);
13815
16338
  } else {
13816
16339
  const c = document.createElement("canvas");
@@ -13835,6 +16358,7 @@ async function fastExport(opts = {}) {
13835
16358
  const pct = ((f + 1) / frames) * 100;
13836
16359
  els.exportProgress.style.width = pct.toFixed(1) + "%";
13837
16360
  els.exportTitle.textContent = `Rendering… ${pct.toFixed(0)}%`;
16361
+ if (opts.onProgress) opts.onProgress(0.97 * (f + 1) / frames);
13838
16362
  if (job) reportExportJob(job, { progress: 0.97 * (f + 1) / frames });
13839
16363
  }
13840
16364
  await pixelChain;
@@ -13847,7 +16371,23 @@ async function fastExport(opts = {}) {
13847
16371
  }
13848
16372
  const end = await fetch("/api/export/end?id=" + sessId, { method: "POST", signal }).then((r) => r.json());
13849
16373
  if (!end.src) throw new Error(end.error || "encode failed");
13850
- if (job) await reportExportJob(job, { status: "done", src: end.src }, true);
16374
+ const outs = end.outputs || [{ file: decodeURIComponent(end.src.split("/").pop()), ok: true, src: end.src }];
16375
+ // what each output was asked to be, beside what came out
16376
+ result = { outputs: outs.map((o, i) => ({ ...o, ...(begin.outputs && begin.outputs[i] ? { summary: begin.outputs[i].summary, notes: begin.outputs[i].notes } : {}) })) };
16377
+ if (job) await reportExportJob(job, { status: "done", src: end.src, ...(delivery ? { result: { summary: begin.summary, notes: begin.notes || [], outputs: result.outputs } } : {}) }, true);
16378
+ else if (opts.silent) { /* the queue lists the files */ }
16379
+ else if (delivery && result.outputs[0]) {
16380
+ const o = result.outputs[0];
16381
+ exportQueue.push({ id: "q" + Math.random().toString(36).slice(2, 8), label: queueLabel(delivery), spec: delivery,
16382
+ name: String(o.file || "").replace(/\.[^.]+$/, ""), range: exportRangeMode(), status: "done", progress: 1,
16383
+ src: o.src, file: o.file, report: o.report || null });
16384
+ renderQueue();
16385
+ toast(o.report && !o.report.ok ? `Exported ${o.file} — check: ${o.report.checks.filter((c) => !c.ok).map((c) => c.text).join("; ")} (Export → Queue)` : `Exported ${o.file}${o.report ? " — checks passed" : ""}`);
16386
+ const a = document.createElement("a");
16387
+ a.href = end.src;
16388
+ a.download = decodeURIComponent(end.src.split("/").pop());
16389
+ a.click();
16390
+ }
13851
16391
  else {
13852
16392
  const a = document.createElement("a");
13853
16393
  a.href = end.src;
@@ -13857,17 +16397,199 @@ async function fastExport(opts = {}) {
13857
16397
  } catch (e) {
13858
16398
  if (sessId) fetch("/api/export/end?id=" + sessId + "&discard=1", { method: "POST" }).catch(() => { });
13859
16399
  const msg = e?.name === "AbortError" ? "cancelled" : String(e.message || e);
16400
+ result = { error: msg, cancelled: msg === "cancelled" };
13860
16401
  if (job) await reportExportJob(job, { status: "failed", error: msg }, true);
13861
- else if (msg !== "cancelled") alert("Export failed: " + msg);
16402
+ else if (msg !== "cancelled" && !opts.silent) alert("Export failed: " + msg);
13862
16403
  } finally {
13863
16404
  exportAbort = null;
16405
+ exportFullCanvas = false;
16406
+ exportDecodeEnd();
13864
16407
  restoreExportVideoState();
13865
16408
  endExportWindow();
13866
16409
  state.exporting = false; state.rendering = false;
16410
+ releaseOriginalPlayers();
13867
16411
  els.exportOverlay.classList.add("hidden");
13868
16412
  els.exportNote.textContent = "Rendering your sequence in real time. Keep this tab focused.";
13869
16413
  if (runtime.pendingSync) syncFromServer();
13870
16414
  }
16415
+ return result;
16416
+ }
16417
+
16418
+ /* ── Export queue ──
16419
+ Renders waiting outputs back to back. Outputs that share a frame rate and a
16420
+ range go out in ONE render: the frames are drawn once and every output's
16421
+ ffmpeg encodes them (up to 8 at a time). Lives in this tab only. */
16422
+ const exportQueue = [];
16423
+ let queueRunning = false, queueStop = false;
16424
+ function queueLabel(spec) {
16425
+ const p = Delivery.PRESETS[spec.preset] || deliveryInfo.saved[spec.preset];
16426
+ return p ? p.label : "Custom";
16427
+ }
16428
+ function queueAdd(spec, name) {
16429
+ const fps = spec.fps || projectFps();
16430
+ exportQueue.push({
16431
+ id: "q" + Math.random().toString(36).slice(2, 8), label: queueLabel(spec), spec,
16432
+ name: name || deliveryFileName(spec, fps), range: exportRangeMode(), status: "pending", progress: 0,
16433
+ });
16434
+ renderQueue();
16435
+ }
16436
+ function openQueue() {
16437
+ renderQueue();
16438
+ $("exportQueue").classList.remove("hidden");
16439
+ ($("btnQueueStart").disabled ? $("btnQueueClose") : $("btnQueueStart")).focus();
16440
+ }
16441
+ function closeQueue() {
16442
+ if (queueRunning) return;
16443
+ $("exportQueue").classList.add("hidden");
16444
+ $("btnExport")?.focus();
16445
+ }
16446
+ function renderQueue() {
16447
+ const list = $("exportQueueList");
16448
+ if (!list) return;
16449
+ const pending = exportQueue.filter((q) => q.status === "pending").length;
16450
+ const done = exportQueue.filter((q) => q.status === "done").length;
16451
+ $("exportQueueNote").textContent = queueRunning
16452
+ ? "Exporting — outputs with the same frame rate and range share one render."
16453
+ : exportQueue.length ? `${pending} waiting · ${done} done` : "Nothing queued — pick settings in Export and press Add to queue.";
16454
+ const btnOpen = $("btnOpenQueue");
16455
+ if (btnOpen) btnOpen.textContent = exportQueue.length ? `Queue · ${pending || exportQueue.length}` : "Queue";
16456
+ const start = $("btnQueueStart");
16457
+ start.textContent = queueRunning ? "Stop" : "Start";
16458
+ start.disabled = !queueRunning && !pending;
16459
+ $("btnQueueClose").disabled = queueRunning;
16460
+ $("btnQueueClear").disabled = queueRunning || !exportQueue.some((q) => q.status !== "pending" && q.status !== "running");
16461
+ if (!exportQueue.length) { list.innerHTML = `<li class="xq-empty">The queue is empty</li>`; return; }
16462
+ list.innerHTML = exportQueue.map((q) => {
16463
+ const ext = Delivery.CONTAINERS[q.spec.container].ext;
16464
+ const fr = deliveryFrame(q.spec), fps = q.spec.fps || projectFps();
16465
+ const status = q.status === "running" ? `Rendering… ${Math.round(q.progress * 100)}%`
16466
+ : q.status === "done" ? `Done → exports/${q.file || q.name + ext}`
16467
+ : q.status === "failed" ? `Failed: ${q.error || "unknown error"}`
16468
+ : q.status === "cancelled" ? "Stopped" : "Waiting";
16469
+ const actions = [
16470
+ q.status === "done" && q.src ? `<a class="btn tiny" href="${escapeHtml(q.src)}" target="_blank" rel="noopener" download>Open</a>` : "",
16471
+ q.status === "failed" || q.status === "cancelled" ? `<button type="button" class="btn tiny" data-q-retry="${q.id}">Retry</button>` : "",
16472
+ q.status !== "running" ? `<button type="button" class="btn tiny" data-q-remove="${q.id}" title="Remove from the queue">✕</button>` : "",
16473
+ ].join("");
16474
+ return `<li class="${q.status}" data-q="${q.id}"><div class="xq-main"><b>${escapeHtml(q.label)} — ${escapeHtml(q.name + ext)}</b>` +
16475
+ `<span class="xq-sub">${escapeHtml(Delivery.describe(q.spec, { width: fr.outW, height: fr.outH, fps }))} · ${q.range === "in-out" ? "IN–OUT" : "entire timeline"}</span>` +
16476
+ (q.status === "running" ? `<div class="progress"><div class="progress-fill" style="width:${(q.progress * 100).toFixed(1)}%"></div></div>` : "") +
16477
+ `<span class="xq-status">${escapeHtml(status)}</span>` +
16478
+ (q.report ? `<span class="xq-report${q.report.ok ? "" : " warn"}">${q.report.ok ? "✓ " : ""}${escapeHtml(q.report.line)}</span>` : "") +
16479
+ `</div><div class="xq-actions">${actions}</div></li>`;
16480
+ }).join("");
16481
+ }
16482
+ function renderQueueProgress() {
16483
+ for (const q of exportQueue) {
16484
+ if (q.status !== "running") continue;
16485
+ const li = document.querySelector(`#exportQueueList li[data-q="${q.id}"]`);
16486
+ if (!li) continue;
16487
+ const fill = li.querySelector(".progress-fill"), st = li.querySelector(".xq-status");
16488
+ if (fill) fill.style.width = (q.progress * 100).toFixed(1) + "%";
16489
+ if (st) st.textContent = `Rendering… ${Math.round(q.progress * 100)}%`;
16490
+ }
16491
+ }
16492
+ async function runQueue() {
16493
+ if (queueRunning || state.exporting) return;
16494
+ if (!(state.connected && state.ffmpeg)) { alert("The export queue needs the server and ffmpeg (Fast export)."); return; }
16495
+ queueRunning = true; queueStop = false;
16496
+ renderQueue();
16497
+ try {
16498
+ while (!queueStop) {
16499
+ const first = exportQueue.find((q) => q.status === "pending");
16500
+ if (!first) break;
16501
+ const fps = first.spec.fps || projectFps();
16502
+ const group = exportQueue.filter((q) => q.status === "pending" && (q.spec.fps || projectFps()) === fps && q.range === first.range).slice(0, 8);
16503
+ for (const q of group) { q.status = "running"; q.progress = 0; q.error = null; }
16504
+ renderQueue();
16505
+ exportRangeForced = first.range === "in-out" && hasWorkArea() ? "in-out" : "entire";
16506
+ let res;
16507
+ try {
16508
+ res = await fastExport({
16509
+ deliveries: group.map((q) => ({ delivery: q.spec, name: q.name })), silent: true,
16510
+ onProgress: (f) => { for (const q of group) q.progress = f; renderQueueProgress(); },
16511
+ });
16512
+ } finally { exportRangeForced = null; }
16513
+ group.forEach((q, i) => {
16514
+ const o = res && res.outputs && res.outputs[i];
16515
+ if (o && o.ok) Object.assign(q, { status: "done", src: o.src, file: o.file, progress: 1, report: o.report || null });
16516
+ else if (res && res.cancelled) q.status = "cancelled";
16517
+ else Object.assign(q, { status: "failed", error: (o && o.error) || (res && res.error) || "export failed" });
16518
+ });
16519
+ renderQueue();
16520
+ }
16521
+ } finally {
16522
+ queueRunning = false;
16523
+ renderQueue();
16524
+ }
16525
+ const done = exportQueue.filter((q) => q.status === "done").length, failed = exportQueue.filter((q) => q.status === "failed").length;
16526
+ const warned = exportQueue.filter((q) => q.status === "done" && q.report && !q.report.ok).length;
16527
+ if (done || failed) toast(`Export queue: ${done} done${failed ? `, ${failed} failed` : ""}${warned ? ` — ${warned} with warnings` : ""}`);
16528
+ }
16529
+ function stopQueue() {
16530
+ queueStop = true;
16531
+ renderCancelled = true;
16532
+ try { exportAbort?.abort(); } catch { }
16533
+ }
16534
+
16535
+ /* ── Batch outputs (project.outputs) ──
16536
+ The project's list of files to make from one timeline. Each entry is a
16537
+ delivery spec plus {id, on}; "Export checked" queues the checked ones. */
16538
+ function projectOutputs() { return Array.isArray(project.outputs) ? project.outputs : []; }
16539
+ function setProjectOutputs(list) {
16540
+ project.outputs = list.length ? list : null;
16541
+ scheduleSave();
16542
+ renderBatchList();
16543
+ }
16544
+ function addBatchOutput(spec) {
16545
+ const list = projectOutputs().slice();
16546
+ if (list.length >= 16) { toast("At most 16 batch outputs"); return; }
16547
+ list.push({ id: "o_" + Math.random().toString(36).slice(2, 8), on: true, ...spec });
16548
+ setProjectOutputs(list);
16549
+ }
16550
+ const TYPICAL_SET = [
16551
+ { preset: "master", filename: "{project}_master_{res}" },
16552
+ { preset: "youtube", filename: "{project}_youtube_{res}" },
16553
+ { preset: "instagram-reels", filename: "{project}_reel_{res}" },
16554
+ { preset: "custom", width: 1080, height: 1080, filename: "{project}_square_{res}" },
16555
+ { preset: "web", filename: "{project}_preview_{res}" },
16556
+ ];
16557
+ function renderBatchList() {
16558
+ const ul = $("dlvBatchList");
16559
+ if (!ul) return;
16560
+ const list = projectOutputs();
16561
+ const on = list.filter((o) => o.on !== false).length;
16562
+ $("dlvBatchCount").textContent = list.length ? `· ${on} of ${list.length} checked` : "";
16563
+ const be = $("btnBatchExport");
16564
+ if (be) { be.disabled = !on; be.textContent = on ? `Export checked (${on})` : "Export checked"; }
16565
+ if (!list.length) { ul.innerHTML = `<li class="bo-empty">No batch outputs yet — add the settings above, or a typical set</li>`; return; }
16566
+ ul.innerHTML = list.map((o) => {
16567
+ const sp = normalizeDelivery(o).spec, fr = deliveryFrame(sp), fps = sp.fps || projectFps();
16568
+ return `<li class="${o.on === false ? "off" : ""}" data-o="${escapeHtml(o.id)}">` +
16569
+ `<input type="checkbox" data-o-on="${escapeHtml(o.id)}"${o.on === false ? "" : " checked"} aria-label="Include ${escapeHtml(queueLabel(sp))}">` +
16570
+ `<div class="bo-main"><b>${escapeHtml(deliveryFileName(sp, fps) + Delivery.CONTAINERS[sp.container].ext)}</b>` +
16571
+ `<span>${escapeHtml(queueLabel(sp))} · ${escapeHtml(Delivery.describe(sp, { width: fr.outW, height: fr.outH, fps }))}</span></div>` +
16572
+ `<button type="button" class="btn tiny" data-o-load="${escapeHtml(o.id)}" title="Show these settings above">Load</button>` +
16573
+ `<button type="button" class="btn tiny" data-o-remove="${escapeHtml(o.id)}" title="Remove">✕</button></li>`;
16574
+ }).join("");
16575
+ }
16576
+ function onBatchListClick(e) {
16577
+ const t = e.target;
16578
+ const id = t.dataset.oOn || t.dataset.oLoad || t.dataset.oRemove;
16579
+ if (!id) return;
16580
+ const list = projectOutputs().slice();
16581
+ const i = list.findIndex((o) => o.id === id);
16582
+ if (i < 0) return;
16583
+ if (t.dataset.oOn) { list[i] = { ...list[i], on: t.checked }; setProjectOutputs(list); }
16584
+ else if (t.dataset.oRemove) { list.splice(i, 1); setProjectOutputs(list); }
16585
+ else if (t.dataset.oLoad) {
16586
+ const { id: _id, on: _on, ...spec } = list[i];
16587
+ const n = normalizeDelivery(spec);
16588
+ els.exportProfileSel.value = "d:" + n.spec.preset;
16589
+ if (els.exportProfileSel.value !== "d:" + n.spec.preset) els.exportProfileSel.value = "d:custom";
16590
+ dlvSpec = n.spec; dlvNotes = n.notes;
16591
+ syncExportChoiceUi("edited");
16592
+ }
13871
16593
  }
13872
16594
 
13873
16595
  /* ── Agent-requested export (fablecut_export · POST /api/export/request) ──
@@ -13914,7 +16636,31 @@ async function runExportJob(ticket) {
13914
16636
  try {
13915
16637
  if (exportRange().frames < 1) return fail("the export range is empty — IN/OUT is at or past the end of the timeline");
13916
16638
  reportExportJob(ticket.id, { progress: 0 }, true);
13917
- await fastExport({ job: ticket.id, profile: ticket.profile });
16639
+ // an explicit profile wins; then the job's delivery spec, the project's, else the raw default
16640
+ const want = ticket.profile || ticket.deliveries ? null : ticket.delivery || project.delivery || null;
16641
+ if (want || ticket.deliveries) await fetchDeliveryInfo();
16642
+ if (ticket.deliveries) {
16643
+ // one render per frame rate; the job reports every file at the end
16644
+ const specs = ticket.deliveries.map((d) => normalizeDelivery(d).spec);
16645
+ const groups = new Map();
16646
+ for (const sp of specs) { const k = sp.fps || projectFps(); if (!groups.has(k)) groups.set(k, []); groups.get(k).push(sp); }
16647
+ if (groups.size === 1) await fastExport({ job: ticket.id, deliveries: specs.map((delivery) => ({ delivery })) });
16648
+ else {
16649
+ const all = [];
16650
+ let i = 0;
16651
+ for (const group of groups.values()) {
16652
+ const res = await fastExport({ deliveries: group.map((delivery) => ({ delivery })), silent: true,
16653
+ onProgress: (f) => reportExportJob(ticket.id, { progress: (i + f) / groups.size }) });
16654
+ i++;
16655
+ if (res && res.cancelled) return reportExportJob(ticket.id, { status: "failed", error: "cancelled" }, true);
16656
+ if (res && res.outputs) all.push(...res.outputs);
16657
+ else all.push(...group.map((sp) => ({ file: deliveryFileName(sp), ok: false, error: (res && res.error) || "export failed" })));
16658
+ }
16659
+ const ok = all.find((o) => o.ok);
16660
+ if (!ok) return fail(all.map((o) => o.error).join(" · "));
16661
+ await reportExportJob(ticket.id, { status: "done", src: ok.src, result: { outputs: all } }, true);
16662
+ }
16663
+ } else await fastExport(want ? { job: ticket.id, delivery: normalizeDelivery(want).spec } : { job: ticket.id, profile: ticket.profile });
13918
16664
  } finally {
13919
16665
  exportRangeForced = null;
13920
16666
  }
@@ -14027,6 +16773,10 @@ async function runTrackJob(ticket, fail) {
14027
16773
  tracks), then measure it with color.js scopeStats. The user's playhead
14028
16774
  stays where it is. */
14029
16775
  async function renderStillAt(t) {
16776
+ if (!runtime.forceOriginals) { // measured and shown to agents as export renders it: the originals
16777
+ await useOriginalPlayers();
16778
+ try { return await renderStillAt(t); } finally { releaseOriginalPlayers(); }
16779
+ }
14030
16780
  const waits = [];
14031
16781
  for (const c of mediaClips()) {
14032
16782
  if (!clipRenders(c) || !activeAt(c, t)) continue;
@@ -14047,6 +16797,7 @@ async function renderStillAt(t) {
14047
16797
  }
14048
16798
  async function runScopesJob(ticket, fail) {
14049
16799
  const wasPlaying = state.playing;
16800
+ let heldOriginals = false;
14050
16801
  try {
14051
16802
  if (wasPlaying) pause();
14052
16803
  await loadProjectFonts();
@@ -14060,6 +16811,8 @@ async function runScopesJob(ticket, fail) {
14060
16811
  const kClip = ticket.mask && getClip(ticket.mask.clip), view = runtime.maskView;
14061
16812
  runtime.maskCapture = kClip ? { id: kClip.id } : null;
14062
16813
  runtime.maskView = null;
16814
+ // the matte below re-grades the captured original — keep the originals loaded until then
16815
+ if (!runtime.forceOriginals) { await useOriginalPlayers(); heldOriginals = true; }
14063
16816
  try { await renderStillAt(t); } finally { runtime.matte = shown; runtime.maskView = view; }
14064
16817
  const kcap = runtime.maskCapture;
14065
16818
  runtime.maskCapture = null;
@@ -14114,6 +16867,14 @@ async function runScopesJob(ticket, fail) {
14114
16867
  else if (!kcap || kcap.coverage == null) mask.error = "the clip is not on screen at that time (or its masks are all off)";
14115
16868
  else Object.assign(mask, { masks: Mask.describe(clipMasks(kClip)), coverage: kcap.coverage, frameCoverage: kcap.frameCoverage });
14116
16869
  }
16870
+ /* fablecut_frame {time} with no src: hand back the same graded still as a
16871
+ JPEG so the agent can see what it is measuring. toDataURL can throw on a
16872
+ canvas tainted by a cross-origin src — the numbers still stand. */
16873
+ let image = null;
16874
+ if (ticket.image) {
16875
+ try { image = cv.toDataURL("image/jpeg", 0.85); }
16876
+ catch (err) { image = null; }
16877
+ }
14117
16878
  const onScreen = visibleClipsAt(t), mattes = matteTracksAt(onScreen);
14118
16879
  const clips = onScreen.map((c) => {
14119
16880
  const tm = clipMatte(c);
@@ -14126,13 +16887,14 @@ async function runScopesJob(ticket, fail) {
14126
16887
  ...(c.props.blend && c.props.blend !== "normal" ? { blend: c.props.blend } : {}),
14127
16888
  };
14128
16889
  });
14129
- await reportExportJob(ticket.id, { status: "done", result: { time: +t.toFixed(3), frame: { w: Math.round(r.w), h: Math.round(r.h) }, stats, clips, matte, mask } }, true);
16890
+ await reportExportJob(ticket.id, { status: "done", result: { time: +t.toFixed(3), frame: { w: Math.round(r.w), h: Math.round(r.h) }, stats, clips, matte, mask, image } }, true);
14130
16891
  } catch (err) {
14131
16892
  fail("could not measure the frame: " + (err && err.message || err));
14132
16893
  } finally {
14133
16894
  runtime.gradeCapture = null;
14134
16895
  runtime.maskCapture = null;
14135
16896
  state.rendering = false;
16897
+ if (heldOriginals) releaseOriginalPlayers();
14136
16898
  seekMediaWhilePaused(); // the videos sat on the job's frame — back to the playhead
14137
16899
  if (wasPlaying) play();
14138
16900
  }
@@ -14248,6 +17010,8 @@ async function webCodecsExport() {
14248
17010
  await loadProjectFonts();
14249
17011
  resetExportCanvases();
14250
17012
  await armExportCors();
17013
+ await useOriginalPlayers(); // proxies are for editing — export reads the originals
17014
+ exportDecodeBegin();
14251
17015
 
14252
17016
  for (let f = 0; f < frames; f++) {
14253
17017
  if (renderCancelled || signal.aborted) throw new Error("cancelled");
@@ -14303,9 +17067,11 @@ async function webCodecsExport() {
14303
17067
  if (msg !== "cancelled") alert("Export failed: " + msg);
14304
17068
  } finally {
14305
17069
  exportAbort = null;
17070
+ exportDecodeEnd();
14306
17071
  restoreExportVideoState();
14307
17072
  endExportWindow();
14308
17073
  state.exporting = false; state.rendering = false;
17074
+ releaseOriginalPlayers();
14309
17075
  els.exportOverlay.classList.add("hidden");
14310
17076
  els.exportNote.textContent = "Rendering your sequence in real time. Keep this tab focused.";
14311
17077
  if (runtime.pendingSync) syncFromServer();
@@ -14331,6 +17097,7 @@ async function startExport() {
14331
17097
  pause();
14332
17098
  const { start } = beginExportWindow();
14333
17099
  state.time = start;
17100
+ await useOriginalPlayers(); // proxies are for editing — export reads the originals
14334
17101
  seekMediaWhilePaused();
14335
17102
  await new Promise((r) => setTimeout(r, 350)); // let first frames decode
14336
17103
  await loadProjectFonts();
@@ -14362,6 +17129,7 @@ async function startExport() {
14362
17129
  function finishExport(keep) {
14363
17130
  if (!state.exporting) return;
14364
17131
  state.exporting = false;
17132
+ releaseOriginalPlayers();
14365
17133
  endExportWindow();
14366
17134
  if (runtime.pendingSync) syncFromServer();
14367
17135
  recDiscard = !keep;
@@ -14411,14 +17179,80 @@ els.exportSetup?.addEventListener("change", (e) => {
14411
17179
  }
14412
17180
  if (e.target.id === "exportRangeSel") syncExportRangeUi();
14413
17181
  });
14414
- els.exportProfileSel?.addEventListener("change", (e) => {
14415
- const id = e.target.value;
14416
- if (!project.encodeProfile) {
14417
- setSetting("encodeProfile", id === encodeProfiles.default ? null : id);
17182
+ els.exportProfileSel?.addEventListener("change", () => {
17183
+ const c = selectedExportChoice();
17184
+ if (c.kind === "profile" && !project.encodeProfile)
17185
+ setSetting("encodeProfile", c.id === encodeProfiles.default ? null : c.id);
17186
+ syncExportChoiceUi("preset");
17187
+ });
17188
+ $("dlvBody")?.addEventListener("change", onDeliveryControl);
17189
+ $("dlvBody")?.addEventListener("input", onDeliveryControl);
17190
+ $("dlvSaveBtn")?.addEventListener("click", () => {
17191
+ $("dlvSaveRow").classList.remove("hidden");
17192
+ const p = Delivery.PRESETS[dlvSpec?.preset] || deliveryInfo.saved[dlvSpec?.preset];
17193
+ $("dlvSaveName").value = p && !Delivery.PRESETS[dlvSpec.preset] ? p.label : "";
17194
+ $("dlvSaveName").focus();
17195
+ });
17196
+ $("dlvSaveOk")?.addEventListener("click", saveDeliveryPreset);
17197
+ $("dlvSaveName")?.addEventListener("keydown", (e) => {
17198
+ if (e.key === "Enter") { e.preventDefault(); saveDeliveryPreset(); }
17199
+ if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); $("dlvSaveRow").classList.add("hidden"); }
17200
+ });
17201
+ $("dlvSaveCancel")?.addEventListener("click", () => $("dlvSaveRow").classList.add("hidden"));
17202
+ $("dlvDeleteBtn")?.addEventListener("click", deleteDeliveryPreset);
17203
+ $("dlvBatchList")?.addEventListener("click", onBatchListClick);
17204
+ $("dlvBatchList")?.addEventListener("change", onBatchListClick);
17205
+ $("dlvBatchAdd")?.addEventListener("click", () => { if (dlvSpec) addBatchOutput(dlvSpec); });
17206
+ $("dlvBatchTypical")?.addEventListener("click", () => {
17207
+ const have = new Set(projectOutputs().map((o) => o.filename));
17208
+ for (const t of TYPICAL_SET) if (!have.has(t.filename)) addBatchOutput(normalizeDelivery(t).spec);
17209
+ });
17210
+ function exportPreflight() {
17211
+ if (exportRange().frames < 1) {
17212
+ alert("Export range is empty — IN/OUT is at or past the end of the timeline. Choose Entire timeline, or move the markers.");
17213
+ return false;
14418
17214
  }
14419
- updateExportProfileNote(id);
17215
+ return true;
17216
+ }
17217
+ $("btnQueueExport")?.addEventListener("click", () => {
17218
+ if (selectedExportChoice().kind !== "delivery" || !dlvSpec) { alert("The queue takes delivery presets — pick one above (encoding profiles export one at a time)."); return; }
17219
+ if (!exportPreflight()) return;
17220
+ setSetting("exportKind", "delivery");
17221
+ setSetting("delivery", dlvSpec);
17222
+ queueAdd(dlvSpec);
17223
+ els.exportSetup.classList.add("hidden");
17224
+ openQueue();
17225
+ });
17226
+ $("btnBatchExport")?.addEventListener("click", () => {
17227
+ const on = projectOutputs().filter((o) => o.on !== false);
17228
+ if (!on.length || !exportPreflight()) return;
17229
+ for (const o of on) { const { id: _id, on: _on, ...spec } = o; queueAdd(normalizeDelivery(spec).spec); }
17230
+ els.exportSetup.classList.add("hidden");
17231
+ openQueue();
17232
+ runQueue();
17233
+ });
17234
+ $("btnOpenQueue")?.addEventListener("click", () => { els.exportSetup.classList.add("hidden"); openQueue(); });
17235
+ $("btnQueueStart")?.addEventListener("click", () => (queueRunning ? stopQueue() : runQueue()));
17236
+ $("btnQueueClose")?.addEventListener("click", closeQueue);
17237
+ $("exportQueue")?.addEventListener("keydown", (e) => {
17238
+ if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closeQueue(); }
17239
+ });
17240
+ $("btnQueueClear")?.addEventListener("click", () => {
17241
+ for (let i = exportQueue.length - 1; i >= 0; i--) if (exportQueue[i].status !== "pending" && exportQueue[i].status !== "running") exportQueue.splice(i, 1);
17242
+ renderQueue();
17243
+ });
17244
+ $("exportQueueList")?.addEventListener("click", (e) => {
17245
+ const r = e.target.dataset.qRetry, x = e.target.dataset.qRemove;
17246
+ const q = exportQueue.find((v) => v.id === (r || x));
17247
+ if (!q) return;
17248
+ if (r) { q.status = "pending"; q.error = null; q.progress = 0; }
17249
+ else exportQueue.splice(exportQueue.indexOf(q), 1);
17250
+ renderQueue();
17251
+ });
17252
+ $("btnCancelSetup").addEventListener("click", closeExportSetup);
17253
+ els.exportSetup?.addEventListener("keydown", (e) => {
17254
+ if (e.key === "Escape" && !e.defaultPrevented) { e.preventDefault(); e.stopPropagation(); closeExportSetup(); }
14420
17255
  });
14421
- $("btnCancelSetup").addEventListener("click", () => els.exportSetup.classList.add("hidden"));
14422
17256
  els.engineFast?.addEventListener("change", syncExportWcOpts);
14423
17257
  els.engineRealtime?.addEventListener("change", syncExportWcOpts);
14424
17258
  $("exportWcBitrate")?.addEventListener("change", persistExportWcOpts);
@@ -14605,6 +17439,14 @@ function openProjectTabMenu(clientX, clientY) {
14605
17439
  enterComp(comp.id);
14606
17440
  });
14607
17441
  menu.appendChild(compItem);
17442
+ const vids = project.media.filter((m) => m.kind === "video" && !proxyOf(m) && !isMediaOffline(m.id));
17443
+ if (vids.length && state.connected && state.ffmpeg) {
17444
+ const px = document.createElement("div");
17445
+ px.className = "ctx-opt";
17446
+ px.textContent = `Create proxies for ${vids.length} video${vids.length === 1 ? "" : "s"}`;
17447
+ px.addEventListener("click", () => { closeBinCtxMenu(); createProxies(vids, 540); });
17448
+ menu.appendChild(px);
17449
+ }
14608
17450
  document.body.appendChild(menu);
14609
17451
  const pad = 6;
14610
17452
  const w = menu.offsetWidth, h = menu.offsetHeight;
@@ -15030,6 +17872,18 @@ window.addEventListener("keydown", (e) => {
15030
17872
  return;
15031
17873
  }
15032
17874
  }
17875
+ // Ctrl/Cmd+S: save a version of the open project (the editor saves every change anyway)
17876
+ if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && (k === "s" || k === "S")) {
17877
+ e.preventDefault(); // never the browser's Save Page dialog, and not S (split) either
17878
+ if (!e.repeat && $("btnProjectsDash") && !$("btnProjectsDash").classList.contains("hidden")) saveVersionNow(); // holding the keys makes one
17879
+ return;
17880
+ }
17881
+ // Ctrl/Cmd+O: the Projects dashboard (where the editor server has projects)
17882
+ if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && (k === "o" || k === "O") && $("btnProjectsDash") && !$("btnProjectsDash").classList.contains("hidden")) {
17883
+ e.preventDefault();
17884
+ openProjects();
17885
+ return;
17886
+ }
15033
17887
  if (k === "Escape" && els.importUrlOverlay && !els.importUrlOverlay.classList.contains("hidden")) {
15034
17888
  e.preventDefault();
15035
17889
  closeImportUrl();
@@ -15079,7 +17933,7 @@ window.addEventListener("keydown", (e) => {
15079
17933
  e.preventDefault(); // Ctrl/Cmd+L would otherwise focus the address bar
15080
17934
  toggleLinkSelected();
15081
17935
  }
15082
- else if (k === "s" || k === "S") splitAtPlayhead();
17936
+ else if ((k === "s" || k === "S") && !e.ctrlKey && !e.metaKey) splitAtPlayhead();
15083
17937
  else if (k === "," && !e.ctrlKey && !e.metaKey && !e.altKey) {
15084
17938
  e.preventDefault();
15085
17939
  insertSourceAtPlayhead();