Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Add the export view, its styles and the workspace route

Bitti5c08f3384ad4
diff --git a/src/components/ProjectWorkspace.tsx b/src/components/ProjectWorkspace.tsx
index 9f085ff..b08f554 100644
--- a/src/components/ProjectWorkspace.tsx
+++ b/src/components/ProjectWorkspace.tsx
@@ -3,11 +3,12 @@ import { useState } from "react";
import type { ProjectConfig, ProjectRecord } from "../lib/project";
import { CHECKING_PROVIDERS, type RuntimeStatus } from "../lib/runtime";
import { AgentDock } from "./workspace/AgentDock";
+import { ExportView } from "./workspace/ExportView";
import { GeneratorView } from "./workspace/GeneratorView";
import { ReferencesView } from "./workspace/ReferencesView";
import { TimelineView } from "./workspace/TimelineView";
-export type ProjectView = "timeline" | "generator" | "references";
+export type ProjectView = "timeline" | "generator" | "references" | "export";
export function formatDurationTimecode(totalSeconds: number): string {
const seconds = Math.max(0, Math.floor(totalSeconds));
@@ -74,9 +75,16 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =
</nav>
<div className="project-topbar__actions">
- {/* Export is not wired to anything yet, so it must not look like a working action. */}
- <button className="secondary-button" type="button" disabled title="Export isn’t available yet. PolStudio can’t save generated shots as video files yet, so there is nothing to export.">
- <Download size={16} aria-hidden="true" /> Export <span className="project-topbar__soon">Soon</span>
+ {/* A real view now: it renders the timeline through WebCodecs and writes
+ an .mp4. It stays honest about what it cannot do inside itself. */}
+ <button
+ className="secondary-button"
+ type="button"
+ aria-current={view === "export" ? "page" : undefined}
+ onClick={() => setView("export")}
+ title="Render the timeline to a video file"
+ >
+ <Download size={16} aria-hidden="true" /> Export
</button>
{/* The standing "All changes saved" pill is gone; the button itself is
now the only save state there is, so it has to carry it. Off means
@@ -91,9 +99,10 @@ export function ProjectWorkspace({ project, initialView = "timeline", runtime =
{view === "timeline" && <TimelineView config={config} folderPath={project.folderPath} onChange={changeConfig} onOpenGenerator={(jobId) => { setSelectedGenerationJobId(jobId); setView("generator"); }} />}
{view === "generator" && <GeneratorView config={config} folderPath={project.folderPath} runtime={runtime?.vidfab ?? null} onChange={changeConfig} selectedJobId={selectedGenerationJobId} onOpenTimeline={() => setView("timeline")} draftPrompt={generatorPrompt} onDraftPromptChange={setGeneratorPrompt} />}
{view === "references" && <ReferencesView config={config} folderPath={project.folderPath} onChange={changeConfig} />}
+ {view === "export" && <ExportView config={config} folderPath={project.folderPath} />}
</div>
<footer className="project-agent-row"><AgentDock
- context={view === "timeline" ? "the edit" : view === "generator" ? "this generation queue" : "project references"}
+ context={view === "timeline" ? "the edit" : view === "generator" ? "this generation queue" : view === "export" ? "this export" : "project references"}
record={{ ...project, config }}
providers={runtime?.providers ?? CHECKING_PROVIDERS}
/* Routed through the same save() as the Save button. Clearing `dirty`
diff --git a/src/components/workspace/ExportView.tsx b/src/components/workspace/ExportView.tsx
new file mode 100644
index 0000000..7d8e98f
--- /dev/null
+++ b/src/components/workspace/ExportView.tsx
@@ -0,0 +1,419 @@
+import { CircleCheck, Download, FileVideo, TriangleAlert, X } from "lucide-react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import {
+ bitrateFor,
+ buildExportPlan,
+ defaultExportSettings,
+ estimatedBytes,
+ formatBytes,
+ formatDuration,
+ outputDimensions,
+ OUTPUT_CODECS,
+ QUALITY_PRESETS,
+ qualityPreset,
+ suggestedFileName,
+ visibleClipAt,
+ type ExportSettings,
+ type FrameRate,
+ type OutputCodecId,
+ type QualityId,
+} from "../../lib/export";
+import {
+ chooseExportDestination,
+ detectExportSupport,
+ drawPreviewFrame,
+ ExportCancelled,
+ PreviewSources,
+ probeAllCodecs,
+ runExport,
+ writeExportFile,
+ type CodecProbe,
+ type CompositorKind,
+ type ExportProgress,
+} from "../../lib/exportPipeline";
+import type { ProjectConfig, Resolution } from "../../lib/project";
+
+const RESOLUTIONS: Resolution[] = ["720p", "1080p", "4k"];
+const FRAME_RATES: FrameRate[] = [24, 25, 30, 60];
+/* The preview is a picture, not a deliverable: 480px on the long edge is
+ enough to judge framing and costs a fraction of a full-size decode. */
+const PREVIEW_LONG_EDGE = 480;
+
+const describe = (reason: unknown) => (reason instanceof Error ? reason.message : String(reason));
+
+interface FinishedExport {
+ path: string;
+ bytes: number;
+ compositor: CompositorKind;
+ codecString: string;
+}
+
+export function ExportView({ config, folderPath }: { config: ProjectConfig; folderPath: string }) {
+ const [settings, setSettings] = useState<ExportSettings>(() => defaultExportSettings(config));
+ const plan = useMemo(() => buildExportPlan(config, settings), [config, settings]);
+ const bitrate = useMemo(
+ () => bitrateFor(plan.width, plan.height, plan.frameRate, settings.quality),
+ [plan.width, plan.height, plan.frameRate, settings.quality],
+ );
+ /* What this computer can actually do, asked once. Everything the view offers
+ is gated on the answer rather than on what the code hopes is there. */
+ const support = useMemo(detectExportSupport, []);
+ const [probes, setProbes] = useState<CodecProbe[] | null>(null);
+
+ const [previewTimeMs, setPreviewTimeMs] = useState(0);
+ const [previewBusy, setPreviewBusy] = useState(false);
+ const [previewError, setPreviewError] = useState<string | null>(null);
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ const sourcesRef = useRef<PreviewSources | null>(null);
+
+ const [progress, setProgress] = useState<ExportProgress | null>(null);
+ const [result, setResult] = useState<FinishedExport | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [cancelled, setCancelled] = useState(false);
+ const cancelRef = useRef(false);
+ const running = progress !== null;
+
+ const previewScale = Math.min(1, PREVIEW_LONG_EDGE / Math.max(plan.width, plan.height));
+ const previewWidth = Math.max(2, Math.round(plan.width * previewScale));
+ const previewHeight = Math.max(2, Math.round(plan.height * previewScale));
+
+ const previewClip = useMemo(
+ () => visibleClipAt(config.timeline.tracks, previewTimeMs),
+ [config.timeline.tracks, previewTimeMs],
+ );
+
+ useEffect(() => {
+ const sources = new PreviewSources(folderPath);
+ sourcesRef.current = sources;
+ return () => {
+ sources.dispose();
+ sourcesRef.current = null;
+ };
+ }, [folderPath]);
+
+ // A scrub past the end of a shortened timeline would ask for a frame nothing
+ // renders, so the playhead follows the content.
+ useEffect(() => {
+ setPreviewTimeMs((current) => Math.min(current, Math.max(0, plan.durationMs - 1)));
+ }, [plan.durationMs]);
+
+ useEffect(() => {
+ if (!support.encoder || plan.frameCount === 0) {
+ setProbes(null);
+ return;
+ }
+ let live = true;
+ setProbes(null);
+ void probeAllCodecs(plan, bitrate)
+ .then((found) => {
+ if (live) setProbes(found);
+ })
+ .catch(() => {
+ if (live) setProbes(null);
+ });
+ return () => {
+ live = false;
+ };
+ /* Deliberately keyed on the plan's shape rather than on the plan: it is a
+ new object on every settings change, and re-probing the encoder for a
+ changed clip label would be a stutter for nothing. */
+ }, [support.encoder, plan.width, plan.height, plan.frameRate, plan.frameCount, bitrate]);
+
+ /* The preview decodes the real file through the webview's own hardware
+ decoder and lays it out with the export's geometry. It is debounced because
+ a scrub is a hundred requests, not one. */
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ const sources = sourcesRef.current;
+ if (!canvas || !sources || !support.desktop || running) return;
+ let live = true;
+ setPreviewError(null);
+ setPreviewBusy(true);
+ const timer = window.setTimeout(() => {
+ void drawPreviewFrame({
+ canvas,
+ plan,
+ config,
+ sources,
+ clip: previewClip
+ ? {
+ assetId: previewClip.assetId,
+ sourceTimeMs: previewClip.sourceStartMs + (previewTimeMs - previewClip.startMs),
+ }
+ : null,
+ })
+ .then(() => {
+ if (live) setPreviewBusy(false);
+ })
+ .catch((reason) => {
+ if (!live) return;
+ setPreviewBusy(false);
+ setPreviewError(describe(reason));
+ });
+ }, 120);
+ return () => {
+ live = false;
+ window.clearTimeout(timer);
+ };
+ }, [config, previewClip, previewTimeMs, plan.backgroundColor, previewWidth, previewHeight, support.desktop, running]);
+
+ const codecProbe = probes?.find((probe) => probe.id === settings.codec) ?? null;
+ const blockers = [...plan.blockers];
+ if (!support.desktop) {
+ blockers.push(
+ "This is the browser preview. There is no project folder to read media from and nowhere on disk to write a file, so exporting is only available in the PolStudio desktop app.",
+ );
+ }
+ if (!support.encoder || !support.decoder) {
+ blockers.push("This webview has no WebCodecs VideoEncoder/VideoDecoder, so it cannot decode or encode video.");
+ }
+ if (codecProbe && !codecProbe.supported) {
+ blockers.push(`This computer will not encode ${settings.codec.toUpperCase()} at ${plan.width}×${plan.height}: ${codecProbe.detail}`);
+ }
+ const canExport = blockers.length === 0 && !running;
+
+ const start = async () => {
+ setError(null);
+ setResult(null);
+ setCancelled(false);
+ let destination: string | null = null;
+ try {
+ destination = await chooseExportDestination(suggestedFileName(config.name));
+ } catch (reason) {
+ setError(describe(reason));
+ return;
+ }
+ if (!destination) return; // The user closed the save dialog. Nothing to say.
+ cancelRef.current = false;
+ setProgress({ phase: "preparing", framesDone: 0, frameCount: plan.frameCount, detail: "Starting…" });
+ try {
+ const outcome = await runExport({
+ folderPath,
+ config,
+ settings,
+ plan,
+ bitrate,
+ onProgress: setProgress,
+ cancelled: () => cancelRef.current,
+ });
+ setProgress({
+ phase: "writing",
+ framesDone: plan.frameCount,
+ frameCount: plan.frameCount,
+ detail: `Writing ${formatBytes(outcome.bytes.byteLength)} to ${destination}…`,
+ });
+ const written = await writeExportFile(destination, outcome.bytes);
+ setResult({ path: destination, bytes: written, compositor: outcome.compositor, codecString: outcome.codecString });
+ } catch (reason) {
+ if (reason instanceof ExportCancelled) setCancelled(true);
+ else setError(describe(reason));
+ } finally {
+ setProgress(null);
+ }
+ };
+
+ const summary: Array<[string, string, string?]> = [
+ ["Duration", formatDuration(plan.durationMs), `${plan.frameCount} frames at ${plan.frameRate} fps`],
+ ["Clips", String(plan.clipCount), plan.gapFrames > 0 ? `${plan.gapFrames} background frames` : "no gaps"],
+ ["Frame", `${plan.width} × ${plan.height}`, `${config.settings.aspectRatio} · ${settings.resolution}`],
+ [
+ "Video",
+ `${OUTPUT_CODECS.find((codec) => codec.id === settings.codec)?.label ?? settings.codec} in MP4`,
+ codecProbe?.codecString ?? (probes ? "unsupported here" : "asking the encoder…"),
+ ],
+ ["Bitrate", `${(bitrate / 1_000_000).toFixed(1)} Mbit/s`, qualityPreset(settings.quality).label],
+ [
+ "Estimated size",
+ formatBytes(estimatedBytes(bitrate, plan.durationMs)),
+ "target bitrate × duration, not a measurement",
+ ],
+ ["Sound", "None", "video only — see below"],
+ ];
+
+ return <div className="export-view">
+ <header className="export-heading">
+ <div>
+ <span className="eyebrow">Deliver</span>
+ <h1>Export</h1>
+ <p>
+ PolStudio renders the video tracks in order — trims, gaps and all — decoding each source file with this
+ computer’s hardware, compositing on the GPU and writing a real .mp4. Nothing below is a mock-up: if a control
+ cannot do its job here, it says why instead of pretending.
+ </p>
+ </div>
+ </header>
+
+ <div className="export-layout">
+ <section className="export-preview" aria-labelledby="export-preview-heading">
+ <h2 id="export-preview-heading">Preview</h2>
+ <div className="export-stage" style={{ aspectRatio: `${plan.width} / ${plan.height}` }}>
+ {support.desktop
+ ? <canvas ref={canvasRef} width={previewWidth} height={previewHeight} aria-label={`Frame at ${formatDuration(previewTimeMs)}`} />
+ : <p className="export-stage__note">
+ No frame to show. The browser preview has no project folder, so there is no file to decode —
+ this is a labelled empty stage, not a picture of your edit.
+ </p>}
+ {previewError && <p className="export-stage__note export-stage__note--bad"><TriangleAlert size={16} aria-hidden="true" /> {previewError}</p>}
+ </div>
+ <label className="export-scrub" htmlFor="export-scrub">
+ <span>Playhead</span>
+ <input
+ id="export-scrub"
+ type="range"
+ min={0}
+ max={Math.max(0, plan.durationMs - 1)}
+ step={Math.max(1, Math.round(1000 / plan.frameRate))}
+ value={previewTimeMs}
+ disabled={plan.frameCount === 0}
+ onChange={(event) => setPreviewTimeMs(Number(event.target.value))}
+ />
+ <output htmlFor="export-scrub">{formatDuration(previewTimeMs)}</output>
+ </label>
+ <p className="export-stage__caption">
+ {plan.frameCount === 0
+ ? "There is nothing on the timeline yet."
+ : previewClip
+ ? <>Frame {Math.round((previewTimeMs * plan.frameRate) / 1000)} · <strong>{previewClip.label}</strong> at {formatDuration(previewClip.sourceStartMs + (previewTimeMs - previewClip.startMs))} into its source file{previewBusy ? " · decoding…" : ""}</>
+ : <>Frame {Math.round((previewTimeMs * plan.frameRate) / 1000)} · no clip here, so the frame is solid {plan.backgroundColor}.</>}
+ </p>
+ </section>
+
+ <section className="export-settings" aria-labelledby="export-settings-heading">
+ <h2 id="export-settings-heading">Settings</h2>
+ <p className="export-settings__lead">These start from this project’s own settings. Changing them here does not change the project.</p>
+
+ <div className="export-fields">
+ <label htmlFor="export-resolution">
+ <span>Resolution</span>
+ <select
+ id="export-resolution"
+ value={settings.resolution}
+ disabled={running}
+ onChange={(event) => setSettings({ ...settings, resolution: event.target.value as Resolution })}
+ >
+ {RESOLUTIONS.map((resolution) => {
+ const size = outputDimensions(resolution, config.settings.aspectRatio);
+ return <option key={resolution} value={resolution}>{resolution} · {size.width} × {size.height}</option>;
+ })}
+ </select>
+ </label>
+
+ <label htmlFor="export-frame-rate">
+ <span>Frame rate</span>
+ <select
+ id="export-frame-rate"
+ value={settings.frameRate}
+ disabled={running}
+ onChange={(event) => setSettings({ ...settings, frameRate: Number(event.target.value) as FrameRate })}
+ >
+ {FRAME_RATES.map((rate) => <option key={rate} value={rate}>{rate} fps</option>)}
+ </select>
+ </label>
+
+ <label htmlFor="export-codec">
+ <span>Container &amp; codec</span>
+ <select
+ id="export-codec"
+ value={settings.codec}
+ disabled={running}
+ onChange={(event) => setSettings({ ...settings, codec: event.target.value as OutputCodecId })}
+ >
+ {OUTPUT_CODECS.map((codec) => {
+ const probe = probes?.find((candidate) => candidate.id === codec.id);
+ const unsupported = probe ? !probe.supported : false;
+ return <option key={codec.id} value={codec.id} disabled={unsupported} title={probe?.detail ?? codec.detail}>
+ .mp4 · {codec.label}{unsupported ? " — not supported here" : ""}
+ </option>;
+ })}
+ </select>
+ </label>
+
+ <label htmlFor="export-quality">
+ <span>Quality</span>
+ <select
+ id="export-quality"
+ value={settings.quality}
+ disabled={running}
+ onChange={(event) => setSettings({ ...settings, quality: event.target.value as QualityId })}
+ >
+ {QUALITY_PRESETS.map((preset) => <option key={preset.id} value={preset.id} title={preset.detail}>
+ {preset.label} · {(bitrateFor(plan.width, plan.height, plan.frameRate, preset.id) / 1_000_000).toFixed(1)} Mbit/s
+ </option>)}
+ </select>
+ </label>
+
+ <div className="export-field-note">
+ <span>Destination</span>
+ <p>{result
+ ? <>Last written to <code>{result.path}</code>.</>
+ : "PolStudio opens your computer’s save dialog when you press Export, and writes only after the encode finishes."}</p>
+ </div>
+ </div>
+
+ <h2>What this export will be</h2>
+ <dl className="export-summary">
+ {summary.map(([term, value, detail]) => <div key={term}>
+ <dt>{term}</dt>
+ <dd>{value}{detail && <small>{detail}</small>}</dd>
+ </div>)}
+ </dl>
+
+ {plan.notes.length > 0 && <div className="export-notice" role="note">
+ <h3><TriangleAlert size={16} aria-hidden="true" /> True of this export</h3>
+ <ul>{plan.notes.map((note) => <li key={note}>{note}</li>)}</ul>
+ </div>}
+
+ {blockers.length > 0 && <div className="export-notice export-notice--bad" role="alert">
+ <h3><TriangleAlert size={16} aria-hidden="true" /> Not possible yet</h3>
+ <ul>{blockers.map((blocker) => <li key={blocker}>{blocker}</li>)}</ul>
+ </div>}
+
+ <div className="export-actions">
+ <button
+ className="primary-button"
+ type="button"
+ disabled={!canExport}
+ onClick={() => void start()}
+ title={canExport ? "Choose where to save, then render the timeline" : blockers[0] ?? "Export is running"}
+ >
+ <Download size={16} aria-hidden="true" /> {running ? "Exporting…" : "Export video"}
+ </button>
+ {running && <button
+ className="secondary-button"
+ type="button"
+ onClick={() => { cancelRef.current = true; }}
+ title="Stop encoding. Nothing has been written to disk yet."
+ ><X size={16} aria-hidden="true" /> Cancel</button>}
+ </div>
+
+ {progress && <div className="export-progress" role="status">
+ <div className="progress-track">
+ <i style={{ width: `${progress.frameCount === 0 ? 0 : Math.round((progress.framesDone / progress.frameCount) * 100)}%` }} />
+ </div>
+ <p>{progress.detail} <small>{progress.framesDone} / {progress.frameCount} frames</small></p>
+ </div>}
+
+ {cancelled && <p className="export-outcome" role="status">
+ Export cancelled. Nothing was written — the file is only saved once the whole encode finishes.
+ </p>}
+
+ {error && <div className="export-notice export-notice--bad" role="alert">
+ <h3><TriangleAlert size={16} aria-hidden="true" /> The export failed</h3>
+ {/* Verbatim. A rewritten error is an error nobody can act on. */}
+ <p>{error}</p>
+ </div>}
+
+ {result && <div className="export-outcome export-outcome--good" role="status">
+ <h3><CircleCheck size={16} aria-hidden="true" /> Saved</h3>
+ <p>
+ <FileVideo size={14} aria-hidden="true" /> <code>{result.path}</code>
+ </p>
+ <p>
+ {formatBytes(result.bytes)} written · {result.codecString} · composited with{" "}
+ {result.compositor === "webgpu" ? "WebGPU" : "a 2D canvas (WebGPU was unavailable)"} · no audio track.
+ </p>
+ </div>}
+ </section>
+ </div>
+ </div>;
+}
diff --git a/src/lib/export.test.ts b/src/lib/export.test.ts
new file mode 100644
index 0000000..8be1d5e
--- /dev/null
+++ b/src/lib/export.test.ts
@@ -0,0 +1,295 @@
+import { describe, expect, it } from "vitest";
+import {
+ bitrateFor,
+ buildExportPlan,
+ defaultExportSettings,
+ estimatedBytes,
+ fitRect,
+ formatBytes,
+ formatDuration,
+ outputDimensions,
+ sourceTimeMsForFrame,
+ suggestedFileName,
+ videoDurationMs,
+ visibleClipAt,
+ type ExportSegment,
+ type ExportSettings,
+} from "./export";
+import { createProjectConfig, type ProjectAsset, type ProjectConfig, type TimelineClip } from "./project";
+
+const asset = (id: string, overrides: Partial<ProjectAsset> = {}): ProjectAsset => ({
+ id,
+ kind: "video",
+ name: id,
+ relativePath: `media/${id}.mp4`,
+ mimeType: "video/mp4",
+ durationMs: 10_000,
+ width: 1920,
+ height: 1080,
+ createdAt: new Date(0).toISOString(),
+ ...overrides,
+});
+
+const clip = (id: string, trackId: string, startMs: number, durationMs: number, overrides: Partial<TimelineClip> = {}): TimelineClip => ({
+ id,
+ assetId: `asset-${id}`,
+ trackId,
+ startMs,
+ durationMs,
+ sourceStartMs: 0,
+ label: id,
+ color: null,
+ status: "approved",
+ ...overrides,
+});
+
+/** A project with the app's own five tracks, `clips` distributed by trackId. */
+function project(clips: TimelineClip[], assets: ProjectAsset[], overrides: Partial<ProjectConfig["settings"]> = {}): ProjectConfig {
+ const base = createProjectConfig({
+ name: "Test", prompt: "A test", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30,
+ });
+ return {
+ ...base,
+ settings: { ...base.settings, ...overrides },
+ assets,
+ timeline: {
+ tracks: base.timeline.tracks.map((track) => ({ ...track, clips: clips.filter((item) => item.trackId === track.id) })),
+ },
+ };
+}
+
+const settings = (overrides: Partial<ExportSettings> = {}): ExportSettings => ({
+ resolution: "1080p", frameRate: 30, codec: "h264", quality: "balanced", ...overrides,
+});
+
+const clipSegments = (segments: ExportSegment[]) => segments.flatMap((segment) => (segment.kind === "clip" ? [segment] : []));
+
+describe("output geometry", () => {
+ it("gives every aspect ratio the same short edge", () => {
+ expect(outputDimensions("1080p", "16:9")).toEqual({ width: 1920, height: 1080 });
+ expect(outputDimensions("1080p", "9:16")).toEqual({ width: 1080, height: 1920 });
+ expect(outputDimensions("1080p", "1:1")).toEqual({ width: 1080, height: 1080 });
+ expect(outputDimensions("1080p", "4:5")).toEqual({ width: 1080, height: 1350 });
+ expect(outputDimensions("720p", "16:9")).toEqual({ width: 1280, height: 720 });
+ expect(outputDimensions("4k", "16:9")).toEqual({ width: 3840, height: 2160 });
+ });
+
+ it("never produces an odd edge, which a 4:2:0 encoder refuses", () => {
+ for (const resolution of ["720p", "1080p", "4k"] as const) {
+ for (const ratio of ["16:9", "9:16", "1:1", "4:5"] as const) {
+ const { width, height } = outputDimensions(resolution, ratio);
+ expect(width % 2).toBe(0);
+ expect(height % 2).toBe(0);
+ }
+ }
+ });
+
+ it("fits a wide source into a tall frame with bars above and below", () => {
+ const box = fitRect(1920, 1080, 1080, 1920);
+ expect(box.width).toBe(1080);
+ expect(box.height).toBeCloseTo(607.5, 3);
+ expect(box.x).toBe(0);
+ expect(box.y).toBeCloseTo((1920 - 607.5) / 2, 3);
+ });
+
+ it("fills the frame exactly when the source already matches it", () => {
+ expect(fitRect(1920, 1080, 1280, 720)).toEqual({ x: 0, y: 0, width: 1280, height: 720 });
+ });
+
+ it("falls back to the whole frame rather than dividing by a zero size", () => {
+ expect(fitRect(0, 0, 640, 360)).toEqual({ x: 0, y: 0, width: 640, height: 360 });
+ });
+});
+
+describe("defaults", () => {
+ it("starts from the project's own settings instead of inventing numbers", () => {
+ const config = project([], [], { resolution: "4k", frameRate: 24 });
+ expect(defaultExportSettings(config)).toEqual({ resolution: "4k", frameRate: 24, codec: "h264", quality: "balanced" });
+ });
+
+ it("derives the bitrate from the frame size and rate", () => {
+ expect(bitrateFor(1920, 1080, 30, "balanced")).toBe(Math.round(1920 * 1080 * 30 * 0.09));
+ expect(bitrateFor(1920, 1080, 30, "draft")).toBeLessThan(bitrateFor(1920, 1080, 30, "high"));
+ expect(estimatedBytes(8_000_000, 10_000)).toBe(10_000_000);
+ });
+});
+
+describe("which clip is on screen at time T", () => {
+ const tracks = () =>
+ project(
+ [clip("a", "track-story", 0, 4_000), clip("b", "track-story", 4_000, 4_000), clip("over", "track-overlay", 2_000, 1_000)],
+ [],
+ ).timeline.tracks;
+
+ it("treats a clip as covering its start and not its end", () => {
+ expect(visibleClipAt(tracks(), 0)?.id).toBe("a");
+ expect(visibleClipAt(tracks(), 3_999)?.id).toBe("a");
+ expect(visibleClipAt(tracks(), 4_000)?.id).toBe("b");
+ expect(visibleClipAt(tracks(), 7_999)?.id).toBe("b");
+ expect(visibleClipAt(tracks(), 8_000)).toBeNull();
+ });
+
+ it("lets the upper track cover the one below it", () => {
+ expect(visibleClipAt(tracks(), 2_500)?.id).toBe("over");
+ expect(visibleClipAt(tracks(), 2_999)?.id).toBe("over");
+ expect(visibleClipAt(tracks(), 3_000)?.id).toBe("a");
+ });
+
+ it("puts the later clip on top when two on one track overlap", () => {
+ const overlapping = project([clip("under", "track-story", 0, 4_000), clip("later", "track-story", 1_000, 1_000)], []);
+ expect(visibleClipAt(overlapping.timeline.tracks, 1_500)?.id).toBe("later");
+ expect(visibleClipAt(overlapping.timeline.tracks, 500)?.id).toBe("under");
+ });
+
+ it("ignores audio tracks, which have no picture", () => {
+ const withSound = project([clip("music", "track-music", 0, 5_000)], []);
+ expect(visibleClipAt(withSound.timeline.tracks, 1_000)).toBeNull();
+ expect(videoDurationMs(withSound)).toBe(0);
+ });
+});
+
+describe("the plan", () => {
+ it("turns two back-to-back clips into two segments of the right length", () => {
+ const config = project(
+ [clip("a", "track-story", 0, 2_000), clip("b", "track-story", 2_000, 1_000)],
+ [asset("asset-a"), asset("asset-b")],
+ );
+ const plan = buildExportPlan(config, settings());
+ expect(plan.durationMs).toBe(3_000);
+ expect(plan.frameCount).toBe(90);
+ expect(plan.clipCount).toBe(2);
+ expect(plan.gapFrames).toBe(0);
+ expect(plan.blockers).toEqual([]);
+ expect(clipSegments(plan.segments).map((segment) => [segment.clipId, segment.startFrame, segment.endFrame])).toEqual([
+ ["a", 0, 60],
+ ["b", 60, 90],
+ ]);
+ });
+
+ it("counts frames at the rate the user picked, not the project's", () => {
+ const config = project([clip("a", "track-story", 0, 2_000)], [asset("asset-a")]);
+ expect(buildExportPlan(config, settings({ frameRate: 24 })).frameCount).toBe(48);
+ expect(buildExportPlan(config, settings({ frameRate: 60 })).frameCount).toBe(120);
+ });
+
+ it("fills a hole between clips with background frames and says so", () => {
+ const config = project(
+ [clip("a", "track-story", 0, 1_000), clip("b", "track-story", 2_000, 1_000)],
+ [asset("asset-a"), asset("asset-b")],
+ );
+ const plan = buildExportPlan(config, settings());
+ expect(plan.segments.map((segment) => segment.kind)).toEqual(["clip", "gap", "clip"]);
+ expect(plan.gapFrames).toBe(30);
+ expect(plan.notes.join(" ")).toContain("30 of 90 frames have no clip over them");
+ });
+
+ it("splits one clip into two segments when an overlay cuts through it", () => {
+ const config = project(
+ [clip("under", "track-story", 0, 3_000), clip("over", "track-overlay", 1_000, 1_000)],
+ [asset("asset-under"), asset("asset-over")],
+ );
+ const plan = buildExportPlan(config, settings());
+ expect(clipSegments(plan.segments).map((segment) => [segment.clipId, segment.startFrame, segment.endFrame])).toEqual([
+ ["under", 0, 30],
+ ["over", 30, 60],
+ ["under", 60, 90],
+ ]);
+ expect(plan.clipCount).toBe(2);
+ });
+
+ it("says nothing about a soundtrack it cannot mux, but does not stay silent either", () => {
+ const config = project(
+ [clip("a", "track-story", 0, 1_000), clip("score", "track-music", 0, 5_000)],
+ [asset("asset-a"), asset("asset-score", { kind: "audio", mimeType: "audio/wav" })],
+ );
+ const plan = buildExportPlan(config, settings());
+ expect(plan.audioClipCount).toBe(1);
+ expect(plan.durationMs).toBe(1_000);
+ expect(plan.notes.join(" ")).toContain("no sound");
+ });
+
+ it("blocks on an empty timeline, on missing media and on a container it cannot demux", () => {
+ expect(buildExportPlan(project([], []), settings()).blockers[0]).toContain("no video clips");
+
+ const orphan = project([clip("a", "track-story", 0, 1_000)], []);
+ expect(buildExportPlan(orphan, settings()).blockers.join(" ")).toContain("not in this project");
+
+ const webm = project([clip("a", "track-story", 0, 1_000)], [asset("asset-a", { mimeType: "video/webm" })]);
+ expect(buildExportPlan(webm, settings()).blockers.join(" ")).toContain("video/webm");
+ });
+
+ it("accepts a still image on a video track", () => {
+ const config = project([clip("a", "track-story", 0, 1_000)], [asset("asset-a", { kind: "image", mimeType: "image/png" })]);
+ expect(buildExportPlan(config, settings()).blockers).toEqual([]);
+ });
+
+ it("reports clips that are hidden underneath another track", () => {
+ const config = project(
+ [clip("hidden", "track-b-roll", 0, 1_000), clip("over", "track-story", 0, 1_000)],
+ [asset("asset-hidden"), asset("asset-over")],
+ );
+ expect(buildExportPlan(config, settings()).notes.join(" ")).toContain("hidden underneath");
+ });
+});
+
+describe("where each output frame comes from inside the source file", () => {
+ it("starts at the clip's own trim point and advances one frame at a time", () => {
+ const config = project(
+ [clip("a", "track-story", 4_000, 2_000, { sourceStartMs: 10_000 })],
+ [asset("asset-a")],
+ );
+ const plan = buildExportPlan(config, settings({ frameRate: 25 }));
+ const [segment] = clipSegments(plan.segments);
+ expect([segment.startFrame, segment.endFrame]).toEqual([100, 150]);
+ // Output frame 100 sits at 4000 ms, which is the first frame of the clip.
+ expect(sourceTimeMsForFrame(segment, 100, 25)).toBe(10_000);
+ expect(sourceTimeMsForFrame(segment, 101, 25)).toBe(10_040);
+ expect(sourceTimeMsForFrame(segment, 149, 25)).toBe(11_960);
+ });
+
+ it("keeps the source offset when a clip does not begin on a frame boundary", () => {
+ const config = project([clip("a", "track-story", 0, 1_000, { sourceStartMs: 500 })], [asset("asset-a")]);
+ const plan = buildExportPlan(config, settings({ frameRate: 24 }));
+ const [segment] = clipSegments(plan.segments);
+ // 24 fps has no frame at 500 ms; frame 12 is at 500 ms exactly, frame 13 at 541.67.
+ expect(sourceTimeMsForFrame(segment, 0, 24)).toBe(500);
+ expect(sourceTimeMsForFrame(segment, 12, 24)).toBe(1_000);
+ expect(sourceTimeMsForFrame(segment, 13, 24)).toBeCloseTo(1_041.667, 3);
+ });
+
+ it("reads the second half of a split clip from the second half of the file", () => {
+ const config = project(
+ [
+ clip("a", "track-story", 0, 1_000, { sourceStartMs: 0 }),
+ clip("a-b", "track-story", 1_000, 1_000, { assetId: "asset-a", sourceStartMs: 1_000 }),
+ ],
+ [asset("asset-a")],
+ );
+ const plan = buildExportPlan(config, settings());
+ const [first, second] = clipSegments(plan.segments);
+ expect(sourceTimeMsForFrame(first, first.startFrame, 30)).toBe(0);
+ expect(sourceTimeMsForFrame(second, second.startFrame, 30)).toBe(1_000);
+ expect(second.assetId).toBe("asset-a");
+ });
+});
+
+describe("formatting", () => {
+ it("scales bytes without claiming precision it does not have", () => {
+ expect(formatBytes(512)).toBe("512 B");
+ expect(formatBytes(2_400)).toBe("2.4 kB");
+ expect(formatBytes(15_600_000)).toBe("15.6 MB");
+ expect(formatBytes(2_400_000_000)).toBe("2.4 GB");
+ });
+
+ it("writes a timeline duration to the millisecond", () => {
+ expect(formatDuration(0)).toBe("00:00.000");
+ expect(formatDuration(31_800)).toBe("00:31.800");
+ expect(formatDuration(125_004)).toBe("02:05.004");
+ });
+
+ it("turns a project name into something a filesystem accepts", () => {
+ expect(suggestedFileName("Northern Light — Brand Film")).toBe("Northern Light — Brand Film.mp4");
+ expect(suggestedFileName("a/b:c*d?")).toBe("a b c d.mp4");
+ expect(suggestedFileName(" ")).toBe("PolStudio export.mp4");
+ });
+});
diff --git a/src/styles/export.css b/src/styles/export.css
new file mode 100644
index 0000000..3bf2b40
--- /dev/null
+++ b/src/styles/export.css
@@ -0,0 +1,389 @@
+/* ============================================================================
+ export.css — the Export screen: settings, preview, and the run itself.
+
+ Sizing contract (see tokens.css): no literal px type sizes, nothing below
+ --text-2xs (12px), every interactive control at least --control-sm (36px).
+ ========================================================================== */
+
+.export-view {
+ height: 100%;
+ min-height: 0;
+ overflow-y: auto;
+ padding: var(--space-6) var(--space-7) var(--space-7);
+ background:
+ radial-gradient(circle at 80% -20%, rgba(47, 69, 107, 0.13), transparent 38%),
+ var(--bg);
+}
+
+.export-heading {
+ max-width: var(--content-max);
+ margin: 0 auto var(--space-5);
+}
+
+.export-heading h1 {
+ margin: var(--space-2) 0;
+ font-size: var(--text-2xl);
+ font-weight: var(--weight-semibold);
+ line-height: var(--leading-tight);
+ letter-spacing: var(--tracking-hero);
+}
+
+.export-heading p {
+ margin: 0;
+ max-width: 76ch;
+ color: var(--text-secondary);
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+}
+
+/* --- Layout ---------------------------------------------------------------- */
+
+.export-layout {
+ max-width: var(--content-max);
+ margin: 0 auto;
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 420px;
+ gap: var(--space-5);
+ align-items: start;
+}
+
+@media (max-width: 1120px) {
+ .export-layout {
+ grid-template-columns: minmax(0, 1fr);
+ }
+}
+
+.export-preview,
+.export-settings {
+ min-width: 0;
+ padding: var(--space-5);
+ border: 1px solid var(--line-strong);
+ border-radius: var(--radius-lg);
+ background: var(--panel);
+}
+
+.export-preview h2,
+.export-settings h2 {
+ margin: 0 0 var(--space-3);
+ font-size: var(--text-md);
+ font-weight: var(--weight-semibold);
+ letter-spacing: var(--tracking-tight);
+}
+
+.export-settings h2:not(:first-of-type) {
+ margin-top: var(--space-5);
+}
+
+/* --- Preview --------------------------------------------------------------- */
+
+.export-stage {
+ position: relative;
+ width: 100%;
+ max-height: 56vh;
+ margin-bottom: var(--space-3);
+ display: grid;
+ place-items: center;
+ overflow: hidden;
+ border: 1px solid var(--line);
+ border-radius: var(--radius-md);
+ /* Deliberately not the project background: the frame paints its own, and a
+ matching surround would hide where the picture actually ends. */
+ background: #05070b;
+}
+
+.export-stage canvas {
+ width: 100%;
+ height: 100%;
+ display: block;
+ object-fit: contain;
+}
+
+.export-stage__note {
+ max-width: 46ch;
+ margin: 0;
+ padding: var(--space-4);
+ color: var(--text-muted);
+ font-size: var(--text-xs);
+ line-height: var(--leading-normal);
+ text-align: center;
+}
+
+.export-stage__note--bad {
+ position: absolute;
+ inset: auto var(--space-3) var(--space-3);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: var(--space-2);
+ border: 1px solid rgba(236, 125, 134, 0.4);
+ border-radius: var(--radius-sm);
+ color: var(--danger);
+ background: rgba(12, 8, 10, 0.9);
+ text-align: left;
+}
+
+.export-stage__note--bad svg {
+ flex: 0 0 auto;
+}
+
+.export-stage__caption {
+ margin: var(--space-3) 0 0;
+ color: var(--text-muted);
+ font-size: var(--text-xs);
+ line-height: var(--leading-normal);
+}
+
+.export-stage__caption strong {
+ color: var(--text-secondary);
+ font-weight: var(--weight-medium);
+}
+
+.export-scrub {
+ min-height: var(--control-sm);
+ display: flex;
+ align-items: center;
+ gap: var(--space-3);
+}
+
+.export-scrub > span {
+ flex: 0 0 auto;
+ color: var(--text-muted);
+ font-size: var(--text-2xs);
+ font-weight: var(--weight-medium);
+ letter-spacing: var(--tracking-label);
+ text-transform: uppercase;
+}
+
+.export-scrub input[type="range"] {
+ flex: 1 1 auto;
+ min-width: 0;
+ height: var(--control-sm);
+ accent-color: var(--accent-bright);
+ cursor: pointer;
+}
+
+.export-scrub output {
+ flex: 0 0 auto;
+ color: var(--text-secondary);
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs);
+}
+
+/* --- Settings -------------------------------------------------------------- */
+
+.export-settings__lead {
+ margin: 0 0 var(--space-4);
+ color: var(--text-muted);
+ font-size: var(--text-xs);
+ line-height: var(--leading-normal);
+}
+
+.export-fields {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
+ gap: var(--space-3);
+}
+
+.export-fields label,
+.export-field-note {
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+}
+
+.export-field-note {
+ grid-column: 1 / -1;
+}
+
+.export-fields label > span,
+.export-field-note > span {
+ color: var(--text-muted);
+ font-size: var(--text-2xs);
+ font-weight: var(--weight-medium);
+ letter-spacing: var(--tracking-label);
+ text-transform: uppercase;
+}
+
+.export-fields select {
+ width: 100%;
+ height: var(--field-height);
+ padding: 0 var(--space-2);
+ border: 1px solid var(--line-strong);
+ border-radius: var(--radius-sm);
+ font-size: var(--text-sm);
+}
+
+.export-fields select:disabled {
+ color: var(--text-faint);
+ cursor: not-allowed;
+}
+
+.export-field-note p {
+ margin: 0;
+ color: var(--text-secondary);
+ font-size: var(--text-xs);
+ line-height: var(--leading-normal);
+}
+
+.export-field-note code,
+.export-outcome code {
+ color: var(--text-primary);
+ font-size: var(--text-2xs);
+ word-break: break-all;
+}
+
+/* --- Summary --------------------------------------------------------------- */
+
+.export-summary {
+ margin: 0;
+ display: grid;
+ gap: 1px;
+ overflow: hidden;
+ border: 1px solid var(--line);
+ border-radius: var(--radius-md);
+ background: var(--line);
+}
+
+.export-summary > div {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: var(--space-3);
+ padding: var(--space-2) var(--space-3);
+ background: var(--panel-2);
+}
+
+.export-summary dt {
+ flex: 0 0 auto;
+ color: var(--text-muted);
+ font-size: var(--text-2xs);
+ font-weight: var(--weight-medium);
+ letter-spacing: var(--tracking-label);
+ text-transform: uppercase;
+}
+
+.export-summary dd {
+ min-width: 0;
+ margin: 0;
+ color: var(--text-primary);
+ font-size: var(--text-sm);
+ text-align: right;
+}
+
+.export-summary dd small {
+ display: block;
+ color: var(--text-faint);
+ font-size: var(--text-2xs);
+ line-height: var(--leading-snug);
+}
+
+/* --- Notices --------------------------------------------------------------- */
+
+.export-notice {
+ margin-top: var(--space-4);
+ padding: var(--space-3) var(--space-4);
+ border: 1px solid rgba(227, 168, 98, 0.34);
+ border-radius: var(--radius-md);
+ background: rgba(58, 44, 25, 0.24);
+}
+
+.export-notice--bad {
+ border-color: rgba(236, 125, 134, 0.4);
+ background: rgba(58, 26, 30, 0.26);
+}
+
+.export-notice h3 {
+ margin: 0 0 var(--space-2);
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ color: var(--warning);
+ font-size: var(--text-xs);
+ font-weight: var(--weight-semibold);
+ letter-spacing: var(--tracking-label);
+ text-transform: uppercase;
+}
+
+.export-notice--bad h3 {
+ color: var(--danger);
+}
+
+.export-notice ul {
+ margin: 0;
+ padding-left: var(--space-4);
+}
+
+.export-notice li,
+.export-notice p {
+ margin: 0;
+ color: var(--text-secondary);
+ font-size: var(--text-xs);
+ line-height: var(--leading-normal);
+}
+
+.export-notice li + li {
+ margin-top: var(--space-1);
+}
+
+/* --- Running and finishing ------------------------------------------------- */
+
+.export-actions {
+ margin-top: var(--space-5);
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-2);
+}
+
+.export-progress p {
+ margin: 0;
+ color: var(--text-secondary);
+ font-size: var(--text-xs);
+ line-height: var(--leading-normal);
+}
+
+.export-progress small {
+ color: var(--text-faint);
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs);
+}
+
+.export-outcome {
+ margin-top: var(--space-4);
+ padding: var(--space-3) var(--space-4);
+ border: 1px solid var(--line-strong);
+ border-radius: var(--radius-md);
+ color: var(--text-secondary);
+ background: var(--panel-2);
+ font-size: var(--text-xs);
+ line-height: var(--leading-normal);
+}
+
+.export-outcome--good {
+ border-color: rgba(110, 207, 149, 0.36);
+ background: rgba(26, 48, 36, 0.26);
+}
+
+.export-outcome h3 {
+ margin: 0 0 var(--space-2);
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ color: var(--success);
+ font-size: var(--text-xs);
+ font-weight: var(--weight-semibold);
+ letter-spacing: var(--tracking-label);
+ text-transform: uppercase;
+}
+
+.export-outcome p {
+ margin: 0;
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+}
+
+.export-outcome p + p {
+ margin-top: var(--space-2);
+ color: var(--text-muted);
+}
diff --git a/src/styles/index.css b/src/styles/index.css
index 75911ca..327a654 100644
--- a/src/styles/index.css
+++ b/src/styles/index.css
@@ -22,3 +22,4 @@
@import "./generator.css";
@import "./timeline.css";
@import "./references.css";
+@import "./export.css";