Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

feat(export): the RenderPlan data model and audio-concat planner, threaded through the exporter

Etienne Lescot589c1bfdb048
diff --git a/src/lib/ai-edition/exporter/audioConcatPlan.test.ts b/src/lib/ai-edition/exporter/audioConcatPlan.test.ts
new file mode 100644
index 000000000..0ef6e3649
--- /dev/null
+++ b/src/lib/ai-edition/exporter/audioConcatPlan.test.ts
@@ -0,0 +1,172 @@
+import { describe, expect, it } from "vitest";
+import { type AudioConcatSegmentInput, buildAudioConcatPlan } from "./audioConcatPlan";
+
+// --- Factory helpers (lean: only fields the builder reads) --------------------
+
+function seg(clipId: string, outputFrameCount: number, hasAudio: boolean): AudioConcatSegmentInput {
+ return { clipId, outputFrameCount, hasAudio };
+}
+
+// --- Defaults + layout -------------------------------------------------------
+
+describe("buildAudioConcatPlan — layout", () => {
+ it("single segment with audio: sampleCount = round(300/30*48000)=480000, silence false, totalSamples 480000", () => {
+ const plan = buildAudioConcatPlan([seg("c1", 300, true)], { frameRate: 30 });
+ expect(plan.sampleRate).toBe(48_000);
+ expect(plan.channels).toBe(2);
+ expect(plan.totalSamples).toBe(480_000);
+ expect(plan.segments).toEqual([
+ { clipId: "c1", startSample: 0, sampleCount: 480_000, silence: false },
+ ]);
+ });
+
+ it("defaults sampleRate=48000 and channels=2 when options omit them", () => {
+ const plan = buildAudioConcatPlan([seg("c1", 0, true)], { frameRate: 30 });
+ expect(plan.sampleRate).toBe(48_000);
+ expect(plan.channels).toBe(2);
+ });
+
+ it("honors custom sampleRate=44100 and channels=1 in both the plan header and sample math", () => {
+ // round(480/24 * 44100) = round(882000) = 882000 (exact integer — the
+ // sample-math assertion still confirms the custom rate is plugged in).
+ const plan = buildAudioConcatPlan([seg("c1", 480, true)], {
+ frameRate: 24,
+ sampleRate: 44_100,
+ channels: 1,
+ });
+ expect(plan.sampleRate).toBe(44_100);
+ expect(plan.channels).toBe(1);
+ expect(plan.segments[0].sampleCount).toBe(882_000);
+ expect(plan.totalSamples).toBe(882_000);
+ });
+});
+
+// --- Offsets + integer accumulation (R5) -------------------------------------
+
+describe("buildAudioConcatPlan — offsets", () => {
+ it("three audio segments: startSample[i] = sum(prior sampleCounts); totalSamples = sum(all)", () => {
+ // frameRate 60, sampleRate 48000 → sampleCount = outputFrameCount * 800.
+ const plans = buildAudioConcatPlan(
+ [seg("a", 60, true), seg("b", 30, true), seg("c", 90, true)],
+ { frameRate: 60 },
+ );
+ expect(plans.segments.map((s) => s.startSample)).toEqual([0, 48_000, 72_000]);
+ expect(plans.segments.map((s) => s.sampleCount)).toEqual([48_000, 24_000, 72_000]);
+ expect(plans.totalSamples).toBe(48_000 + 24_000 + 72_000);
+ // cumulative-shapes equivalence for exact-integer math.
+ expect(plans.totalSamples).toBe(0 + 48_000 + 24_000 + 72_000);
+ });
+
+ it("silence padding: a hasAudio=false segment occupies its full sampleCount and shifts the next startSample", () => {
+ // frameRate 30, sampleRate 48000 → sampleCount = outputFrameCount * 1600.
+ const plans = buildAudioConcatPlan(
+ [seg("a", 30, true), seg("b", 15, false), seg("c", 30, true)],
+ { frameRate: 30 },
+ );
+ expect(plans.segments).toEqual([
+ { clipId: "a", startSample: 0, sampleCount: 48_000, silence: false },
+ { clipId: "b", startSample: 48_000, sampleCount: 24_000, silence: true },
+ { clipId: "c", startSample: 72_000, sampleCount: 48_000, silence: false },
+ ]);
+ expect(plans.totalSamples).toBe(48_000 + 24_000 + 48_000);
+ });
+
+ it("mixed [audio, no-audio, audio]: offsets correct, only the middle flagged silence", () => {
+ const plans = buildAudioConcatPlan(
+ [seg("a", 30, true), seg("b", 15, false), seg("c", 30, true)],
+ { frameRate: 30 },
+ );
+ expect(plans.segments.map((s) => s.silence)).toEqual([false, true, false]);
+ // startSample[2] is exactly startSample[1] + sampleCount[1] (no rounding
+ // shortcut) — A/V stays locked through the silence gap.
+ expect(plans.segments[2].startSample).toBe(
+ plans.segments[1].startSample + plans.segments[1].sampleCount,
+ );
+ });
+
+ it("integer accumulation / no drift (R5): startSample[i] === sum(prior sampleCounts), NOT round(cumulativeSeconds * sampleRate)", () => {
+ // frameRate 24, sampleRate 44100, frameCount 1 → round(1837.5) = 1838
+ // per segment. The fractional intermediate is the whole point — summing
+ // the rounded integers must NOT equal round(cumulativeSeconds * sr).
+ const plans = buildAudioConcatPlan(
+ [seg("s1", 1, true), seg("s2", 1, true), seg("s3", 1, true)],
+ { frameRate: 24, sampleRate: 44_100 },
+ );
+
+ // Every output field is an integer (no half-sample leakage anywhere).
+ for (const s of plans.segments) {
+ expect(Number.isInteger(s.startSample)).toBe(true);
+ expect(Number.isInteger(s.sampleCount)).toBe(true);
+ }
+ expect(Number.isInteger(plans.totalSamples)).toBe(true);
+
+ // Each segment = 1838 samples (= round(1/24 * 44100)).
+ expect(plans.segments.map((s) => s.sampleCount)).toEqual([1838, 1838, 1838]);
+
+ // Integer accumulation: startSample[i] is the SUM of prior sampleCounts.
+ expect(plans.segments.map((s) => s.startSample)).toEqual([0, 1838, 3676]);
+ expect(plans.totalSamples).toBe(5514);
+
+ // …which DIFFERS from `round(cumulativeSeconds * sampleRate)` (the
+ // drift-prone shortcut). Document the gap explicitly so a future refactor
+ // can't accidentally swap integer accumulation for cumulative rounding.
+ const sampleRate = plans.sampleRate;
+ const frameRate = 24;
+ const cumRoundedAt = (n: number) => Math.round(((n * 1) / frameRate) * sampleRate);
+ expect(cumRoundedAt(1)).toBe(1838); // matches — boundary case
+ expect(cumRoundedAt(2)).toBe(3675); // ≠ 3676 (drift by 1)
+ expect(cumRoundedAt(3)).toBe(5513); // ≠ 5514 (drift by 1)
+ });
+});
+
+// --- Degenerate inputs --------------------------------------------------------
+
+describe("buildAudioConcatPlan — degenerate inputs", () => {
+ it("zero segments → empty segments, totalSamples 0, layout still set", () => {
+ const plan = buildAudioConcatPlan([], { frameRate: 30 });
+ expect(plan.segments).toEqual([]);
+ expect(plan.totalSamples).toBe(0);
+ expect(plan.sampleRate).toBe(48_000);
+ expect(plan.channels).toBe(2);
+ });
+
+ it("zero-length segment: outputFrameCount 0 → sampleCount 0, next startSample unchanged", () => {
+ const plan = buildAudioConcatPlan([seg("a", 30, true), seg("b", 0, true), seg("c", 30, true)], {
+ frameRate: 30,
+ });
+ expect(plan.segments).toEqual([
+ { clipId: "a", startSample: 0, sampleCount: 48_000, silence: false },
+ { clipId: "b", startSample: 48_000, sampleCount: 0, silence: false },
+ { clipId: "c", startSample: 48_000, sampleCount: 48_000, silence: false },
+ ]);
+ expect(plan.totalSamples).toBe(96_000);
+ });
+
+ it("frameRate = 0 guard: all sampleCounts 0, totalSamples 0, no NaN (no throw)", () => {
+ const plan = buildAudioConcatPlan(
+ [seg("a", 100, true), seg("b", 200, false), seg("c", 300, true)],
+ { frameRate: 0 },
+ );
+ expect(plan.segments).toEqual([
+ { clipId: "a", startSample: 0, sampleCount: 0, silence: false },
+ { clipId: "b", startSample: 0, sampleCount: 0, silence: true },
+ { clipId: "c", startSample: 0, sampleCount: 0, silence: false },
+ ]);
+ expect(plan.totalSamples).toBe(0);
+ // Explicit NaN sweep — divide-by-zero / Infinity must NOT leak through.
+ for (const s of plan.segments) {
+ expect(Number.isNaN(s.startSample)).toBe(false);
+ expect(Number.isNaN(s.sampleCount)).toBe(false);
+ }
+ expect(Number.isNaN(plan.totalSamples)).toBe(false);
+ });
+
+ it("frameRate < 0 guard: negative frameRate treated the same as zero (degenerate, no NaN)", () => {
+ const plan = buildAudioConcatPlan([seg("a", 100, true)], { frameRate: -30 });
+ expect(plan.segments).toEqual([
+ { clipId: "a", startSample: 0, sampleCount: 0, silence: false },
+ ]);
+ expect(plan.totalSamples).toBe(0);
+ expect(Number.isNaN(plan.totalSamples)).toBe(false);
+ });
+});
diff --git a/src/lib/ai-edition/exporter/audioConcatPlan.ts b/src/lib/ai-edition/exporter/audioConcatPlan.ts
new file mode 100644
index 000000000..319d48d18
--- /dev/null
+++ b/src/lib/ai-edition/exporter/audioConcatPlan.ts
@@ -0,0 +1,94 @@
+// AudioConcatPlan: pure-logic timing for the v2 multi-asset export audio track.
+//
+// ponytail: the v1 `documentExporter` runs a single continuous source stream
+// (the primary asset), so audio "follows" video implicitly and the exporter
+// just trims/speed-stretches one buffer end-to-end. The v2 renderer walks an
+// ordered list of per-clip render segments (each drawing from its own source
+// asset), so we have to concatenate N per-segment audio buffers into one
+// output track — and the silence gaps for segments whose asset has no audio
+// must be sized so A/V never drifts. This module computes the INTEGER sample
+// accounting only; it does NOT decode, encode, resample, or touch WebCodecs
+// / AudioContext. A downstream audio encoder/mixer reads the plan and emits
+// the actual PCM.
+//
+// Integer accumulation matters (spec risk R5): each segment's audio length
+// is rounded independently from its `outputFrameCount`, then offsets are the
+// integer sum of prior rounded lengths. Never `round(cumulativeSeconds *
+// sampleRate)` — that compounds per-segment rounding error across a long
+// multi-segment timeline into audible A/V drift.
+
+const DEFAULT_SAMPLE_RATE = 48_000;
+const DEFAULT_CHANNELS = 2;
+
+// One entry per RenderPlan segment (same order). The v2 segment loop supplies
+// the output video frame count so audio can be locked 1:1 to the retimed
+// video — same SSOT the video path uses (see audioEncoder's
+// `round(frameCount / frameRate * sampleRate)` accounting).
+export interface AudioConcatSegmentInput {
+ clipId: string;
+ // OUTPUT (virtual-timeline) video frames this segment renders. Audio is
+ // sized from this so A/V never drifts — same SSOT the video path uses.
+ outputFrameCount: number;
+ // Whether this segment's asset has a usable audio track. When false, the
+ // segment contributes SILENCE for its whole output duration (keeps A/V
+ // aligned).
+ hasAudio: boolean;
+}
+
+export interface AudioConcatSegmentPlan {
+ clipId: string;
+ startSample: number; // inclusive, output samples at `sampleRate`
+ sampleCount: number; // samples this segment occupies in the concatenated output
+ silence: boolean; // true → fill with silence (asset had no audio)
+}
+
+export interface AudioConcatPlan {
+ sampleRate: number;
+ channels: number;
+ totalSamples: number; // sum of all segment sampleCounts
+ segments: AudioConcatSegmentPlan[];
+}
+
+export interface BuildAudioConcatPlanOptions {
+ frameRate: number;
+ // Common output layout, chosen up-front by the caller (spec §6.3: from the
+ // first segment with audio, or the 48 kHz stereo default). Defaulted here.
+ sampleRate?: number; // default 48000
+ channels?: number; // default 2
+}
+
+export function buildAudioConcatPlan(
+ segments: AudioConcatSegmentInput[],
+ options: BuildAudioConcatPlanOptions,
+): AudioConcatPlan {
+ const sampleRate = options.sampleRate ?? DEFAULT_SAMPLE_RATE;
+ const channels = options.channels ?? DEFAULT_CHANNELS;
+
+ // Degenerate frameRate (0 or negative) → no segment can be sized without
+ // divide-by-zero / NaN. Return a plan with all-zero sample counts rather
+ // than throwing; the downstream encoder will still see a well-formed
+ // (if empty) buffer layout and the timeline is otherwise deterministic.
+ const frameRateValid = options.frameRate > 0;
+
+ const plans: AudioConcatSegmentPlan[] = [];
+ let cursor = 0;
+ for (const seg of segments) {
+ const sampleCount = frameRateValid
+ ? Math.max(0, Math.round((seg.outputFrameCount / options.frameRate) * sampleRate))
+ : 0;
+ plans.push({
+ clipId: seg.clipId,
+ startSample: cursor,
+ sampleCount,
+ silence: !seg.hasAudio,
+ });
+ cursor += sampleCount;
+ }
+
+ return {
+ sampleRate,
+ channels,
+ totalSamples: cursor,
+ segments: plans,
+ };
+}
diff --git a/src/lib/ai-edition/exporter/documentExporter.test.ts b/src/lib/ai-edition/exporter/documentExporter.test.ts
index 31b2025cd..28f884c79 100644
--- a/src/lib/ai-edition/exporter/documentExporter.test.ts
+++ b/src/lib/ai-edition/exporter/documentExporter.test.ts
@@ -1,6 +1,12 @@
import { describe, expect, it } from "vitest";
-import type { AxcutClip, AxcutTrimRange } from "../schema";
-import { computeCropSchedule, computeExportTrimRegions } from "./documentExporter";
+import type { CursorRecordingData } from "@/native/contracts";
+import type { AxcutAsset, AxcutClip, AxcutDocument, AxcutTrimRange } from "../schema";
+import type { DocumentExportOptions } from "./documentExporter";
+import {
+ buildDocumentRenderPlan,
+ computeCropSchedule,
+ computeExportTrimRegions,
+} from "./documentExporter";
function clip(p: Partial<AxcutClip> & Pick<AxcutClip, "id">): AxcutClip {
return {
@@ -92,3 +98,146 @@ describe("computeCropSchedule", () => {
]);
});
});
+
+describe("buildDocumentRenderPlan", () => {
+ function assetOf(p: Partial<AxcutAsset> & Pick<AxcutAsset, "id">): AxcutAsset {
+ return {
+ kind: "video",
+ label: "Asset",
+ originalPath: `/tmp/${p.id}.mp4`,
+ cameraTrack: null,
+ ...p,
+ };
+ }
+
+ // Minimal document — buildDocumentRenderPlan/buildRenderPlan only read project,
+ // assets, timeline.{clips,trimRanges}, zoomRanges, annotations, legacyEditor.
+ function docOf(p: {
+ assets: AxcutAsset[];
+ clips: AxcutClip[];
+ primaryAssetId?: string;
+ legacyEditor?: Record<string, unknown> | null;
+ }): AxcutDocument {
+ return {
+ project: { primaryAssetId: p.primaryAssetId },
+ assets: p.assets,
+ timeline: { clips: p.clips, trimRanges: [] },
+ zoomRanges: [],
+ annotations: [],
+ legacyEditor: p.legacyEditor ?? null,
+ } as unknown as AxcutDocument;
+ }
+
+ const baseOptions: DocumentExportOptions = { quality: "source", format: "mp4" };
+
+ it("maps codec + frameRate and sizes output from the largest asset", () => {
+ const doc = docOf({
+ assets: [
+ assetOf({
+ id: "a",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ ],
+ clips: [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })],
+ });
+ const plan = buildDocumentRenderPlan(doc, { ...baseOptions, codec: "h265", frameRate: 30 });
+ expect(plan.output.codec).toBe("hvc1.1.6.L120.90");
+ expect(plan.output.frameRate).toBe(30);
+ expect(plan.output.width).toBe(1920);
+ expect(plan.output.height).toBe(1080);
+ expect(plan.segments).toHaveLength(1);
+ });
+
+ it("uses options.sourceWidth/Height as fallback dims when the asset has no video block", () => {
+ const doc = docOf({
+ assets: [assetOf({ id: "a", durationSec: 30 })], // no `video`
+ clips: [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })],
+ });
+ const plan = buildDocumentRenderPlan(doc, {
+ ...baseOptions,
+ sourceWidth: 1280,
+ sourceHeight: 720,
+ });
+ expect(plan.segments[0].sourceWidth).toBe(1280);
+ expect(plan.segments[0].sourceHeight).toBe(720);
+ });
+
+ it("threads cursor recording + scale + theme into plan.cursor and partitions samples per segment", () => {
+ const recordingData: CursorRecordingData = {
+ version: 1,
+ provider: "native",
+ assets: [],
+ samples: [
+ { timeMs: 100, cx: 0.5, cy: 0.5, assetId: "a" },
+ { timeMs: 200, cx: 0.4, cy: 0.4, assetId: "b" },
+ ],
+ };
+ const doc = docOf({
+ assets: [
+ assetOf({
+ id: "a",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ assetOf({
+ id: "b",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ ],
+ clips: [
+ clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 5,
+ timelineStartSec: 0,
+ timelineEndSec: 5,
+ }),
+ clip({
+ id: "c2",
+ assetId: "b",
+ sourceStartSec: 0,
+ sourceEndSec: 5,
+ timelineStartSec: 5,
+ timelineEndSec: 10,
+ }),
+ ],
+ legacyEditor: { cursorTheme: "dark" },
+ });
+ const plan = buildDocumentRenderPlan(doc, {
+ ...baseOptions,
+ cursorRecordingData: recordingData,
+ cursorScale: 1.2,
+ cursorSmoothing: 0.4,
+ });
+ expect(plan.cursor).toMatchObject({ scale: 1.2, smoothing: 0.4, theme: "dark" });
+ expect(plan.segments[0].cursorSamples.map((s) => s.timeMs)).toEqual([100]);
+ expect(plan.segments[1].cursorSamples.map((s) => s.timeMs)).toEqual([200]);
+ });
+
+ it("leaves plan.cursor null when cursor scale is unset (0)", () => {
+ const recordingData: CursorRecordingData = {
+ version: 1,
+ provider: "native",
+ assets: [],
+ samples: [{ timeMs: 0, cx: 0.5, cy: 0.5, assetId: "a" }],
+ };
+ const doc = docOf({
+ assets: [
+ assetOf({
+ id: "a",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ ],
+ clips: [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })],
+ });
+ const plan = buildDocumentRenderPlan(doc, {
+ ...baseOptions,
+ cursorRecordingData: recordingData,
+ });
+ expect(plan.cursor).toBeNull();
+ });
+});
diff --git a/src/lib/ai-edition/exporter/documentExporter.ts b/src/lib/ai-edition/exporter/documentExporter.ts
index c4cdc5fbd..67ca34df4 100644
--- a/src/lib/ai-edition/exporter/documentExporter.ts
+++ b/src/lib/ai-edition/exporter/documentExporter.ts
@@ -43,6 +43,7 @@ import { createId } from "../document/ids";
import { type Interval, normalizeIntervals, primaryAssetDuration } from "../document/timeline";
import type { AxcutDocument } from "../schema";
import { projectRegionsToSourceTime } from "../timeline/region-ventilation";
+import { buildRenderPlan, type RenderPlan } from "./renderPlan";
export type ExportVideoCodec = "h264" | "h265" | "vp9";
@@ -157,6 +158,36 @@ function extractLegacyField<T>(
return fallback;
}
+// Maps the dialog's DocumentExportOptions onto the v2 RenderPlan (multi-asset,
+// virtual-time effects, per-segment cursor). This is the single boundary where
+// the document + export options become the plan the segment-loop renderer will
+// consume. It runs today alongside the legacy config assembly below — the plan
+// is threaded to VideoExporter but only drives rendering once the segment loop
+// is enabled (see VideoExporterConfig.renderPlan). Cursor scale/theme come from
+// options + legacyEditor exactly as the legacy path reads them.
+export function buildDocumentRenderPlan(
+ document: AxcutDocument,
+ options: DocumentExportOptions,
+): RenderPlan {
+ const legacy = document.legacyEditor as Record<string, unknown> | null;
+ return buildRenderPlan(document, {
+ quality: options.quality,
+ frameRate: options.frameRate ?? 60,
+ codec: options.codec ?? "h264",
+ fallbackSourceWidth: options.sourceWidth,
+ fallbackSourceHeight: options.sourceHeight,
+ cursor: {
+ recordingData: options.cursorRecordingData ?? null,
+ scale: options.cursorScale ?? 0,
+ smoothing: options.cursorSmoothing,
+ motionBlur: options.cursorMotionBlur,
+ clickBounce: options.cursorClickBounce,
+ clipToBounds: options.cursorClipToBounds,
+ theme: extractLegacyField(legacy, "cursorTheme", ""),
+ },
+ });
+}
+
export async function exportAxcutDocument(
document: AxcutDocument,
options: DocumentExportOptions,
@@ -305,6 +336,10 @@ export async function exportAxcutDocument(
frameRate: options.frameRate ?? 60,
bitrate: settings.bitrate,
codec: CODEC_STRINGS[options.codec ?? "h264"],
+ // v2 multi-asset plan, threaded to the exporter. Consumed only once the
+ // segment-loop path is enabled; the legacy single-asset config above still
+ // drives rendering until then.
+ renderPlan: buildDocumentRenderPlan(document, options),
});
return exporter.export();
}
diff --git a/src/lib/ai-edition/exporter/renderPlan.test.ts b/src/lib/ai-edition/exporter/renderPlan.test.ts
new file mode 100644
index 000000000..0f5c7317e
--- /dev/null
+++ b/src/lib/ai-edition/exporter/renderPlan.test.ts
@@ -0,0 +1,888 @@
+import { describe, expect, it } from "vitest";
+import type { AnnotationRegion, SpeedRegion, ZoomRegion } from "@/components/video-editor/types";
+import { calculateMp4ExportSettings } from "@/lib/exporter/mp4ExportSettings";
+import type { CursorRecordingData, CursorRecordingSample } from "@/native/contracts";
+import type { AxcutAsset, AxcutClip, AxcutTrimRange } from "../schema";
+import { buildRenderPlan, isIdentityFastPathEligible } from "./renderPlan";
+
+// --- Factory helpers (lean: only fields the builder reads) --------------------
+
+function asset(p: Partial<AxcutAsset> & Pick<AxcutAsset, "id">): AxcutAsset {
+ return {
+ kind: "video",
+ label: "Asset",
+ originalPath: "/tmp/asset.mp4",
+ cameraTrack: null,
+ ...p,
+ };
+}
+
+function clip(p: Partial<AxcutClip> & Pick<AxcutClip, "id">): AxcutClip {
+ return {
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ ...p,
+ };
+}
+
+function trim(p: Partial<AxcutTrimRange> & Pick<AxcutTrimRange, "id">): AxcutTrimRange {
+ return { assetId: "a", startSec: 0, endSec: 1, origin: "user", reason: "", ...p };
+}
+
+function zoom(p: Partial<ZoomRegion> & Pick<ZoomRegion, "id">): ZoomRegion {
+ return {
+ startMs: 0,
+ endMs: 1000,
+ depth: 2,
+ focus: { cx: 0.5, cy: 0.5 },
+ ...p,
+ };
+}
+
+function annotation(p: Partial<AnnotationRegion> & Pick<AnnotationRegion, "id">): AnnotationRegion {
+ return {
+ startMs: 0,
+ endMs: 1000,
+ type: "text",
+ content: "hi",
+ position: { x: 50, y: 50 },
+ size: { width: 30, height: 20 },
+ style: {
+ color: "#fff",
+ backgroundColor: "transparent",
+ fontSize: 32,
+ fontFamily: "Inter",
+ fontWeight: "bold",
+ fontStyle: "normal",
+ textDecoration: "none",
+ textAlign: "center",
+ },
+ zIndex: 1,
+ ...p,
+ };
+}
+
+function speed(p: Partial<SpeedRegion> & Pick<SpeedRegion, "id">): SpeedRegion {
+ return { startMs: 0, endMs: 1000, speed: 1, ...p };
+}
+
+function cursorSample(
+ p: Partial<CursorRecordingSample> & Pick<CursorRecordingSample, "timeMs">,
+): CursorRecordingSample {
+ return { cx: 0.5, cy: 0.5, ...p };
+}
+
+function cursorRecording(p: Partial<CursorRecordingData> = {}): CursorRecordingData {
+ return { version: 1, provider: "native", samples: [], assets: [], ...p };
+}
+
+// Minimal valid document for the builder — the builder only reads project,
+// assets, timeline.{clips, trimRanges}, zoomRanges, annotations, legacyEditor.
+//
+// ponytail: `zoomRegions` (with `s`) is the spec-facing key on RenderPlan and
+// what tests pass in; `zoomRanges` (without) is the schema field on the
+// document we feed the builder. Keep both names straight.
+function doc(
+ p: Partial<{
+ assets: AxcutAsset[];
+ clips: AxcutClip[];
+ trimRanges: AxcutTrimRange[];
+ zoomRegions: ZoomRegion[];
+ annotations: AnnotationRegion[];
+ legacyEditor: Record<string, unknown> | null;
+ primaryAssetId: string;
+ }> = {},
+) {
+ return {
+ project: { primaryAssetId: p.primaryAssetId },
+ assets: p.assets ?? [],
+ timeline: {
+ clips: p.clips ?? [],
+ trimRanges: p.trimRanges ?? [],
+ },
+ zoomRanges: p.zoomRegions ?? [],
+ annotations: p.annotations ?? [],
+ legacyEditor: p.legacyEditor ?? null,
+ };
+}
+
+// --- buildRenderPlan: segments ------------------------------------------------
+
+describe("buildRenderPlan — segments", () => {
+ it("single asset, identity: one segment with the expected fields and identity fast path", () => {
+ const assets = [
+ asset({
+ id: "a",
+ originalPath: "/tmp/a.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ ];
+ const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })];
+ const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });
+
+ expect(plan.segments).toHaveLength(1);
+ expect(plan.segments[0]).toEqual({
+ clipId: "c1",
+ assetId: "a",
+ videoUrl: "file:///tmp/a.mp4",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ intraTrims: [],
+ cropRegion: { x: 0, y: 0, width: 1, height: 1 },
+ sourceWidth: 1920,
+ sourceHeight: 1080,
+ camera: null,
+ cursorSamples: [],
+ });
+ expect(plan.cursor).toBeNull();
+ // Output = source for a 1920x1080 ref at 16:9 source quality → same dims.
+ expect(plan.output.width).toBe(1920);
+ expect(plan.output.height).toBe(1080);
+ expect(isIdentityFastPathEligible(plan)).toBe(true);
+ });
+
+ it("two clips across two assets: one segment per clip, each carrying its own videoUrl + dims", () => {
+ const assets = [
+ asset({
+ id: "a1",
+ originalPath: "/tmp/a1.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ asset({
+ id: "a2",
+ originalPath: "/tmp/a2.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ ];
+ const clips = [
+ clip({
+ id: "c1",
+ assetId: "a1",
+ sourceStartSec: 0,
+ sourceEndSec: 5,
+ timelineStartSec: 0,
+ timelineEndSec: 5,
+ }),
+ clip({
+ id: "c2",
+ assetId: "a2",
+ sourceStartSec: 5,
+ sourceEndSec: 10,
+ timelineStartSec: 5,
+ timelineEndSec: 10,
+ }),
+ ];
+ const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });
+
+ expect(plan.segments).toHaveLength(2);
+ expect(plan.segments[0]).toMatchObject({
+ clipId: "c1",
+ assetId: "a1",
+ videoUrl: "file:///tmp/a1.mp4",
+ sourceWidth: 1920,
+ sourceHeight: 1080,
+ });
+ expect(plan.segments[1]).toMatchObject({
+ clipId: "c2",
+ assetId: "a2",
+ videoUrl: "file:///tmp/a2.mp4",
+ sourceWidth: 1920,
+ sourceHeight: 1080,
+ });
+ expect(isIdentityFastPathEligible(plan)).toBe(false);
+ });
+
+ it("sorts segments by timelineStartSec regardless of input order", () => {
+ const assets = [
+ asset({
+ id: "a1",
+ originalPath: "/tmp/a1.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ asset({
+ id: "a2",
+ originalPath: "/tmp/a2.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ ];
+ // Inserted in reverse timeline order — builder must reorder by timelineStartSec.
+ const clips = [
+ clip({
+ id: "c2",
+ assetId: "a2",
+ sourceStartSec: 5,
+ sourceEndSec: 10,
+ timelineStartSec: 5,
+ timelineEndSec: 10,
+ }),
+ clip({
+ id: "c1",
+ assetId: "a1",
+ sourceStartSec: 0,
+ sourceEndSec: 5,
+ timelineStartSec: 0,
+ timelineEndSec: 5,
+ }),
+ ];
+ const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });
+ expect(plan.segments.map((s) => s.clipId)).toEqual(["c1", "c2"]);
+ });
+
+ it("falls back to asset.durationSec when clip.sourceEndSec is undefined", () => {
+ const assets = [
+ asset({
+ id: "a",
+ originalPath: "/tmp/a.mp4",
+ durationSec: 42,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ ];
+ const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 5, sourceEndSec: undefined })];
+ const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });
+ expect(plan.segments[0].sourceEndSec).toBe(42);
+ });
+
+ it("skips clips whose asset is missing (no throw, no segment)", () => {
+ const assets = [
+ asset({
+ id: "a",
+ originalPath: "/tmp/a.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ ];
+ const clips = [
+ clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 5 }),
+ clip({ id: "c2", assetId: "ghost", sourceStartSec: 5, sourceEndSec: 10 }),
+ ];
+ const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });
+ expect(plan.segments.map((s) => s.clipId)).toEqual(["c1"]);
+ });
+});
+
+// --- buildRenderPlan: intraTrims (per-segment scoping + clamping) -------------
+
+describe("buildRenderPlan — intraTrims", () => {
+ const assets = [
+ asset({
+ id: "a",
+ originalPath: "/tmp/a.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ asset({
+ id: "b",
+ originalPath: "/tmp/b.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ ];
+
+ it("scopes intraTrims by assetId: trims on a different asset are dropped", () => {
+ const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 20 })];
+ const trimRanges = [
+ trim({ id: "t1", assetId: "a", startSec: 5, endSec: 8 }),
+ trim({ id: "t2", assetId: "b", startSec: 5, endSec: 8 }), // different asset → ignored
+ ];
+ const plan = buildRenderPlan(doc({ assets, clips, trimRanges }), { quality: "source" });
+ expect(plan.segments[0].intraTrims).toEqual([{ startSec: 5, endSec: 8 }]);
+ });
+
+ it("clamps a partly-outside trim to the clip's [start, end) window", () => {
+ const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 10, sourceEndSec: 20 })];
+ const trimRanges = [trim({ id: "t1", assetId: "a", startSec: 5, endSec: 15 })];
+ const plan = buildRenderPlan(doc({ assets, clips, trimRanges }), { quality: "source" });
+ expect(plan.segments[0].intraTrims).toEqual([{ startSec: 10, endSec: 15 }]);
+ });
+
+ it("drops a trim that is fully outside the clip's source range", () => {
+ const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 10, sourceEndSec: 20 })];
+ const trimRanges = [trim({ id: "t1", assetId: "a", startSec: 0, endSec: 5 })];
+ const plan = buildRenderPlan(doc({ assets, clips, trimRanges }), { quality: "source" });
+ expect(plan.segments[0].intraTrims).toEqual([]);
+ });
+});
+
+// --- buildRenderPlan: crop & camera -------------------------------------------
+
+describe("buildRenderPlan — crop & camera", () => {
+ it("carries an explicit clip.cropRegion through verbatim", () => {
+ const assets = [
+ asset({
+ id: "a",
+ originalPath: "/tmp/a.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ ];
+ const crop = { x: 0.25, y: 0.25, width: 0.5, height: 0.5 };
+ const clips = [
+ clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10, cropRegion: crop }),
+ ];
+ const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });
+ expect(plan.segments[0].cropRegion).toEqual(crop);
+ });
+
+ it("defaults to the identity crop when the clip has none", () => {
+ const assets = [
+ asset({
+ id: "a",
+ originalPath: "/tmp/a.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ ];
+ const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })];
+ const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });
+ expect(plan.segments[0].cropRegion).toEqual({ x: 0, y: 0, width: 1, height: 1 });
+ });
+
+ it("attaches a camera entry when the asset's cameraTrack is visible + has a sourcePath", () => {
+ const assets = [
+ asset({
+ id: "a",
+ originalPath: "/tmp/a.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ cameraTrack: {
+ sourcePath: "/tmp/a-cam.mp4",
+ startMs: 0,
+ offsetMs: 250,
+ visible: true,
+ },
+ }),
+ ];
+ const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })];
+ const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });
+ expect(plan.segments[0].camera).toEqual({
+ videoUrl: "file:///tmp/a-cam.mp4",
+ offsetMs: 250,
+ });
+ });
+
+ it("omits camera when cameraTrack is invisible", () => {
+ const assets = [
+ asset({
+ id: "a",
+ originalPath: "/tmp/a.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ cameraTrack: {
+ sourcePath: "/tmp/a-cam.mp4",
+ startMs: 0,
+ offsetMs: 0,
+ visible: false,
+ },
+ }),
+ ];
+ const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })];
+ const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });
+ expect(plan.segments[0].camera).toBeNull();
+ });
+
+ it("omits camera when cameraTrack is null", () => {
+ const assets = [
+ asset({
+ id: "a",
+ originalPath: "/tmp/a.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ cameraTrack: null,
+ }),
+ ];
+ const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })];
+ const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });
+ expect(plan.segments[0].camera).toBeNull();
+ });
+});
+
+// --- buildRenderPlan: output sizing -------------------------------------------
+
+describe("buildRenderPlan — output sizing", () => {
+ it("sizes output from the largest-by-pixel-area segment and matches calculateMp4ExportSettings", () => {
+ const assets = [
+ asset({
+ id: "a1",
+ originalPath: "/tmp/a1.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1280, height: 720, fps: 30 },
+ }),
+ asset({
+ id: "a2",
+ originalPath: "/tmp/a2.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 3840, height: 2160, fps: 30 },
+ }),
+ ];
+ const clips = [
+ clip({
+ id: "c1",
+ assetId: "a1",
+ sourceStartSec: 0,
+ sourceEndSec: 5,
+ timelineStartSec: 0,
+ timelineEndSec: 5,
+ }),
+ clip({
+ id: "c2",
+ assetId: "a2",
+ sourceStartSec: 5,
+ sourceEndSec: 10,
+ timelineStartSec: 5,
+ timelineEndSec: 10,
+ }),
+ ];
+ const plan = buildRenderPlan(doc({ assets, clips, legacyEditor: { aspectRatio: "16:9" } }), {
+ quality: "source",
+ });
+ const expected = calculateMp4ExportSettings({
+ quality: "source",
+ sourceWidth: 3840,
+ sourceHeight: 2160,
+ aspectRatioValue: 16 / 9,
+ });
+ expect(plan.output.width).toBe(expected.width);
+ expect(plan.output.height).toBe(expected.height);
+ expect(plan.output.bitrate).toBe(expected.bitrate);
+ expect(plan.aspectRatioValue).toBeCloseTo(16 / 9, 6);
+ });
+
+ it("falls back to the option-provided fallback dims when there are no segments", () => {
+ const plan = buildRenderPlan(doc({ assets: [], clips: [] }), {
+ quality: "source",
+ fallbackSourceWidth: 640,
+ fallbackSourceHeight: 480,
+ });
+ const expected = calculateMp4ExportSettings({
+ quality: "source",
+ sourceWidth: 640,
+ sourceHeight: 480,
+ aspectRatioValue: 16 / 9,
+ });
+ expect(plan.output.width).toBe(expected.width);
+ expect(plan.output.height).toBe(expected.height);
+ });
+
+ it("honors frameRate + codec options", () => {
+ const assets = [
+ asset({
+ id: "a",
+ originalPath: "/tmp/a.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ ];
+ const clips = [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })];
+ const plan = buildRenderPlan(doc({ assets, clips }), {
+ quality: "source",
+ frameRate: 30,
+ codec: "h265",
+ });
+ expect(plan.output.frameRate).toBe(30);
+ expect(plan.output.codec).toBe("hvc1.1.6.L120.90");
+ });
+});
+
+// --- buildRenderPlan: effects pass-through (VIRTUAL time, NO projection) ------
+
+describe("buildRenderPlan — effects pass-through", () => {
+ const baseAssets = [
+ asset({
+ id: "a",
+ originalPath: "/tmp/a.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ ];
+ const baseClips = [clip({ id: "c1", assetId: "a", sourceStartSec: 0, sourceEndSec: 10 })];
+
+ it("carries zoomRanges verbatim (same ids + startMs + endMs) — no projection", () => {
+ const zoomRegions = [
+ zoom({ id: "z1", startMs: 500, endMs: 2500, depth: 3 }),
+ zoom({ id: "z2", startMs: 4000, endMs: 6000, depth: 4 }),
+ ];
+ const plan = buildRenderPlan(doc({ assets: baseAssets, clips: baseClips, zoomRegions }), {
+ quality: "source",
+ });
+ expect(plan.zoomRegions).toEqual(zoomRegions);
+ });
+
+ it("carries annotations verbatim (same ids + startMs + endMs) — no projection", () => {
+ const annotations = [
+ annotation({ id: "a1", startMs: 1000, endMs: 3000 }),
+ annotation({ id: "a2", startMs: 3500, endMs: 5500 }),
+ ];
+ const plan = buildRenderPlan(doc({ assets: baseAssets, clips: baseClips, annotations }), {
+ quality: "source",
+ });
+ expect(plan.annotationRegions).toEqual(annotations);
+ });
+
+ it("carries speedRegions verbatim (same ids + startMs + endMs + speed) — no projection", () => {
+ const speedRegions = [
+ speed({ id: "s1", startMs: 1500, endMs: 2500, speed: 2 }),
+ speed({ id: "s2", startMs: 4000, endMs: 5000, speed: 0.5 }),
+ ];
+ const plan = buildRenderPlan(
+ doc({
+ assets: baseAssets,
+ clips: baseClips,
+ legacyEditor: { speedRegions },
+ }),
+ { quality: "source" },
+ );
+ expect(plan.speedRegions).toEqual(speedRegions);
+ });
+
+ it("defaults speedRegions to [] when legacyEditor is null and skips speedRegions absent", () => {
+ const plan = buildRenderPlan(doc({ assets: baseAssets, clips: baseClips }), {
+ quality: "source",
+ });
+ expect(plan.speedRegions).toEqual([]);
+ });
+
+ it("reads appearance defaults from legacyEditor with the documented fallbacks", () => {
+ const plan = buildRenderPlan(doc({ assets: baseAssets, clips: baseClips }), {
+ quality: "source",
+ });
+ expect(plan.appearance).toEqual({
+ wallpaper: "",
+ padding: 50,
+ borderRadius: 0,
+ shadowIntensity: 0,
+ showBlur: false,
+ motionBlurAmount: 0,
+ });
+ });
+});
+
+// --- buildRenderPlan: cursor (per-segment, decision D1) ----------------------
+
+describe("buildRenderPlan — cursor", () => {
+ const twoAssets = [
+ asset({
+ id: "a1",
+ originalPath: "/tmp/a1.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ asset({
+ id: "a2",
+ originalPath: "/tmp/a2.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ ];
+ const twoClips = [
+ clip({
+ id: "c1",
+ assetId: "a1",
+ sourceStartSec: 0,
+ sourceEndSec: 5,
+ timelineStartSec: 0,
+ timelineEndSec: 5,
+ }),
+ clip({
+ id: "c2",
+ assetId: "a2",
+ sourceStartSec: 5,
+ sourceEndSec: 10,
+ timelineStartSec: 5,
+ timelineEndSec: 10,
+ }),
+ ];
+
+ it("partitions samples per segment by assetId — each segment gets only its asset's samples", () => {
+ const recordingData = cursorRecording({
+ samples: [
+ cursorSample({ timeMs: 100, assetId: "a1" }),
+ cursorSample({ timeMs: 200, assetId: "a2" }),
+ cursorSample({ timeMs: 300, assetId: "a1" }),
+ ],
+ });
+ const plan = buildRenderPlan(doc({ assets: twoAssets, clips: twoClips }), {
+ quality: "source",
+ cursor: { recordingData, scale: 1 },
+ });
+ expect(plan.segments[0].cursorSamples.map((s) => s.timeMs)).toEqual([100, 300]);
+ expect(plan.segments[1].cursorSamples.map((s) => s.timeMs)).toEqual([200]);
+ });
+
+ it("attributes untagged samples (no assetId) to the primary asset", () => {
+ const recordingData = cursorRecording({
+ samples: [cursorSample({ timeMs: 100 }), cursorSample({ timeMs: 200, assetId: "a2" })],
+ });
+ const plan = buildRenderPlan(
+ doc({ assets: twoAssets, clips: twoClips, primaryAssetId: "a1" }),
+ { quality: "source", cursor: { recordingData, scale: 1 } },
+ );
+ expect(plan.segments[0].cursorSamples.map((s) => s.timeMs)).toEqual([100]);
+ expect(plan.segments[1].cursorSamples.map((s) => s.timeMs)).toEqual([200]);
+ });
+
+ it("falls back to the first asset for untagged samples when primaryAssetId is unset", () => {
+ const recordingData = cursorRecording({ samples: [cursorSample({ timeMs: 100 })] });
+ const plan = buildRenderPlan(doc({ assets: twoAssets, clips: twoClips }), {
+ quality: "source",
+ cursor: { recordingData, scale: 1 },
+ });
+ expect(plan.segments[0].cursorSamples.map((s) => s.timeMs)).toEqual([100]);
+ expect(plan.segments[1].cursorSamples).toEqual([]);
+ });
+
+ it("gives a segment whose asset has no cursor data an empty samples array (no overlay)", () => {
+ const recordingData = cursorRecording({
+ samples: [cursorSample({ timeMs: 100, assetId: "a1" })],
+ });
+ const plan = buildRenderPlan(doc({ assets: twoAssets, clips: twoClips }), {
+ quality: "source",
+ cursor: { recordingData, scale: 1 },
+ });
+ expect(plan.segments[1].cursorSamples).toEqual([]);
+ });
+
+ it("builds plan.cursor (shared atlas + style) when scale > 0 and a recording is present", () => {
+ const spriteAsset = {
+ id: "cur1",
+ platform: "windows",
+ imageDataUrl: "data:,",
+ width: 16,
+ height: 16,
+ hotspotX: 0,
+ hotspotY: 0,
+ } as CursorRecordingData["assets"][number];
+ const recordingData = cursorRecording({
+ version: 2,
+ provider: "native",
+ assets: [spriteAsset],
+ samples: [cursorSample({ timeMs: 0, assetId: "a1" })],
+ });
+ const plan = buildRenderPlan(doc({ assets: twoAssets, clips: twoClips }), {
+ quality: "source",
+ cursor: {
+ recordingData,
+ scale: 1.5,
+ smoothing: 0.3,
+ motionBlur: 0.2,
+ clickBounce: 0.5,
+ clipToBounds: true,
+ theme: "dark",
+ },
+ });
+ expect(plan.cursor).toEqual({
+ version: 2,
+ provider: "native",
+ assets: [spriteAsset],
+ scale: 1.5,
+ smoothing: 0.3,
+ motionBlur: 0.2,
+ clickBounce: 0.5,
+ clipToBounds: true,
+ theme: "dark",
+ });
+ });
+
+ it("leaves plan.cursor null and carries no samples when scale is 0 (cursor disabled)", () => {
+ const recordingData = cursorRecording({
+ samples: [cursorSample({ timeMs: 0, assetId: "a1" })],
+ });
+ const plan = buildRenderPlan(doc({ assets: twoAssets, clips: twoClips }), {
+ quality: "source",
+ cursor: { recordingData, scale: 0 },
+ });
+ expect(plan.cursor).toBeNull();
+ expect(plan.segments.every((s) => s.cursorSamples.length === 0)).toBe(true);
+ });
+
+ it("leaves plan.cursor null when no recording is supplied", () => {
+ const plan = buildRenderPlan(doc({ assets: twoAssets, clips: twoClips }), {
+ quality: "source",
+ cursor: { scale: 1 },
+ });
+ expect(plan.cursor).toBeNull();
+ expect(plan.segments.every((s) => s.cursorSamples.length === 0)).toBe(true);
+ });
+});
+
+// --- isIdentityFastPathEligible -----------------------------------------------
+
+describe("isIdentityFastPathEligible", () => {
+ function singleUntouchedAsset() {
+ return asset({
+ id: "a",
+ originalPath: "/tmp/a.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ });
+ }
+ function singleClipOn(assetId: string) {
+ return clip({ id: "c1", assetId, sourceStartSec: 0, sourceEndSec: 10 });
+ }
+
+ it("returns true for an untouched single clip whose output matches source dims", () => {
+ const assets = [singleUntouchedAsset()];
+ const clips = [singleClipOn("a")];
+ const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });
+ expect(isIdentityFastPathEligible(plan)).toBe(true);
+ });
+
+ it("returns false when there are 2+ segments", () => {
+ const assets = [
+ singleUntouchedAsset(),
+ asset({
+ id: "a2",
+ originalPath: "/tmp/a2.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 1920, height: 1080, fps: 30 },
+ }),
+ ];
+ const clips = [
+ clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 5,
+ timelineStartSec: 0,
+ timelineEndSec: 5,
+ }),
+ clip({
+ id: "c2",
+ assetId: "a2",
+ sourceStartSec: 0,
+ sourceEndSec: 5,
+ timelineStartSec: 5,
+ timelineEndSec: 10,
+ }),
+ ];
+ const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });
+ expect(isIdentityFastPathEligible(plan)).toBe(false);
+ });
+
+ it("returns false when the single segment has intraTrims", () => {
+ const assets = [singleUntouchedAsset()];
+ const clips = [singleClipOn("a")];
+ const trimRanges = [trim({ id: "t1", assetId: "a", startSec: 3, endSec: 5 })];
+ const plan = buildRenderPlan(doc({ assets, clips, trimRanges }), { quality: "source" });
+ expect(isIdentityFastPathEligible(plan)).toBe(false);
+ });
+
+ it("returns false when the single segment has a non-identity crop", () => {
+ const assets = [singleUntouchedAsset()];
+ const clips = [
+ clip({
+ id: "c1",
+ assetId: "a",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ cropRegion: { x: 0.1, y: 0.1, width: 0.8, height: 0.8 },
+ }),
+ ];
+ const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });
+ expect(isIdentityFastPathEligible(plan)).toBe(false);
+ });
+
+ it("returns false when any active (non-zero-length, non-1x) speedRegion is present", () => {
+ const assets = [singleUntouchedAsset()];
+ const clips = [singleClipOn("a")];
+ const plan = buildRenderPlan(
+ doc({
+ assets,
+ clips,
+ legacyEditor: { speedRegions: [speed({ id: "s1", startMs: 1000, endMs: 3000, speed: 2 })] },
+ }),
+ { quality: "source" },
+ );
+ expect(isIdentityFastPathEligible(plan)).toBe(false);
+ });
+
+ it("treats a 1x speedRegion of any length as inactive", () => {
+ const assets = [singleUntouchedAsset()];
+ const clips = [singleClipOn("a")];
+ const plan = buildRenderPlan(
+ doc({
+ assets,
+ clips,
+ legacyEditor: {
+ speedRegions: [
+ speed({ id: "s1", startMs: 1000, endMs: 3000, speed: 1 }),
+ speed({ id: "s2", startMs: 0, endMs: 0, speed: 2 }), // zero-length → inactive
+ ],
+ },
+ }),
+ { quality: "source" },
+ );
+ expect(isIdentityFastPathEligible(plan)).toBe(true);
+ });
+
+ it("returns false when a zoomRegion is present", () => {
+ const assets = [singleUntouchedAsset()];
+ const clips = [singleClipOn("a")];
+ const plan = buildRenderPlan(doc({ assets, clips, zoomRegions: [zoom({ id: "z1" })] }), {
+ quality: "source",
+ });
+ expect(isIdentityFastPathEligible(plan)).toBe(false);
+ });
+
+ it("returns false when an annotationRegion is present", () => {
+ const assets = [singleUntouchedAsset()];
+ const clips = [singleClipOn("a")];
+ const plan = buildRenderPlan(
+ doc({ assets, clips, annotations: [annotation({ id: "ann1" })] }),
+ { quality: "source" },
+ );
+ expect(isIdentityFastPathEligible(plan)).toBe(false);
+ });
+
+ it("returns false when output dims differ from source dims", () => {
+ const assets = [
+ asset({
+ id: "a",
+ originalPath: "/tmp/a.mp4",
+ durationSec: 30,
+ video: { codec: "h264", width: 3840, height: 2160, fps: 30 },
+ }),
+ ];
+ const clips = [singleClipOn("a")];
+ // quality: "good" → output short-side 1080 at 16:9 → 1920x1080, smaller than 3840x2160.
+ const plan = buildRenderPlan(doc({ assets, clips }), { quality: "good" });
+ expect(isIdentityFastPathEligible(plan)).toBe(false);
+ });
+
+ it("returns false when an active cursor overlay covers the single segment", () => {
+ const assets = [singleUntouchedAsset()];
+ const clips = [singleClipOn("a")];
+ const recordingData = cursorRecording({
+ samples: [cursorSample({ timeMs: 0, assetId: "a" })],
+ });
+ const plan = buildRenderPlan(doc({ assets, clips }), {
+ quality: "source",
+ cursor: { recordingData, scale: 1 },
+ });
+ expect(plan.segments[0].cursorSamples.length).toBeGreaterThan(0);
+ expect(isIdentityFastPathEligible(plan)).toBe(false);
+ });
+
+ it("stays eligible when a cursor recording exists but cursor is disabled (scale 0)", () => {
+ const assets = [singleUntouchedAsset()];
+ const clips = [singleClipOn("a")];
+ const recordingData = cursorRecording({
+ samples: [cursorSample({ timeMs: 0, assetId: "a" })],
+ });
+ const plan = buildRenderPlan(doc({ assets, clips }), {
+ quality: "source",
+ cursor: { recordingData, scale: 0 },
+ });
+ expect(isIdentityFastPathEligible(plan)).toBe(true);
+ });
+});
diff --git a/src/lib/ai-edition/exporter/renderPlan.ts b/src/lib/ai-edition/exporter/renderPlan.ts
new file mode 100644
index 000000000..7697ca095
--- /dev/null
+++ b/src/lib/ai-edition/exporter/renderPlan.ts
@@ -0,0 +1,372 @@
+// RenderPlan: the v2 multi-asset export pipeline's pure-logic data model.
+//
+// ponytail: today `documentExporter` plays a single continuous source stream
+// (the primary asset) and projects timeline-authored effects (zoom / annotation
+// / speed) onto each frame's *source* time, so any clip that points at a
+// different asset is silently dropped. The v2 renderer decodes one segment at
+// a time, so effects stay keyed in VIRTUAL (output) time and the plan just
+// carries an ordered list of per-clip render segments — each with its own
+// source stream and intra-clip cuts — plus the output framing and the
+// pass-through effect arrays.
+//
+// This module is the foundation: a pure (no DOM, no IPC, no side effects)
+// builder + a small `isIdentityFastPathEligible` helper the renderer can use
+// to skip re-encode-worthy work for untouched single-clip projects.
+
+import { toFileUrl } from "@/components/video-editor/projectPersistence";
+import type {
+ AnnotationRegion,
+ CropRegion,
+ SpeedRegion,
+ ZoomRegion,
+} from "@/components/video-editor/types";
+import { calculateMp4ExportSettings } from "@/lib/exporter/mp4ExportSettings";
+import type { ExportQuality } from "@/lib/exporter/types";
+import type {
+ CursorProviderKind,
+ CursorRecordingData,
+ CursorRecordingSample,
+ NativeCursorAsset,
+} from "@/native/contracts";
+import {
+ type AspectRatio,
+ getAspectRatioValue,
+ getNativeAspectRatioValue,
+} from "@/utils/aspectRatioUtils";
+import { type Interval, normalizeIntervals } from "../document/timeline";
+import type { AxcutDocument } from "../schema";
+
+export type ExportVideoCodec = "h264" | "h265" | "vp9";
+
+// WebCodecs encoder strings per user-facing codec choice. The muxer derives
+// its mp4 track family from the same string.
+const CODEC_STRINGS: Record<ExportVideoCodec, string> = {
+ h264: "avc1.640033",
+ h265: "hvc1.1.6.L120.90",
+ vp9: "vp09.00.10.08",
+};
+
+const IDENTITY_CROP: CropRegion = { x: 0, y: 0, width: 1, height: 1 };
+
+const DEFAULT_FRAME_RATE = 60;
+const DEFAULT_FALLBACK_SOURCE_WIDTH = 1920;
+const DEFAULT_FALLBACK_SOURCE_HEIGHT = 1080;
+
+// ponytail: one render segment = one source clip fed into the decoder +
+// frame loop. The renderer iterates these in order; the segment loop tracks a
+// running output/virtual-time cursor so effects (passed through separately,
+// keyed in virtual ms) land on the right frames regardless of which asset
+// each clip draws from.
+export interface RenderSegment {
+ clipId: string;
+ assetId: string;
+ videoUrl: string;
+ sourceStartSec: number;
+ sourceEndSec: number;
+ // Cuts INSIDE this clip, scoped per segment (unlike today's single global
+ // complement in `computeExportTrimRegions`). Pre-merged + clamped via
+ // `normalizeIntervals` so the renderer can drop straight in.
+ intraTrims: Interval[];
+ cropRegion: CropRegion;
+ sourceWidth: number;
+ sourceHeight: number;
+ // Camera (webcam) attached to this segment's asset, when present and
+ // visible. The renderer treats it as a derived stream like the existing
+ // exporter does — no per-clip stitching beyond what `cameraTrack.offsetMs`
+ // already encodes.
+ camera: { videoUrl: string; offsetMs: number } | null;
+ // Native-cursor telemetry for THIS segment's asset only (decision D1 —
+ // per-segment cursor). `CursorRecordingSample.assetId` already tags each
+ // sample with its recording, so the plan partitions the shared recording by
+ // `assetId`; samples with no tag fall back to the primary asset (older
+ // single-asset recordings). `timeMs` stays in the asset's own source time —
+ // the renderer matches it against each frame's source time inside this
+ // segment's window. Empty when the asset has no cursor data (§6.4 / risk R3):
+ // that segment renders with no cursor overlay, which is correct, not a gap.
+ cursorSamples: CursorRecordingSample[];
+}
+
+export interface RenderPlanOutput {
+ width: number;
+ height: number;
+ frameRate: number;
+ bitrate: number;
+ codec: string;
+}
+
+export interface RenderPlanAppearance {
+ wallpaper: string;
+ padding: number;
+ borderRadius: number;
+ shadowIntensity: number;
+ showBlur: boolean;
+ motionBlurAmount: number;
+}
+
+// Plan-level cursor: the SHARED parts of a native-cursor render — the sprite
+// atlas (`assets`) and the style knobs — held once for the whole export. The
+// time-varying samples live per segment on `RenderSegment.cursorSamples`
+// (partitioned by asset). `null` when the export has no cursor recording, or
+// cursor rendering is disabled (`scale <= 0`).
+export interface RenderPlanCursor {
+ version: number;
+ provider: CursorProviderKind;
+ assets: NativeCursorAsset[];
+ scale: number;
+ smoothing?: number;
+ motionBlur?: number;
+ clickBounce?: number;
+ clipToBounds?: boolean;
+ theme?: string;
+}
+
+export interface RenderPlan {
+ output: RenderPlanOutput;
+ aspectRatioValue: number;
+ // Timeline order = output order. Sorted by `timelineStartSec` ascending so
+ // the renderer can walk segments and effects (which are keyed in virtual
+ // ms) in a single forward pass.
+ segments: RenderSegment[];
+ // VIRTUAL (output) time. Direct pass-through of the document's regions with
+ // NO projection — the segment loop already tracks the virtual-time cursor
+ // that today required `projectRegionsToSourceTime`.
+ zoomRegions: ZoomRegion[];
+ annotationRegions: AnnotationRegion[];
+ speedRegions: SpeedRegion[];
+ appearance: RenderPlanAppearance;
+ // Shared cursor style + sprite atlas (per-segment samples live on each
+ // segment). `null` when there is no recording or cursor is disabled.
+ cursor: RenderPlanCursor | null;
+}
+
+export interface BuildRenderPlanCursorOptions {
+ recordingData?: CursorRecordingData | null;
+ scale?: number;
+ smoothing?: number;
+ motionBlur?: number;
+ clickBounce?: number;
+ clipToBounds?: boolean;
+ theme?: string;
+}
+
+export interface BuildRenderPlanOptions {
+ quality: ExportQuality;
+ frameRate?: number;
+ codec?: ExportVideoCodec;
+ fallbackSourceWidth?: number;
+ fallbackSourceHeight?: number;
+ // Cursor recording + style, supplied by the caller (ExportDialog) — the
+ // document/asset schema does not persist cursor telemetry. Omit for no cursor.
+ cursor?: BuildRenderPlanCursorOptions;
+}
+
+function extractLegacyField<T>(
+ legacy: Record<string, unknown> | null,
+ key: string,
+ fallback: T,
+): T {
+ if (legacy && typeof legacy[key] === typeof fallback) {
+ return legacy[key] as T;
+ }
+ return fallback;
+}
+
+// Stable, clone-only sort — never mutates the document's clips array. JS's
+// `Array.prototype.sort` is stable per ECMA-262 since ES2019, so identical
+// `timelineStartSec` preserves insertion order.
+function sortClipsByTimelineStart<T extends { timelineStartSec: number }>(clips: T[]): T[] {
+ return [...clips].sort((a, b) => a.timelineStartSec - b.timelineStartSec);
+}
+
+function buildIntraTrims(
+ document: AxcutDocument,
+ clip: AxcutDocument["timeline"]["clips"][number],
+ sourceStartSec: number,
+ sourceEndSec: number,
+): Interval[] {
+ const intersected: Interval[] = [];
+ for (const trim of document.timeline.trimRanges) {
+ if (trim.assetId !== clip.assetId) continue;
+ intersected.push({
+ startSec: Math.max(trim.startSec, sourceStartSec),
+ endSec: Math.min(trim.endSec, sourceEndSec),
+ });
+ }
+ return normalizeIntervals(sourceEndSec, intersected);
+}
+
+// Native-cursor samples belonging to one asset (decision D1 — per-segment
+// cursor). A sample with no `assetId` predates multi-asset cursor tagging, so it
+// belongs to the primary asset — attributing it there keeps single-asset
+// projects rendering their cursor exactly as before.
+function cursorSamplesForAsset(
+ recordingData: CursorRecordingData | null | undefined,
+ assetId: string,
+ primaryAssetId: string | undefined,
+): CursorRecordingSample[] {
+ if (!recordingData) return [];
+ return recordingData.samples.filter((s) => (s.assetId ?? primaryAssetId) === assetId);
+}
+
+function pickReferenceDimensions(
+ segments: RenderSegment[],
+ fallbackWidth: number,
+ fallbackHeight: number,
+): { width: number; height: number } {
+ if (segments.length === 0) {
+ return { width: fallbackWidth, height: fallbackHeight };
+ }
+ let bestArea = -1;
+ let best: { width: number; height: number } = { width: fallbackWidth, height: fallbackHeight };
+ for (const segment of segments) {
+ const area = segment.sourceWidth * segment.sourceHeight;
+ if (area > bestArea) {
+ bestArea = area;
+ best = { width: segment.sourceWidth, height: segment.sourceHeight };
+ }
+ }
+ return best;
+}
+
+export function buildRenderPlan(
+ document: AxcutDocument,
+ options: BuildRenderPlanOptions,
+): RenderPlan {
+ const fallbackWidth = options.fallbackSourceWidth ?? DEFAULT_FALLBACK_SOURCE_WIDTH;
+ const fallbackHeight = options.fallbackSourceHeight ?? DEFAULT_FALLBACK_SOURCE_HEIGHT;
+ const codec: ExportVideoCodec = options.codec ?? "h264";
+ const frameRate = options.frameRate ?? DEFAULT_FRAME_RATE;
+
+ // Primary asset id anchors untagged cursor samples (see cursorSamplesForAsset).
+ const primaryAssetId = document.project.primaryAssetId ?? document.assets[0]?.id;
+ // Cursor is only rendered when scaled up (matches the existing exporter's
+ // `hasNativeCursorOverlay = cursorScale > 0`). When disabled, carry no samples
+ // and leave `plan.cursor` null so the identity fast path stays available.
+ const cursorScale = options.cursor?.scale ?? 0;
+ const cursorRecording = cursorScale > 0 ? (options.cursor?.recordingData ?? null) : null;
+
+ // --- Segments ---
+ const sortedClips = sortClipsByTimelineStart(document.timeline.clips);
+ const segments: RenderSegment[] = [];
+ for (const clip of sortedClips) {
+ const asset = document.assets.find((a) => a.id === clip.assetId);
+ if (!asset) continue; // orphan clip — can't render, skip silently (matches today).
+
+ const sourceStartSec = clip.sourceStartSec;
+ const sourceEndSec = clip.sourceEndSec ?? asset.durationSec ?? sourceStartSec;
+ const sourceWidth = asset.video?.width || fallbackWidth || DEFAULT_FALLBACK_SOURCE_WIDTH;
+ const sourceHeight = asset.video?.height || fallbackHeight || DEFAULT_FALLBACK_SOURCE_HEIGHT;
+ const cameraTrack = asset.cameraTrack;
+ const camera =
+ cameraTrack && cameraTrack.visible && cameraTrack.sourcePath
+ ? { videoUrl: toFileUrl(cameraTrack.sourcePath), offsetMs: cameraTrack.offsetMs }
+ : null;
+
+ segments.push({
+ clipId: clip.id,
+ assetId: asset.id,
+ videoUrl: toFileUrl(asset.originalPath),
+ sourceStartSec,
+ sourceEndSec,
+ intraTrims: buildIntraTrims(document, clip, sourceStartSec, sourceEndSec),
+ cropRegion: clip.cropRegion ?? IDENTITY_CROP,
+ sourceWidth,
+ sourceHeight,
+ camera,
+ cursorSamples: cursorSamplesForAsset(cursorRecording, asset.id, primaryAssetId),
+ });
+ }
+
+ // --- Output sizing ---
+ const ref = pickReferenceDimensions(segments, fallbackWidth, fallbackHeight);
+ const legacy = document.legacyEditor as Record<string, unknown> | null;
+ const aspectRatio = extractLegacyField<AspectRatio>(legacy, "aspectRatio", "16:9");
+ const aspectRatioValue =
+ aspectRatio === "native"
+ ? getNativeAspectRatioValue(ref.width, ref.height)
+ : getAspectRatioValue(aspectRatio);
+ const settings = calculateMp4ExportSettings({
+ quality: options.quality,
+ sourceWidth: ref.width,
+ sourceHeight: ref.height,
+ aspectRatioValue,
+ });
+
+ // --- Effects (virtual time, pass-through, NO projection) ---
+ const zoomRegions = document.zoomRanges as unknown as ZoomRegion[];
+ const annotationRegions = document.annotations as unknown as AnnotationRegion[];
+ const speedRegions = extractLegacyField<SpeedRegion[]>(legacy, "speedRegions", []);
+
+ // --- Appearance ---
+ const appearance: RenderPlanAppearance = {
+ wallpaper: extractLegacyField(legacy, "wallpaper", ""),
+ padding: extractLegacyField(legacy, "padding", 50),
+ borderRadius: extractLegacyField(legacy, "borderRadius", 0),
+ shadowIntensity: extractLegacyField(legacy, "shadowIntensity", 0),
+ showBlur: extractLegacyField(legacy, "showBlur", false),
+ motionBlurAmount: extractLegacyField(legacy, "motionBlurAmount", 0),
+ };
+
+ // --- Cursor (shared atlas + style; per-segment samples set above) ---
+ const cursor: RenderPlanCursor | null = cursorRecording
+ ? {
+ version: cursorRecording.version,
+ provider: cursorRecording.provider,
+ assets: cursorRecording.assets,
+ scale: cursorScale,
+ smoothing: options.cursor?.smoothing,
+ motionBlur: options.cursor?.motionBlur,
+ clickBounce: options.cursor?.clickBounce,
+ clipToBounds: options.cursor?.clipToBounds,
+ theme: options.cursor?.theme,
+ }
+ : null;
+
+ return {
+ output: {
+ width: settings.width,
+ height: settings.height,
+ frameRate,
+ bitrate: settings.bitrate,
+ codec: CODEC_STRINGS[codec],
+ },
+ aspectRatioValue,
+ segments,
+ zoomRegions,
+ annotationRegions,
+ speedRegions,
+ appearance,
+ cursor,
+ };
+}
+
+function isIdentityCrop(region: CropRegion): boolean {
+ return region.x === 0 && region.y === 0 && region.width === 1 && region.height === 1;
+}
+
+// ponytail: when the only segment needs no re-encode-worthy effects AND the
+// output frame is the source frame (1:1, no aspect re-framing, no scaling),
+// the renderer can take a stream-copy fast path (remux-only) instead of a
+// full decode → composite → encode round trip.
+export function isIdentityFastPathEligible(plan: RenderPlan): boolean {
+ if (plan.segments.length !== 1) return false;
+ const segment = plan.segments[0];
+ if (segment.intraTrims.length !== 0) return false;
+ if (!isIdentityCrop(segment.cropRegion)) return false;
+ if (plan.zoomRegions.length !== 0) return false;
+ if (plan.annotationRegions.length !== 0) return false;
+ // An active cursor overlay composites pixels → no stream-copy.
+ if (plan.cursor && segment.cursorSamples.length > 0) return false;
+
+ for (const region of plan.speedRegions) {
+ const duration = region.endMs - region.startMs;
+ if (duration > 0.0001 && Math.abs(region.speed - 1) > 0.0001) {
+ return false;
+ }
+ }
+
+ if (plan.output.width !== segment.sourceWidth) return false;
+ if (plan.output.height !== segment.sourceHeight) return false;
+
+ return true;
+}
diff --git a/src/lib/exporter/videoExporter.ts b/src/lib/exporter/videoExporter.ts
index a3ac11d50..8e0f217bb 100644
--- a/src/lib/exporter/videoExporter.ts
+++ b/src/lib/exporter/videoExporter.ts
@@ -8,6 +8,7 @@ import type {
WebcamSizePreset,
ZoomRegion,
} from "@/components/video-editor/types";
+import type { RenderPlan } from "@/lib/ai-edition/exporter/renderPlan";
import { BackgroundLoadError } from "@/lib/wallpaper";
import type { CursorRecordingData } from "@/native/contracts";
import { getPlatform } from "@/utils/platformUtils";
@@ -104,6 +105,10 @@ export interface VideoExporterConfig extends ExportConfig {
cursorTelemetry?: import("@/components/video-editor/types").CursorTelemetryPoint[];
cursorClickTimestamps?: number[];
onProgress?: (progress: ExportProgress) => void;
+ // v2 multi-asset render plan (ordered segments, virtual-time effects,
+ // per-segment cursor). Present when built by documentExporter; the segment
+ // loop consumes it. Absent for the legacy single-asset callers.
+ renderPlan?: RenderPlan;
}
const SOURCE_COPY_EPSILON = 0.0001;