Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Keep Long Shot playback continuous

Bittid2e977c5d664
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index 629ad16..f8d8dde 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -42,6 +42,7 @@ This alpha update adds LAN generation workers, Linux support, expanded color gra
## Fixes and improvements
+- Long Shot timeline playback keeps the same video player running across adjacent scenes in a joined generation, avoiding a playback restart at bridge boundaries.
- Reduced memory retained between generations: release Slopfab samples and handles after consumption, discard completed queue snapshots, close encoders on errors, and clean up abandoned LAN generation results.
- Inspector instructions now appear as tooltips on field labels, keeping the right-side panels compact.
- Scene generation prompts now mark shot times as `[Shot 2] At 00:03.500,`.
diff --git a/src/components/workspace/ProgramLayer.tsx b/src/components/workspace/ProgramLayer.tsx
index 4f6dac1..0c7ef6a 100644
--- a/src/components/workspace/ProgramLayer.tsx
+++ b/src/components/workspace/ProgramLayer.tsx
@@ -21,8 +21,9 @@ export function previewMediaStyle(frame: ClipFrameStyle): CSSProperties {
}
/** Prepared clips keep their decoder and effect renderer when made visible. */
-export function ProgramLayer({ clip, asset, sources, playheadMs, playing, rate = 1, active, foreground, muted, externalSeek, depth, media, composited }: {
+export function ProgramLayer({ clip, playerKey, asset, sources, playheadMs, playing, rate = 1, active, foreground, muted, externalSeek, depth, media, composited }: {
clip: TimelineClip;
+ playerKey: string;
asset: ProjectAsset | undefined;
sources: PreviewSources;
playheadMs: number;
@@ -44,12 +45,12 @@ export function ProgramLayer({ clip, asset, sources, playheadMs, playing, rate =
const image = useRef<HTMLImageElement | null>(null);
const registerVideo = useCallback((element: HTMLVideoElement | null) => {
video.current = element;
- media.set(clip.id, element);
- }, [media, clip.id]);
+ media.set(playerKey, element);
+ }, [media, playerKey]);
const registerImage = useCallback((element: HTMLImageElement | null) => {
image.current = element;
- media.set(clip.id, element);
- }, [media, clip.id]);
+ media.set(playerKey, element);
+ }, [media, playerKey]);
const position = useRef({ clip, playheadMs, playing, active, externalSeek });
position.current = { clip, playheadMs, playing, active, externalSeek };
const isImage = asset?.kind === "image" || asset?.mimeType.startsWith("image/");
diff --git a/src/components/workspace/ProgramMonitor.test.tsx b/src/components/workspace/ProgramMonitor.test.tsx
index 8aaf020..2c219e3 100644
--- a/src/components/workspace/ProgramMonitor.test.tsx
+++ b/src/components/workspace/ProgramMonitor.test.tsx
@@ -3,7 +3,7 @@
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { useState } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { createProjectConfig, parseProjectConfig, STORY_TRACK_ID, type ProjectConfig, type TimelineClip } from "../../lib/project";
+import { createDraftGenerationJob, createProjectConfig, parseProjectConfig, STORY_TRACK_ID, type ProjectConfig, type TimelineClip } from "../../lib/project";
import { ProgramMonitor } from "./ProgramMonitor";
import { PreviewSources } from "../../lib/exportPipeline";
@@ -53,6 +53,73 @@ const monitor = (config: ProjectConfig, playheadMs: number) => render(
);
describe("the program monitor", () => {
+ it.each([1, 2])("keeps the Long Shot video running across both bridge boundaries at %sx speed", async (playbackRate) => {
+ const read = vi.spyOn(PreviewSources.prototype, "url").mockImplementation(async (asset) => `blob:${asset.id}`);
+ const playingElements = new WeakSet<HTMLMediaElement>();
+ const play = vi.spyOn(HTMLMediaElement.prototype, "play").mockImplementation(function (this: HTMLMediaElement) {
+ playingElements.add(this);
+ return Promise.resolve();
+ });
+ const pause = vi.spyOn(HTMLMediaElement.prototype, "pause").mockImplementation(function (this: HTMLMediaElement) { playingElements.delete(this); });
+ vi.spyOn(HTMLMediaElement.prototype, "paused", "get").mockImplementation(function (this: HTMLMediaElement) { return !playingElements.has(this); });
+ vi.spyOn(HTMLMediaElement.prototype, "readyState", "get").mockReturnValue(4);
+ const seek = vi.spyOn(HTMLMediaElement.prototype, "currentTime", "set");
+ let now = 0, nextId = 0;
+ const frames = new Map<number, FrameRequestCallback>();
+ vi.spyOn(performance, "now").mockImplementation(() => now);
+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => { frames.set(++nextId, callback); return nextId; });
+ vi.stubGlobal("cancelAnimationFrame", (id: number) => frames.delete(id));
+ const config = project([]);
+ const parts = [124, 46, 124].map((frameCount, index) => ({ sceneId: String(index), frameCount,
+ startFrame: [0, 124, 170][index], latentRelativePath: `latents/${index}.safetensors` }));
+ config.generationJobs = parts.map((part) => ({ ...createDraftGenerationJob("Walk", { id: part.sceneId, sceneType: "long-shot" }),
+ status: "completed", latentRelativePath: part.latentRelativePath }));
+ config.assets = parts.map((part, index) => ({ ...config.assets[0], id: `asset-${part.sceneId}`, kind: "generated",
+ sourcePath: `D:/scene-${index}.mp4`, hasAudio: true,
+ sceneSegments: index === 1 ? parts : [{ ...part, startFrame: 0 }] }));
+ let startMs = 0;
+ const clips = parts.map((part) => {
+ const durationMs = Math.round(part.frameCount * 1000 / 24 / playbackRate);
+ const next = clip({ id: part.sceneId, assetId: `asset-${part.sceneId}`, startMs, durationMs, sourceStartMs: 0, playbackRate,
+ transform: { scale: 80 + Number(part.sceneId), rotation: 0, positionX: 0, positionY: 0 } });
+ startMs += durationMs;
+ return next;
+ });
+ config.timeline.tracks.find((track) => track.id === STORY_TRACK_ID)!.clips = clips;
+ let scrub: (time: number) => void = () => undefined;
+ function Harness() {
+ const [position, setPosition] = useState(0);
+ scrub = setPosition;
+ return <ProgramMonitor config={config} folderPath="C:/Film" playheadMs={position} playing
+ onSeek={setPosition} onPlayingChange={() => undefined} />;
+ }
+ const view = render(<Harness />);
+ await act(async () => undefined);
+ const video = view.container.querySelector("video")!;
+ expect(view.container.querySelectorAll("video")).toHaveLength(1);
+ expect(video.src).toBe("blob:asset-1");
+ for (const next of clips.slice(1)) {
+ // Model the running media clock before React advances across the cut.
+ now = next.startMs + 16;
+ video.currentTime = now * playbackRate / 1000;
+ seek.mockClear(); play.mockClear(); pause.mockClear();
+ await act(async () => {
+ const pending = [...frames.values()]; frames.clear(); pending.forEach((callback) => callback(now));
+ });
+ expect(view.container.querySelector(`[data-clip-id="${next.id}"] video`)).toBe(video);
+ expect(video.style.transform).toContain(`scale(${next.transform!.scale / 100})`);
+ expect(video.paused).toBe(false);
+ expect(video.muted).toBe(false);
+ expect(seek).not.toHaveBeenCalled();
+ expect(play).not.toHaveBeenCalled();
+ expect(pause).not.toHaveBeenCalled();
+ }
+ await act(async () => scrub(1000));
+ expect(view.container.querySelector('[data-clip-id="0"] video')).toBe(video);
+ expect(video.currentTime).toBe(playbackRate);
+ expect(read).toHaveBeenCalledTimes(1);
+ });
+
it.each([0.5, 2])("seeks and plays video and audio at %sx clip speed", async (playbackRate) => {
vi.spyOn(PreviewSources.prototype, "url").mockImplementation(async (asset) => `blob:${asset.id}`);
vi.spyOn(HTMLMediaElement.prototype, "play").mockResolvedValue();
diff --git a/src/components/workspace/ProgramMonitor.tsx b/src/components/workspace/ProgramMonitor.tsx
index 790e81d..55163a7 100644
--- a/src/components/workspace/ProgramMonitor.tsx
+++ b/src/components/workspace/ProgramMonitor.tsx
@@ -8,15 +8,14 @@ import { isTauri } from "../../lib/persistence";
import type { ClipTransform, ProjectAsset, ProjectConfig, TimelineClip } from "../../lib/project";
import { clipEndMs } from "../../lib/timeline";
import { PreviewSources } from "../../lib/exportPipeline";
-import { preparedPreviewClips, previewSegmentIndex, previewSegments } from "../../lib/timelinePreview";
+import { preparedPreviewClips, previewPlayerKeys, previewSegmentIndex, previewSegments } from "../../lib/timelinePreview";
import { PreviewMedia } from "../../lib/previewPresentation";
import { PLAYBACK_SAMPLE_MS, previewEngine } from "../../lib/previewEngine";
import { continuationPlaybackTracks } from "../../lib/continuationMedia";
-/* The monitor owns a continuous timeline clock. Each visible or upcoming clip
- * owns a persistent media element: loading, decoding the first frame and seeking
- * a trim happen ahead of a cut. Promoting a prepared layer preserves its decoder
- * and effect renderer, including when a lower track becomes the foreground. */
+/* The monitor owns a continuous timeline clock. Visible and upcoming clips
+ * prepare persistent media elements ahead of a cut. Adjacent ranges of a joined
+ * generation keep the same running player while retaining each clip's effects. */
/** How far a sound may drift from the cut before it is pulled back. Below this
* a correction is more audible than the drift it fixes. */
@@ -76,7 +75,8 @@ export function ProgramMonitor({ config, folderPath, playheadMs, playing, rate =
const segments = useMemo(() => previewSegments(tracks, assetsById), [tracks, assetsById]);
const segmentIndex = previewSegmentIndex(segments, playheadMs);
const layers = segments[segmentIndex].clips;
- const prepared = useMemo(() => preparedPreviewClips(segments, segmentIndex), [segments, segmentIndex]);
+ const playerKeys = useMemo(() => previewPlayerKeys(tracks, assetsById), [tracks, assetsById]);
+ const prepared = useMemo(() => preparedPreviewClips(segments, segmentIndex, playerKeys), [segments, segmentIndex, playerKeys]);
const clip = layers[0] ?? null;
const asset = useMemo(
() => (clip ? config.assets.find((candidate) => candidate.id === clip.assetId) : undefined),
@@ -338,14 +338,15 @@ export function ProgramMonitor({ config, folderPath, playheadMs, playing, rate =
onSelectClip(clip.id);
}}
>
- <ProgramPicture key={folderPath} media={media} layers={layers} playheadMs={playheadMs}
+ <ProgramPicture key={folderPath} media={media} playerKeys={playerKeys} layers={layers} playheadMs={playheadMs}
width={Math.round(dimensions.width * previewScale)} height={Math.round(dimensions.height * previewScale)}
background={config.settings.backgroundColor} onAvailable={setComposited} />
- <div className="program-media">{prepared.map(({ clip: layer, prepareAtMs }) => {
+ <div className="program-media">{prepared.map(({ clip: layer, prepareAtMs, playerKey }) => {
const depth = layers.findIndex((visible) => visible.id === layer.id);
return <ProgramLayer
- key={`${folderPath}:${layer.id}`}
+ key={`${folderPath}:${playerKey}`}
clip={layer}
+ playerKey={playerKey}
asset={assetsById.get(layer.assetId)}
sources={sources}
media={media}
diff --git a/src/components/workspace/ProgramPicture.tsx b/src/components/workspace/ProgramPicture.tsx
index 0081837..3b35886 100644
--- a/src/components/workspace/ProgramPicture.tsx
+++ b/src/components/workspace/ProgramPicture.tsx
@@ -6,8 +6,9 @@ import type { TimelineClip } from "../../lib/project";
/** A persistent presentation surface: media elements may come and go, but a
* cut never removes the canvas containing the last complete picture. */
-export function ProgramPicture({ media, layers, playheadMs, width, height, background, onAvailable }: {
+export function ProgramPicture({ media, playerKeys, layers, playheadMs, width, height, background, onAvailable }: {
media: PreviewMedia;
+ playerKeys?: ReadonlyMap<string, string>;
layers: TimelineClip[];
playheadMs: number;
width: number;
@@ -16,8 +17,8 @@ export function ProgramPicture({ media, layers, playheadMs, width, height, backg
onAvailable: (available: boolean) => void;
}) {
const canvas = useRef<HTMLCanvasElement>(null);
- const current = useRef({ layers, playheadMs, onAvailable });
- current.current = { layers, playheadMs, onAvailable };
+ const current = useRef({ layers, playheadMs, onAvailable, playerKeys });
+ current.current = { layers, playheadMs, onAvailable, playerKeys };
const redraw = useRef<((tick?: boolean) => void) | null>(null);
const [available, setAvailable] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -30,7 +31,7 @@ export function ProgramPicture({ media, layers, playheadMs, width, height, backg
const draw = (tick = false) => {
if (!live || !compositor) return;
try {
- const presented = presentPreviewFrame(compositor, media, current.current.layers, current.current.playheadMs);
+ const presented = presentPreviewFrame(compositor, media, current.current.layers, current.current.playheadMs, current.current.playerKeys);
if (tick) previewEngine.tick(presented);
}
catch (reason) { setError(String(reason)); }
@@ -55,7 +56,7 @@ export function ProgramPicture({ media, layers, playheadMs, width, height, backg
compositor?.dispose();
};
}, [media, width, height, background]);
- useLayoutEffect(() => redraw.current?.(true), [layers, playheadMs]);
+ useLayoutEffect(() => redraw.current?.(true), [layers, playheadMs, playerKeys]);
return <>
<canvas ref={canvas} className="program-composited-picture" aria-label="Video preview" style={{ visibility: available ? "visible" : "hidden" }} />
{available && error && <div className="program-note program-note--error" role="alert">{error}</div>}
diff --git a/src/lib/previewPresentation.test.ts b/src/lib/previewPresentation.test.ts
index 1a73f8f..699b5e5 100644
--- a/src/lib/previewPresentation.test.ts
+++ b/src/lib/previewPresentation.test.ts
@@ -14,6 +14,26 @@ const video = (ready = true) => {
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); });
describe("persistent preview presentation", () => {
+ it("draws the shared Long Shot player immediately when the scene changes", () => {
+ const sources: unknown[] = [];
+ const close = vi.fn();
+ vi.stubGlobal("VideoFrame", class {
+ close = close;
+ constructor(source: unknown) { sources.push(source); }
+ });
+ const media = new PreviewMedia();
+ const joined = video();
+ media.set("first", joined);
+ const output = compositor();
+ const keys = new Map([["first", "first"], ["bridge", "first"], ["last", "first"]]);
+ for (const [index, id] of ["first", "bridge", "last"].entries()) {
+ expect(presentPreviewFrame(output, media, [clip(id)], index * 1000, keys)).toBe(true);
+ }
+ expect(sources).toEqual([joined, joined, joined]);
+ expect(output.draw).toHaveBeenCalledTimes(3);
+ expect(close).toHaveBeenCalledTimes(3);
+ });
+
it("keeps the outgoing pixels until the incoming frame is available, then replaces them in the same surface", () => {
const frames: { source: unknown; close: ReturnType<typeof vi.fn> }[] = [];
vi.stubGlobal("VideoFrame", class {
diff --git a/src/lib/previewPresentation.ts b/src/lib/previewPresentation.ts
index beaf687..b955b3e 100644
--- a/src/lib/previewPresentation.ts
+++ b/src/lib/previewPresentation.ts
@@ -4,7 +4,7 @@ import type { TimelineClip } from "./project";
type PreviewMediaElement = HTMLVideoElement | HTMLImageElement;
-/** Prepared decoders belong to clips; the displayed canvas belongs to the
+/** Prepared decoders belong to players; the displayed canvas belongs to the
* monitor. Media arriving asynchronously requests a redraw of the current cut. */
export class PreviewMedia {
private elements = new Map<string, PreviewMediaElement>();
@@ -33,11 +33,11 @@ export class PreviewMedia {
/** Capture every layer BEFORE clearing the display. If any decoder is still
* loading/seeking, keep the complete previous picture. A real timeline gap
* deliberately clears the canvas. No pixel readback or CPU frame copies. */
-export function presentPreviewFrame(compositor: Compositor, media: PreviewMedia, layers: TimelineClip[], playheadMs: number): boolean {
+export function presentPreviewFrame(compositor: Compositor, media: PreviewMedia, layers: TimelineClip[], playheadMs: number, playerKeys?: ReadonlyMap<string, string>): boolean {
const pictures: { frame: VideoFrame; clip: TimelineClip }[] = [];
try {
for (const clip of layers) {
- const element = media.get(clip.id);
+ const element = media.get(playerKeys?.get(clip.id) ?? clip.id);
if (!element) return false;
const video = element instanceof HTMLVideoElement;
if (video ? element.readyState < 2 || element.seeking || !element.videoWidth || !element.videoHeight
diff --git a/src/lib/timelinePreview.test.ts b/src/lib/timelinePreview.test.ts
index 1be30b7..0494d30 100644
--- a/src/lib/timelinePreview.test.ts
+++ b/src/lib/timelinePreview.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { ProjectAsset, TimelineClip, TimelineTrack } from "./project";
-import { preparedPreviewClips, previewSegmentIndex, previewSegments } from "./timelinePreview";
+import { preparedPreviewClips, previewPlayerKeys, previewSegmentIndex, previewSegments } from "./timelinePreview";
const asset = { id: "video", kind: "video", mimeType: "video/mp4" } as ProjectAsset;
const assets = new Map([[asset.id, asset]]);
@@ -10,6 +10,24 @@ const clip = (id: string, startMs: number, durationMs: number, extra: Partial<Ti
const track = (clips: TimelineClip[]): TimelineTrack => ({ id: "track", name: "Picture", kind: "video", muted: false, locked: false, clips });
describe("prepared timeline pictures", () => {
+ it("shares a joined decoder across rounded scene boundaries, but keeps distinct seeks separate", () => {
+ const joined = new Map([[asset.id, { ...asset, sceneSegments: [
+ { sceneId: "a", latentRelativePath: "a", startFrame: 0, frameCount: 124 },
+ { sceneId: "b", latentRelativePath: "b", startFrame: 124, frameCount: 46 },
+ ] }]]);
+ const a = clip("a", 0, 5167);
+ const b = clip("b", 5167, 1917, { sourceStartMs: 124 * 1000 / 24 });
+ const tracks = [track([a, b])];
+ const segments = previewSegments(tracks, joined);
+ const keys = previewPlayerKeys(tracks, joined);
+ expect(preparedPreviewClips(segments, 0, keys).map((entry) => [entry.clip.id, entry.playerKey])).toEqual([["a", "a"]]);
+ expect(preparedPreviewClips(segments, 1, keys).map((entry) => [entry.clip.id, entry.playerKey])).toEqual([["b", "a"]]);
+ for (const change of [{ sourceStartMs: b.sourceStartMs + 1 }, { startMs: 5168 }, { startMs: 5166 }, { playbackRate: 2 }]) {
+ expect(previewPlayerKeys([track([a, { ...b, ...change }])], joined).get("b")).toBe("b");
+ }
+ expect(previewPlayerKeys(tracks, assets).get("b")).toBe("b");
+ });
+
it("prepares a covered lower track at the time it will be revealed", () => {
const segments = previewSegments([track([clip("top", 0, 2000)]), track([clip("lower", 0, 6000, { sourceStartMs: 8000 })])], assets);
expect(segments.map((segment) => [segment.startMs, segment.clips.map((clip) => clip.id)])).toEqual([
diff --git a/src/lib/timelinePreview.ts b/src/lib/timelinePreview.ts
index bdc5ce1..f263152 100644
--- a/src/lib/timelinePreview.ts
+++ b/src/lib/timelinePreview.ts
@@ -1,4 +1,5 @@
import { visibleClipsAt } from "./export";
+import { clipPlaybackRate, clipSourceTimeMs } from "./clipTiming";
import { clipTransition, type ProjectAsset, type TimelineClip, type TimelineTrack } from "./project";
export type PreviewSegment = { startMs: number; clips: TimelineClip[] };
@@ -38,16 +39,40 @@ export function previewSegmentIndex(segments: PreviewSegment[], timeMs: number):
return low;
}
-/** Keep the current picture and the next two pictures mounted. A prepared
- * player is keyed by clip, since two trims of one asset need separate seeks. */
-export function preparedPreviewClips(segments: PreviewSegment[], index: number) {
- const prepared = new Map<string, { clip: TimelineClip; prepareAtMs: number }>();
+/** Adjacent ranges of a joined generation can keep one running decoder.
+ * Preserve separate players for gaps, overlaps, changed speeds and other trims. */
+export function previewPlayerKeys(tracks: TimelineTrack[], assets: ReadonlyMap<string, ProjectAsset>) {
+ const keys = new Map<string, string>();
+ for (const track of tracks) {
+ if (track.kind !== "video") continue;
+ let previous: TimelineClip | undefined;
+ for (const clip of [...track.clips].sort((a, b) => a.startMs - b.startMs)) {
+ const asset = assets.get(clip.assetId);
+ const rate = clipPlaybackRate(clip);
+ const continuous = previous && (asset?.sceneSegments?.length ?? 0) > 1
+ && previous.assetId === clip.assetId && clipPlaybackRate(previous) === rate
+ && previous.startMs + previous.durationMs === clip.startMs
+ // Scene durations are stored in whole milliseconds; their frame
+ // offsets are exact. Allow only that half-millisecond rounding error.
+ && Math.abs(clipSourceTimeMs(previous, clip.startMs) - clip.sourceStartMs) <= rate / 2 + 1e-6;
+ keys.set(clip.id, continuous ? keys.get(previous!.id)! : clip.id);
+ previous = clip;
+ }
+ }
+ return keys;
+}
+
+/** Keep the current picture and the next two pictures mounted. Continuous
+ * joined scenes share a player; unrelated trims still prepare independently. */
+export function preparedPreviewClips(segments: PreviewSegment[], index: number, playerKeys?: ReadonlyMap<string, string>) {
+ const prepared = new Map<string, { clip: TimelineClip; prepareAtMs: number; playerKey: string }>();
let pictures = 0;
for (let next = index; next < segments.length && pictures < 3; next++) {
const segment = segments[next];
if (segment.clips.length) pictures++;
for (const clip of segment.clips) {
- if (!prepared.has(clip.id)) prepared.set(clip.id, { clip, prepareAtMs: segment.startMs });
+ const playerKey = playerKeys?.get(clip.id) ?? clip.id;
+ if (!prepared.has(playerKey)) prepared.set(playerKey, { clip, prepareAtMs: segment.startMs, playerKey });
}
}
return [...prepared.values()];