Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refuse a v1 clips save that would drop stills, and tag timeline renders BT.709

[._.]/ Adam Eivy94321d75e747
diff --git a/client/src/components/media/VideoTimelineInspector.jsx b/client/src/components/media/VideoTimelineInspector.jsx
new file mode 100644
index 0000000000..862a3fa924
--- /dev/null
+++ b/client/src/components/media/VideoTimelineInspector.jsx
@@ -0,0 +1,72 @@
+/**
+ * Inspector fields for the layered video timeline editor.
+ *
+ * Every numeric field declares its bounds ONCE: `NumberField` puts them on the
+ * `<input>` and clamps the committed value with the same pair, so an input
+ * whose `max` and clamp disagree isn't expressible.
+ */
+
+import { memo } from 'react';
+import { Trash2 } from 'lucide-react';
+import useFieldDraft from '../../hooks/useFieldDraft';
+import { clamp } from '../../utils/formatters';
+
+/**
+ * Commit-on-blur numeric input. The draft buffer is what lets the user type
+ * "0." — committing per keystroke would round-trip each stroke through the
+ * clamp and make that impossible.
+ */
+export const NumberField = memo(function NumberField({ id, label, value, step = 0.05, min = 0, max, hint, onCommit }) {
+ const draft = useFieldDraft(Number.isFinite(value) ? Number(value).toFixed(2) : '', (next) => {
+ const n = Number(next);
+ // A non-numeric draft is discarded — useFieldDraft falls back to the
+ // persisted value, so the input snaps back rather than committing NaN.
+ if (Number.isFinite(n)) onCommit(clamp(n, min, max ?? Infinity));
+ });
+ return (
+ <label htmlFor={id} className="block text-xs text-gray-400">
+ {label}
+ <input
+ id={id}
+ type="number"
+ step={step}
+ min={min}
+ max={max}
+ value={draft.value}
+ onChange={draft.onChange}
+ onBlur={draft.onBlur}
+ className="w-full mt-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent"
+ />
+ {hint && <span className="block mt-0.5 text-[10px] text-gray-500">{hint}</span>}
+ </label>
+ );
+});
+
+/** The fade pair every lane entry carries, bounded by its own duration. */
+export const FadeFields = memo(function FadeFields({ idPrefix, entry, duration, onCommit }) {
+ const max = Math.max(0, duration);
+ return (
+ <div className="grid grid-cols-2 gap-2">
+ <NumberField
+ id={`${idPrefix}-fade-in`} label="Fade in (s)" value={entry.fadeInSec ?? 0} max={max}
+ onCommit={(n) => onCommit({ fadeInSec: n })}
+ />
+ <NumberField
+ id={`${idPrefix}-fade-out`} label="Fade out (s)" value={entry.fadeOutSec ?? 0} max={max}
+ onCommit={(n) => onCommit({ fadeOutSec: n })}
+ />
+ </div>
+ );
+});
+
+export const RemoveButton = memo(function RemoveButton({ label, onClick }) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className="w-full px-2 py-1.5 bg-port-error/20 hover:bg-port-error/40 text-port-error text-xs rounded flex items-center justify-center gap-1"
+ >
+ <Trash2 className="w-3 h-3" /> {label}
+ </button>
+ );
+});
diff --git a/client/src/components/media/VideoTimelineLanes.jsx b/client/src/components/media/VideoTimelineLanes.jsx
new file mode 100644
index 0000000000..618ea5ac29
--- /dev/null
+++ b/client/src/components/media/VideoTimelineLanes.jsx
@@ -0,0 +1,267 @@
+/**
+ * Presentational blocks for the layered video timeline editor.
+ *
+ * The video lane is dnd-sortable and lays its blocks out sequentially; the
+ * overlay and audio lanes are free-floating and position every block by
+ * absolute project time. All of them are memoized — the editor's playhead
+ * advances once per animation frame during playback, so an unmemoized block
+ * would re-render (and, in the video lane, re-run `useSortable`) 60×/s.
+ */
+
+import { memo } from 'react';
+import { useSortable } from '@dnd-kit/sortable';
+import { X, Film, Plus, Music } from 'lucide-react';
+import { dndTransformToCss } from '../../lib/dndTransform';
+import { clickableProps } from '../../lib/a11yKeyboard.js';
+import { assetUrl, segmentDuration } from '../../lib/videoTimelineModel';
+
+const segmentLabel = (segment, meta) => {
+ if (!segment) return 'clip';
+ if (segment.type === 'still') return segment.assetFile || 'still';
+ return meta?.prompt?.trim().slice(0, 40) || 'clip';
+};
+
+// Black wedge over the head or tail of a block, sized to the fade's share of
+// the segment — the cut reads at a glance without opening the inspector.
+function FadeRamp({ side, fadeSec, duration }) {
+ if (!(fadeSec > 0)) return null;
+ return (
+ <div
+ data-testid={`fade-${side}-ramp`}
+ aria-hidden="true"
+ style={{ width: `${Math.min(100, (fadeSec / duration) * 100)}%` }}
+ className={`absolute inset-y-0 pointer-events-none ${
+ side === 'in'
+ ? 'left-0 rounded-l-md bg-gradient-to-r from-black/80 to-transparent'
+ : 'right-0 rounded-r-md bg-gradient-to-l from-black/80 to-transparent'
+ }`}
+ />
+ );
+}
+
+// Draggable+sortable video-lane block. Snaps the segment's project-time length
+// to a width derived from `pxPerSec` so longer segments visibly take more
+// horizontal space.
+export const TimelineBlock = memo(function TimelineBlock({
+ clip, clipMeta, isSelected, isMissing, pxPerSec, onSelect, onRemove,
+}) {
+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: clip._key });
+ const isStill = clip.type === 'still';
+ const dur = Math.max(0.05, segmentDuration(clip));
+ const label = segmentLabel(clip, clipMeta);
+ const removeLabel = isMissing ? 'missing clip' : label;
+ const thumbSrc = isStill
+ ? assetUrl(clip.assetKind, clip.assetFile)
+ : (clipMeta?.thumbnail ? assetUrl('video-thumbnails', clipMeta.thumbnail) : null);
+ const style = {
+ transform: dndTransformToCss(transform),
+ transition,
+ width: `${Math.max(60, dur * pxPerSec)}px`,
+ opacity: isDragging ? 0.4 : 1,
+ };
+ return (
+ <div
+ ref={setNodeRef}
+ style={style}
+ className={`relative shrink-0 h-20 rounded-md border-2 cursor-pointer transition-colors group ${
+ isMissing
+ ? 'bg-port-error/20 border-port-error'
+ : isSelected
+ ? 'border-port-accent bg-port-accent/10'
+ : 'bg-port-card border-port-border hover:border-port-accent/50'
+ }`}
+ onClick={() => onSelect(clip._key)}
+ {...attributes}
+ {...listeners}
+ {...clickableProps(() => onSelect(clip._key))}
+ >
+ {thumbSrc && (
+ <img src={thumbSrc} alt="" draggable={false} className="w-full h-full object-cover rounded-md opacity-80" />
+ )}
+ <div className="absolute inset-0 rounded-md bg-gradient-to-t from-black/70 via-transparent to-transparent pointer-events-none" />
+ <FadeRamp side="in" fadeSec={clip.fadeInSec} duration={dur} />
+ <FadeRamp side="out" fadeSec={clip.fadeOutSec} duration={dur} />
+ <div className="absolute bottom-1 left-1.5 right-1.5 text-[10px] text-white truncate font-medium">
+ {isMissing ? '(missing)' : label}
+ </div>
+ <div className="absolute top-1 left-1.5 text-[9px] text-white bg-black/60 px-1 rounded">
+ {isStill ? `still · ${dur.toFixed(2)}s` : `${dur.toFixed(2)}s`}
+ </div>
+ <button
+ type="button"
+ onClick={(e) => { e.stopPropagation(); onRemove(clip._key); }}
+ onPointerDown={(e) => e.stopPropagation()}
+ className="absolute top-0 right-0 inline-flex min-w-[44px] min-h-[44px] items-start justify-end p-1 rounded opacity-40 lg:opacity-0 lg:group-hover:opacity-100 focus-visible:opacity-100 transition-opacity text-white group/remove"
+ title="Remove from timeline"
+ aria-label={`Remove ${removeLabel} from timeline`}
+ >
+ <span className="inline-flex items-center justify-center p-0.5 bg-black/60 group-hover/remove:bg-port-error rounded transition-colors" aria-hidden="true">
+ <X className="w-3 h-3" />
+ </span>
+ </button>
+ </div>
+ );
+});
+
+// A free-floating lane block (overlay or audio bed). Unlike the video lane
+// these are positioned by absolute project time, so they carry no sort order —
+// the inspector's start field is what moves them.
+export const LaneBlock = memo(function LaneBlock({
+ entry, label, tone, isSelected, isMissing, pxPerSec, onSelect, onRemove,
+}) {
+ const dur = Math.max(0.05, entry.durationSec || 0);
+ const style = {
+ left: `${(entry.startSec || 0) * pxPerSec}px`,
+ width: `${Math.max(28, dur * pxPerSec)}px`,
+ };
+ return (
+ <div
+ style={style}
+ className={`absolute top-1 bottom-1 rounded border cursor-pointer overflow-hidden ${
+ isMissing
+ ? 'bg-port-error/20 border-port-error'
+ : isSelected
+ ? 'border-port-accent bg-port-accent/20'
+ : `${tone} hover:border-port-accent/50`
+ }`}
+ onClick={() => onSelect(entry._key)}
+ {...clickableProps(() => onSelect(entry._key))}
+ >
+ <span className="absolute inset-x-1 top-0.5 text-[9px] text-white truncate pointer-events-none">
+ {isMissing ? '(missing)' : label}
+ </span>
+ <button
+ type="button"
+ onClick={(e) => { e.stopPropagation(); onRemove(entry._key); }}
+ onPointerDown={(e) => e.stopPropagation()}
+ className="absolute bottom-0 right-0 p-0.5 text-white/70 hover:text-port-error"
+ title="Remove"
+ aria-label={`Remove ${label} from timeline`}
+ >
+ <X className="w-3 h-3" aria-hidden="true" />
+ </button>
+ </div>
+ );
+});
+
+/**
+ * One free-floating lane (overlays or audio), with its own playhead marker.
+ * Both lanes are in true project-time coordinates; the video lane is not (it
+ * lays blocks out sequentially with a gap and a minimum width), which is why
+ * the marker lives here rather than spanning all three.
+ */
+export const FloatingLane = memo(function FloatingLane({
+ title, entries, emptyHint, tone, labelOf, isMissing, selectedKey, pxPerSec, width, playheadSec, onSelect, onRemove,
+}) {
+ return (
+ <>
+ <div className="text-[9px] uppercase tracking-wide text-gray-600 px-0.5 pt-1">{title}</div>
+ <div className="relative h-8 bg-port-bg/40 rounded" style={{ width: `${width}px` }}>
+ {entries.length === 0 && (
+ <span className="absolute inset-0 flex items-center pl-2 text-[10px] text-gray-600">{emptyHint}</span>
+ )}
+ {entries.map((entry) => (
+ <LaneBlock
+ key={entry._key}
+ entry={entry}
+ label={labelOf(entry)}
+ tone={tone}
+ isSelected={entry._key === selectedKey}
+ isMissing={isMissing(entry)}
+ pxPerSec={pxPerSec}
+ onSelect={onSelect}
+ onRemove={onRemove}
+ />
+ ))}
+ <div
+ data-testid={`${title.toLowerCase()}-playhead`}
+ aria-hidden="true"
+ style={{ left: `${playheadSec * pxPerSec}px` }}
+ className="absolute inset-y-0 w-px bg-port-accent pointer-events-none"
+ />
+ </div>
+ </>
+ );
+});
+
+// Library tile — renders a clip from history with an "Add to timeline" button.
+// Click-to-add-at-end is simpler than DnD here and equally functional;
+// reordering on the timeline itself uses sortable.
+export const LibraryTile = memo(function LibraryTile({ clip, onAdd }) {
+ const dur = clip.numFrames && clip.fps ? clip.numFrames / clip.fps : 0;
+ return (
+ <div className="bg-port-card border border-port-border rounded-md overflow-hidden hover:border-port-accent/50 transition-colors">
+ <div className="aspect-video bg-port-bg relative">
+ {clip.thumbnail ? (
+ <img src={assetUrl('video-thumbnails', clip.thumbnail)} alt={clip.prompt} className="w-full h-full object-cover" loading="lazy" />
+ ) : (
+ <div className="w-full h-full flex items-center justify-center text-gray-600">
+ <Film className="w-6 h-6" />
+ </div>
+ )}
+ <span className="absolute bottom-1 right-1 text-[9px] px-1 py-0.5 bg-black/70 text-white rounded">
+ {dur.toFixed(1)}s
+ </span>
+ </div>
+ <div className="p-1.5 space-y-1">
+ <p className="text-[10px] text-gray-300 line-clamp-2" title={clip.prompt}>{clip.prompt}</p>
+ <button
+ type="button"
+ onClick={() => onAdd(clip)}
+ className="w-full flex items-center justify-center gap-1 px-1.5 py-1 bg-port-accent/20 hover:bg-port-accent/40 text-port-accent text-[10px] rounded"
+ >
+ <Plus className="w-3 h-3" /> Add to timeline
+ </button>
+ </div>
+ </div>
+ );
+});
+
+// Gallery tile — one image, two destinations. A still joins the video lane as
+// its own held segment; an overlay floats above whatever is playing at the
+// current playhead.
+export const StillTile = memo(function StillTile({ image, onAddStill, onAddOverlay }) {
+ const src = assetUrl('images', image.filename);
+ return (
+ <div className="bg-port-card border border-port-border rounded-md overflow-hidden hover:border-port-accent/50 transition-colors">
+ <div className="aspect-video bg-port-bg">
+ {src && <img src={src} alt={image.filename} className="w-full h-full object-cover" loading="lazy" />}
+ </div>
+ <div className="p-1.5 space-y-1">
+ <p className="text-[10px] text-gray-300 truncate" title={image.filename}>{image.filename}</p>
+ <div className="flex gap-1">
+ <button
+ type="button"
+ onClick={() => onAddStill(image)}
+ className="flex-1 px-1 py-1 bg-port-accent/20 hover:bg-port-accent/40 text-port-accent text-[10px] rounded"
+ >
+ Still
+ </button>
+ <button
+ type="button"
+ onClick={() => onAddOverlay(image)}
+ className="flex-1 px-1 py-1 bg-port-card border border-port-border hover:border-port-accent text-gray-300 text-[10px] rounded"
+ >
+ Overlay
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+});
+
+export const AudioRow = memo(function AudioRow({ track, onAdd }) {
+ return (
+ <div className="flex items-center gap-2 bg-port-card border border-port-border rounded-md px-2 py-1.5 hover:border-port-accent/50 transition-colors">
+ <Music className="w-3 h-3 text-gray-500 shrink-0" aria-hidden="true" />
+ <span className="text-[10px] text-gray-300 truncate flex-1" title={track.filename}>{track.label || track.filename}</span>
+ <button
+ type="button"
+ onClick={() => onAdd(track)}
+ className="px-1.5 py-1 bg-port-accent/20 hover:bg-port-accent/40 text-port-accent text-[10px] rounded shrink-0"
+ >
+ Add
+ </button>
+ </div>
+ );
+});
diff --git a/client/src/pages/VideoTimelineEditor.test.jsx b/client/src/components/media/VideoTimelineLanes.test.jsx
similarity index 77%
rename from client/src/pages/VideoTimelineEditor.test.jsx
rename to client/src/components/media/VideoTimelineLanes.test.jsx
index 8795909fb8..21d7099cd7 100644
--- a/client/src/pages/VideoTimelineEditor.test.jsx
+++ b/client/src/components/media/VideoTimelineLanes.test.jsx
@@ -18,7 +18,7 @@ vi.mock('@dnd-kit/sortable', async () => {
};
});
-import { TimelineBlock, LaneBlock, clampTrim, fitFadePatch } from './VideoTimelineEditor';
+import { TimelineBlock, LaneBlock, FloatingLane } from './VideoTimelineLanes';
const clip = { _key: 'clip-key', clipId: 'clip-1', inSec: 0, outSec: 2 };
const clipMeta = { prompt: 'A dramatic sunrise' };
@@ -175,39 +175,49 @@ describe('LaneBlock — free-floating overlay/bed placement', () => {
});
});
-describe('clampTrim', () => {
- const segment = { inSec: 0, outSec: 4, fadeInSec: 0, fadeOutSec: 0 };
-
- it('clamps out to the source duration', () => {
- expect(clampTrim(segment, { outSec: 99 }, 5, 24)).toMatchObject({ outSec: 5 });
- });
-
- it('keeps at least one frame between in and out, matching the server guard', () => {
- // 24fps → 1/24s minimum, not the old hardcoded 0.04.
- expect(clampTrim(segment, { inSec: 4 }, 4, 24).outSec - clampTrim(segment, { inSec: 4 }, 4, 24).inSec)
- .toBeCloseTo(1 / 24);
- });
+describe('FloatingLane', () => {
+ const overlay = (over = {}) => ({ _key: 'ov-1', assetFile: 'logo.png', startSec: 1, durationSec: 2, ...over });
+
+ const renderLane = (props = {}) => render(
+ <FloatingLane
+ title="Overlays"
+ entries={[overlay()]}
+ emptyHint="Add an overlay from the Stills tab"
+ tone=""
+ labelOf={(e) => e.assetFile}
+ isMissing={() => false}
+ selectedKey={null}
+ pxPerSec={40}
+ width={400}
+ playheadSec={2.5}
+ onSelect={vi.fn()}
+ onRemove={vi.fn()}
+ {...props}
+ />,
+ );
- it('shrinks fades that no longer fit the tightened trim', () => {
- const faded = { inSec: 0, outSec: 4, fadeInSec: 1, fadeOutSec: 1 };
- const patched = clampTrim(faded, { outSec: 1 }, 4, 24);
- expect(patched.fadeInSec + patched.fadeOutSec).toBeCloseTo(1);
+ it('places its own playhead in project-time coordinates', () => {
+ renderLane();
+ expect(screen.getByTestId('overlays-playhead')).toHaveStyle({ left: '100px' });
});
-});
-describe('fitFadePatch', () => {
- it('leaves a fitting fade pair untouched', () => {
- expect(fitFadePatch({ fadeInSec: 0.5, fadeOutSec: 0.5 }, { fadeInSec: 1 }, 4)).toEqual({ fadeInSec: 1 });
+ it('gives each lane a distinct playhead testid so neither query is ambiguous', () => {
+ renderLane();
+ renderLane({ title: 'Audio' });
+ expect(screen.getByTestId('overlays-playhead')).toBeInTheDocument();
+ expect(screen.getByTestId('audio-playhead')).toBeInTheDocument();
});
- it('scales an over-long pair down proportionally rather than dropping one', () => {
- const patched = fitFadePatch({ fadeInSec: 1, fadeOutSec: 3 }, { fadeInSec: 1 }, 2);
- expect(patched.fadeInSec).toBeCloseTo(0.5);
- expect(patched.fadeOutSec).toBeCloseTo(1.5);
+ it('shows the empty hint instead of a bare lane', () => {
+ renderLane({ entries: [] });
+ expect(screen.getByText('Add an overlay from the Stills tab')).toBeInTheDocument();
});
- it('zeroes both fades when the duration collapses', () => {
- const patched = fitFadePatch({ fadeInSec: 1, fadeOutSec: 1 }, { durationSec: 0 }, 0);
- expect(patched).toMatchObject({ fadeInSec: 0, fadeOutSec: 0 });
+ it('marks only the selected block', () => {
+ renderLane({ entries: [overlay(), overlay({ _key: 'ov-2', assetFile: 'badge.png' })], selectedKey: 'ov-2' });
+ // Match the selected-only fill, not `border-port-accent` — every block
+ // carries that as a `hover:` variant.
+ expect(screen.getByText('badge.png').closest('div').className).toContain('bg-port-accent/20');
+ expect(screen.getByText('logo.png').closest('div').className).not.toContain('bg-port-accent/20');
});
});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 7ada22d180..d3d8608fdf 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -200,6 +200,6 @@ grep -i "what you want to do" client/src/lib/README.md
| `threejsSculpt.js` | Three.js construction helpers for the validated procedural sculpt spec (`server/lib/threejsModel.js`) used by the Three.js Models preview. `createSculptBufferGeometry(definition)` builds the schema forms r3f has no direct element for — `custom` (indexed BufferGeometry), `extrude` (closed 2D outline + holes swept to `depth`, optional bevel) and `tube` (CatmullRom path swept at `radius`) — returning null for primitives, which stay declarative; callers own disposal. `needsSculptBufferGeometry(definition)` is the matching predicate. `sculptMaterialProps(definition, envMapIntensity)` maps a material definition to its Three.js props, forwarding the physical-only channels (`clearcoat`, `ior`, `transmission`, `thickness`, `sheen`, `iridescence`, `anisotropy`) only for `type: physical`, and the spec-level `environment.intensity` as `envMapIntensity` on every lit material (`basic` is unlit and takes none). Mirrors the `createGeometry`/`createMaterial` bodies `buildThreejsFactorySource()` emits, so the preview and the exported standalone factory render the same scene. |
| `universeBuilderShared.js` | Shared constants + pure category/trunk/composite helpers for the Universe Builder page and its extracted tab/editor components (#2374): `TRUNK_TABS`/`TRUNK_BY_ID`/`TRUNK_BY_KIND`, `TAB_*` + `BUCKET_CANON`, `CATEGORY_LABELS`, `DEFAULT_RENDER_OPTS`, `COMPOSITE_BOARD_KINDS`; and helpers `groupBucketsByKind`, `normalizeCategoryKey`, `humanizeCategory`, `ensureDraftCategories`, `getCategoryKeys`, `compositeKindLabel`. No React state — safe to import from the page or any tab component without a cycle. |
| `universeBuilderCounts.js` | Pure prompt-count helpers for the Universe Builder render buttons (#2374), mirroring the server's compile/skip rules so inline counts match what `/render` will enqueue: `totalVariationCount`, `canonEntryHasContent`, `countCanonWithContent`, `renderPromptCount`, `scopedPromptCount`. The server `compilePrompts`/`synthesizeCanonPrompt` copy is authoritative — keep in sync. |
-| `videoTimelineModel.js` | Pure model helpers for the layered video timeline, mirroring `server/services/videoTimeline/segments.js` so the browser preview and the ffmpeg export make the same cut/geometry/mix decisions: `segmentDuration`/`timelineDuration`/`segmentStarts`/`findSegmentAt` (project-time ↔ segment mapping), `fadeMultiplier` (linear, matching ffmpeg's default `tri` curve), `overlayOpacityAt`, `audioTrackStateAt`, `assetUrl(assetKind, assetFile)`, and the save helpers `stripKey`/`withKeys`/`timelinePatch`. Change a rule here and in the server module in the same commit. |
+| `videoTimelineModel.js` | Pure model helpers for the layered video timeline, mirroring `server/services/videoTimeline/segments.js` so the browser preview and the ffmpeg export make the same cut/geometry/mix decisions: `segmentDuration`/`timelineDuration`/`findSegmentAt` (project-time ↔ segment mapping), `fadeMultiplier` (linear, matching ffmpeg's default `tri` curve), `overlayOpacityAt`, `audioTrackStateAt`, `segmentVolumeAt` (clipVolume × segment volume × fade — the product the export writes into each segment audio chain, so the preview auditions the mix that renders), `assetUrl(assetKind, assetFile)`, the edit clamps `clampTrim` (keeps ≥ 1 frame, matching the server's CLIP_TOO_SHORT floor) and `fitFadePatch` (shrinks an over-long fade pair proportionally instead of letting the PATCH 400), and the save helpers `stripKey`/`withKeys`/`timelinePatch`. Change a rule here and in the server module in the same commit. |
| `wrSceneCursor.js` | Resolve which script scene the editor caret sits in (`sceneAtCursor`, `sceneAnchorIndex`) — inverse of WorkEditor's jump-to-scene text search; drives the live render preview's "scene at cursor" target. |
| `writingGuide.js` | Canonical Writers Room reference data + craft principles rendered by the Guide page (`/writers-room/guide`): `WRITING_LENGTH_TARGETS` (microfiction→novel word/char bands), `BOOK_LENGTH_ESTIMATES` (page-based), `WRITING_PRINCIPLES`, `PLANNED_ANALYSES` (e.g. the emotional-roadmap evaluator), and `classifyByWordCount(n)` for labelling a draft's length. Future word-count gauges / length checks read from here so targets don't drift from the docs. |
diff --git a/client/src/lib/videoTimelineModel.js b/client/src/lib/videoTimelineModel.js
index 63d83e8447..7209e28a98 100644
--- a/client/src/lib/videoTimelineModel.js
+++ b/client/src/lib/videoTimelineModel.js
@@ -11,7 +11,7 @@
* tests alike.
*/
-export const TIMELINE_SCHEMA_VERSION = 2;
+import { clamp } from '../utils/formatters';
export const IMAGE_ASSET_KINDS = ['images', 'video-thumbnails'];
export const AUDIO_ASSET_KINDS = ['audio', 'music'];
@@ -131,3 +131,52 @@ export const laneKey = (prefix, idx) => `${prefix}-${idx}-${Math.random().toStri
/** Attach `_key` to every entry of a lane loaded from the server. */
export const withKeys = (entries, prefix) => (entries || []).map((e, idx) => ({ ...e, _key: laneKey(prefix, idx) }));
+
+/**
+ * Shrink a fade pair that no longer fits its own duration, scaling both
+ * proportionally so the author's balance survives. Mirrors the server's
+ * `fitFades` (`server/services/videoTimeline/local.js`) — ffmpeg's `fade`
+ * renders the whole segment black when its start time goes negative, and the
+ * persist-time validator rejects an over-long pair outright, so the editor
+ * shrinks rather than letting the PATCH 400 mid-edit.
+ *
+ * Returns the caller's `patch` with the fades folded in only when they had to
+ * move, so an already-fitting edit round-trips untouched.
+ */
+export function fitFadePatch(entry, patch, duration) {
+ const merged = { ...entry, ...patch };
+ const fin = Math.max(0, merged.fadeInSec || 0);
+ const fout = Math.max(0, merged.fadeOutSec || 0);
+ if (fin + fout <= duration) return patch;
+ const scale = fin + fout > 0 ? Math.max(0, duration) / (fin + fout) : 0;
+ return { ...patch, fadeInSec: fin * scale, fadeOutSec: fout * scale };
+}
+
+/**
+ * Clamp a trim edit to `0..sourceDur`, keeping at least one frame between in
+ * and out. The floor is `1/fps` to match the server's CLIP_TOO_SHORT guard —
+ * a hardcoded floor was too lenient at 24fps and let the editor build a
+ * project the render then rejected with a 400.
+ */
+export function clampTrim(segment, patch, sourceDur, fps) {
+ const limit = sourceDur || Infinity;
+ const minDur = fps && fps > 0 ? 1 / fps : 0.04;
+ let inSec = patch.inSec != null ? patch.inSec : segment.inSec;
+ let outSec = patch.outSec != null ? patch.outSec : segment.outSec;
+ inSec = Math.max(0, Math.min(inSec, limit - minDur));
+ outSec = Math.max(inSec + minDur, Math.min(outSec, limit));
+ return fitFadePatch(segment, { inSec, outSec }, outSec - inSec);
+}
+
+/**
+ * Effective playback volume for a video segment at `within` seconds in — the
+ * project's clip-audio multiplier, the segment's own trim, and its fade ramp,
+ * exactly as the export composes them (`volume=` ahead of `afade` in the
+ * segment's audio chain).
+ */
+export const segmentVolumeAt = (segment, clipVolume, within) => {
+ if (!segment || segment.type === 'still') return 0;
+ const duration = segmentDuration(segment);
+ const base = (clipVolume == null ? 1 : clipVolume) * (segment.volume == null ? 1 : segment.volume);
+ return clamp(base * fadeMultiplier(segment.fadeInSec || 0, segment.fadeOutSec || 0, duration, within), 0, 1);
+};
diff --git a/client/src/lib/videoTimelineModel.test.js b/client/src/lib/videoTimelineModel.test.js
index 435e323621..e92f904d8f 100644
--- a/client/src/lib/videoTimelineModel.test.js
+++ b/client/src/lib/videoTimelineModel.test.js
@@ -10,6 +10,9 @@ import {
stripKey,
withKeys,
timelinePatch,
+ clampTrim,
+ fitFadePatch,
+ segmentVolumeAt,
} from './videoTimelineModel';
const clip = (inSec, outSec) => ({ type: 'clip', clipId: 'c', inSec, outSec });
@@ -158,3 +161,65 @@ describe('save helpers', () => {
expect(timelinePatch({})).toEqual({ segments: [], overlays: [], audio: { clipVolume: 1, tracks: [] } });
});
});
+describe('clampTrim', () => {
+ const segment = { inSec: 0, outSec: 4, fadeInSec: 0, fadeOutSec: 0 };
+
+ it('clamps out to the source duration', () => {
+ expect(clampTrim(segment, { outSec: 99 }, 5, 24)).toMatchObject({ outSec: 5 });
+ });
+
+ it('keeps at least one frame between in and out, matching the server guard', () => {
+ // 24fps → 1/24s minimum, not the old hardcoded 0.04.
+ expect(clampTrim(segment, { inSec: 4 }, 4, 24).outSec - clampTrim(segment, { inSec: 4 }, 4, 24).inSec)
+ .toBeCloseTo(1 / 24);
+ });
+
+ it('shrinks fades that no longer fit the tightened trim', () => {
+ const faded = { inSec: 0, outSec: 4, fadeInSec: 1, fadeOutSec: 1 };
+ const patched = clampTrim(faded, { outSec: 1 }, 4, 24);
+ expect(patched.fadeInSec + patched.fadeOutSec).toBeCloseTo(1);
+ });
+});
+
+describe('fitFadePatch', () => {
+ it('leaves a fitting fade pair untouched', () => {
+ expect(fitFadePatch({ fadeInSec: 0.5, fadeOutSec: 0.5 }, { fadeInSec: 1 }, 4)).toEqual({ fadeInSec: 1 });
+ });
+
+ it('scales an over-long pair down proportionally rather than dropping one', () => {
+ const patched = fitFadePatch({ fadeInSec: 1, fadeOutSec: 3 }, { fadeInSec: 1 }, 2);
+ expect(patched.fadeInSec).toBeCloseTo(0.5);
+ expect(patched.fadeOutSec).toBeCloseTo(1.5);
+ });
+
+ it('zeroes both fades when the duration collapses', () => {
+ const patched = fitFadePatch({ fadeInSec: 1, fadeOutSec: 1 }, { durationSec: 0 }, 0);
+ expect(patched).toMatchObject({ fadeInSec: 0, fadeOutSec: 0 });
+ });
+});
+
+describe('segmentVolumeAt — preview must audition what the export mixes', () => {
+ const seg = { type: 'clip', clipId: 'c', inSec: 0, outSec: 4, volume: 0.5, fadeInSec: 1, fadeOutSec: 0 };
+
+ it('multiplies the project clip volume by the segment volume, exactly as the export chain does', () => {
+ // Export builds `volume=${clipVolume * seg.volume}` ahead of the afade.
+ expect(segmentVolumeAt(seg, 0.4, 2)).toBeCloseTo(0.2);
+ });
+
+ it('applies the segment fade on top of that product', () => {
+ expect(segmentVolumeAt(seg, 1, 0.5)).toBeCloseTo(0.25);
+ expect(segmentVolumeAt(seg, 1, 1)).toBeCloseTo(0.5);
+ });
+
+ it('defaults a missing clipVolume/volume to unity', () => {
+ expect(segmentVolumeAt({ type: 'clip', inSec: 0, outSec: 2 }, null, 1)).toBe(1);
+ });
+
+ it('caps at 1 — a >1x multiplier cannot be honoured by a media element', () => {
+ expect(segmentVolumeAt({ type: 'clip', inSec: 0, outSec: 2, volume: 4 }, 2, 1)).toBe(1);
+ });
+
+ it('is silent for a still — it carries no audio track', () => {
+ expect(segmentVolumeAt({ type: 'still', durationSec: 3 }, 1, 1)).toBe(0);
+ });
+});
diff --git a/client/src/pages/VideoTimelineEditor.jsx b/client/src/pages/VideoTimelineEditor.jsx
index 362268ee20..c226dcbfdc 100644
--- a/client/src/pages/VideoTimelineEditor.jsx
+++ b/client/src/pages/VideoTimelineEditor.jsx
@@ -11,18 +11,19 @@ import {
SortableContext,
arrayMove,
horizontalListSortingStrategy,
- useSortable,
} from '@dnd-kit/sortable';
-import { dndTransformToCss } from '../lib/dndTransform';
import {
- Play, Pause, Plus, Trash2, X, Save, Film, Loader2, ArrowLeft, Volume2, VolumeX,
+ Play, Pause, Save, Film, Loader2, ArrowLeft, Volume2, VolumeX,
Image as ImageIcon, Music,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import * as api from '../services/api';
-import { formatTimecode } from '../utils/formatters';
+import { formatTimecode, clamp } from '../utils/formatters';
import { useSseProgress, isTerminalSseFrame } from '../hooks/useSseProgress';
-import { clickableProps } from '../lib/a11yKeyboard.js';
+import {
+ TimelineBlock, FloatingLane, LibraryTile, StillTile, AudioRow,
+} from '../components/media/VideoTimelineLanes';
+import { NumberField, FadeFields, RemoveButton } from '../components/media/VideoTimelineInspector';
import {
assetUrl,
segmentDuration,
@@ -31,6 +32,9 @@ import {
fadeMultiplier,
overlayOpacityAt,
audioTrackStateAt,
+ segmentVolumeAt,
+ clampTrim,
+ fitFadePatch,
timelinePatch,
withKeys,
laneKey,
@@ -44,247 +48,31 @@ const EMPTY_LANES = { segments: [], overlays: [], audio: { clipVolume: 1, tracks
const DEFAULT_STILL_SEC = 3;
const DEFAULT_OVERLAY_SEC = 3;
const DEFAULT_BED_SEC = 10;
-
-const num2 = (n) => (Number.isFinite(n) ? Number(n).toFixed(2) : '');
-
-const segmentLabel = (segment, meta) => {
- if (!segment) return 'clip';
- if (segment.type === 'still') return segment.assetFile || 'still';
- return meta?.prompt?.trim().slice(0, 40) || 'clip';
+// Mirrors MAX_STILL_SEC / MIN_MEDIA_SEC on the server.
+const MIN_ENTRY_SEC = 0.05;
+const MAX_ENTRY_SEC = 600;
+const MAX_VOLUME = 4;
+
+const LIBRARY_TABS = [
+ { id: 'clips', label: 'Clips', Icon: Film },
+ { id: 'stills', label: 'Stills', Icon: ImageIcon },
+ { id: 'audio', label: 'Audio', Icon: Music },
+];
+
+// One accessor per lane, so adding a lane doesn't mean a fourth branch in
+// every ternary chain that needs "the entries for this lane".
+const laneEntries = (lanes, lane) => {
+ if (lane === 'overlay') return lanes.overlays;
+ if (lane === 'audio') return lanes.audio.tracks;
+ if (lane === 'segment') return lanes.segments;
+ return null;
};
-// Draggable+sortable video-lane block. Snaps the segment's project-time length
-// to a width derived from `pxPerSec` so longer segments visibly take more
-// horizontal space, and marks its fades so a cut reads at a glance.
-export function TimelineBlock({ clip, clipMeta, isSelected, isMissing, pxPerSec, onSelect, onRemove }) {
- const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: clip._key });
- const isStill = clip.type === 'still';
- const dur = Math.max(0.05, segmentDuration(clip));
- const label = segmentLabel(clip, clipMeta);
- const removeLabel = isMissing ? 'missing clip' : label;
- const width = Math.max(60, dur * pxPerSec);
- const thumbSrc = isStill
- ? assetUrl(clip.assetKind, clip.assetFile)
- : (clipMeta?.thumbnail ? `/data/video-thumbnails/${clipMeta.thumbnail}` : null);
- const style = {
- transform: dndTransformToCss(transform),
- transition,
- width: `${width}px`,
- opacity: isDragging ? 0.4 : 1,
- };
- return (
- <div
- ref={setNodeRef}
- style={style}
- className={`relative shrink-0 h-20 rounded-md border-2 cursor-pointer transition-colors group ${
- isMissing
- ? 'bg-port-error/20 border-port-error'
- : isSelected
- ? 'border-port-accent bg-port-accent/10'
- : 'bg-port-card border-port-border hover:border-port-accent/50'
- }`}
- onClick={() => onSelect(clip._key)}
- {...attributes}
- {...listeners}
- {...clickableProps(() => onSelect(clip._key))}
- >
- {thumbSrc && (
- <img
- src={thumbSrc}
- alt=""
- draggable={false}
- className="w-full h-full object-cover rounded-md opacity-80"
- />
- )}
- <div className="absolute inset-0 rounded-md bg-gradient-to-t from-black/70 via-transparent to-transparent pointer-events-none" />
- {/* Fade ramps read as wedges of black over the head/tail of the block. */}
- {clip.fadeInSec > 0 && (
- <div
- data-testid="fade-in-ramp"
- aria-hidden="true"
- style={{ width: `${Math.min(100, (clip.fadeInSec / dur) * 100)}%` }}
- className="absolute inset-y-0 left-0 rounded-l-md bg-gradient-to-r from-black/80 to-transparent pointer-events-none"
- />
- )}
- {clip.fadeOutSec > 0 && (
- <div
- data-testid="fade-out-ramp"
- aria-hidden="true"
- style={{ width: `${Math.min(100, (clip.fadeOutSec / dur) * 100)}%` }}
- className="absolute inset-y-0 right-0 rounded-r-md bg-gradient-to-l from-black/80 to-transparent pointer-events-none"
- />
- )}
- <div className="absolute bottom-1 left-1.5 right-1.5 text-[10px] text-white truncate font-medium">
- {isMissing ? '(missing)' : label}
- </div>
- <div className="absolute top-1 left-1.5 text-[9px] text-white bg-black/60 px-1 rounded">
- {isStill ? `still · ${dur.toFixed(2)}s` : `${dur.toFixed(2)}s`}
- </div>
- <button
- type="button"
- onClick={(e) => { e.stopPropagation(); onRemove(clip._key); }}
- onPointerDown={(e) => e.stopPropagation()}
- className="absolute top-0 right-0 inline-flex min-w-[44px] min-h-[44px] items-start justify-end p-1 rounded opacity-40 lg:opacity-0 lg:group-hover:opacity-100 focus-visible:opacity-100 transition-opacity text-white group/remove"
- title="Remove from timeline"
- aria-label={`Remove ${removeLabel} from timeline`}
- >
- <span className="inline-flex items-center justify-center p-0.5 bg-black/60 group-hover/remove:bg-port-error rounded transition-colors" aria-hidden="true">
- <X className="w-3 h-3" />
- </span>
- </button>
- </div>
- );
-}
-
-// A free-floating lane block (overlay or audio bed). Unlike the video lane
-// these are positioned by absolute project time, so they carry no sort order —
-// the inspector's start field is what moves them.
-export function LaneBlock({ entry, label, tone, isSelected, isMissing, pxPerSec, onSelect, onRemove }) {
- const dur = Math.max(0.05, entry.durationSec || 0);
- const style = {
- left: `${(entry.startSec || 0) * pxPerSec}px`,
- width: `${Math.max(28, dur * pxPerSec)}px`,
- };
- return (
- <div
- style={style}
- className={`absolute top-1 bottom-1 rounded border cursor-pointer overflow-hidden ${
- isMissing
- ? 'bg-port-error/20 border-port-error'
- : isSelected
- ? 'border-port-accent bg-port-accent/20'
- : `${tone} hover:border-port-accent/50`
- }`}
- onClick={() => onSelect(entry._key)}
- {...clickableProps(() => onSelect(entry._key))}
- >
- <span className="absolute inset-x-1 top-0.5 text-[9px] text-white truncate pointer-events-none">
- {isMissing ? '(missing)' : label}
- </span>
- <button
- type="button"
- onClick={(e) => { e.stopPropagation(); onRemove(entry._key); }}
- onPointerDown={(e) => e.stopPropagation()}
- className="absolute bottom-0 right-0 p-0.5 text-white/70 hover:text-port-error"
- title="Remove"
- aria-label={`Remove ${label} from timeline`}
- >
- <X className="w-3 h-3" aria-hidden="true" />
- </button>
- </div>
- );
-}
-
-// Library tile — renders a clip from history with an "Add to timeline" button.
-// Does not use DnD here; click-to-add at end is simpler and equally functional.
-// Reordering on the timeline itself uses sortable.
-function LibraryTile({ clip, onAdd }) {
- const dur = clip.numFrames && clip.fps ? clip.numFrames / clip.fps : 0;
- return (
- <div className="bg-port-card border border-port-border rounded-md overflow-hidden hover:border-port-accent/50 transition-colors">
- <div className="aspect-video bg-port-bg relative">
- {clip.thumbnail ? (
- <img src={`/data/video-thumbnails/${clip.thumbnail}`} alt={clip.prompt} className="w-full h-full object-cover" loading="lazy" />
- ) : (
- <div className="w-full h-full flex items-center justify-center text-gray-600">
- <Film className="w-6 h-6" />
- </div>
- )}
- <span className="absolute bottom-1 right-1 text-[9px] px-1 py-0.5 bg-black/70 text-white rounded">
- {dur.toFixed(1)}s
- </span>
- </div>
- <div className="p-1.5 space-y-1">
- <p className="text-[10px] text-gray-300 line-clamp-2" title={clip.prompt}>{clip.prompt}</p>
- <button
- type="button"
- onClick={() => onAdd(clip)}
- className="w-full flex items-center justify-center gap-1 px-1.5 py-1 bg-port-accent/20 hover:bg-port-accent/40 text-port-accent text-[10px] rounded"
- >
- <Plus className="w-3 h-3" /> Add to timeline
- </button>
- </div>
- </div>
- );
-}
-
-// Gallery tile — one image, two destinations. A still joins the video lane as
-// its own held segment; an overlay floats above whatever is playing at the
-// current playhead.
-function StillTile({ image, onAddStill, onAddOverlay }) {
- const src = assetUrl('images', image.filename);
- return (
- <div className="bg-port-card border border-port-border rounded-md overflow-hidden hover:border-port-accent/50 transition-colors">
- <div className="aspect-video bg-port-bg">
- {src && <img src={src} alt={image.filename} className="w-full h-full object-cover" loading="lazy" />}
- </div>
- <div className="p-1.5 space-y-1">
- <p className="text-[10px] text-gray-300 truncate" title={image.filename}>{image.filename}</p>
- <div className="flex gap-1">
- <button
- type="button"
- onClick={() => onAddStill(image)}
- className="flex-1 px-1 py-1 bg-port-accent/20 hover:bg-port-accent/40 text-port-accent text-[10px] rounded"
- >
- Still
- </button>
- <button
- type="button"
- onClick={() => onAddOverlay(image)}
- className="flex-1 px-1 py-1 bg-port-card border border-port-border hover:border-port-accent text-gray-300 text-[10px] rounded"
- >
- Overlay
- </button>
- </div>
- </div>
- </div>
- );
-}
-
-function AudioRow({ track, onAdd }) {
- return (
- <div className="flex items-center gap-2 bg-port-card border border-port-border rounded-md px-2 py-1.5 hover:border-port-accent/50 transition-colors">
- <Music className="w-3 h-3 text-gray-500 shrink-0" aria-hidden="true" />
- <span className="text-[10px] text-gray-300 truncate flex-1" title={track.filename}>{track.label || track.filename}</span>
- <button
- type="button"
- onClick={() => onAdd(track)}
- className="px-1.5 py-1 bg-port-accent/20 hover:bg-port-accent/40 text-port-accent text-[10px] rounded shrink-0"
- >
- Add
- </button>
- </div>
- );
-}
-
-// Inspector number input with its own draft state. Editing the canonical value
-// on every keystroke forces each stroke through toFixed(), which prevents
-// typing "0." at all; committing on blur avoids that and batches the PATCH.
-function NumberField({ id, label, value, step = 0.05, min, max, hint, onCommit }) {
- const [draft, setDraft] = useState(num2(value));
- useEffect(() => { setDraft(num2(value)); }, [value]);
- return (
- <label htmlFor={id} className="block text-xs text-gray-400">
- {label}
- <input
- id={id}
- type="number"
- step={step}
- min={min}
- max={max}
- value={draft}
- onChange={(e) => setDraft(e.target.value)}
- onBlur={(e) => {
- const n = Number(e.target.value);
- if (Number.isFinite(n)) onCommit(n);
- else setDraft(num2(value));
- }}
- className="w-full mt-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent"
- />
- {hint && <span className="block mt-0.5 text-[10px] text-gray-500">{hint}</span>}
- </label>
- );
-}
+const withLaneEntries = (lanes, lane, next) => {
+ if (lane === 'overlay') return { ...lanes, overlays: next };
+ if (lane === 'audio') return { ...lanes, audio: { ...lanes.audio, tracks: next } };
+ return { ...lanes, segments: next };
+};
export default function VideoTimelineEditor() {
const { projectId } = useParams();
@@ -303,7 +91,7 @@ export default function VideoTimelineEditor() {
const [selection, setSelection] = useState(null);
// Track the current selection by its STABLE position so a refresh — which
// regenerates every entry's random _key — can re-derive it instead of
- // collapsing the inspector to "Select a clip". Read from a ref so refresh
+ // collapsing the inspector to "Select a block". Read from a ref so refresh
// needn't depend on lanes/selection (which would re-trigger the load-on-mount loop).
const selectionRef = useRef({ lane: null, index: -1 });
const [pxPerSec, setPxPerSec] = useState(60);
@@ -311,7 +99,6 @@ export default function VideoTimelineEditor() {
const [playing, setPlaying] = useState(false);
const [muted, setMuted] = useState(false);
const [renderJobId, setRenderJobId] = useState(null);
- const [renderProgress, setRenderProgress] = useState(0);
const [showLibrary, setShowLibrary] = useState(true);
const [libraryTab, setLibraryTab] = useState('clips');
// Local input draft. Editing the canonical state on every keystroke makes the
@@ -329,6 +116,10 @@ export default function VideoTimelineEditor() {
const playSegmentIndexRef = useRef(-1);
// One <audio> element per bed track, keyed by its client-side _key.
const bedRefs = useRef(new Map());
+ // `updatedAt` is the only field the save path reads off `project`; holding it
+ // in a ref keeps the whole updateLanes → patchLane callback chain stable
+ // across the setProject that every successful save performs.
+ const updatedAtRef = useRef(null);
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));
@@ -353,15 +144,14 @@ export default function VideoTimelineEditor() {
},
};
setProject(proj);
+ updatedAtRef.current = proj.updatedAt;
setLanes(nextLanes);
// Re-derive selection from its lane + prior position so a refresh — e.g. a
// CONFLICT reload mid-edit — doesn't leave `selection` pointing at a
// now-regenerated _key and collapse the inspector.
const { lane, index } = selectionRef.current;
- const laneEntries = lane === 'overlay' ? nextLanes.overlays
- : lane === 'audio' ? nextLanes.audio.tracks
- : lane === 'segment' ? nextLanes.segments : null;
- setSelection(laneEntries?.[index] ? { lane, key: laneEntries[index]._key } : null);
+ const entries = laneEntries(nextLanes, lane);
+ setSelection(entries?.[index] ? { lane, key: entries[index]._key } : null);
}
setHistory(Array.isArray(hist) ? hist : []);
setImages(Array.isArray(gallery) ? gallery : []);
@@ -374,12 +164,10 @@ export default function VideoTimelineEditor() {
// Keep the stable-position mirror of the current selection current so refresh()
// can reattach it after it regenerates lane _keys.
useEffect(() => {
- if (!selection) { selectionRef.current = { lane: null, index: -1 }; return; }
- const entries = selection.lane === 'overlay' ? overlays
- : selection.lane === 'audio' ? audio.tracks : segments;
- const idx = entries.findIndex((e) => e._key === selection.key);
+ const entries = selection && laneEntries(lanes, selection.lane);
+ const idx = entries ? entries.findIndex((e) => e._key === selection.key) : -1;
selectionRef.current = idx >= 0 ? { lane: selection.lane, index: idx } : { lane: null, index: -1 };
- }, [selection, segments, overlays, audio.tracks]);
+ }, [selection, lanes]);
useEffect(() => { refresh(); }, [refresh]);
@@ -390,14 +178,10 @@ export default function VideoTimelineEditor() {
if (project?.name) setNameDraft(project.name);
}, [project?.id, project?.name]);
- // O(1) clip metadata lookup. The video-sync effect runs on every rAF tick
- // during playback; a linear find() per frame multiplied by segment count is
+ // O(1) clip metadata lookup. The video-sync effect can run per frame during
+ // playback; a linear find() per frame multiplied by segment count is
// measurable on long timelines.
- const historyMap = useMemo(() => {
- const m = new Map();
- for (const h of history) m.set(h.id, h);
- return m;
- }, [history]);
+ const historyMap = useMemo(() => new Map(history.map((h) => [h.id, h])), [history]);
const metaFor = useCallback((clipId) => historyMap.get(clipId), [historyMap]);
const imageNames = useMemo(() => new Set(images.map((i) => i.filename)), [images]);
@@ -407,7 +191,7 @@ export default function VideoTimelineEditor() {
// from — the render would 404, so the editor flags it up front.
const isSegmentMissing = useCallback((seg) => (seg.type === 'still'
? !imageNames.has(seg.assetFile)
- : !metaFor(seg.clipId)), [imageNames, metaFor]);
+ : !historyMap.has(seg.clipId)), [imageNames, historyMap]);
const isOverlayMissing = useCallback((ov) => !imageNames.has(ov.assetFile), [imageNames]);
const isBedMissing = useCallback((tr) => tr.assetKind === 'music' && !musicNames.has(tr.assetFile), [musicNames]);
@@ -425,10 +209,10 @@ export default function VideoTimelineEditor() {
// and returns the canonical project; we only update updatedAt and preserve
// local _keys to avoid blowing away the dnd identity.
const saveTimeline = useCallback(async (next) => {
- if (!project) return false;
+ if (updatedAtRef.current == null) return false;
const updated = await api.updateTimelineProject(projectId, {
...timelinePatch(next),
- expectedUpdatedAt: project.updatedAt,
+ expectedUpdatedAt: updatedAtRef.current,
}, { silent: true }).catch((err) => {
if (err.code === 'CONFLICT') {
toast.error('Project was modified elsewhere — reloading');
@@ -439,9 +223,10 @@ export default function VideoTimelineEditor() {
return null;
});
if (!updated) return false;
+ updatedAtRef.current = updated.updatedAt;
setProject((p) => ({ ...p, updatedAt: updated.updatedAt }));
return true;
- }, [project, projectId, refresh]);
+ }, [projectId, refresh]);
// Debounced save: trim/fade edits fire many PATCHes per drag if we don't
// batch them. 400ms gives the user time to stop fiddling before we hit the
@@ -464,33 +249,31 @@ export default function VideoTimelineEditor() {
});
}, [queueSave]);
- const patchSegment = useCallback((key, patch) => {
- updateLanes((prev) => ({
- ...prev,
- segments: prev.segments.map((s) => (s._key === key ? { ...s, ...patch(s) } : s)),
- }));
+ // One patcher for every lane — `patch(entry)` returns the fields to merge.
+ const patchLane = useCallback((lane, key, patch) => {
+ updateLanes((prev) => withLaneEntries(
+ prev,
+ lane,
+ laneEntries(prev, lane).map((e) => (e._key === key ? { ...e, ...patch(e) } : e)),
+ ));
}, [updateLanes]);
- const patchOverlay = useCallback((key, patch) => {
- updateLanes((prev) => ({
- ...prev,
- overlays: prev.overlays.map((o) => (o._key === key ? { ...o, ...patch(o) } : o)),
- }));
+ const addToLane = useCallback((lane, entry) => {
+ updateLanes((prev) => withLaneEntries(prev, lane, [...laneEntries(prev, lane), entry]));
+ setSelection({ lane, key: entry._key });
}, [updateLanes]);
- const patchBed = useCallback((key, patch) => {
- updateLanes((prev) => ({
- ...prev,
- audio: { ...prev.audio, tracks: prev.audio.tracks.map((tr) => (tr._key === key ? { ...tr, ...patch(tr) } : tr)) },
- }));
+ const removeFromLane = useCallback((lane, key) => {
+ updateLanes((prev) => withLaneEntries(prev, lane, laneEntries(prev, lane).filter((e) => e._key !== key)));
+ setSelection((sel) => (sel && sel.key === key ? null : sel));
}, [updateLanes]);
- // --- Add / remove -----------------------------------------------------
+ // --- Add ---------------------------------------------------------------
- const addClip = (clip) => {
+ const addClip = useCallback((clip) => {
const fullDur = clip.numFrames && clip.fps ? clip.numFrames / clip.fps : 4;
- const next = {
- _key: laneKey(clip.id, segments.length),
+ addToLane('segment', {
+ _key: laneKey(clip.id, 0),
type: 'clip',
clipId: clip.id,
inSec: 0,
@@ -498,32 +281,35 @@ export default function VideoTimelineEditor() {
fadeInSec: 0,
fadeOutSec: 0,
volume: 1,
- };
- updateLanes((prev) => ({ ...prev, segments: [...prev.segments, next] }));
- setSelection({ lane: 'segment', key: next._key });
- };
+ });
+ }, [addToLane]);
- const addStill = (image) => {
- const next = {
- _key: laneKey('still', segments.length),
+ const addStill = useCallback((image) => {
+ addToLane('segment', {
+ _key: laneKey('still', 0),
type: 'still',
assetKind: 'images',
assetFile: image.filename,
durationSec: DEFAULT_STILL_SEC,
fadeInSec: 0,
fadeOutSec: 0,
- };
- updateLanes((prev) => ({ ...prev, segments: [...prev.segments, next] }));
- setSelection({ lane: 'segment', key: next._key });
- };
-
- const addOverlay = (image) => {
- const next = {
- _key: laneKey('ov', overlays.length),
+ });
+ }, [addToLane]);
+
+ // Overlays and beds land at the playhead — the user has already scrubbed to
+ // the moment they want them.
+ const playheadRef = useRef(0);
+ useEffect(() => { playheadRef.current = t; }, [t]);
+ const totalRef = useRef(0);
+ useEffect(() => { totalRef.current = total; }, [total]);
+
+ const addOverlay = useCallback((image) => {
+ addToLane('overlay', {
+ _key: laneKey('ov', 0),
type: 'image',
assetKind: 'images',
assetFile: image.filename,
- startSec: Math.min(t, Math.max(0, total - 0.1)),
+ startSec: Math.min(playheadRef.current, Math.max(0, totalRef.current - 0.1)),
durationSec: DEFAULT_OVERLAY_SEC,
x: 0.05,
y: 0.05,
@@ -531,39 +317,26 @@ export default function VideoTimelineEditor() {
opacity: 1,
fadeInSec: 0,
fadeOutSec: 0,
- };
- updateLanes((prev) => ({ ...prev, overlays: [...prev.overlays, next] }));
- setSelection({ lane: 'overlay', key: next._key });
- };
+ });
+ }, [addToLane]);
- const addBed = (track) => {
- const next = {
- _key: laneKey('bed', audio.tracks.length),
+ const addBed = useCallback((track) => {
+ addToLane('audio', {
+ _key: laneKey('bed', 0),
assetKind: 'music',
assetFile: track.filename,
- startSec: Math.min(t, Math.max(0, total - 0.1)),
+ startSec: Math.min(playheadRef.current, Math.max(0, totalRef.current - 0.1)),
offsetSec: 0,
// The client can't probe the file; the server clamps this down to the
// real duration when it renders.
- durationSec: Math.max(1, Math.min(DEFAULT_BED_SEC, total || DEFAULT_BED_SEC)),
+ durationSec: Math.max(1, Math.min(DEFAULT_BED_SEC, totalRef.current || DEFAULT_BED_SEC)),
volume: 0.6,
fadeInSec: 0,
fadeOutSec: 0,
- };
- updateLanes((prev) => ({ ...prev, audio: { ...prev.audio, tracks: [...prev.audio.tracks, next] } }));
- setSelection({ lane: 'audio', key: next._key });
- };
-
- const removeFromLane = (lane, key) => {
- updateLanes((prev) => {
- if (lane === 'overlay') return { ...prev, overlays: prev.overlays.filter((o) => o._key !== key) };
- if (lane === 'audio') return { ...prev, audio: { ...prev.audio, tracks: prev.audio.tracks.filter((tr) => tr._key !== key) } };
- return { ...prev, segments: prev.segments.filter((s) => s._key !== key) };
});
- setSelection((sel) => (sel && sel.key === key ? null : sel));
- };
+ }, [addToLane]);
- const onDragEnd = ({ active, over }) => {
+ const onDragEnd = useCallback(({ active, over }) => {
if (!over || active.id === over.id) return;
updateLanes((prev) => {
const oldIdx = prev.segments.findIndex((s) => s._key === active.id);
@@ -571,9 +344,9 @@ export default function VideoTimelineEditor() {
if (oldIdx === -1 || newIdx === -1) return prev;
return { ...prev, segments: arrayMove(prev.segments, oldIdx, newIdx) };
});
- };
+ }, [updateLanes]);
- // --- Preview ----------------------------------------------------------
+ // --- Preview -----------------------------------------------------------
// Playback: keep a single <video> element that follows project-time. On every
// rAF tick, advance `t` by elapsed wall-time; the sync effects below drive
@@ -600,31 +373,32 @@ export default function VideoTimelineEditor() {
return () => cancelAnimationFrame(rafRef.current);
}, [playing, total]);
- const active = useMemo(() => {
- if (segments.length === 0) return null;
- const { index, within } = findSegmentAt(segments, t);
- if (index < 0) return null;
- const segment = segments[index];
- return { index, within, segment, duration: segmentDuration(segment) };
- }, [segments, t]);
-
- // Sync the <video> element to project-time `t` whenever it changes. A still
- // segment has no video source — the effect parks the element so the <img>
- // below can take over the frame.
+ const { index: activeIndex, within: activeWithin } = useMemo(
+ () => (segments.length > 0 ? findSegmentAt(segments, t) : { index: -1, within: 0 }),
+ [segments, t],
+ );
+ const activeSegment = activeIndex >= 0 ? segments[activeIndex] : null;
+ // `within` advances every frame; the media-sync effects read it from a ref so
+ // they re-run on a segment CHANGE rather than once per animation frame.
+ const withinRef = useRef(0);
+ useEffect(() => { withinRef.current = activeWithin; }, [activeWithin]);
+
+ // Sync the <video> element to project-time whenever the active segment or the
+ // scrub position changes. A still segment has no video source — the effect
+ // parks the element so the <img> below takes over the frame.
useEffect(() => {
- if (!active) return;
const video = videoRef.current;
- if (!video) return;
- if (active.segment.type === 'still') {
+ if (!video || !activeSegment) return;
+ if (activeSegment.type === 'still') {
lastSrcRef.current = '';
- playSegmentIndexRef.current = active.index;
+ playSegmentIndexRef.current = activeIndex;
video.pause();
return;
}
- const meta = metaFor(active.segment.clipId);
+ const meta = metaFor(activeSegment.clipId);
if (!meta) return;
const src = `/data/videos/${meta.filename}`;
- const wantTime = active.segment.inSec + active.within;
+ const wantTime = activeSegment.inSec + withinRef.current;
if (lastSrcRef.current !== src) {
lastSrcRef.current = src;
video.src = src;
@@ -638,43 +412,57 @@ export default function VideoTimelineEditor() {
video.currentTime = wantTime;
if (playingRef.current) video.play().catch(() => {});
};
- } else if (active.index !== playSegmentIndexRef.current) {
+ } else if (activeIndex !== playSegmentIndexRef.current) {
video.currentTime = wantTime;
} else if (!playing && Math.abs(video.currentTime - wantTime) > 0.05) {
- // Scrubbing while paused or moving the playhead within the same segment:
- // the rAF loop only fires while playing, so we need to drive the element
- // manually. During playback the video element advances on its own —
- // re-seeking on every rAF tick would cause buffering stutter.
+ // Scrubbing while paused: the rAF loop only runs while playing, so we
+ // drive the element manually. During playback the element advances on its
+ // own — re-seeking every frame would cause buffering stutter.
video.currentTime = wantTime;
}
- playSegmentIndexRef.current = active.index;
- }, [active, metaFor, playing]);
+ playSegmentIndexRef.current = activeIndex;
+ }, [activeSegment, activeIndex, activeWithin, metaFor, playing]);
// Pause/play the underlying element in lockstep with `playing`. A still
// segment holds no video, so there is nothing to start.
useEffect(() => {
const video = videoRef.current;
if (!video) return;
- if (playing && active?.segment.type !== 'still') video.play().catch(() => {});
+ if (playing && activeSegment?.type !== 'still') video.play().catch(() => {});
else video.pause();
- }, [playing, active?.segment.type]);
-
+ }, [playing, activeSegment?.type]);
+
+ // The clip lane's own audio level — clipVolume × the segment's volume × its
+ // fade ramp, the same product the export builds into each segment's chain.
+ // Without this the user ducks the dialogue, hears no change while auditioning,
+ // and gets a different mix out of the render.
+ const clipVolume = audio.clipVolume;
+ const activeClipVolume = segmentVolumeAt(activeSegment, clipVolume, activeWithin);
useEffect(() => {
const video = videoRef.current;
- if (video) video.muted = muted;
- }, [muted]);
+ if (!video) return;
+ if (video.muted !== muted) video.muted = muted;
+ // Only correct real drift — a media property write per frame queues a
+ // `volumechange` event per frame for no audible gain.
+ if (Math.abs(video.volume - activeClipVolume) > 0.01) video.volume = activeClipVolume;
+ }, [muted, activeClipVolume]);
// Drive the bed <audio> elements from the same playhead the export mixes
// against, so what the user hears while scrubbing is what amix will produce.
+ const setBedRef = useCallback((key) => (el) => {
+ if (el) bedRefs.current.set(key, el);
+ else bedRefs.current.delete(key);
+ }, []);
useEffect(() => {
for (const track of audio.tracks) {
const el = bedRefs.current.get(track._key);
if (!el) continue;
const state = audioTrackStateAt(track, t);
- el.muted = muted;
+ if (el.muted !== muted) el.muted = muted;
// clipVolume scales the video lane's OWN audio, not the bed — the export
// applies it inside each segment's chain, before amix.
- el.volume = Math.min(1, Math.max(0, state.volume));
+ const want = clamp(state.volume, 0, 1);
+ if (Math.abs(el.volume - want) > 0.01) el.volume = want;
if (!state.active) {
if (!el.paused) el.pause();
continue;
@@ -693,7 +481,7 @@ export default function VideoTimelineEditor() {
return () => { for (const el of els.values()) el?.pause(); };
}, []);
- // --- Render -----------------------------------------------------------
+ // --- Render ------------------------------------------------------------
const handleRender = async () => {
if (segments.length === 0) {
@@ -719,27 +507,23 @@ export default function VideoTimelineEditor() {
toast.error(`Render failed: ${err.message}`);
return null;
});
- if (result?.jobId) {
- setRenderJobId(result.jobId);
- setRenderProgress(0);
- }
+ if (result?.jobId) setRenderJobId(result.jobId);
};
// SSE progress wiring — subscribes to the render jobId's event stream (via
- // the shared useSseProgress lifecycle), updates the progress bar, and on
- // 'complete' navigates to Media History focused on the new clip. Frame
- // shapes come from server/services/videoTimeline/local.js
- // (progress / complete / error / canceled).
+ // the shared useSseProgress lifecycle) and, on 'complete', navigates to Media
+ // History focused on the new clip. Frame shapes come from
+ // server/services/videoTimeline/local.js (progress / complete / error / canceled).
const { latest: renderFrame, closed: renderStreamClosed } = useSseProgress(
renderJobId ? `/api/video-timeline/${renderJobId}/events` : null,
{ enabled: !!renderJobId },
);
+ // Derived, not stored: a terminal frame isn't type 'progress', so the reset to
+ // zero on complete/error/cancel falls out for free.
+ const renderProgress = renderFrame?.type === 'progress' ? renderFrame.progress : 0;
useEffect(() => {
if (!renderJobId || !renderFrame) return;
- if (renderFrame.type === 'progress') {
- setRenderProgress(renderFrame.progress);
- return;
- }
+ if (renderFrame.type === 'progress') return;
// A genuine terminal frame sets `latest` and `closed` in the same commit,
// so they're visible together here. A STALE terminal frame — the hook
// keeps `latest` across the disabled gap, so starting a second render
@@ -758,7 +542,6 @@ export default function VideoTimelineEditor() {
// canceled (either spelling — the hook treats both as terminal)
toast('Render cancelled');
setRenderJobId(null);
- setRenderProgress(0);
}
}, [renderJobId, renderFrame, renderStreamClosed, navigate]);
useEffect(() => {
@@ -768,9 +551,41 @@ export default function VideoTimelineEditor() {
if (isTerminalSseFrame(renderFrame)) return;
toast.error('Lost connection to render — check Media History');
setRenderJobId(null);
- setRenderProgress(0);
}, [renderJobId, renderStreamClosed, renderFrame]);
+ // --- Derived view data -------------------------------------------------
+
+ // Filter the library: hide outputs of any timeline render so the rail
+ // doesn't grow unbounded with the user's own renders.
+ const libraryClips = useMemo(
+ () => history.filter((h) => !h.timelineProjectId && !h.hidden),
+ [history],
+ );
+ const usedClipIds = useMemo(
+ () => new Set(segments.filter((s) => s.type === 'clip').map((s) => s.clipId)),
+ [segments],
+ );
+ const segmentKeys = useMemo(() => segments.map((s) => s._key), [segments]);
+ // Everything about an overlay except its opacity is frame-invariant; only the
+ // opacity is recomputed as the playhead moves.
+ const overlayChrome = useMemo(() => overlays.map((ov) => ({
+ key: ov._key,
+ src: assetUrl(ov.assetKind, ov.assetFile),
+ left: `${(ov.x || 0) * 100}%`,
+ top: `${(ov.y || 0) * 100}%`,
+ width: `${(ov.width || 0.25) * 100}%`,
+ overlay: ov,
+ })), [overlays]);
+
+ const selectSegment = useCallback((key) => setSelection({ lane: 'segment', key }), []);
+ const removeSegment = useCallback((key) => removeFromLane('segment', key), [removeFromLane]);
+ const selectOverlay = useCallback((key) => setSelection({ lane: 'overlay', key }), []);
+ const removeOverlay = useCallback((key) => removeFromLane('overlay', key), [removeFromLane]);
+ const selectBed = useCallback((key) => setSelection({ lane: 'audio', key }), []);
+ const removeBed = useCallback((key) => removeFromLane('audio', key), [removeFromLane]);
+ const overlayLabel = useCallback((ov) => ov.assetFile, []);
+ const bedLabel = useCallback((tr) => tr.assetFile, []);
+
if (loading) return <div className="text-gray-500 text-sm">Loading project…</div>;
if (error || !project) {
return (
@@ -787,27 +602,33 @@ export default function VideoTimelineEditor() {
);
}
- const selectedSegment = selection?.lane === 'segment' ? segments.find((s) => s._key === selection.key) : null;
- const selectedOverlay = selection?.lane === 'overlay' ? overlays.find((o) => o._key === selection.key) : null;
- const selectedBed = selection?.lane === 'audio' ? audio.tracks.find((tr) => tr._key === selection.key) : null;
+ const selected = selection ? laneEntries(lanes, selection.lane)?.find((e) => e._key === selection.key) : null;
+ const selectedSegment = selection?.lane === 'segment' ? selected : null;
+ const selectedOverlay = selection?.lane === 'overlay' ? selected : null;
+ const selectedBed = selection?.lane === 'audio' ? selected : null;
const selectedMeta = selectedSegment?.type === 'clip' ? metaFor(selectedSegment.clipId) : null;
const selectedSourceDur = selectedMeta?.numFrames && selectedMeta?.fps ? selectedMeta.numFrames / selectedMeta.fps : null;
- // Filter the library: hide outputs of any timeline render so the rail
- // doesn't grow unbounded with the user's own renders.
- const libraryClips = history.filter((h) => !h.timelineProjectId && !h.hidden);
- const usedClipIds = new Set(segments.filter((s) => s.type === 'clip').map((s) => s.clipId));
+ // Committing a duration also has to refit the fades that were sized against
+ // the old one, so the three lanes share one commit path.
+ const commitDuration = (lane, key, seconds) => patchLane(lane, key, (e) => fitFadePatch(e, { durationSec: seconds }, seconds));
- const activeStillSrc = active?.segment.type === 'still'
- ? assetUrl(active.segment.assetKind, active.segment.assetFile)
+ const activeStillSrc = activeSegment?.type === 'still'
+ ? assetUrl(activeSegment.assetKind, activeSegment.assetFile)
: null;
// The same linear ramp ffmpeg's `fade` applies, rendered as a black scrim so
// the preview shows the cut the export will make.
- const activeFadeScrim = active
- ? 1 - fadeMultiplier(active.segment.fadeInSec || 0, active.segment.fadeOutSec || 0, active.duration, active.within)
+ const activeFadeScrim = activeSegment
+ ? 1 - fadeMultiplier(
+ activeSegment.fadeInSec || 0,
+ activeSegment.fadeOutSec || 0,
+ segmentDuration(activeSegment),
+ activeWithin,
+ )
: 0;
const laneWidth = Math.max(240, total * pxPerSec);
+ const playheadSec = Math.min(t, total);
return (
<div className="space-y-3">
@@ -831,13 +652,14 @@ export default function VideoTimelineEditor() {
if (!trimmed) { setNameDraft(project.name); return; }
if (trimmed === project.name) return;
const updated = await api.updateTimelineProject(projectId, {
- name: trimmed, expectedUpdatedAt: project.updatedAt,
+ name: trimmed, expectedUpdatedAt: updatedAtRef.current,
}, { silent: true }).catch((err) => {
toast.error(`Rename failed: ${err.message}`);
setNameDraft(project.name);
return null;
});
if (updated) {
+ updatedAtRef.current = updated.updatedAt;
setProject((p) => ({ ...p, name: updated.name, updatedAt: updated.updatedAt }));
setNameDraft(updated.name);
}
@@ -873,11 +695,7 @@ export default function VideoTimelineEditor() {
{showLibrary && (
<div className="bg-port-card/50 border border-port-border rounded-lg p-2 max-h-[600px] overflow-y-auto">
<div className="flex gap-1 mb-2" role="tablist" aria-label="Clip library">
- {[
- { id: 'clips', label: 'Clips', Icon: Film },
- { id: 'stills', label: 'Stills', Icon: ImageIcon },
- { id: 'audio', label: 'Audio', Icon: Music },
- ].map(({ id, label, Icon }) => (
+ {LIBRARY_TABS.map(({ id, label, Icon }) => (
<button
key={id}
type="button"
@@ -942,28 +760,20 @@ export default function VideoTimelineEditor() {
<img src={activeStillSrc} alt="" className="absolute inset-0 w-full h-full object-contain" />
)}
{/* Overlay lane, composited exactly as ffmpeg will: normalized
- position/width against the canvas, alpha from the same ramp. */}
- {overlays.map((ov) => {
- const opacity = overlayOpacityAt(ov, t);
- if (opacity <= 0) return null;
- const src = assetUrl(ov.assetKind, ov.assetFile);
- if (!src) return null;
- return (
- <img
- key={ov._key}
- src={src}
- alt=""
- data-testid="overlay-preview"
- style={{
- left: `${(ov.x || 0) * 100}%`,
- top: `${(ov.y || 0) * 100}%`,
- width: `${(ov.width || 0.25) * 100}%`,
- opacity,
- }}
- className="absolute pointer-events-none"
- />
- );
- })}
+ position/width against the canvas, alpha from the same ramp.
+ Every overlay stays MOUNTED and rides its opacity to zero —
+ unmounting at the window edge would re-decode the image on each
+ boundary crossing while scrubbing. */}
+ {overlayChrome.map(({ key, src, left, top, width, overlay }) => (src ? (
+ <img
+ key={key}
+ src={src}
+ alt=""
+ data-testid="overlay-preview"
+ style={{ left, top, width, opacity: overlayOpacityAt(overlay, t) }}
+ className="absolute pointer-events-none"
+ />
+ ) : null))}
{activeFadeScrim > 0 && (
<div
data-testid="fade-scrim"
@@ -986,10 +796,7 @@ export default function VideoTimelineEditor() {
return (
<audio
key={track._key}
- ref={(el) => {
- if (el) bedRefs.current.set(track._key, el);
- else bedRefs.current.delete(track._key);
- }}
+ ref={setBedRef(track._key)}
src={src}
preload="auto"
className="hidden"
@@ -1021,7 +828,7 @@ export default function VideoTimelineEditor() {
min={0}
max={Math.max(0.01, total)}
step={0.01}
- value={Math.min(t, total)}
+ value={playheadSec}
onChange={(e) => { setPlaying(false); setT(Number(e.target.value)); }}
className="flex-1"
disabled={segments.length === 0}
@@ -1052,7 +859,7 @@ export default function VideoTimelineEditor() {
<>
<div className="text-[9px] uppercase tracking-wide text-gray-600 px-0.5">Video</div>
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>
- <SortableContext items={segments.map((s) => s._key)} strategy={horizontalListSortingStrategy}>
+ <SortableContext items={segmentKeys} strategy={horizontalListSortingStrategy}>
<div className="flex gap-1 items-stretch min-w-min py-1">
{segments.map((segment) => (
<TimelineBlock
@@ -1062,70 +869,43 @@ export default function VideoTimelineEditor() {
isSelected={selection?.lane === 'segment' && segment._key === selection.key}
isMissing={isSegmentMissing(segment)}
pxPerSec={pxPerSec}
- onSelect={(key) => setSelection({ lane: 'segment', key })}
- onRemove={(key) => removeFromLane('segment', key)}
+ onSelect={selectSegment}
+ onRemove={removeSegment}
/>
))}
</div>
</SortableContext>
</DndContext>
- <div className="text-[9px] uppercase tracking-wide text-gray-600 px-0.5 pt-1">Overlays</div>
- <div className="relative h-8 bg-port-bg/40 rounded" style={{ width: `${laneWidth}px` }}>
- {overlays.length === 0 && (
- <span className="absolute inset-0 flex items-center pl-2 text-[10px] text-gray-600">
- Add an overlay from the Stills tab
- </span>
- )}
- {overlays.map((ov) => (
- <LaneBlock
- key={ov._key}
- entry={ov}
- label={ov.assetFile}
- tone="bg-port-accent/15 border-port-accent/40"
- isSelected={selection?.lane === 'overlay' && ov._key === selection.key}
- isMissing={isOverlayMissing(ov)}
- pxPerSec={pxPerSec}
- onSelect={(key) => setSelection({ lane: 'overlay', key })}
- onRemove={(key) => removeFromLane('overlay', key)}
- />
- ))}
- <div
- data-testid="lane-playhead"
- aria-hidden="true"
- style={{ left: `${Math.min(t, total) * pxPerSec}px` }}
- className="absolute inset-y-0 w-px bg-port-accent pointer-events-none"
- />
- </div>
-
- <div className="text-[9px] uppercase tracking-wide text-gray-600 px-0.5 pt-1">Audio</div>
- <div className="relative h-8 bg-port-bg/40 rounded" style={{ width: `${laneWidth}px` }}>
- {audio.tracks.length === 0 && (
- <span className="absolute inset-0 flex items-center pl-2 text-[10px] text-gray-600">
- Add a bed from the Audio tab
- </span>
- )}
- {audio.tracks.map((track) => (
- <LaneBlock
- key={track._key}
- entry={track}
- label={track.assetFile}
- tone="bg-port-success/15 border-port-success/40"
- isSelected={selection?.lane === 'audio' && track._key === selection.key}
- isMissing={isBedMissing(track)}
- pxPerSec={pxPerSec}
- onSelect={(key) => setSelection({ lane: 'audio', key })}
- onRemove={(key) => removeFromLane('audio', key)}
- />
- ))}
- <div
- data-testid="lane-playhead"
- aria-hidden="true"
- style={{ left: `${Math.min(t, total) * pxPerSec}px` }}
- className="absolute inset-y-0 w-px bg-port-accent pointer-events-none"
- />
- </div>
+ <FloatingLane
+ title="Overlays"
+ entries={overlays}
+ emptyHint="Add an overlay from the Stills tab"
+ tone="bg-port-accent/15 border-port-accent/40"
+ labelOf={overlayLabel}
+ isMissing={isOverlayMissing}
+ selectedKey={selection?.lane === 'overlay' ? selection.key : null}
+ pxPerSec={pxPerSec}
+ width={laneWidth}
+ playheadSec={playheadSec}
+ onSelect={selectOverlay}
+ onRemove={removeOverlay}
+ />
+ <FloatingLane
+ title="Audio"
+ entries={audio.tracks}
+ emptyHint="Add a bed from the Audio tab"
+ tone="bg-port-success/15 border-port-success/40"
+ labelOf={bedLabel}
+ isMissing={isBedMissing}
+ selectedKey={selection?.lane === 'audio' ? selection.key : null}
+ pxPerSec={pxPerSec}
+ width={laneWidth}
+ playheadSec={playheadSec}
+ onSelect={selectBed}
+ onRemove={removeBed}
+ />
</>
)}
</div>
@@ -1135,39 +915,33 @@ export default function VideoTimelineEditor() {
<div className="bg-port-card/50 border border-port-border rounded-lg p-3 space-y-3">
<div className="text-xs uppercase text-gray-500 tracking-wide">Inspector</div>
- {!selection && (
+ {!selected && (
<div className="text-xs text-gray-500">Select a block on the timeline to edit it.</div>
)}
{selectedSegment && isSegmentMissing(selectedSegment) && (
<div className="text-xs text-port-error space-y-2">
<p>Source missing — it may have been deleted from the gallery. Remove this block from the timeline.</p>
- <button
- type="button"
- onClick={() => removeFromLane('segment', selectedSegment._key)}
- className="w-full px-2 py-1.5 bg-port-error/20 hover:bg-port-error/40 text-port-error text-xs rounded flex items-center justify-center gap-1"
- >
- <Trash2 className="w-3 h-3" /> Remove
- </button>
+ <RemoveButton label="Remove" onClick={() => removeSegment(selectedSegment._key)} />
</div>
)}
{selectedSegment && !isSegmentMissing(selectedSegment) && selectedSegment.type === 'clip' && (
<>
{selectedMeta?.thumbnail && (
- <img src={`/data/video-thumbnails/${selectedMeta.thumbnail}`} alt="" className="w-full aspect-video object-cover rounded" />
+ <img src={assetUrl('video-thumbnails', selectedMeta.thumbnail)} alt="" className="w-full aspect-video object-cover rounded" />
)}
<div className="text-[11px] text-gray-300 line-clamp-3" title={selectedMeta?.prompt}>{selectedMeta?.prompt}</div>
<div className="text-[10px] text-gray-500">
source: {selectedSourceDur?.toFixed(2) ?? '?'}s · {selectedMeta?.width}×{selectedMeta?.height} · {selectedMeta?.fps}fps
</div>
<NumberField
- id="segment-in" label="In (s)" value={selectedSegment.inSec} min={0} max={selectedSourceDur || undefined}
- onCommit={(n) => patchSegment(selectedSegment._key, (s) => clampTrim(s, { inSec: n }, selectedSourceDur, selectedMeta?.fps))}
+ id="segment-in" label="In (s)" value={selectedSegment.inSec} max={selectedSourceDur ?? undefined}
+ onCommit={(n) => patchLane('segment', selectedSegment._key, (s) => clampTrim(s, { inSec: n }, selectedSourceDur, selectedMeta?.fps))}
/>
<NumberField
- id="segment-out" label="Out (s)" value={selectedSegment.outSec} min={0} max={selectedSourceDur || undefined}
- onCommit={(n) => patchSegment(selectedSegment._key, (s) => clampTrim(s, { outSec: n }, selectedSourceDur, selectedMeta?.fps))}
+ id="segment-out" label="Out (s)" value={selectedSegment.outSec} max={selectedSourceDur ?? undefined}
+ onCommit={(n) => patchLane('segment', selectedSegment._key, (s) => clampTrim(s, { outSec: n }, selectedSourceDur, selectedMeta?.fps))}
/>
<div className="text-[10px] text-gray-500">
trimmed: {segmentDuration(selectedSegment).toFixed(2)}s
@@ -1176,13 +950,13 @@ export default function VideoTimelineEditor() {
idPrefix="segment"
entry={selectedSegment}
duration={segmentDuration(selectedSegment)}
- onCommit={(patch) => patchSegment(selectedSegment._key, (s) => fitFadePatch(s, patch, segmentDuration(s)))}
+ onCommit={(patch) => patchLane('segment', selectedSegment._key, (s) => fitFadePatch(s, patch, segmentDuration(s)))}
/>
<NumberField
- id="segment-volume" label="Volume (×)" value={selectedSegment.volume ?? 1} step={0.05} min={0} max={4}
- onCommit={(n) => patchSegment(selectedSegment._key, () => ({ volume: clamp(n, 0, 4) }))}
+ id="segment-volume" label="Volume (×)" value={selectedSegment.volume ?? 1} max={MAX_VOLUME}
+ onCommit={(n) => patchLane('segment', selectedSegment._key, () => ({ volume: n }))}
/>
- <RemoveButton label="Remove from timeline" onClick={() => removeFromLane('segment', selectedSegment._key)} />
+ <RemoveButton label="Remove from timeline" onClick={() => removeSegment(selectedSegment._key)} />
</>
)}
@@ -1191,16 +965,16 @@ export default function VideoTimelineEditor() {
<img src={assetUrl(selectedSegment.assetKind, selectedSegment.assetFile)} alt="" className="w-full aspect-video object-cover rounded" />
<div className="text-[11px] text-gray-300 truncate" title={selectedSegment.assetFile}>{selectedSegment.assetFile}</div>
<NumberField
- id="still-duration" label="Hold (s)" value={selectedSegment.durationSec} min={0.05} max={600}
- onCommit={(n) => patchSegment(selectedSegment._key, (s) => fitFadePatch(s, { durationSec: clamp(n, 0.05, 600) }, clamp(n, 0.05, 600)))}
+ id="still-duration" label="Hold (s)" value={selectedSegment.durationSec} min={MIN_ENTRY_SEC} max={MAX_ENTRY_SEC}
+ onCommit={(n) => commitDuration('segment', selectedSegment._key, n)}
/>
<FadeFields
idPrefix="still"
entry={selectedSegment}
duration={segmentDuration(selectedSegment)}
- onCommit={(patch) => patchSegment(selectedSegment._key, (s) => fitFadePatch(s, patch, segmentDuration(s)))}
+ onCommit={(patch) => patchLane('segment', selectedSegment._key, (s) => fitFadePatch(s, patch, segmentDuration(s)))}
/>
- <RemoveButton label="Remove from timeline" onClick={() => removeFromLane('segment', selectedSegment._key)} />
+ <RemoveButton label="Remove from timeline" onClick={() => removeSegment(selectedSegment._key)} />
</>
)}
@@ -1208,27 +982,27 @@ export default function VideoTimelineEditor() {
<>
<img src={assetUrl(selectedOverlay.assetKind, selectedOverlay.assetFile)} alt="" className="w-full aspect-video object-contain rounded bg-port-bg" />
<div className="text-[11px] text-gray-300 truncate" title={selectedOverlay.assetFile}>{selectedOverlay.assetFile}</div>
- <NumberField id="overlay-start" label="Start (s)" value={selectedOverlay.startSec} min={0}
- onCommit={(n) => patchOverlay(selectedOverlay._key, () => ({ startSec: Math.max(0, n) }))} />
- <NumberField id="overlay-duration" label="Duration (s)" value={selectedOverlay.durationSec} min={0.05} max={600}
- onCommit={(n) => patchOverlay(selectedOverlay._key, (o) => fitFadePatch(o, { durationSec: clamp(n, 0.05, 600) }, clamp(n, 0.05, 600)))} />
+ <NumberField id="overlay-start" label="Start (s)" value={selectedOverlay.startSec}
+ onCommit={(n) => patchLane('overlay', selectedOverlay._key, () => ({ startSec: n }))} />
+ <NumberField id="overlay-duration" label="Duration (s)" value={selectedOverlay.durationSec} min={MIN_ENTRY_SEC} max={MAX_ENTRY_SEC}
+ onCommit={(n) => commitDuration('overlay', selectedOverlay._key, n)} />
<div className="grid grid-cols-2 gap-2">
<NumberField id="overlay-x" label="X (0–1)" value={selectedOverlay.x ?? 0} step={0.01} min={-1} max={2}
- onCommit={(n) => patchOverlay(selectedOverlay._key, () => ({ x: clamp(n, -1, 2) }))} />
+ onCommit={(n) => patchLane('overlay', selectedOverlay._key, () => ({ x: n }))} />
<NumberField id="overlay-y" label="Y (0–1)" value={selectedOverlay.y ?? 0} step={0.01} min={-1} max={2}
- onCommit={(n) => patchOverlay(selectedOverlay._key, () => ({ y: clamp(n, -1, 2) }))} />
+ onCommit={(n) => patchLane('overlay', selectedOverlay._key, () => ({ y: n }))} />
</div>
<NumberField id="overlay-width" label="Width (× canvas)" value={selectedOverlay.width ?? 0.25} step={0.01} min={0.01} max={4}
- onCommit={(n) => patchOverlay(selectedOverlay._key, () => ({ width: clamp(n, 0.01, 4) }))} />
- <NumberField id="overlay-opacity" label="Opacity (0–1)" value={selectedOverlay.opacity ?? 1} step={0.05} min={0} max={1}
- onCommit={(n) => patchOverlay(selectedOverlay._key, () => ({ opacity: clamp(n, 0, 1) }))} />
+ onCommit={(n) => patchLane('overlay', selectedOverlay._key, () => ({ width: n }))} />
+ <NumberField id="overlay-opacity" label="Opacity (0–1)" value={selectedOverlay.opacity ?? 1} max={1}
+ onCommit={(n) => patchLane('overlay', selectedOverlay._key, () => ({ opacity: n }))} />
<FadeFields
idPrefix="overlay"
entry={selectedOverlay}
duration={selectedOverlay.durationSec}
- onCommit={(patch) => patchOverlay(selectedOverlay._key, (o) => fitFadePatch(o, patch, o.durationSec))}
+ onCommit={(patch) => patchLane('overlay', selectedOverlay._key, (o) => fitFadePatch(o, patch, o.durationSec))}
/>
- <RemoveButton label="Remove overlay" onClick={() => removeFromLane('overlay', selectedOverlay._key)} />
+ <RemoveButton label="Remove overlay" onClick={() => removeOverlay(selectedOverlay._key)} />
</>
)}
@@ -1238,23 +1012,23 @@ export default function VideoTimelineEditor() {
<Music className="w-3 h-3 text-gray-500" aria-hidden="true" />
<span className="truncate" title={selectedBed.assetFile}>{selectedBed.assetFile}</span>
</div>
- <NumberField id="bed-start" label="Start (s)" value={selectedBed.startSec} min={0}
- onCommit={(n) => patchBed(selectedBed._key, () => ({ startSec: Math.max(0, n) }))} />
- <NumberField id="bed-offset" label="Source offset (s)" value={selectedBed.offsetSec ?? 0} min={0}
+ <NumberField id="bed-start" label="Start (s)" value={selectedBed.startSec}
+ onCommit={(n) => patchLane('audio', selectedBed._key, () => ({ startSec: n }))} />
+ <NumberField id="bed-offset" label="Source offset (s)" value={selectedBed.offsetSec ?? 0}
hint="Where playback starts inside the file"
- onCommit={(n) => patchBed(selectedBed._key, () => ({ offsetSec: Math.max(0, n) }))} />
- <NumberField id="bed-duration" label="Duration (s)" value={selectedBed.durationSec} min={0.05} max={600}
+ onCommit={(n) => patchLane('audio', selectedBed._key, () => ({ offsetSec: n }))} />
+ <NumberField id="bed-duration" label="Duration (s)" value={selectedBed.durationSec} min={MIN_ENTRY_SEC} max={MAX_ENTRY_SEC}
hint="Clamped to the file's real length at render"
- onCommit={(n) => patchBed(selectedBed._key, (tr) => fitFadePatch(tr, { durationSec: clamp(n, 0.05, 600) }, clamp(n, 0.05, 600)))} />
- <NumberField id="bed-volume" label="Volume (×)" value={selectedBed.volume ?? 1} step={0.05} min={0} max={4}
- onCommit={(n) => patchBed(selectedBed._key, () => ({ volume: clamp(n, 0, 4) }))} />
+ onCommit={(n) => commitDuration('audio', selectedBed._key, n)} />
+ <NumberField id="bed-volume" label="Volume (×)" value={selectedBed.volume ?? 1} max={MAX_VOLUME}
+ onCommit={(n) => patchLane('audio', selectedBed._key, () => ({ volume: n }))} />
<FadeFields
idPrefix="bed"
entry={selectedBed}
duration={selectedBed.durationSec}
- onCommit={(patch) => patchBed(selectedBed._key, (tr) => fitFadePatch(tr, patch, tr.durationSec))}
+ onCommit={(patch) => patchLane('audio', selectedBed._key, (tr) => fitFadePatch(tr, patch, tr.durationSec))}
/>
- <RemoveButton label="Remove bed" onClick={() => removeFromLane('audio', selectedBed._key)} />
+ <RemoveButton label="Remove bed" onClick={() => removeBed(selectedBed._key)} />
</>
)}
@@ -1262,12 +1036,10 @@ export default function VideoTimelineEditor() {
<NumberField
id="mix-clip-volume"
label="Clip audio (×)"
- value={audio.clipVolume ?? 1}
- step={0.05}
- min={0}
- max={4}
+ value={clipVolume ?? 1}
+ max={MAX_VOLUME}
hint="Scales every video segment's own audio"
- onCommit={(n) => updateLanes((prev) => ({ ...prev, audio: { ...prev.audio, clipVolume: clamp(n, 0, 4) } }))}
+ onCommit={(n) => updateLanes((prev) => ({ ...prev, audio: { ...prev.audio, clipVolume: n } }))}
/>
</div>
</div>
@@ -1275,58 +1047,3 @@ export default function VideoTimelineEditor() {
</div>
);
}
-
-// --- Small shared pieces ------------------------------------------------
-
-export const clamp = (n, min, max) => Math.min(max, Math.max(min, n));
-
-// Clamp a trim edit to 0..sourceDuration, matching the server's CLIP_TOO_SHORT
-// guard (1/fps). A hardcoded floor was too lenient at 24fps and let the UI
-// build a project the render then rejected with 400.
-export function clampTrim(segment, patch, sourceDur, fps) {
- const limit = sourceDur || Infinity;
- const minDur = fps && fps > 0 ? 1 / fps : 0.04;
- let inSec = patch.inSec != null ? patch.inSec : segment.inSec;
- let outSec = patch.outSec != null ? patch.outSec : segment.outSec;
- inSec = Math.max(0, Math.min(inSec, limit - minDur));
- outSec = Math.max(inSec + minDur, Math.min(outSec, limit));
- return fitFadePatch(segment, { inSec, outSec }, outSec - inSec);
-}
-
-// The server refuses a fade pair that outlasts its own duration, so shrink the
-// OTHER fade rather than letting the PATCH 400 mid-edit.
-export function fitFadePatch(entry, patch, duration) {
- const merged = { ...entry, ...patch };
- const fin = Math.max(0, merged.fadeInSec || 0);
- const fout = Math.max(0, merged.fadeOutSec || 0);
- if (fin + fout <= duration) return patch;
- const scale = fin + fout > 0 ? Math.max(0, duration) / (fin + fout) : 0;
- return { ...patch, fadeInSec: fin * scale, fadeOutSec: fout * scale };
-}
-
-function FadeFields({ idPrefix, entry, duration, onCommit }) {
- return (
- <div className="grid grid-cols-2 gap-2">
- <NumberField
- id={`${idPrefix}-fade-in`} label="Fade in (s)" value={entry.fadeInSec ?? 0} step={0.05} min={0} max={duration}
- onCommit={(n) => onCommit({ fadeInSec: clamp(n, 0, Math.max(0, duration)) })}
- />
- <NumberField
- id={`${idPrefix}-fade-out`} label="Fade out (s)" value={entry.fadeOutSec ?? 0} step={0.05} min={0} max={duration}
- onCommit={(n) => onCommit({ fadeOutSec: clamp(n, 0, Math.max(0, duration)) })}
- />
- </div>
- );
-}
-
-function RemoveButton({ label, onClick }) {
- return (
- <button
- type="button"
- onClick={onClick}
- className="w-full px-2 py-1.5 bg-port-error/20 hover:bg-port-error/40 text-port-error text-xs rounded flex items-center justify-center gap-1"
- >
- <Trash2 className="w-3 h-3" /> {label}
- </button>
- );
-}
diff --git a/scripts/migrations/295-video-timeline-segments.js b/scripts/migrations/295-video-timeline-segments.js
index 681e70d7cc..11cab2ae4e 100644
--- a/scripts/migrations/295-video-timeline-segments.js
+++ b/scripts/migrations/295-video-timeline-segments.js
@@ -9,47 +9,22 @@
* The service normalizes on every read too, so this migration is not strictly
* required for correctness. It exists so the on-disk file matches what the app
* writes: without it, a project the user never re-saves keeps its v1 shape
- * forever, and a backup/restore or a peer-copied file carries the old layout
- * around indefinitely.
+ * forever, and a backup/restore carries the old layout around indefinitely.
+ * That is also why the upgrade itself is `normalizeProject` from the service
+ * rather than a copy — a second implementation would drift, and the read-time
+ * normalizer would silently paper over the difference.
*
* `clips` is deliberately RETAINED as a derived mirror of the clip segments —
* an install rolled back to a v1 build still renders its video lane instead of
* opening an empty project. Idempotent: a project already at schemaVersion 2
- * with a matching mirror is left untouched.
+ * with a lane array is left untouched.
*/
import { existsSync } from 'fs';
import { readFile } from 'fs/promises';
import { join } from 'path';
import { writeJsonAtomic } from './_lib.js';
-
-const SCHEMA_VERSION = 2;
-
-const num = (value, fallback = 0) => {
- const n = Number(value);
- return Number.isFinite(n) ? n : fallback;
-};
-
-const deriveClips = (segments) => segments
- .filter((s) => s.type === 'clip')
- .map((s) => ({ clipId: s.clipId, inSec: s.inSec, outSec: s.outSec }));
-
-// A v1 clip entry only carries clipId/inSec/outSec; everything the lane model
-// adds gets its neutral default so the upgraded project renders identically.
-const upgradeClip = (raw) => {
- const inSec = Math.max(0, num(raw.inSec, 0));
- const outSec = num(raw.outSec, NaN);
- if (!Number.isFinite(outSec) || outSec <= inSec) return null;
- return {
- type: 'clip',
- clipId: String(raw.clipId || ''),
- inSec,
- outSec,
- fadeInSec: 0,
- fadeOutSec: 0,
- volume: 1,
- };
-};
+import { normalizeProject, TIMELINE_SCHEMA_VERSION } from '../../server/services/videoTimeline/segments.js';
export default {
async up({ rootDir }) {
@@ -73,24 +48,9 @@ export default {
let updated = 0;
const next = projects.map((project) => {
if (!project || typeof project !== 'object') return project;
- if (project.schemaVersion === SCHEMA_VERSION && Array.isArray(project.segments)) return project;
-
- const legacyClips = Array.isArray(project.clips) ? project.clips : [];
- const segments = Array.isArray(project.segments)
- ? project.segments
- : legacyClips.map(upgradeClip).filter(Boolean);
-
+ if (project.schemaVersion === TIMELINE_SCHEMA_VERSION && Array.isArray(project.segments)) return project;
updated += 1;
- return {
- ...project,
- schemaVersion: SCHEMA_VERSION,
- segments,
- overlays: Array.isArray(project.overlays) ? project.overlays : [],
- audio: project.audio && typeof project.audio === 'object' && !Array.isArray(project.audio)
- ? { clipVolume: num(project.audio.clipVolume, 1), tracks: Array.isArray(project.audio.tracks) ? project.audio.tracks : [] }
- : { clipVolume: 1, tracks: [] },
- clips: deriveClips(segments),
- };
+ return normalizeProject(project);
});
if (!updated) return { ok: true, reason: 'already-current', updated: 0 };
diff --git a/server/routes/videoTimeline.js b/server/routes/videoTimeline.js
index ba159eac90..631fcada68 100644
--- a/server/routes/videoTimeline.js
+++ b/server/routes/videoTimeline.js
@@ -20,6 +20,16 @@ import {
attachSseClient,
cancelRender,
} from '../services/videoTimeline/local.js';
+import {
+ IMAGE_ASSET_KINDS,
+ AUDIO_ASSET_KINDS,
+ MAX_SEGMENTS,
+ MAX_OVERLAYS,
+ MAX_AUDIO_TRACKS,
+ MAX_FADE_SEC,
+ MAX_STILL_SEC,
+ MAX_VOLUME,
+} from '../services/videoTimeline/segments.js';
const router = Router();
@@ -27,13 +37,22 @@ const router = Router();
// coarse shape/bounds gate at the edge; the service validators re-check the
// cross-field rules (fades fitting inside their own duration, asset
// containment under an allowlisted data/ subdirectory) that a schema can't
-// express against the filesystem.
-const IMAGE_ASSET_KINDS = ['images', 'video-thumbnails'];
-const AUDIO_ASSET_KINDS = ['audio', 'music'];
-
+// express against the filesystem. That split is deliberate — but the kind
+// lists and the numeric bounds come FROM the service, so a new asset kind or a
+// raised cap can't be accepted by one layer and 400'd by the other.
const fadeFields = {
- fadeInSec: z.number().min(0).max(30).optional(),
- fadeOutSec: z.number().min(0).max(30).optional(),
+ fadeInSec: z.number().min(0).max(MAX_FADE_SEC).optional(),
+ fadeOutSec: z.number().min(0).max(MAX_FADE_SEC).optional(),
+};
+
+const outAfterIn = [
+ (c) => c.outSec > c.inSec,
+ { message: 'outSec must be > inSec', path: ['outSec'] },
+];
+const clipTrimFields = {
+ clipId: z.string().guid(),
+ inSec: z.number().min(0),
+ outSec: z.number().min(0),
};
const assetFields = (kinds) => ({
@@ -43,25 +62,19 @@ const assetFields = (kinds) => ({
assetFile: z.string().min(1).max(255),
});
-const clipSchema = z.object({
- clipId: z.string().guid(),
- inSec: z.number().min(0),
- outSec: z.number().min(0),
-}).refine((c) => c.outSec > c.inSec, { message: 'outSec must be > inSec', path: ['outSec'] });
+const clipSchema = z.object(clipTrimFields).refine(...outAfterIn);
const clipSegmentSchema = z.object({
type: z.literal('clip'),
- clipId: z.string().guid(),
- inSec: z.number().min(0),
- outSec: z.number().min(0),
- volume: z.number().min(0).max(4).optional(),
+ ...clipTrimFields,
+ volume: z.number().min(0).max(MAX_VOLUME).optional(),
...fadeFields,
-}).refine((c) => c.outSec > c.inSec, { message: 'outSec must be > inSec', path: ['outSec'] });
+}).refine(...outAfterIn);
const stillSegmentSchema = z.object({
type: z.literal('still'),
...assetFields(IMAGE_ASSET_KINDS),
- durationSec: z.number().gt(0).max(600),
+ durationSec: z.number().gt(0).max(MAX_STILL_SEC),
...fadeFields,
});
@@ -71,7 +84,7 @@ const overlaySchema = z.object({
type: z.literal('image').optional(),
...assetFields(IMAGE_ASSET_KINDS),
startSec: z.number().min(0),
- durationSec: z.number().gt(0).max(600),
+ durationSec: z.number().gt(0).max(MAX_STILL_SEC),
// Normalized to the canonical canvas so placement survives a change of
// canonical dimensions. Slight overscan lets a graphic bleed off-frame.
x: z.number().min(-1).max(2).optional(),
@@ -85,34 +98,34 @@ const audioTrackSchema = z.object({
...assetFields(AUDIO_ASSET_KINDS),
startSec: z.number().min(0),
offsetSec: z.number().min(0).optional(),
- durationSec: z.number().gt(0).max(600),
- volume: z.number().min(0).max(4).optional(),
+ durationSec: z.number().gt(0).max(MAX_STILL_SEC),
+ volume: z.number().min(0).max(MAX_VOLUME).optional(),
...fadeFields,
});
const audioSchema = z.object({
- clipVolume: z.number().min(0).max(4).optional(),
- tracks: z.array(audioTrackSchema).max(20).optional(),
+ clipVolume: z.number().min(0).max(MAX_VOLUME).optional(),
+ tracks: z.array(audioTrackSchema).max(MAX_AUDIO_TRACKS).optional(),
});
const createBodySchema = z.object({
name: z.string().min(1).max(200),
});
-const LANE_KEYS = ['name', 'clips', 'segments', 'overlays', 'audio'];
+const PATCHABLE_KEYS = ['name', 'clips', 'segments', 'overlays', 'audio'];
const updateBodySchema = z.object({
name: z.string().min(1).max(200).optional(),
// `clips` is the v1 video lane. Still accepted so an older client (or an
// older peer-authored payload) keeps working; the service upgrades it to
// clip segments, and `segments` wins when both are present.
- clips: z.array(clipSchema).max(200).optional(),
- segments: z.array(segmentSchema).max(200).optional(),
- overlays: z.array(overlaySchema).max(50).optional(),
+ clips: z.array(clipSchema).max(MAX_SEGMENTS).optional(),
+ segments: z.array(segmentSchema).max(MAX_SEGMENTS).optional(),
+ overlays: z.array(overlaySchema).max(MAX_OVERLAYS).optional(),
audio: audioSchema.optional(),
expectedUpdatedAt: z.string().optional(),
-}).refine((b) => LANE_KEYS.some((k) => b[k] !== undefined), {
- message: `PATCH body must include at least one of: ${LANE_KEYS.join(', ')}`,
+}).refine((b) => PATCHABLE_KEYS.some((k) => b[k] !== undefined), {
+ message: `PATCH body must include at least one of: ${PATCHABLE_KEYS.join(', ')}`,
});
// Backward-compatible by default: returns the full projects array. When a client
diff --git a/server/services/videoTimeline/local.crud.test.js b/server/services/videoTimeline/local.crud.test.js
index 11eda88927..d1fcfb672f 100644
--- a/server/services/videoTimeline/local.crud.test.js
+++ b/server/services/videoTimeline/local.crud.test.js
@@ -164,3 +164,48 @@ describe('deleteProject', () => {
await expect(deleteProject('p1')).rejects.toMatchObject({ code: 'NOT_FOUND' });
});
});
+
+describe('updateProject — the v1 clips payload cannot silently destroy the new lanes', () => {
+ it('refuses a clips-only save against a project holding stills', async () => {
+ seed([{
+ id: 'p1', updatedAt: 'u1', schemaVersion: 2, clips: [{ clipId: CLIP_A, inSec: 0, outSec: 2 }],
+ segments: [
+ { type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 2 },
+ { type: 'still', assetKind: 'images', assetFile: 'plate.png', durationSec: 3 },
+ ],
+ overlays: [], audio: { clipVolume: 1, tracks: [] },
+ }]);
+
+ // A rolled-back v1 editor reads only the `clips` mirror, so writing it back
+ // would drop the still it never saw.
+ await expect(updateProject('p1', { clips: [{ clipId: CLIP_A, inSec: 0, outSec: 2 }] }))
+ .rejects.toMatchObject({ code: 'SCHEMA_TOO_NEW' });
+
+ expect(onDisk()[0].segments).toHaveLength(2);
+ expect(onDisk()[0].updatedAt).toBe('u1');
+ });
+
+ it('still accepts a clips-only save when the lane is all clips — nothing can be lost', async () => {
+ seed([{
+ id: 'p1', updatedAt: 'u1', schemaVersion: 2, clips: [{ clipId: CLIP_A, inSec: 0, outSec: 2 }],
+ segments: [{ type: 'clip', clipId: CLIP_A, inSec: 0, outSec: 2 }],
+ overlays: [], audio: { clipVolume: 1, tracks: [] },
+ }]);
+
+ const updated = await updateProject('p1', { clips: [{ clipId: CLIP_B, inSec: 0, outSec: 5 }] });
+ expect(updated.segments[0].clipId).toBe(CLIP_B);
+ });
+
+ it('lets a v2 client edit the same project through the segments lane', async () => {
+ seed([{
+ id: 'p1', updatedAt: 'u1', schemaVersion: 2, clips: [],
+ segments: [{ type: 'still', assetKind: 'images', assetFile: 'plate.png', durationSec: 3 }],
+ overlays: [], audio: { clipVolume: 1, tracks: [] },
+ }]);
+
+ const updated = await updateProject('p1', {
+ segments: [{ type: 'still', assetKind: 'images', assetFile: 'plate.png', durationSec: 4 }],
+ });
+ expect(updated.segments[0].durationSec).toBe(4);
+ });
+});
diff --git a/server/services/videoTimeline/local.js b/server/services/videoTimeline/local.js
index b858b8fc3c..5f22bf311b 100644
--- a/server/services/videoTimeline/local.js
+++ b/server/services/videoTimeline/local.js
@@ -23,7 +23,7 @@ import { randomUUID } from 'crypto';
import { ensureDir, PATHS, readJSONFile, atomicWrite } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
-import { findFfmpeg, findFfprobe, safeUnder, generateThumbnail } from '../../lib/ffmpeg.js';
+import { findFfmpeg, findFfprobe, safeUnder, generateThumbnail, probeVideoDuration, BT709_CONTAINER_ARGS } from '../../lib/ffmpeg.js';
import { safeChildProcessOptions } from '../../lib/processEnv.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { attachFfmpegRenderGuard } from '../../lib/ffmpegRenderGuard.js';
@@ -40,7 +40,6 @@ import {
defaultAudio,
deriveLegacyClips,
resolveAsset,
- segmentDuration,
} from './segments.js';
const PROJECTS_FILE = join(PATHS.data, 'video-projects.json');
@@ -53,6 +52,8 @@ const DEFAULT_CANVAS = { width: 1280, height: 720, fps: 24 };
// Floor for a probe-clamped audio slice — atrim with start === end produces
// an empty stream that amix rejects.
const MIN_MEDIA_SEC = 0.05;
+// Every audio branch entering concat must present identical link parameters.
+const AUDIO_NORM = 'aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo';
// Per-project render mutex map. Keyed by projectId so two different projects
// can render in parallel; same project re-render returns 409 with the
@@ -79,16 +80,23 @@ export function getRenderJobStatus(jobId) {
// Project CRUD
// =====================================================================
+// Raw, un-normalized read. Callers that touch a single record (or only compare
+// ids) use this and normalize just what they need — normalizing every project
+// on every request is pure waste on a library of any size.
+const loadRawProjects = async () => {
+ const raw = await readJSONFile(PROJECTS_FILE, []);
+ return Array.isArray(raw) ? raw : [];
+};
+
export const loadProjects = async () => {
// Defend against a hand-edited / corrupted JSON state file. Without this,
// a non-array root would crash every CRUD path with "x.findIndex is not a
// function" instead of degrading gracefully to an empty list.
- const raw = await readJSONFile(PROJECTS_FILE, []);
// Every read upgrades v1 (`clips`-only) projects to the v2 lane shape in
// memory, so the rest of the service only ever sees `segments`/`overlays`/
// `audio`. The on-disk upgrade is migration 295; this keeps a project the
- // migration missed (restored backup, peer-copied file) working anyway.
- return Array.isArray(raw) ? raw.map(normalizeProject) : [];
+ // migration missed (a restored backup, a hand-edited file) working anyway.
+ return (await loadRawProjects()).map(normalizeProject);
};
const saveProjects = async (projects) => {
// First write on a fresh install lands before PATHS.data is created by any
@@ -103,8 +111,8 @@ export async function listProjects() {
}
export async function getProject(id) {
- const projects = await loadProjects();
- return projects.find((p) => p.id === id) || null;
+ const project = (await loadRawProjects()).find((p) => p.id === id);
+ return project ? normalizeProject(project) : null;
}
export async function createProject(name) {
@@ -159,12 +167,24 @@ export async function updateProject(id, patch, expectedUpdatedAt) {
if (patch.segments != null) {
project.segments = validateSegments(patch.segments);
} else if (patch.clips != null) {
- // Legacy v1 client (or an older peer-authored payload): a flat clip array
- // replaces the whole video lane. Upgraded in place so the persisted model
- // stays single-shaped regardless of which client wrote it.
+ // Legacy v1 client: a flat clip array replaces the whole video lane, and is
+ // upgraded in place so the persisted model stays single-shaped.
+ //
+ // A v1 build reads the `clips` mirror and cannot see stills, so letting it
+ // write that mirror back would silently DELETE every still in the lane —
+ // turning a degraded read into unrecoverable data loss on the next save.
+ // Refuse instead, the way every other version-gated payload in PortOS does.
if (!Array.isArray(patch.clips)) {
throw new ServerError('clips must be an array', { status: 400, code: 'VALIDATION_ERROR' });
}
+ const nonClip = (project.segments || []).filter((s) => s.type !== 'clip');
+ if (nonClip.length > 0) {
+ throw new ServerError('Project uses the layered timeline — a clips-only save would drop its non-clip segments', {
+ status: 409,
+ code: 'SCHEMA_TOO_NEW',
+ context: { schemaVersion: TIMELINE_SCHEMA_VERSION, droppedSegmentCount: nonClip.length },
+ });
+ }
project.segments = validateSegments(patch.clips.map((c) => ({ type: 'clip', ...(c && typeof c === 'object' ? c : {}) })));
}
if (patch.overlays != null) project.overlays = validateOverlays(patch.overlays);
@@ -180,7 +200,8 @@ export async function updateProject(id, patch, expectedUpdatedAt) {
}
export async function deleteProject(id) {
- const projects = await loadProjects();
+ // Only ids are compared here — nothing to normalize.
+ const projects = await loadRawProjects();
const filtered = projects.filter((p) => p.id !== id);
if (filtered.length === projects.length) {
throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
@@ -216,28 +237,14 @@ const probeAudio = async (videoPath) => {
});
};
-// ffprobe a media file's duration in seconds, or null when ffprobe is missing
-// or the container reports no duration. Used to clamp an audio track's
-// requested slice to what the file actually holds — an atrim past EOF yields a
-// shorter-than-declared bed, which amix then pads with silence.
-const probeDuration = async (mediaPath) => {
- const ffprobe = await findFfprobe();
- if (!ffprobe) return null;
- return new Promise((resolve) => {
- const proc = spawn(ffprobe, [
- '-v', 'error',
- '-show_entries', 'format=duration',
- '-of', 'default=nw=1:nk=1',
- mediaPath,
- ], safeChildProcessOptions({ stdio: ['ignore', 'pipe', 'ignore'] }));
- let out = '';
- proc.stdout.on('data', (c) => { out += c.toString(); });
- proc.on('close', () => {
- const n = Number(out.trim());
- resolve(Number.isFinite(n) && n > 0 ? n : null);
- });
- proc.on('error', () => resolve(null));
- });
+// Run `probe` over the DISTINCT paths in `paths`, bounded by PROBE_CONCURRENCY,
+// and return a path → result map. Deduping here rather than at the call site
+// keeps a timeline that reuses one source from spawning an ffprobe per
+// placement.
+const probeByPath = async (paths, probe) => {
+ const distinct = [...new Set(paths)];
+ const results = await mapWithConcurrency(distinct, PROBE_CONCURRENCY, probe);
+ return new Map(distinct.map((p, i) => [p, results[i]]));
};
// Resolve a project's three lanes to verified on-disk paths + durations +
@@ -245,7 +252,9 @@ const probeDuration = async (mediaPath) => {
// missing asset so the editor can highlight them all in one pass instead of
// surfacing one broken reference per failed render.
export async function resolveTimeline(rawProject) {
- const project = normalizeProject(rawProject);
+ // getProject already normalized — only a caller handing us a raw record pays
+ // for a second full rebuild.
+ const project = rawProject?.schemaVersion === TIMELINE_SCHEMA_VERSION ? rawProject : normalizeProject(rawProject);
const segments = project.segments || [];
if (segments.length === 0) {
throw new ServerError('Project has no clips', { status: 400, code: 'EMPTY_PROJECT' });
@@ -307,24 +316,30 @@ export async function resolveTimeline(rawProject) {
});
}
+ // Probe once per distinct FILE, not per placement: a cut that returns to the
+ // same source clip, or a bed placed twice, would otherwise spawn an identical
+ // ffprobe per occurrence. Both fan-outs are independent, so they share the
+ // wall clock — each stays capped at PROBE_CONCURRENCY on its own.
const clipEntries = prepared.filter((p) => p.kind === 'clip');
- const audioFlags = new Map();
- const clipAudio = await mapWithConcurrency(clipEntries, PROBE_CONCURRENCY, (p) => probeAudio(p.videoPath));
- clipEntries.forEach((p, j) => audioFlags.set(p.i, clipAudio[j]));
+ const [audioFlagByPath, durationByPath] = await Promise.all([
+ probeByPath(clipEntries.map((p) => p.videoPath), probeAudio),
+ probeByPath(audioTracks.map((tr) => tr.assetPath), probeVideoDuration),
+ ]);
+
+ for (const p of clipEntries) p.hasAudio = audioFlagByPath.get(p.videoPath) === true;
- const bedDurations = await mapWithConcurrency(audioTracks, PROBE_CONCURRENCY, (tr) => probeDuration(tr.assetPath));
- audioTracks.forEach((tr, j) => {
- const probed = bedDurations[j];
+ for (const tr of audioTracks) {
+ const probed = durationByPath.get(tr.assetPath);
// A probe reporting LESS than the requested slice is authoritative.
// `null` (no ffprobe on PATH, unreadable container) must NOT collapse into
// "0 seconds available" — leave the stored slice alone in that case.
- if (probed == null) return;
+ if (probed == null) continue;
tr.offsetSec = Math.min(tr.offsetSec, Math.max(0, probed - MIN_MEDIA_SEC));
tr.durationSec = Math.min(tr.durationSec, Math.max(MIN_MEDIA_SEC, probed - tr.offsetSec));
const fitted = fitFades(tr.fadeInSec, tr.fadeOutSec, tr.durationSec);
tr.fadeInSec = fitted.fadeInSec;
tr.fadeOutSec = fitted.fadeOutSec;
- });
+ }
const resolvedSegments = prepared.map((p) => (p.kind === 'still'
? {
@@ -348,7 +363,7 @@ export async function resolveTimeline(rawProject) {
width: p.entry.width,
height: p.entry.height,
fps: p.entry.fps,
- hasAudio: audioFlags.get(p.i) === true,
+ hasAudio: p.hasAudio,
fadeInSec: p.fades.fadeInSec,
fadeOutSec: p.fades.fadeOutSec,
volume: p.seg.volume,
@@ -368,14 +383,6 @@ export async function resolveTimeline(rawProject) {
};
}
-/**
- * Back-compat wrapper: the v1 entry point returned only the video lane.
- * Retained so any caller still asking for "the resolved clips" keeps working.
- */
-export async function resolveClips(project) {
- return (await resolveTimeline(project)).segments;
-}
-
// Filter-graph number formatting. Raw interpolation of a subtraction result
// leaks float noise (`2.9000000000000004`) into the graph string, while
// toFixed would pad clean integers to `4.000`. Round to microseconds, then
@@ -394,21 +401,15 @@ function fitFades(fadeInSec, fadeOutSec, duration) {
return { fadeInSec: fin * scale, fadeOutSec: fout * scale };
}
-const videoFades = (seg, duration) => {
- const parts = [];
- if (seg.fadeInSec > 0) parts.push(`fade=t=in:st=0:d=${fmt(seg.fadeInSec)}`);
- if (seg.fadeOutSec > 0) {
- parts.push(`fade=t=out:st=${fmt(Math.max(0, duration - seg.fadeOutSec))}:d=${fmt(seg.fadeOutSec)}`);
- }
- return parts.length > 0 ? `,${parts.join(',')}` : '';
-};
-
-const audioShaping = (seg, duration, volume) => {
- const parts = [];
- if (volume !== 1) parts.push(`volume=${fmt(volume)}`);
- if (seg.fadeInSec > 0) parts.push(`afade=t=in:st=0:d=${fmt(seg.fadeInSec)}`);
- if (seg.fadeOutSec > 0) {
- parts.push(`afade=t=out:st=${fmt(Math.max(0, duration - seg.fadeOutSec))}:d=${fmt(seg.fadeOutSec)}`);
+// Fade filters for one segment, in the segment's own post-setpts clock.
+// `prefix` is 'fade' (video) or 'afade' (audio) — the two must agree on the
+// fade-out start, so they share one expression. `lead` carries filters that
+// belong ahead of the ramp (an audio volume trim).
+const fadeChain = (prefix, { fadeInSec = 0, fadeOutSec = 0 }, duration, lead = []) => {
+ const parts = [...lead];
+ if (fadeInSec > 0) parts.push(`${prefix}=t=in:st=0:d=${fmt(fadeInSec)}`);
+ if (fadeOutSec > 0) {
+ parts.push(`${prefix}=t=out:st=${fmt(Math.max(0, duration - fadeOutSec))}:d=${fmt(fadeOutSec)}`);
}
return parts.length > 0 ? `,${parts.join(',')}` : '';
};
@@ -418,32 +419,33 @@ const audioShaping = (seg, duration, volume) => {
// link parameters do not match" mid-render — and an RGBA still concatenated
// after a yuv420p clip fails exactly the same way.
//
-// Accepts either a resolved timeline object from resolveTimeline() or a bare
-// segment array (the v1 signature — video lane only, no overlays or bed).
+// Takes a RESOLVED timeline from resolveTimeline() — every segment already
+// carries its on-disk path, its project-time `duration`, and (for a clip) its
+// probed `hasAudio`. Geometry comes off the timeline rather than being
+// re-derived here, so exactly one place decides the canvas.
export function buildFfmpegArgs(timeline, outputPath) {
- const t = Array.isArray(timeline) ? { segments: timeline } : (timeline || {});
+ const t = timeline || {};
const segments = t.segments || [];
if (segments.length === 0) throw new Error('buildFfmpegArgs: empty clips');
const overlays = t.overlays || [];
const audioTracks = t.audioTracks || [];
const clipVolume = t.clipVolume == null ? 1 : t.clipVolume;
- const firstClip = segments.find((seg) => (seg.type || 'clip') === 'clip');
- const canonW = t.canonW || firstClip?.width || DEFAULT_CANVAS.width;
- const canonH = t.canonH || firstClip?.height || DEFAULT_CANVAS.height;
- const fps = t.fps || firstClip?.fps || DEFAULT_CANVAS.fps;
+ const canonW = t.canonW || DEFAULT_CANVAS.width;
+ const canonH = t.canonH || DEFAULT_CANVAS.height;
+ const fps = t.fps || DEFAULT_CANVAS.fps;
const inputs = [];
const filters = [];
const concatStreams = [];
let inputIdx = 0;
- const totalDuration = segments.reduce((sum, seg) => sum + (seg.duration ?? segmentDuration(seg)), 0);
+ const totalDuration = segments.reduce((sum, seg) => sum + seg.duration, 0);
for (let i = 0; i < segments.length; i++) {
const seg = segments[i];
- const isStill = (seg.type || 'clip') === 'still';
- const duration = seg.duration ?? segmentDuration(seg);
+ const isStill = seg.type === 'still';
+ const { duration } = seg;
const vIdx = inputIdx++;
if (isStill) {
@@ -462,32 +464,25 @@ export function buildFfmpegArgs(timeline, outputPath) {
? `trim=start=0:end=${fmt(duration)}`
: `trim=start=${fmt(seg.inSec)}:end=${fmt(seg.outSec)}`;
filters.push(
- `[${vIdx}:v]scale=${canonW}:${canonH}:force_original_aspect_ratio=decrease,pad=${canonW}:${canonH}:(ow-iw)/2:(oh-ih)/2,setsar=1,format=yuv420p,fps=${fps},${trim},setpts=PTS-STARTPTS${videoFades(seg, duration)}[v${i}]`
+ `[${vIdx}:v]scale=${canonW}:${canonH}:force_original_aspect_ratio=decrease,pad=${canonW}:${canonH}:(ow-iw)/2:(oh-ih)/2,setsar=1,format=yuv420p,fps=${fps},${trim},setpts=PTS-STARTPTS${fadeChain('fade', seg, duration)}[v${i}]`
);
- const hasAudio = !isStill && seg.hasAudio;
- let aIdx;
- if (hasAudio) {
- aIdx = vIdx;
- } else {
- // -t bounds the otherwise-infinite anullsrc to match the segment's
- // duration so concat=v=1:a=1 gets a length-matched silent track.
- aIdx = inputIdx++;
- inputs.push('-f', 'lavfi', '-t', fmt(duration), '-i', `anullsrc=channel_layout=stereo:sample_rate=48000`);
- }
- if (hasAudio) {
+ // The silent stub must share the real-audio branches' sample format and
+ // layout — concat=v=1:a=1 fails fast with "Input link parameters do not
+ // match" if they diverge.
+ if (!isStill && seg.hasAudio) {
const vol = clipVolume * (seg.volume == null ? 1 : seg.volume);
+ const lead = vol === 1 ? [] : [`volume=${fmt(vol)}`];
filters.push(
- `[${aIdx}:a]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,atrim=start=${fmt(seg.inSec)}:end=${fmt(seg.outSec)},asetpts=PTS-STARTPTS${audioShaping(seg, duration, vol)}[a${i}]`
+ `[${vIdx}:a]${AUDIO_NORM},atrim=start=${fmt(seg.inSec)}:end=${fmt(seg.outSec)},asetpts=PTS-STARTPTS${fadeChain('afade', seg, duration, lead)}[a${i}]`
);
} else {
- // The silent input must match the same sample-format/layout as the
- // real-audio branches; concat=v=1:a=1 fails fast with "Input link
- // parameters do not match" if they diverge. No volume or fade here — the
+ // -t bounds the otherwise-infinite anullsrc to the segment's duration so
+ // concat gets a length-matched silent track. No volume or fade here — the
// stream is already silence.
- filters.push(
- `[${aIdx}:a]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,asetpts=PTS-STARTPTS[a${i}]`
- );
+ const aIdx = inputIdx++;
+ inputs.push('-f', 'lavfi', '-t', fmt(duration), '-i', 'anullsrc=channel_layout=stereo:sample_rate=48000');
+ filters.push(`[${aIdx}:a]${AUDIO_NORM},asetpts=PTS-STARTPTS[a${i}]`);
}
concatStreams.push(`[v${i}][a${i}]`);
}
@@ -571,6 +566,10 @@ export function buildFfmpegArgs(timeline, outputPath) {
'-pix_fmt', 'yuv420p',
'-c:a', 'aac',
'-b:a', '192k',
+ // Untagged H.264 decodes washed-out or over-saturated depending on the
+ // player; stills and overlays re-encoded here must match the tagged stitch
+ // path or one output file carries two colour interpretations.
+ ...BT709_CONTAINER_ARGS,
'-movflags', '+faststart',
'-progress', 'pipe:2',
'-y',
diff --git a/server/services/videoTimeline/local.terminal.test.js b/server/services/videoTimeline/local.terminal.test.js
index f3c626dfd4..9fa173eeb5 100644
--- a/server/services/videoTimeline/local.terminal.test.js
+++ b/server/services/videoTimeline/local.terminal.test.js
@@ -49,6 +49,8 @@ vi.mock('../../lib/ffmpeg.js', () => ({
findFfprobe: vi.fn(async () => null), // → probeAudio returns false without spawning
safeUnder: (root, name) => (name ? `${root}/${name}` : null),
generateThumbnail: vi.fn(async () => 'thumb.jpg'),
+ probeVideoDuration: vi.fn(async () => null), // no bed probing in these render-lifecycle cases
+ BT709_CONTAINER_ARGS: ['-color_primaries', 'bt709', '-color_trc', 'bt709', '-colorspace', 'bt709'],
}));
vi.mock('../../lib/processEnv.js', () => ({
safeChildProcessOptions: (options = {}) => ({ ...options, env: {}, windowsHide: true }),
diff --git a/server/services/videoTimeline/local.test.js b/server/services/videoTimeline/local.test.js
index d24095d2ea..893f6a63fa 100644
--- a/server/services/videoTimeline/local.test.js
+++ b/server/services/videoTimeline/local.test.js
@@ -1,7 +1,11 @@
import { describe, it, expect } from 'vitest';
import { buildFfmpegArgs } from './local.js';
+// buildFfmpegArgs consumes RESOLVED segments — resolveTimeline has already
+// attached the on-disk path, the project-time `duration`, the probed
+// `hasAudio`, and the canonical geometry.
const baseClip = (overrides = {}) => ({
+ type: 'clip',
index: 0,
clipId: 'clip-1',
videoPath: '/tmp/clip-1.mp4',
@@ -12,17 +16,30 @@ const baseClip = (overrides = {}) => ({
height: 512,
fps: 24,
hasAudio: true,
+ fadeInSec: 0,
+ fadeOutSec: 0,
+ volume: 1,
...overrides,
});
+// A resolved timeline whose geometry defaults to the first clip's, mirroring
+// what resolveTimeline computes.
+const lane = (segments, extra = {}) => ({
+ segments,
+ canonW: segments[0]?.width ?? 1280,
+ canonH: segments[0]?.height ?? 720,
+ fps: segments[0]?.fps ?? 24,
+ ...extra,
+});
+
describe('buildFfmpegArgs', () => {
it('throws on empty clip list', () => {
- expect(() => buildFfmpegArgs([], '/out.mp4')).toThrow(/empty/i);
+ expect(() => buildFfmpegArgs({ segments: [] }, '/out.mp4')).toThrow(/empty/i);
});
it('produces a single-clip filter_complex with audio passthrough', () => {
const clips = [baseClip()];
- const { args, totalDuration, canonW, canonH } = buildFfmpegArgs(clips, '/out.mp4');
+ const { args, totalDuration, canonW, canonH } = buildFfmpegArgs(lane(clips), '/out.mp4');
expect(totalDuration).toBe(4);
expect(canonW).toBe(768);
@@ -46,7 +63,7 @@ describe('buildFfmpegArgs', () => {
baseClip({ hasAudio: false, duration: 3, outSec: 3 }),
baseClip({ hasAudio: true, duration: 5, outSec: 5 }),
];
- const { args } = buildFfmpegArgs(clips, '/out.mp4');
+ const { args } = buildFfmpegArgs(lane(clips), '/out.mp4');
// Inputs: -i clip0, -f lavfi -t 3 -i anullsrc..., -i clip1
// Indices: 0 = clip0 video, 1 = silent stub, 2 = clip1 (with audio at 2:a)
@@ -73,7 +90,7 @@ describe('buildFfmpegArgs', () => {
baseClip({ hasAudio: false, inSec: 1, outSec: 4, duration: 3 }),
baseClip({ hasAudio: true, inSec: 0.5, outSec: 3, duration: 2.5 }),
];
- const { args, totalDuration } = buildFfmpegArgs(clips, '/out.mp4');
+ const { args, totalDuration } = buildFfmpegArgs(lane(clips), '/out.mp4');
expect(totalDuration).toBeCloseTo(7.5);
@@ -91,7 +108,7 @@ describe('buildFfmpegArgs', () => {
baseClip({ width: 1024, height: 576 }),
baseClip({ width: 768, height: 512 }), // different — should still be padded to 1024x576
];
- const { args, canonW, canonH } = buildFfmpegArgs(clips, '/out.mp4');
+ const { args, canonW, canonH } = buildFfmpegArgs(lane(clips), '/out.mp4');
expect(canonW).toBe(1024);
expect(canonH).toBe(576);
const filter = args[args.indexOf('-filter_complex') + 1];
@@ -101,7 +118,7 @@ describe('buildFfmpegArgs', () => {
});
it('emits encoder + faststart + progress flags', () => {
- const { args } = buildFfmpegArgs([baseClip()], '/out.mp4');
+ const { args } = buildFfmpegArgs(lane([baseClip()]), '/out.mp4');
expect(args).toContain('-c:v');
expect(args).toContain('libx264');
expect(args).toContain('-c:a');
@@ -339,10 +356,18 @@ describe('buildFfmpegArgs — combined lanes and input indexing', () => {
expect(args).toContain('[outa]');
});
- it('accepts the v1 bare-array signature and produces the same minimal graph', () => {
- const fromArray = buildFfmpegArgs([baseClip()], '/out.mp4');
- const fromObject = buildFfmpegArgs({ segments: [baseClip()] }, '/out.mp4');
- expect(fromArray.args).toEqual(fromObject.args);
+ it('tags BT.709 so a re-encoded still cannot decode with a different colour guess than the clips beside it', () => {
+ const { args } = buildFfmpegArgs(lane([baseClip(), stillSegment()]), '/out.mp4');
+ expect(args).toContain('-color_primaries');
+ expect(args).toContain('-colorspace');
+ expect(args[args.indexOf('-color_trc') + 1]).toBe('bt709');
+ });
+
+ it('falls back to the default canvas when the timeline carries no geometry', () => {
+ // resolveTimeline always supplies canonW/H/fps; this is the last-resort
+ // guard, not a second place that derives geometry from the segments.
+ const { canonW, canonH, fps } = buildFfmpegArgs({ segments: [baseClip({ width: 1920, height: 1080, fps: 60 })] }, '/out.mp4');
+ expect([canonW, canonH, fps]).toEqual([1280, 720, 24]);
});
it('rounds float noise out of the graph instead of leaking it', () => {
diff --git a/server/services/videoTimeline/segments.js b/server/services/videoTimeline/segments.js
index 283eeb46c6..b6cfe4b9e7 100644
--- a/server/services/videoTimeline/segments.js
+++ b/server/services/videoTimeline/segments.js
@@ -49,9 +49,9 @@ export const AUDIO_ASSET_KINDS = ['audio', 'music'];
export const MAX_SEGMENTS = 200;
export const MAX_OVERLAYS = 50;
export const MAX_AUDIO_TRACKS = 20;
-const MAX_FADE_SEC = 30;
-const MAX_STILL_SEC = 600;
-const MAX_VOLUME = 4;
+export const MAX_FADE_SEC = 30;
+export const MAX_STILL_SEC = 600;
+export const MAX_VOLUME = 4;
const bad = (message, context) => new ServerError(message, { status: 400, code: 'VALIDATION_ERROR', context });