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): render multi-asset timelines through the v2 segment loop

Etienne Lescot93a71493da49
diff --git a/src/lib/ai-edition/exporter/audioConcatAssembler.test.ts b/src/lib/ai-edition/exporter/audioConcatAssembler.test.ts
new file mode 100644
index 000000000..1b41886a0
--- /dev/null
+++ b/src/lib/ai-edition/exporter/audioConcatAssembler.test.ts
@@ -0,0 +1,427 @@
+import { describe, expect, it } from "vitest";
+import {
+ type AssembleOptions,
+ type AudioConcatAssemblerSegmentInput,
+ assembleConcatenatedPcm,
+} from "./audioConcatAssembler";
+import type { AudioConcatPlan, AudioConcatSegmentPlan } from "./audioConcatPlan";
+
+// --- Factory helpers ---------------------------------------------------------
+
+// `plan` builds a minimal `AudioConcatPlan` literal — the assembler only reads
+// the documented fields (sampleRate, channels, totalSamples, segments[*]),
+// so we don't have to go through `buildAudioConcatPlan` here.
+function plan(
+ segs: AudioConcatSegmentPlan[],
+ header: { sampleRate?: number; channels?: number; totalSamples?: number } = {},
+): AudioConcatPlan {
+ return {
+ sampleRate: header.sampleRate ?? 48_000,
+ channels: header.channels ?? 1,
+ totalSamples: header.totalSamples ?? segs.reduce((acc, s) => acc + s.sampleCount, 0),
+ segments: segs,
+ };
+}
+
+function seg(
+ clipId: string,
+ startSample: number,
+ sampleCount: number,
+ silence: boolean,
+): AudioConcatSegmentPlan {
+ return { clipId, startSample, sampleCount, silence };
+}
+
+function pcm(...channels: number[][]): Float32Array[] {
+ return channels.map((c) => Float32Array.from(c));
+}
+
+function f32(values: number[]): Float32Array {
+ return Float32Array.from(values);
+}
+
+// --- Copy semantics ----------------------------------------------------------
+
+describe("assembleConcatenatedPcm — single segment", () => {
+ it("single mono segment at exact length: pcm samples copied as-is, no fade, no padding", () => {
+ const segPlan = seg("c1", 0, 4, false);
+ const pl = plan([segPlan]);
+ const inputs: AudioConcatAssemblerSegmentInput[] = [{ pcm: pcm([1, 2, 3, 4]) }];
+ const out = assembleConcatenatedPcm(inputs, pl);
+ expect(out).toHaveLength(1);
+ expect(Array.from(out[0])).toEqual([1, 2, 3, 4]);
+ // totalSamples enforces the buffer length — the slot never overflows.
+ expect(out[0].length).toBe(pl.totalSamples);
+ });
+});
+
+describe("assembleConcatenatedPcm — concatenation", () => {
+ it("two mono segments: seg B's samples land at seg B's startSample; output length == totalSamples", () => {
+ // seg A: [10..14), seg B: [14..19) — butt-joined, no overlap.
+ const pl = plan([seg("a", 0, 4, false), seg("b", 4, 5, false)], { totalSamples: 9 });
+ const inputs: AudioConcatAssemblerSegmentInput[] = [
+ { pcm: pcm([10, 11, 12, 13]) },
+ { pcm: pcm([20, 21, 22, 23, 24]) },
+ ];
+ const out = assembleConcatenatedPcm(inputs, pl);
+ expect(out).toHaveLength(1);
+ expect(out[0].length).toBe(9);
+ expect(Array.from(out[0])).toEqual([10, 11, 12, 13, 20, 21, 22, 23, 24]);
+ });
+
+ it("plan-vs-segments length mismatch: missing input(s) are treated as silence at the planned offset", () => {
+ // Skip the middle input → seg b's planned range renders zeros at its
+ // startSample; seg c's samples still land at offset 5 unchanged.
+ const pl = plan([seg("a", 0, 2, false), seg("b", 2, 3, false), seg("c", 5, 2, false)], {
+ totalSamples: 7,
+ });
+ const inputs: AudioConcatAssemblerSegmentInput[] = [
+ { pcm: pcm([1, 2]) },
+ { pcm: null }, // middle segment's input omitted → silent
+ { pcm: pcm([9, 10]) },
+ ];
+ const out = assembleConcatenatedPcm(inputs, pl);
+ expect(Array.from(out[0])).toEqual([1, 2, 0, 0, 0, 9, 10]);
+ });
+});
+
+describe("assembleConcatenatedPcm — silence / missing input", () => {
+ it("silence: true → the segment's range stays all zeros; neighbors unaffected", () => {
+ const pl = plan([seg("a", 0, 2, false), seg("b", 2, 3, true), seg("c", 5, 2, false)], {
+ totalSamples: 7,
+ });
+ const inputs: AudioConcatAssemblerSegmentInput[] = [
+ { pcm: pcm([1, 2]) },
+ { pcm: pcm([100, 101, 102]) }, // would be written, but silence flag wins
+ { pcm: pcm([9, 10]) },
+ ];
+ const out = assembleConcatenatedPcm(inputs, pl);
+ expect(Array.from(out[0])).toEqual([1, 2, 0, 0, 0, 9, 10]);
+ });
+
+ it("pcm: null (without silence flag) → treated as silent", () => {
+ const pl = plan([seg("a", 0, 2, false), seg("b", 2, 3, false)], { totalSamples: 5 });
+ const inputs: AudioConcatAssemblerSegmentInput[] = [{ pcm: pcm([1, 2]) }, { pcm: null }];
+ const out = assembleConcatenatedPcm(inputs, pl);
+ expect(Array.from(out[0])).toEqual([1, 2, 0, 0, 0]);
+ });
+});
+
+describe("assembleConcatenatedPcm — length clamping", () => {
+ it("short input is zero-padded at the tail; the NEXT segment still starts at its offset", () => {
+ // seg A length 5 but pcm length 2 → pad to 5; seg B starts at offset 5 unchanged.
+ const pl = plan([seg("a", 0, 5, false), seg("b", 5, 3, false)], { totalSamples: 8 });
+ const inputs: AudioConcatAssemblerSegmentInput[] = [
+ { pcm: pcm([100, 200]) },
+ { pcm: pcm([9, 10, 11]) },
+ ];
+ const out = assembleConcatenatedPcm(inputs, pl);
+ expect(Array.from(out[0])).toEqual([100, 200, 0, 0, 0, 9, 10, 11]);
+ });
+
+ it("long input is truncated; extra samples do NOT leak into the next segment's range", () => {
+ // seg A length 3 but pcm length 6 → only the first 3 land; seg B's offset is preserved.
+ const pl = plan([seg("a", 0, 3, false), seg("b", 3, 3, false)], { totalSamples: 6 });
+ const inputs: AudioConcatAssemblerSegmentInput[] = [
+ { pcm: pcm([1, 2, 3, 4, 5, 6]) }, // 4,5,6 must NOT appear in output
+ { pcm: pcm([9, 10, 11]) },
+ ];
+ const out = assembleConcatenatedPcm(inputs, pl);
+ expect(Array.from(out[0])).toEqual([1, 2, 3, 9, 10, 11]);
+ });
+});
+
+describe("assembleConcatenatedPcm — multi-channel", () => {
+ it("stereo: two-channel input is written into two output arrays independently per channel", () => {
+ const pl = plan([seg("a", 0, 3, false), seg("b", 3, 3, false)], {
+ channels: 2,
+ totalSamples: 6,
+ });
+ const inputs: AudioConcatAssemblerSegmentInput[] = [
+ { pcm: pcm([10, 11, 12], [20, 21, 22]) }, // ch0: 10..12, ch1: 20..22
+ { pcm: pcm([100, 101, 102], [200, 201, 202]) },
+ ];
+ const out = assembleConcatenatedPcm(inputs, pl);
+ expect(out).toHaveLength(2);
+ expect(Array.from(out[0])).toEqual([10, 11, 12, 100, 101, 102]);
+ expect(Array.from(out[1])).toEqual([20, 21, 22, 200, 201, 202]);
+ });
+
+ it("missing channel: input.pcm has 1 channel but plan.channels is 2 → that channel is silence for the segment", () => {
+ // seg A: stereo plan, only ch0 supplied → ch1 stays zero for seg A's range;
+ // seg B: full stereo, written normally at offset 3.
+ const pl = plan([seg("a", 0, 3, false), seg("b", 3, 3, false)], {
+ channels: 2,
+ totalSamples: 6,
+ });
+ const inputs: AudioConcatAssemblerSegmentInput[] = [
+ { pcm: pcm([10, 11, 12]) }, // no channel 1
+ { pcm: pcm([100, 101, 102], [200, 201, 202]) },
+ ];
+ const out = assembleConcatenatedPcm(inputs, pl);
+ expect(Array.from(out[0])).toEqual([10, 11, 12, 100, 101, 102]);
+ expect(Array.from(out[1])).toEqual([0, 0, 0, 200, 201, 202]);
+ });
+});
+
+// --- Boundary fades (equal-power) -------------------------------------------
+
+describe("assembleConcatenatedPcm — equal-power boundary fade", () => {
+ it("f=2: tail of seg 0 is multiplied by cos((k/f)·π/2); head of seg 1 by sin((k/f)·π/2); cos²+sin² ≈ 1 for the paired offset", () => {
+ // Two segments, each length 4. Fade f=2 → seg 0 indices [2,3) faded out,
+ // seg 1 indices [0,1) faded in. Use a non-1 value (5) so the gain is visible.
+ const pl = plan([seg("a", 0, 4, false), seg("b", 4, 4, false)], { totalSamples: 8 });
+ // Source values: seg a = [5,5,5,5], seg b = [7,7,7,7]. With no fade, output
+ // would be [5,5,5,5,7,7,7,7]. After fade:
+ // a[2] *= cos(0·π/2) = 1 → 5
+ // a[3] *= cos(0.5·π/2) = √2/2 → 5·√2/2
+ // b[0] *= sin(0·π/2) = 0 → 0
+ // b[1] *= sin(0.5·π/2) = √2/2 → 7·√2/2
+ const inputs: AudioConcatAssemblerSegmentInput[] = [
+ { pcm: pcm([5, 5, 5, 5]) },
+ { pcm: pcm([7, 7, 7, 7]) },
+ ];
+ const out = assembleConcatenatedPcm(inputs, pl, { boundaryFadeSamples: 2 });
+
+ // Float32 storage round-trips `input * gain` to ~7 significant digits
+ // (mantissa = 23 bits → ~6-7 decimal). Tolerance 5e-7 (precision=6)
+ // covers the worst-case Float32 quantization around |value|≈10.
+ const sqrt2over2 = Math.sqrt(2) / 2;
+ expect(out[0][0]).toBeCloseTo(5, 6); // far-from-boundary: untouched
+ expect(out[0][1]).toBeCloseTo(5, 6);
+ expect(out[0][2]).toBeCloseTo(5 * 1, 6); // k=0 → cos(0)=1
+ expect(out[0][3]).toBeCloseTo(5 * sqrt2over2, 6); // k=1 → cos(π/4)=√2/2
+ expect(out[0][4]).toBeCloseTo(7 * 0, 6); // seg b[0] → k=0 → sin(0)=0
+ expect(out[0][5]).toBeCloseTo(7 * sqrt2over2, 6); // k=1 → sin(π/4)=√2/2
+ expect(out[0][6]).toBeCloseTo(7, 6); // outside fade region
+ expect(out[0][7]).toBeCloseTo(7, 6);
+
+ // Equal-power check on the paired offset sums: cos² + sin² = 1
+ // (kernel of the spec — perceived loudness stays flat through the join).
+ // This is pure Float64 (no Float32 storage), so tighten to 12.
+ for (let k = 0; k < 2; k++) {
+ const cos = Math.cos((k / 2) * (Math.PI / 2));
+ const sin = Math.sin((k / 2) * (Math.PI / 2));
+ expect(cos * cos + sin * sin).toBeCloseTo(1, 12);
+ }
+ });
+
+ it("no fade at the OUTER edges — first sample of seg 0 and last sample of the last segment are untouched", () => {
+ // Three segments, fade=1 between each. The very first and very last sample
+ // sit one sample OUTSIDE any fade window → unchanged.
+ const pl = plan([seg("a", 0, 3, false), seg("b", 3, 3, false), seg("c", 6, 3, false)], {
+ totalSamples: 9,
+ });
+ const inputs: AudioConcatAssemblerSegmentInput[] = [
+ { pcm: pcm([1, 2, 3]) },
+ { pcm: pcm([9, 9, 9]) },
+ { pcm: pcm([4, 5, 6]) },
+ ];
+ const out = assembleConcatenatedPcm(inputs, pl, { boundaryFadeSamples: 1 });
+ // cos(0)=1, sin(0)=0 — fade-OUT leaves a[2] unchanged, fade-IN zeros b[3].
+ expect(out[0][0]).toBeCloseTo(1, 6); // far outer edge
+ expect(out[0][2]).toBeCloseTo(3, 6); // inside fade-OUT, but k=0 → gain 1
+ expect(out[0][3]).toBeCloseTo(0, 6); // head of seg b, k=0 → gain 0
+ expect(out[0][5]).toBeCloseTo(9, 6); // tail of seg b, k=0 → gain 1
+ expect(out[0][6]).toBeCloseTo(0, 6); // head of seg c, k=0 → gain 0
+ expect(out[0][8]).toBeCloseTo(6, 6); // far outer edge — UNCHANGED
+ });
+
+ it("fade is applied to ALL channels of a multi-channel output", () => {
+ const pl = plan([seg("a", 0, 4, false), seg("b", 4, 4, false)], {
+ channels: 2,
+ totalSamples: 8,
+ });
+ const inputs: AudioConcatAssemblerSegmentInput[] = [
+ { pcm: pcm([5, 5, 5, 5], [50, 50, 50, 50]) },
+ { pcm: pcm([7, 7, 7, 7], [70, 70, 70, 70]) },
+ ];
+ const out = assembleConcatenatedPcm(inputs, pl, { boundaryFadeSamples: 2 });
+ const sqrt2over2 = Math.sqrt(2) / 2;
+ // Both channels follow the same equal-power law independently.
+ // Float32-bound tolerance (see note above).
+ expect(out[0][3]).toBeCloseTo(5 * sqrt2over2, 6);
+ expect(out[0][5]).toBeCloseTo(7 * sqrt2over2, 6);
+ expect(out[1][3]).toBeCloseTo(50 * sqrt2over2, 6);
+ expect(out[1][5]).toBeCloseTo(70 * sqrt2over2, 6);
+ // Untouched outer samples on both channels.
+ expect(out[1][0]).toBeCloseTo(50, 6);
+ expect(out[1][7]).toBeCloseTo(70, 6);
+ });
+
+ it("fade is clamped to floor(sampleCount/2) of each adjacent segment — boundaryFadeSamples larger than the slot", () => {
+ // seg A length 3 → floor(3/2)=1, seg B length 3 → 1: requested f0=100 → effective f=1.
+ const pl = plan([seg("a", 0, 3, false), seg("b", 3, 3, false)], { totalSamples: 6 });
+ const inputs: AudioConcatAssemblerSegmentInput[] = [
+ { pcm: pcm([8, 8, 8]) },
+ { pcm: pcm([9, 9, 9]) },
+ ];
+ const out = assembleConcatenatedPcm(inputs, pl, { boundaryFadeSamples: 100 });
+ // Only index 2 of seg a (tail-of-fade, k=0, cos=1) and index 3 of seg b
+ // (head-of-fade, k=0, sin=0) are affected — index 1 of seg a and index 4
+ // of seg b are well outside the f=1 fade region and must be unchanged.
+ expect(out[0][0]).toBeCloseTo(8, 6);
+ expect(out[0][1]).toBeCloseTo(8, 6); // NOT in the fade region
+ expect(out[0][2]).toBeCloseTo(8, 6); // k=0 → cos(0)=1
+ expect(out[0][3]).toBeCloseTo(0, 6); // k=0 → sin(0)=0
+ expect(out[0][4]).toBeCloseTo(9, 6); // NOT in the fade region
+ expect(out[0][5]).toBeCloseTo(9, 6);
+ });
+
+ it("fade is independently clamped per boundary when adjacent segments have different lengths", () => {
+ // seg A length 10 → floor(10/2)=5 (the binding side; seg B is length 100 → bound by A).
+ const pl = plan([seg("a", 0, 10, false), seg("b", 10, 100, false)], { totalSamples: 110 });
+ // Use 1.0 so any gain shows up verbatim.
+ const inputs: AudioConcatAssemblerSegmentInput[] = [
+ { pcm: pcm(new Array(10).fill(1)) },
+ { pcm: pcm(new Array(100).fill(1)) },
+ ];
+ const out = assembleConcatenatedPcm(inputs, pl, { boundaryFadeSamples: 1000 });
+ // Effective f = min(1000, floor(10/2)=5, floor(100/2)=50) = 5.
+ // seg a tail: indices [5,10) — cos gain applied. k=0 → 1, k=4 → cos(0.8π/2)≈0.309.
+ // Float32-bound tolerance.
+ expect(out[0][5]).toBeCloseTo(Math.cos((0 / 5) * (Math.PI / 2)), 6);
+ expect(out[0][9]).toBeCloseTo(Math.cos((4 / 5) * (Math.PI / 2)), 6);
+ // seg a head: indices [0,5) — unchanged.
+ expect(out[0][0]).toBeCloseTo(1, 6);
+ expect(out[0][4]).toBeCloseTo(1, 6);
+ // seg b head: indices [10,15) — sin gain applied. k=0 → 0, k=4 → sin(0.8π/2)≈0.951.
+ expect(out[0][10]).toBeCloseTo(Math.sin((0 / 5) * (Math.PI / 2)), 6);
+ expect(out[0][14]).toBeCloseTo(Math.sin((4 / 5) * (Math.PI / 2)), 6);
+ // seg b body: indices [15,110) — unchanged.
+ expect(out[0][15]).toBeCloseTo(1, 6);
+ expect(out[0][109]).toBeCloseTo(1, 6);
+ });
+
+ it("a short adjacent segment (sampleCount < 2*f0) still gets its own contribution — only its own half is faded", () => {
+ // seg A length 10, seg B length 2. f = min(f0=5, 5, 1) = 1. Only index 1 of
+ // seg A (cos) and index 0 of seg B (sin) are touched — seg B index 1 is
+ // outside the fade and stays at the input value.
+ const pl = plan([seg("a", 0, 10, false), seg("b", 10, 2, false)], { totalSamples: 12 });
+ const inputs: AudioConcatAssemblerSegmentInput[] = [
+ { pcm: pcm(new Array(10).fill(2)) },
+ { pcm: pcm([3, 3]) },
+ ];
+ const out = assembleConcatenatedPcm(inputs, pl, { boundaryFadeSamples: 5 });
+ // seg a body
+ expect(out[0][0]).toBeCloseTo(2, 6);
+ expect(out[0][8]).toBeCloseTo(2, 6);
+ // seg a tail — k=0 → cos(0)=1
+ expect(out[0][9]).toBeCloseTo(2, 6);
+ // seg b head — k=0 → sin(0)=0
+ expect(out[0][10]).toBeCloseTo(0, 6);
+ // seg b body (outside fade)
+ expect(out[0][11]).toBeCloseTo(3, 6);
+ });
+});
+
+describe("assembleConcatenatedPcm — boundaryFadeSamples edge values", () => {
+ it.each<[string, AssembleOptions | undefined]>([
+ ["undefined", undefined],
+ ["0", { boundaryFadeSamples: 0 }],
+ ["negative", { boundaryFadeSamples: -10 }],
+ ["NaN", { boundaryFadeSamples: Number.NaN }],
+ ["Infinity", { boundaryFadeSamples: Number.POSITIVE_INFINITY }],
+ ])("boundaryFadeSamples %s → no fades (plain concat)", (_label, opts) => {
+ const pl = plan([seg("a", 0, 4, false), seg("b", 4, 4, false)], { totalSamples: 8 });
+ const inputs: AudioConcatAssemblerSegmentInput[] = [
+ { pcm: pcm([5, 5, 5, 5]) },
+ { pcm: pcm([7, 7, 7, 7]) },
+ ];
+ const out = assembleConcatenatedPcm(inputs, pl, opts);
+ expect(Array.from(out[0])).toEqual([5, 5, 5, 5, 7, 7, 7, 7]);
+ });
+});
+
+// --- Degenerate / purity -----------------------------------------------------
+
+describe("assembleConcatenatedPcm — degenerate layouts", () => {
+ it("plan.channels = 0 → returns []", () => {
+ const pl = plan([seg("a", 0, 4, false)], { channels: 0, totalSamples: 4 });
+ const out = assembleConcatenatedPcm([{ pcm: pcm([1, 2, 3, 4]) }], pl);
+ expect(out).toEqual([]);
+ });
+
+ it("plan.totalSamples = 0 with channels=2 → returns 2 empty Float32Arrays", () => {
+ const pl = plan([], { channels: 2, totalSamples: 0 });
+ const out = assembleConcatenatedPcm([], pl);
+ expect(out).toHaveLength(2);
+ expect(out[0]).toBeInstanceOf(Float32Array);
+ expect(out[0].length).toBe(0);
+ expect(out[1]).toBeInstanceOf(Float32Array);
+ expect(out[1].length).toBe(0);
+ });
+
+ it("plan.totalSamples = 0 with channels=0 → returns [] (both guards match)", () => {
+ const pl = plan([], { channels: 0, totalSamples: 0 });
+ const out = assembleConcatenatedPcm([], pl);
+ expect(out).toEqual([]);
+ });
+
+ it("plan.totalSamples = 0 with channels=3, no segments → 3 empty Float32Arrays", () => {
+ const pl = plan([], { channels: 3, totalSamples: 0 });
+ const out = assembleConcatenatedPcm([], pl);
+ expect(out).toHaveLength(3);
+ expect(out.every((a) => a.length === 0)).toBe(true);
+ });
+
+ it("plan with segments but totalSamples = 0 → 2 empty Float32Arrays", () => {
+ // Defends against the all-zero case: even though startSample/sampleCount
+ // are integers, the output buffer is empty and no fades run.
+ const pl = plan([seg("a", 0, 0, false), seg("b", 0, 0, false)], {
+ channels: 2,
+ totalSamples: 0,
+ });
+ const out = assembleConcatenatedPcm([{ pcm: pcm([1, 2]) }, { pcm: pcm([3, 4], [5, 6]) }], pl, {
+ boundaryFadeSamples: 4,
+ });
+ expect(out).toHaveLength(2);
+ expect(out[0].length).toBe(0);
+ expect(out[1].length).toBe(0);
+ });
+});
+
+describe("assembleConcatenatedPcm — purity (does not mutate inputs)", () => {
+ it("input Float32Arrays are not modified by copy or by boundary fades", () => {
+ const pl = plan([seg("a", 0, 4, false), seg("b", 4, 4, false)], { totalSamples: 8 });
+ const srcA = f32([1, 2, 3, 4]);
+ const srcB = f32([5, 6, 7, 8]);
+ const aSnapshot = Array.from(srcA);
+ const bSnapshot = Array.from(srcB);
+
+ const inputs: AudioConcatAssemblerSegmentInput[] = [{ pcm: [srcA] }, { pcm: [srcB] }];
+ const out = assembleConcatenatedPcm(inputs, pl, { boundaryFadeSamples: 2 });
+
+ // Inputs are untouched after the call (compare snapshot to live values).
+ expect(Array.from(srcA)).toEqual(aSnapshot);
+ expect(Array.from(srcB)).toEqual(bSnapshot);
+ // The output reflects the fades (so we know we actually exercised the
+ // fade path — otherwise the purity check would be vacuous).
+ expect(out[0][3]).not.toBe(bSnapshot[3] ?? 0);
+ });
+
+ it("the segments wrapper array is not mutated in length or order", () => {
+ const pl = plan([seg("a", 0, 2, false)], { totalSamples: 2 });
+ const inputs: AudioConcatAssemblerSegmentInput[] = [{ pcm: pcm([9, 9]) }];
+ const beforeLen = inputs.length;
+ assembleConcatenatedPcm(inputs, pl);
+ expect(inputs).toHaveLength(beforeLen);
+ expect(inputs[0].pcm).not.toBeNull();
+ });
+
+ it("a shared input pcm (referenced from two segments) is read-only — both outputs see the same logical source", () => {
+ // Two segments in the plan, each pointing at the same source buffer.
+ // The assembler must not overwrite either output through the shared
+ // input reference. (The fade writes ONLY into the output buffers.)
+ const shared = f32([4, 4, 4, 4]);
+ const pl = plan([seg("a", 0, 4, false), seg("b", 4, 4, false)], { totalSamples: 8 });
+ const inputs: AudioConcatAssemblerSegmentInput[] = [{ pcm: [shared] }, { pcm: [shared] }];
+ const out = assembleConcatenatedPcm(inputs, pl, { boundaryFadeSamples: 2 });
+ // Shared source is still pristine.
+ expect(Array.from(shared)).toEqual([4, 4, 4, 4]);
+ // Fade-OUT still applied to the first segment's tail; equals 4·cos(π/4)=4·√2/2.
+ // Float32-bound tolerance.
+ const sqrt2over2 = Math.sqrt(2) / 2;
+ expect(out[0][3]).toBeCloseTo(4 * sqrt2over2, 6);
+ });
+});
diff --git a/src/lib/ai-edition/exporter/audioConcatAssembler.ts b/src/lib/ai-edition/exporter/audioConcatAssembler.ts
new file mode 100644
index 000000000..32ec82981
--- /dev/null
+++ b/src/lib/ai-edition/exporter/audioConcatAssembler.ts
@@ -0,0 +1,129 @@
+// AudioConcatAssembler: pure-logic PCM assembly for the v2 multi-asset export
+// audio track.
+//
+// ponytail: `audioConcatPlan.ts` decides WHERE each segment's audio lands in
+// the concatenated output (integer sample offsets / counts / silence flags at
+// a common sampleRate + channels). This module does the actual sample copy:
+// for every plan segment, it takes the segment's already-decoded,
+// already-resampled PLANAR PCM (one Float32Array per channel) and writes it
+// into the right offset of a single output buffer, clamping each channel to
+// the planned sampleCount (longer input → truncate; shorter input → zero-pad)
+// so a small decode over/under-run never shifts the timeline. A short
+// equal-power fade is applied at every INTERNAL segment boundary to suppress
+// clicks where two different recordings meet butt-joined — without changing
+// timing, so audio stays locked to the video (which is retimed independently).
+//
+// The plan places segments BUTT-JOINED (segment i+1 starts exactly where i
+// ends, no overlap) because `plan.totalSamples` must equal the video frame
+// count for A/V lock, so a true overlapping crossfade is not an option (it
+// would shorten the track and drift A/V). Instead we use equal-power gains:
+// fade-out gain at offset k∈[0,f) = cos((k/f)·π/2) and fade-in at the matching
+// offset = sin((k/f)·π/2). `cos² + sin² = 1` keeps perceived power even.
+//
+// Pure: no DOM, no IPC, no WebCodecs, no AudioContext — only Float32Array
+// math. Inputs are never mutated.
+
+import type { AudioConcatPlan } from "./audioConcatPlan";
+
+// One entry per plan segment (SAME order/length as `plan.segments`). `pcm` is
+// the segment's decoded audio, PLANAR (one Float32Array per channel), already
+// at `plan.sampleRate` / `plan.channels`. `null` → silent segment (renders
+// zeros — equivalent to `seg.silence === true`). The assembler clamps each
+// channel to the plan's `sampleCount`: a longer buffer is truncated, a
+// shorter one is zero-padded, so a small decode over/under-run never shifts
+// the timeline.
+export interface AudioConcatAssemblerSegmentInput {
+ pcm: Float32Array[] | null;
+}
+
+export interface AssembleOptions {
+ // Equal-power fade length (in samples) applied at each INTERNAL segment
+ // boundary to avoid clicks. Clamped per-boundary to at most
+ // `floor(sampleCount/2)` of each adjacent segment. Default 0 (no fade).
+ // Non-finite / negative values are treated as 0.
+ boundaryFadeSamples?: number;
+}
+
+// Returns `plan.channels` planar Float32Arrays, each of length `plan.totalSamples`.
+// Pure: never mutates `segments` or their `pcm` arrays.
+export function assembleConcatenatedPcm(
+ segments: AudioConcatAssemblerSegmentInput[],
+ plan: AudioConcatPlan,
+ options?: AssembleOptions,
+): Float32Array[] {
+ // Degenerate layouts — no channels to fill.
+ if (plan.channels <= 0) return [];
+ if (plan.totalSamples === 0) {
+ const empty: Float32Array[] = [];
+ for (let i = 0; i < plan.channels; i++) empty.push(new Float32Array(0));
+ return empty;
+ }
+
+ // 1) Allocate `plan.channels` output Float32Arrays (zero-filled = silence).
+ const output: Float32Array[] = [];
+ for (let c = 0; c < plan.channels; c++) {
+ output.push(new Float32Array(plan.totalSamples));
+ }
+
+ // 2) Copy each segment's PCM into its planned slot. A silent segment
+ // (per plan) or a missing/short input leaves zeros in the slot — the
+ // timeline (startSample + sampleCount) is preserved either way.
+ const segCount = plan.segments.length;
+ for (let i = 0; i < segCount; i++) {
+ const seg = plan.segments[i];
+ const start = seg.startSample;
+ const count = seg.sampleCount;
+ if (count <= 0) continue;
+ const input = segments[i];
+ if (seg.silence) continue;
+ if (!input || input.pcm == null) continue;
+
+ const src = input.pcm;
+ for (let c = 0; c < plan.channels; c++) {
+ const dst = output[c];
+ const srcCh = src[c];
+ if (!srcCh) continue; // missing channel → silence for this segment
+ const copy = count < srcCh.length ? count : srcCh.length;
+ // Bounds already enforced (start..start+count ⊂ [0, totalSamples),
+ // srcCh.length ≥ copy) — no overrun possible, no clamp needed.
+ for (let k = 0; k < copy; k++) {
+ dst[start + k] = srcCh[k];
+ }
+ // Any tail beyond `copy` (count > srcCh.length) is left at zero
+ // (the Float32Array was zero-filled at allocation).
+ }
+ }
+
+ // 3) Boundary fades (after all copies). At each INTERNAL boundary the tail
+ // of segment i is multiplied by a fade-out gain (`cos`) and the head of
+ // segment i+1 by a fade-in gain (`sin`) with matching offsets so the sum of
+ // squares is 1 — equal-power, no perceived dip. Applied to every channel
+ // (multiplication by 0 on a silent side is a harmless no-op).
+ const f0 = options?.boundaryFadeSamples ?? 0;
+ if (Number.isFinite(f0) && f0 > 0 && segCount >= 2) {
+ for (let i = 0; i < segCount - 1; i++) {
+ const cur = plan.segments[i];
+ const next = plan.segments[i + 1];
+ const f = Math.min(f0, Math.floor(cur.sampleCount / 2), Math.floor(next.sampleCount / 2));
+ if (f <= 0) continue;
+ const halfPi = Math.PI / 2;
+ for (let c = 0; c < plan.channels; c++) {
+ const dst = output[c];
+ // Fade-OUT tail of cur: k=0 → gain 1, k=f-1 → ~0.
+ const tailStart = cur.startSample + cur.sampleCount - f;
+ for (let k = 0; k < f; k++) {
+ const gain = Math.cos((k / f) * halfPi);
+ dst[tailStart + k] *= gain;
+ }
+ // Fade-IN head of next: k=0 → gain 0, k=f-1 → ~1.
+ const headStart = next.startSample;
+ for (let k = 0; k < f; k++) {
+ const gain = Math.sin((k / f) * halfPi);
+ dst[headStart + k] *= gain;
+ }
+ }
+ }
+ }
+
+ return output;
+}
diff --git a/src/lib/ai-edition/exporter/renderPlan.test.ts b/src/lib/ai-edition/exporter/renderPlan.test.ts
index 0f5c7317e..c9b9fd1ce 100644
--- a/src/lib/ai-edition/exporter/renderPlan.test.ts
+++ b/src/lib/ai-edition/exporter/renderPlan.test.ts
@@ -715,6 +715,58 @@ describe("buildRenderPlan — cursor", () => {
});
});
+// --- buildRenderPlan: webcam layout (global, from legacyEditor) --------------
+
+describe("buildRenderPlan — webcam layout", () => {
+ 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 })];
+
+ it("uses the documented defaults when legacyEditor is null", () => {
+ const plan = buildRenderPlan(doc({ assets, clips }), { quality: "source" });
+ expect(plan.webcam).toEqual({
+ layoutPreset: "picture-in-picture",
+ maskShape: "rectangle",
+ mirrored: false,
+ reactiveZoom: true,
+ sizePreset: 25,
+ position: null,
+ });
+ });
+
+ it("reads webcam layout/style from legacyEditor", () => {
+ const plan = buildRenderPlan(
+ doc({
+ assets,
+ clips,
+ legacyEditor: {
+ webcamLayoutPreset: "vertical-stack",
+ webcamMaskShape: "circle",
+ webcamMirrored: true,
+ webcamReactiveZoom: false,
+ webcamSizePreset: 40,
+ webcamPosition: { cx: 0.8, cy: 0.7 },
+ },
+ }),
+ { quality: "source" },
+ );
+ expect(plan.webcam).toEqual({
+ layoutPreset: "vertical-stack",
+ maskShape: "circle",
+ mirrored: true,
+ reactiveZoom: false,
+ sizePreset: 40,
+ position: { cx: 0.8, cy: 0.7 },
+ });
+ });
+});
+
// --- isIdentityFastPathEligible -----------------------------------------------
describe("isIdentityFastPathEligible", () => {
diff --git a/src/lib/ai-edition/exporter/renderPlan.ts b/src/lib/ai-edition/exporter/renderPlan.ts
index 7697ca095..d07c35370 100644
--- a/src/lib/ai-edition/exporter/renderPlan.ts
+++ b/src/lib/ai-edition/exporter/renderPlan.ts
@@ -18,6 +18,9 @@ import type {
AnnotationRegion,
CropRegion,
SpeedRegion,
+ WebcamLayoutPreset,
+ WebcamMaskShape,
+ WebcamSizePreset,
ZoomRegion,
} from "@/components/video-editor/types";
import { calculateMp4ExportSettings } from "@/lib/exporter/mp4ExportSettings";
@@ -120,6 +123,18 @@ export interface RenderPlanCursor {
theme?: string;
}
+// Global webcam layout/style (from legacyEditor) shared by every segment. The
+// per-segment webcam SOURCE (file + offset) lives on `RenderSegment.camera`; a
+// segment renders a webcam overlay only when its asset has a camera track.
+export interface RenderPlanWebcam {
+ layoutPreset: WebcamLayoutPreset;
+ maskShape: WebcamMaskShape;
+ mirrored: boolean;
+ reactiveZoom: boolean;
+ sizePreset: WebcamSizePreset;
+ position: { cx: number; cy: number } | null;
+}
+
export interface RenderPlan {
output: RenderPlanOutput;
aspectRatioValue: number;
@@ -137,6 +152,8 @@ export interface RenderPlan {
// 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;
+ // Shared webcam layout/style (per-segment webcam source is on the segment).
+ webcam: RenderPlanWebcam;
}
export interface BuildRenderPlanCursorOptions {
@@ -322,6 +339,25 @@ export function buildRenderPlan(
}
: null;
+ // --- Webcam (global layout/style, read from legacyEditor exactly as the
+ // legacy exporter does; per-segment source lives on segment.camera) ---
+ const webcam: RenderPlanWebcam = {
+ layoutPreset: extractLegacyField<string>(
+ legacy,
+ "webcamLayoutPreset",
+ "picture-in-picture",
+ ) as WebcamLayoutPreset,
+ maskShape: extractLegacyField<string>(
+ legacy,
+ "webcamMaskShape",
+ "rectangle",
+ ) as WebcamMaskShape,
+ mirrored: extractLegacyField(legacy, "webcamMirrored", false),
+ reactiveZoom: extractLegacyField(legacy, "webcamReactiveZoom", true),
+ sizePreset: extractLegacyField(legacy, "webcamSizePreset", 25),
+ position: extractLegacyField<{ cx: number; cy: number } | null>(legacy, "webcamPosition", null),
+ };
+
return {
output: {
width: settings.width,
@@ -337,6 +373,7 @@ export function buildRenderPlan(
speedRegions,
appearance,
cursor,
+ webcam,
};
}
diff --git a/src/lib/exporter/audioEncoder.ts b/src/lib/exporter/audioEncoder.ts
index f95c75508..f3ffc7d65 100644
--- a/src/lib/exporter/audioEncoder.ts
+++ b/src/lib/exporter/audioEncoder.ts
@@ -1546,6 +1546,78 @@ export class AudioProcessor {
return offset;
}
+ /**
+ * Encodes an already-assembled planar PCM timeline (one Float32Array per
+ * channel, at `sampleRate`) into `exportCodec` and muxes the chunks. Used by
+ * the v2 multi-asset segment loop: per-segment audio is decoded, concatenated
+ * and boundary-faded upstream (audioConcatAssembler), then handed here as one
+ * continuous buffer — so this method only chops it into encoder-sized frames.
+ */
+ async encodePcmToMuxer(
+ pcm: Float32Array[],
+ sampleRate: number,
+ muxer: VideoMuxer,
+ exportCodec: ExportAudioCodec,
+ ): Promise<void> {
+ if (this.cancelled) return;
+ const channels = pcm.length;
+ const totalFrames = pcm[0]?.length ?? 0;
+ if (channels === 0 || totalFrames === 0) return;
+
+ const encodeConfig: AudioEncoderConfig = {
+ codec: exportCodec.encoderCodec,
+ sampleRate,
+ numberOfChannels: channels,
+ bitrate: AUDIO_BITRATE,
+ };
+ const support = await AudioEncoder.isConfigSupported(encodeConfig);
+ if (!support.supported) {
+ console.warn(`[AudioProcessor] ${exportCodec.label} encoding not supported, skipping audio`);
+ return;
+ }
+
+ const encodedChunks: { chunk: EncodedAudioChunk; meta?: EncodedAudioChunkMetadata }[] = [];
+ const encoder = new AudioEncoder({
+ output: (chunk, meta) => encodedChunks.push({ chunk, meta }),
+ error: (e: DOMException) => console.error("[AudioProcessor] Encode error:", e),
+ });
+ encoder.configure(encodeConfig);
+
+ let offset = 0;
+ while (offset < totalFrames && !this.cancelled) {
+ const count = Math.min(OFFLINE_OUTPUT_FRAMES, totalFrames - offset);
+ // f32-planar layout: channel 0's `count` samples, then channel 1's, …
+ const planar = new Float32Array(count * channels);
+ for (let c = 0; c < channels; c++) {
+ planar.set(pcm[c].subarray(offset, offset + count), c * count);
+ }
+ const audioData = new AudioData({
+ format: "f32-planar",
+ sampleRate,
+ numberOfFrames: count,
+ numberOfChannels: channels,
+ timestamp: Math.round((offset / sampleRate) * 1_000_000),
+ data: planar.buffer as ArrayBuffer,
+ });
+ encoder.encode(audioData);
+ audioData.close();
+ offset += count;
+ while (encoder.encodeQueueSize > ENCODE_BACKPRESSURE_LIMIT && !this.cancelled) {
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ }
+ }
+
+ if (encoder.state === "configured") {
+ await encoder.flush();
+ encoder.close();
+ }
+ for (const { chunk, meta } of encodedChunks) {
+ if (this.cancelled) break;
+ await muxer.addAudioChunk(chunk, meta);
+ }
+ console.log(`[AudioProcessor] Segmented audio: ${encodedChunks.length} chunks`);
+ }
+
cancel(): void {
this.cancelled = true;
}
diff --git a/src/lib/exporter/frameRenderer.ts b/src/lib/exporter/frameRenderer.ts
index 7f2c03bd1..a0e80ee71 100644
--- a/src/lib/exporter/frameRenderer.ts
+++ b/src/lib/exporter/frameRenderer.ts
@@ -199,6 +199,33 @@ export class FrameRenderer {
this.config.cropRegion = cropRegion;
}
+ /**
+ * Reconfigure the renderer's INPUT for the next segment of a multi-asset
+ * export (v2 segment loop). Output dimensions stay fixed for the whole
+ * export; only the source-dependent fields change. `updateLayout()` reads
+ * these from `this.config` fresh every frame and `renderFrame` swaps the
+ * video texture per frame, so mutating config here is picked up with no
+ * teardown. Virtual-time zoom/annotation state is intentionally preserved
+ * (those effects span segments), but per-source cursor/auto-focus continuity
+ * is reset so a new asset doesn't inherit the previous one's smoothed motion.
+ */
+ setSource(source: {
+ videoWidth: number;
+ videoHeight: number;
+ webcamSize?: Size | null;
+ cursorRecordingData?: CursorRecordingData | null;
+ cursorScale?: number;
+ }): void {
+ this.config.videoWidth = source.videoWidth;
+ this.config.videoHeight = source.videoHeight;
+ this.config.webcamSize = source.webcamSize ?? null;
+ this.config.cursorRecordingData = source.cursorRecordingData ?? null;
+ this.config.cursorScale = source.cursorScale ?? 0;
+ this.layoutCache = null;
+ this.smoothedAutoFocus = null;
+ resetNativeCursorMotionBlurState(this.nativeCursorMotionBlurState);
+ }
+
async initialize(): Promise<void> {
const canvas = document.createElement("canvas");
canvas.width = this.config.width;
diff --git a/src/lib/exporter/videoExporter.ts b/src/lib/exporter/videoExporter.ts
index 8e0f217bb..eb7935e87 100644
--- a/src/lib/exporter/videoExporter.ts
+++ b/src/lib/exporter/videoExporter.ts
@@ -8,12 +8,15 @@ import type {
WebcamSizePreset,
ZoomRegion,
} from "@/components/video-editor/types";
-import type { RenderPlan } from "@/lib/ai-edition/exporter/renderPlan";
+import { assembleConcatenatedPcm } from "@/lib/ai-edition/exporter/audioConcatAssembler";
+import { buildAudioConcatPlan } from "@/lib/ai-edition/exporter/audioConcatPlan";
+import type { RenderPlan, RenderSegment } from "@/lib/ai-edition/exporter/renderPlan";
import { BackgroundLoadError } from "@/lib/wallpaper";
import type { CursorRecordingData } from "@/native/contracts";
import { getPlatform } from "@/utils/platformUtils";
-import { AudioProcessor } from "./audioEncoder";
+import { AudioProcessor, downmixPlanarChannelsForExport } from "./audioEncoder";
import { FrameRenderer } from "./frameRenderer";
+import { materializeLocalSourceFile, releaseLocalSourceFile } from "./localSourceFile";
import { VideoMuxer, videoCodecFamily } from "./muxer";
import { MAX_IN_MEMORY_SOURCE_BYTES } from "./sourceFileLimits";
import { StreamingVideoDecoder } from "./streamingDecoder";
@@ -223,6 +226,140 @@ export function getSourceCopyFastPathBlockers(
return blockers;
}
+/** Source-time spans to CUT for one segment so its decoder emits exactly
+ * [sourceStart, sourceEnd) minus the clip's intra-trims: the complement of the
+ * kept window over [0, sourceDuration] plus the intra-trims (v2 segment loop). */
+function buildSegmentRenderTrims(segment: RenderSegment, sourceDurationSec: number): TrimRegion[] {
+ const cuts: Array<{ startSec: number; endSec: number }> = [];
+ if (segment.sourceStartSec > 0) {
+ cuts.push({ startSec: 0, endSec: segment.sourceStartSec });
+ }
+ const keptEnd = Math.min(segment.sourceEndSec, sourceDurationSec);
+ if (keptEnd < sourceDurationSec) {
+ cuts.push({ startSec: keptEnd, endSec: sourceDurationSec });
+ }
+ for (const trim of segment.intraTrims) {
+ cuts.push({ startSec: trim.startSec, endSec: trim.endSec });
+ }
+ return cuts.map((cut, i) => ({
+ id: `seg_trim_${i + 1}`,
+ startMs: Math.round(cut.startSec * 1000),
+ endMs: Math.round(cut.endSec * 1000),
+ }));
+}
+
+/** Per-segment cursor recording for the renderer: the plan's shared cursor
+ * atlas/style + THIS segment's asset samples (empty → no overlay). */
+function segmentCursorRecording(
+ plan: RenderPlan,
+ segment: RenderSegment,
+): CursorRecordingData | null {
+ if (!plan.cursor) return null;
+ return {
+ version: plan.cursor.version,
+ provider: plan.cursor.provider,
+ assets: plan.cursor.assets,
+ samples: segment.cursorSamples,
+ };
+}
+
+// v2 multi-asset audio output layout. Both recording formats are 48 kHz, so
+// decodeAudioData is an identity resample; only channel counts get normalized.
+const AUDIO_OUTPUT_SAMPLE_RATE = 48_000;
+const AUDIO_OUTPUT_CHANNELS = 2;
+// Short equal-power fade applied at each segment audio join (seamless audio).
+const AUDIO_BOUNDARY_FADE_SEC = 0.005;
+
+/** Source-time sub-intervals of a segment that are KEPT — its window minus
+ * intra-trims (the complement of buildSegmentRenderTrims within the clip) — so
+ * the segment's audio removes exactly the same cuts as its video. */
+function keptSourceIntervals(segment: RenderSegment): Array<{ startSec: number; endSec: number }> {
+ const kept: Array<{ startSec: number; endSec: number }> = [];
+ let cursor = segment.sourceStartSec;
+ const trims = [...segment.intraTrims].sort((a, b) => a.startSec - b.startSec);
+ for (const trim of trims) {
+ const trimStart = Math.max(trim.startSec, segment.sourceStartSec);
+ const trimEnd = Math.min(trim.endSec, segment.sourceEndSec);
+ if (trimEnd <= cursor) continue;
+ if (trimStart > cursor) {
+ kept.push({ startSec: cursor, endSec: Math.min(trimStart, segment.sourceEndSec) });
+ }
+ cursor = Math.max(cursor, trimEnd);
+ }
+ if (cursor < segment.sourceEndSec) {
+ kept.push({ startSec: cursor, endSec: segment.sourceEndSec });
+ }
+ return kept;
+}
+
+/** Decodes ONE segment's audio to planar PCM at the common export layout
+ * (sampleRate/channels), keeping only the clip's source window minus its
+ * intra-trims. Channel counts are normalized via the shared downmix. Returns
+ * null when the source has no decodable audio track. */
+async function decodeSegmentAudioPcm(
+ segment: RenderSegment,
+ sampleRate: number,
+ channels: number,
+): Promise<Float32Array[] | null> {
+ let file: File | null = null;
+ try {
+ file = await materializeLocalSourceFile(segment.videoUrl, `seg-${segment.clipId}-audio`);
+ const bytes = await file.arrayBuffer();
+ const ctx = new OfflineAudioContext(Math.max(1, channels), 1, sampleRate);
+ let audioBuffer: AudioBuffer;
+ try {
+ audioBuffer = await ctx.decodeAudioData(bytes);
+ } catch {
+ return null; // no decodable audio track
+ }
+ const sourceChannels = audioBuffer.numberOfChannels;
+ if (sourceChannels === 0) return null;
+
+ const sourcePlanes: Float32Array[] = [];
+ for (let c = 0; c < sourceChannels; c++) sourcePlanes.push(audioBuffer.getChannelData(c));
+
+ // Concatenate the kept source sub-intervals (intra-trims removed), per channel.
+ const kept = keptSourceIntervals(segment);
+ const keptChannels: Float32Array[] = [];
+ for (let c = 0; c < sourceChannels; c++) {
+ const total = kept.reduce((acc, iv) => {
+ const s0 = Math.max(0, Math.round(iv.startSec * sampleRate));
+ const s1 = Math.min(sourcePlanes[c].length, Math.round(iv.endSec * sampleRate));
+ return acc + Math.max(0, s1 - s0);
+ }, 0);
+ const out = new Float32Array(total);
+ let w = 0;
+ for (const iv of kept) {
+ const s0 = Math.max(0, Math.round(iv.startSec * sampleRate));
+ const s1 = Math.min(sourcePlanes[c].length, Math.round(iv.endSec * sampleRate));
+ if (s1 > s0) {
+ out.set(sourcePlanes[c].subarray(s0, s1), w);
+ w += s1 - s0;
+ }
+ }
+ keptChannels.push(out);
+ }
+
+ if (sourceChannels === channels) return keptChannels;
+
+ // Normalize channel count (e.g. mono → stereo) with the shared downmix,
+ // which returns one planar Float32Array (ch0 samples, then ch1, …).
+ const frameCount = keptChannels[0]?.length ?? 0;
+ if (frameCount === 0) return [];
+ const downmixed = downmixPlanarChannelsForExport(keptChannels, channels);
+ const result: Float32Array[] = [];
+ for (let c = 0; c < channels; c++) {
+ result.push(downmixed.subarray(c * frameCount, (c + 1) * frameCount));
+ }
+ return result;
+ } catch (error) {
+ console.warn("[VideoExporter] segment audio decode failed:", error);
+ return null;
+ } finally {
+ if (file) releaseLocalSourceFile(file.name);
+ }
+}
+
function isMp4Source(videoUrl: string, blob: Blob) {
if (blob.type.toLowerCase().includes("mp4")) {
return true;
@@ -310,6 +447,14 @@ export class VideoExporter {
this.fatalEncoderError = null;
try {
+ // v2 multi-asset path: a plan with >1 segment can't be rendered by the
+ // single-stream pipeline below (it would drop every non-primary clip —
+ // the P1 bug). Single-segment exports stay on the proven legacy path.
+ const segmentPlan = this.config.renderPlan;
+ if (segmentPlan && segmentPlan.segments.length > 1) {
+ return await this.runSegmentLoop(encoderPreference, segmentPlan);
+ }
+
const platform = await getPlatform();
const streamingDecoder = new StreamingVideoDecoder();
@@ -612,6 +757,335 @@ export class VideoExporter {
}
}
+ /**
+ * v2 multi-asset segment loop. Walks the RenderPlan's ordered segments,
+ * decoding each from its OWN source asset into ONE renderer + encoder + muxer,
+ * advancing a single continuous virtual-time frame clock across segment
+ * boundaries so the joins are seamless. Fixes P1 (non-primary clips dropped).
+ *
+ * Renders per-segment video + webcam overlay + cursor, each drawn from its
+ * OWN asset (webcam source + cursor samples switch at every segment boundary).
+ * Per-segment audio concat (see audioConcatPlan) and virtual-time speed
+ * mapping are the remaining increments. The caller has already run
+ * cleanup()/reset.
+ */
+ private async runSegmentLoop(
+ encoderPreference: HardwareAcceleration,
+ plan: RenderPlan,
+ ): Promise<ExportResult> {
+ const warnings: string[] = [];
+ const onWarning = (message: string) => warnings.push(message);
+ const platform = await getPlatform();
+ const segments = plan.segments;
+ const firstSegment = segments[0];
+
+ // One renderer for the whole export — output size is fixed; only the
+ // source-dependent fields change per segment via renderer.setSource().
+ const renderer = new FrameRenderer({
+ width: this.config.width,
+ height: this.config.height,
+ wallpaper: plan.appearance.wallpaper,
+ zoomRegions: plan.zoomRegions,
+ annotationRegions: plan.annotationRegions,
+ speedRegions: plan.speedRegions,
+ showShadow: plan.appearance.shadowIntensity > 0,
+ shadowIntensity: plan.appearance.shadowIntensity,
+ showBlur: plan.appearance.showBlur,
+ motionBlurAmount: plan.appearance.motionBlurAmount,
+ borderRadius: plan.appearance.borderRadius,
+ padding: plan.appearance.padding,
+ cropRegion: firstSegment.cropRegion,
+ videoWidth: firstSegment.sourceWidth,
+ videoHeight: firstSegment.sourceHeight,
+ // Source-dependent fields (webcamSize, cursor samples/scale) are set per
+ // segment via setSource; webcam layout + cursor style are global.
+ webcamSize: null,
+ webcamLayoutPreset: plan.webcam.layoutPreset,
+ webcamMaskShape: plan.webcam.maskShape,
+ webcamMirrored: plan.webcam.mirrored,
+ webcamReactiveZoom: plan.webcam.reactiveZoom,
+ webcamSizePreset: plan.webcam.sizePreset,
+ webcamPosition: plan.webcam.position,
+ cursorScale: plan.cursor?.scale ?? 0,
+ cursorSmoothing: plan.cursor?.smoothing,
+ cursorMotionBlur: plan.cursor?.motionBlur,
+ cursorClickBounce: plan.cursor?.clickBounce,
+ cursorClipToBounds: plan.cursor?.clipToBounds,
+ cursorTheme: plan.cursor?.theme,
+ platform,
+ });
+ this.renderer = renderer;
+ await renderer.initialize();
+
+ await this.initializeEncoder(encoderPreference);
+
+ // Audio pre-pass: decode each segment's audio to the common export layout
+ // up-front, so we know whether to declare an audio track on the muxer (mp4
+ // needs that at construction). The concatenation TIMING is applied later,
+ // once the video loop has produced each segment's real frame count.
+ const segmentAudioPcm: (Float32Array[] | null)[] = [];
+ let anySegmentAudio = false;
+ for (const segment of segments) {
+ if (this.cancelled) break;
+ const pcm = await decodeSegmentAudioPcm(
+ segment,
+ AUDIO_OUTPUT_SAMPLE_RATE,
+ AUDIO_OUTPUT_CHANNELS,
+ );
+ if (pcm && pcm.length > 0 && (pcm[0]?.length ?? 0) > 0) anySegmentAudio = true;
+ segmentAudioPcm.push(pcm);
+ }
+ const audioExportCodec = anySegmentAudio
+ ? await AudioProcessor.selectSupportedExportCodec(
+ AUDIO_OUTPUT_SAMPLE_RATE,
+ AUDIO_OUTPUT_CHANNELS,
+ )
+ : null;
+ const hasAudio = Boolean(audioExportCodec);
+
+ const muxer = new VideoMuxer(this.config, hasAudio, audioExportCodec?.muxerCodec);
+ this.muxer = muxer;
+ await muxer.initialize();
+
+ const frameDuration = 1_000_000 / this.config.frameRate;
+ const maxEncodeQueue =
+ encoderPreference === "prefer-software"
+ ? Math.min(this.MAX_ENCODE_QUEUE, 32)
+ : this.MAX_ENCODE_QUEUE;
+
+ // Progress estimate from the plan (no decoder metadata needed): kept
+ // virtual duration of every segment × fps.
+ const estTotalFrames = Math.max(
+ 1,
+ Math.round(
+ segments.reduce((acc, s) => {
+ const intra = s.intraTrims.reduce((a, iv) => a + (iv.endSec - iv.startSec), 0);
+ const kept = Math.max(0, s.sourceEndSec - s.sourceStartSec - intra);
+ return acc + kept * this.config.frameRate;
+ }, 0),
+ ),
+ );
+
+ let frameIndex = 0;
+ // Real per-segment video frame count — audio is sized from this so the
+ // concatenated audio stays locked to the (independently retimed) video.
+ const segmentFrameCounts: number[] = [];
+
+ for (const segment of segments) {
+ if (this.cancelled) break;
+ if (this.fatalEncoderError) throw this.fatalEncoderError;
+
+ const framesBeforeSegment = frameIndex;
+ const decoder = new StreamingVideoDecoder();
+ this.streamingDecoder = decoder;
+
+ // Per-segment webcam overlay (this asset's camera track), decoded
+ // concurrently and matched to each screen frame by source time —
+ // mirrors the legacy single-asset webcam path.
+ let webcamDecoder: StreamingVideoDecoder | null = null;
+ let webcamFrameQueue: TimestampedVideoFrameQueue | null = null;
+ let webcamDecodePromise: Promise<void> | null = null;
+ let stopWebcamDecode = false;
+
+ try {
+ const info = await decoder.loadMetadata(segment.videoUrl);
+ const segmentTrims = buildSegmentRenderTrims(segment, info.duration);
+
+ let webcamSize: { width: number; height: number } | null = null;
+ if (segment.camera) {
+ webcamDecoder = new StreamingVideoDecoder();
+ this.webcamDecoder = webcamDecoder;
+ const webcamInfo = await webcamDecoder.loadMetadata(segment.camera.videoUrl);
+ webcamSize = { width: webcamInfo.width, height: webcamInfo.height };
+ webcamFrameQueue = new TimestampedVideoFrameQueue();
+ const queue = webcamFrameQueue;
+ webcamDecodePromise = webcamDecoder
+ .decodeAll(
+ this.config.frameRate,
+ segmentTrims,
+ undefined,
+ async (webcamFrame, _exportTs, webcamSourceMs) => {
+ while (queue.length >= 12 && !this.cancelled && !stopWebcamDecode) {
+ await new Promise((resolve) => setTimeout(resolve, 2));
+ }
+ if (this.cancelled || stopWebcamDecode) {
+ webcamFrame.close();
+ return;
+ }
+ queue.enqueue(webcamFrame, webcamSourceMs);
+ },
+ onWarning,
+ )
+ .catch((error) => {
+ const err = error instanceof Error ? error : new Error(String(error));
+ this.fatalEncoderError ??= err;
+ queue.fail(err);
+ })
+ .finally(() => {
+ if (!this.cancelled) queue.close();
+ });
+ }
+
+ renderer.setSource({
+ videoWidth: segment.sourceWidth,
+ videoHeight: segment.sourceHeight,
+ webcamSize,
+ cursorRecordingData: segmentCursorRecording(plan, segment),
+ cursorScale: plan.cursor?.scale ?? 0,
+ });
+ renderer.setCropRegion(segment.cropRegion);
+
+ await decoder.decodeAll(
+ this.config.frameRate,
+ segmentTrims,
+ undefined,
+ async (videoFrame, _exportTs, sourceTimestampMs) => {
+ let webcamFrame: VideoFrame | null = null;
+ try {
+ if (this.cancelled) return;
+ if (this.fatalEncoderError) throw this.fatalEncoderError;
+
+ webcamFrame = webcamFrameQueue
+ ? await webcamFrameQueue.frameAt(sourceTimestampMs)
+ : null;
+ if (this.cancelled) return;
+
+ // Continuous virtual-time clock across segments → seamless joins.
+ const timestamp = frameIndex * frameDuration;
+ await renderer.renderFrame(videoFrame, timestamp, webcamFrame);
+
+ const canvas = renderer.getCanvas();
+ let exportFrame: VideoFrame;
+ if (platform === "linux") {
+ const canvasCtx = canvas.getContext("2d")!;
+ const imageData = canvasCtx.getImageData(0, 0, canvas.width, canvas.height);
+ exportFrame = new VideoFrame(imageData.data.buffer, {
+ format: "RGBA",
+ codedWidth: canvas.width,
+ codedHeight: canvas.height,
+ timestamp,
+ duration: frameDuration,
+ colorSpace: {
+ primaries: "bt709",
+ transfer: "iec61966-2-1",
+ matrix: "rgb",
+ fullRange: true,
+ },
+ });
+ } else {
+ exportFrame = new VideoFrame(canvas, { timestamp, duration: frameDuration });
+ }
+
+ try {
+ await waitForEncoderQueueSpace({
+ getQueueSize: () => this.encoder?.encodeQueueSize ?? 0,
+ maxEncodeQueue,
+ isCancelled: () => this.cancelled,
+ encoderPreference,
+ });
+ } catch (error) {
+ exportFrame.close();
+ throw error;
+ }
+
+ if (this.encoder && this.encoder.state === "configured") {
+ this.encodeQueue++;
+ this.encoder.encode(exportFrame, { keyFrame: frameIndex % 150 === 0 });
+ }
+
+ exportFrame.close();
+ frameIndex++;
+ this.reportProgress({
+ currentFrame: frameIndex,
+ totalFrames: estTotalFrames,
+ percentage: Math.min(100, (frameIndex / estTotalFrames) * 100),
+ estimatedTimeRemaining: 0,
+ });
+ } finally {
+ videoFrame.close();
+ webcamFrame?.close();
+ }
+ },
+ onWarning,
+ );
+ } finally {
+ stopWebcamDecode = true;
+ webcamFrameQueue?.destroy();
+ webcamDecoder?.cancel();
+ if (webcamDecodePromise) {
+ await webcamDecodePromise.catch(() => undefined);
+ }
+ if (this.webcamDecoder === webcamDecoder) this.webcamDecoder = null;
+ decoder.destroy();
+ if (this.streamingDecoder === decoder) this.streamingDecoder = null;
+ }
+ segmentFrameCounts.push(frameIndex - framesBeforeSegment);
+ }
+
+ if (this.cancelled) {
+ return { success: false, error: "Export cancelled" };
+ }
+ if (this.fatalEncoderError) {
+ throw this.fatalEncoderError;
+ }
+
+ if (this.encoder && this.encoder.state === "configured") {
+ await this.withTimeout(
+ this.encoder.flush(),
+ ENCODER_FLUSH_TIMEOUT_MS,
+ encoderPreference === "prefer-hardware"
+ ? "The hardware video encoder stopped responding while finalizing the export."
+ : "The video encoder stopped responding while finalizing the export.",
+ );
+ }
+ if (this.fatalEncoderError) {
+ throw this.fatalEncoderError;
+ }
+
+ await Promise.all(this.muxingPromises);
+ this.reportProgress({
+ currentFrame: estTotalFrames,
+ totalFrames: estTotalFrames,
+ percentage: 100,
+ estimatedTimeRemaining: 0,
+ phase: "finalizing",
+ });
+
+ // --- Audio: concatenate every segment's decoded PCM at the plan's offsets
+ // (sized from the REAL per-segment video frame counts so A/V stays locked),
+ // apply an equal-power fade at each join, then encode once and mux. ---
+ if (hasAudio && audioExportCodec && !this.cancelled) {
+ const audioPlan = buildAudioConcatPlan(
+ segments.map((s, i) => ({
+ clipId: s.clipId,
+ outputFrameCount: segmentFrameCounts[i] ?? 0,
+ hasAudio:
+ (segmentAudioPcm[i]?.length ?? 0) > 0 && (segmentAudioPcm[i]?.[0]?.length ?? 0) > 0,
+ })),
+ {
+ frameRate: this.config.frameRate,
+ sampleRate: AUDIO_OUTPUT_SAMPLE_RATE,
+ channels: AUDIO_OUTPUT_CHANNELS,
+ },
+ );
+ const assembled = assembleConcatenatedPcm(
+ segmentAudioPcm.map((pcm) => ({ pcm })),
+ audioPlan,
+ { boundaryFadeSamples: Math.round(AUDIO_OUTPUT_SAMPLE_RATE * AUDIO_BOUNDARY_FADE_SEC) },
+ );
+ this.audioProcessor = new AudioProcessor();
+ await this.audioProcessor.encodePcmToMuxer(
+ assembled,
+ AUDIO_OUTPUT_SAMPLE_RATE,
+ muxer,
+ audioExportCodec,
+ );
+ }
+
+ const blob = await muxer.finalize();
+ return { success: true, blob, warnings: warnings.length > 0 ? warnings : undefined };
+ }
+
private async initializeEncoder(hardwareAcceleration: HardwareAcceleration): Promise<void> {
this.encodeQueue = 0;
this.muxingPromises = [];