Skip to content

Open source CapCut alternative.

TypeScript

refactor(site): share one audio mix, and hold pitch through a speed change

David Le9f4fb7978767
diff --git a/site/src/cut/lib/audioMix.test.ts b/site/src/cut/lib/audioMix.test.ts
new file mode 100644
index 00000000..6d18a0b3
--- /dev/null
+++ b/site/src/cut/lib/audioMix.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, test } from "bun:test";
+import { duckWindows, foldClips, type MixClip, type MixItem } from "./audioMix";
+
+const clip = (over: Partial<MixClip> = {}): MixClip => ({
+ file: "a.mp4",
+ in: 0,
+ out: 4,
+ muted: false,
+ ...over,
+});
+
+const item = (over: Partial<MixItem> = {}): MixItem => ({
+ file: "v.mp3",
+ in: 0,
+ out: 2,
+ start: 0,
+ volume: 1,
+ ...over,
+});
+
+describe("foldClips", () => {
+ test("lays clips end to end when nothing dissolves", () => {
+ const geo = foldClips([clip(), clip(), clip()]);
+ expect(geo.map((g) => g.at)).toEqual([0, 4, 8]);
+ expect(geo.every((g) => g.fadeIn === 0 && g.fadeOut === 0)).toBe(true);
+ });
+
+ test("pulls a clip back by the dissolve it inherits", () => {
+ const geo = foldClips([clip({ transition: 1 }), clip()]);
+ expect(geo[0].at).toBe(0);
+ // The second clip starts a second early so the two overlap.
+ expect(geo[1].at).toBe(3);
+ expect(geo[0].fadeOut).toBe(1);
+ expect(geo[1].fadeIn).toBe(1);
+ });
+
+ test("scales a dissolve down so it cannot swallow its clips", () => {
+ // A two-second overlap between one-second clips would run past both.
+ const geo = foldClips([clip({ out: 1, transition: 2 }), clip({ out: 1 })]);
+ expect(geo[0].fadeOut).toBeLessThanOrEqual(0.9);
+ expect(geo[1].at).toBeGreaterThan(0);
+ });
+
+ test("counts a speed change against the footprint, not the source span", () => {
+ expect(foldClips([clip({ out: 4, speed: 2 })])[0].dur).toBeCloseTo(2, 5);
+ });
+
+ test("keeps a gap spacer's exact length", () => {
+ const geo = foldClips([clip({ file: "", out: 2.5 }), clip()]);
+ expect(geo[0].dur).toBeCloseTo(2.5, 5);
+ expect(geo[1].at).toBeCloseTo(2.5, 5);
+ });
+
+ test("a spacer holds later clips at the time the picture puts them", () => {
+ // The fold is sequential, so a gap only stays a gap if it is in the list.
+ // Without the spacer the clip lands at 0 and the whole mix runs early.
+ const withGap = foldClips([clip({ file: "", out: 3 }), clip()]);
+ const without = foldClips([clip()]);
+ expect(withGap[1].at).toBeCloseTo(3, 5);
+ expect(without[0].at).toBe(0);
+ });
+});
+
+describe("duckWindows", () => {
+ test("has nothing to say when no item ducks", () => {
+ expect(duckWindows([item(), item({ duck: 1 })])).toEqual([]);
+ });
+
+ test("covers a ducking item's own footprint", () => {
+ expect(duckWindows([item({ start: 3, out: 2, duck: 0.2 })])).toEqual([
+ { start: 3, end: 5, gain: 0.2 },
+ ]);
+ });
+
+ test("merges overlapping ducks and takes the deepest", () => {
+ const windows = duckWindows([
+ item({ start: 0, out: 4, duck: 0.5 }),
+ item({ start: 3, out: 4, duck: 0.1 }),
+ ]);
+ expect(windows).toEqual([{ start: 0, end: 7, gain: 0.1 }]);
+ });
+
+ test("keeps separated ducks apart", () => {
+ const windows = duckWindows([
+ item({ start: 0, out: 1, duck: 0.3 }),
+ item({ start: 5, out: 1, duck: 0.4 }),
+ ]);
+ expect(windows).toHaveLength(2);
+ expect(windows[1].start).toBe(5);
+ });
+
+ test("measures a ducking item's window through its speed", () => {
+ expect(duckWindows([item({ start: 0, out: 4, speed: 2, duck: 0.5 })])[0].end).toBeCloseTo(2, 5);
+ });
+});
diff --git a/site/src/cut/lib/audioMix.ts b/site/src/cut/lib/audioMix.ts
new file mode 100644
index 00000000..069dd489
--- /dev/null
+++ b/site/src/cut/lib/audioMix.ts
@@ -0,0 +1,296 @@
+"use client";
+
+/**
+ * The cut's audible mix, rendered in the browser.
+ *
+ * One `OfflineAudioContext` fold that mirrors the engine's ffmpeg audio graph:
+ * track-0 clip audio folds sequentially with cross-dissolves overlapping,
+ * upper-track clips and soundtrack items land at their absolute starts with
+ * their own volumes and fades, a ducking voiceover pulls everything else down
+ * while it speaks, and the whole-project fade rides over the sum.
+ *
+ * Two callers want this and want it at different shapes. Transcription needs a
+ * 16 kHz mono buffer, because that is what a speech model reads; an export
+ * needs full-rate stereo, because that is what goes in the file. Same fold,
+ * different rate and channel count — which is why those are parameters and the
+ * fold is written once. A mix that drifted between them would put captions on
+ * words that the exported audio says at another time.
+ */
+
+import { decodeAudioSpan } from "./mediaRead";
+import { timeStretch } from "./timeStretch";
+
+/** One track-0 clip's audio in the sequential fold. A spacer (no file) only
+ * shapes time. */
+export interface MixClip {
+ file: string;
+ in: number;
+ out: number;
+ muted: boolean;
+ speed?: number;
+ /** Gain on the clip's own audio; absent = 1. */
+ volume?: number;
+ /** Cross-dissolve overlap into the next clip, timeline seconds. */
+ transition?: number;
+}
+
+/** A clip placed at an absolute time: an upper-track video's audio, a
+ * soundtrack bed, or a voiceover. */
+export interface MixItem {
+ file: string;
+ in: number;
+ out: number;
+ start: number;
+ volume: number;
+ speed?: number;
+ muted?: boolean;
+ fadeIn?: number;
+ fadeOut?: number;
+ /** While this item is audible, everything else drops to this gain. */
+ duck?: number;
+}
+
+export interface MixSpec {
+ duration: number;
+ clips: MixClip[];
+ /** Soundtrack, voiceovers, and upper-track clip audio. */
+ items: MixItem[];
+ /** Whole-project audio fades, seconds. */
+ fadeIn?: number;
+ fadeOut?: number;
+}
+
+export interface MixOptions {
+ sampleRate: number;
+ channels: number;
+ /** Resolves a spec file name to something the reader can open. */
+ resolve: (file: string) => string;
+}
+
+const speedOf = (s?: number) => (s && s > 0 ? s : 1);
+
+/** Timeline length of one clip: source span over speed. A gap spacer keeps its
+ * exact length — flooring it would land everything after it late. */
+const clipDur = (c: MixClip) =>
+ c.file ? Math.max(0.1, (c.out - c.in) / speedOf(c.speed)) : Math.max(0, c.out - c.in);
+
+/** Timeline footprint of a placed item. */
+const itemDur = (a: MixItem) => Math.max(0, (a.out - a.in) / speedOf(a.speed));
+
+/**
+ * Where the sequential fold puts each track-0 clip, and how long its
+ * cross-dissolve edges are. Each dissolve pulls the next clip back by the
+ * (clamped) overlap, exactly like the engine's acrossfade chain.
+ */
+export function foldClips(clips: MixClip[]) {
+ const geo = clips.map((clip) => ({ clip, at: 0, dur: clipDur(clip), fadeIn: 0, fadeOut: 0 }));
+ let acc = 0;
+ geo.forEach((g, j) => {
+ const overlap = j > 0 ? Math.min(clips[j - 1].transition ?? 0, acc * 0.9, g.dur * 0.9) : 0;
+ const fade = overlap > 0.01 ? overlap : 0;
+ g.at = j === 0 ? 0 : acc - fade;
+ g.fadeIn = fade;
+ if (j > 0) geo[j - 1].fadeOut = fade;
+ acc = g.at + g.dur;
+ });
+ return geo;
+}
+
+/**
+ * The windows during which a ducking item is audible, merged into a single
+ * envelope: each entry is a stretch of timeline where everything that is not
+ * itself ducking drops to `gain`.
+ *
+ * Overlapping voiceovers take the lowest gain of the ones speaking, which is
+ * what the preview does frame by frame — computed here once for the whole
+ * timeline instead, because a scheduled ramp cannot ask "what is live now?".
+ */
+export function duckWindows(items: MixItem[]): { start: number; end: number; gain: number }[] {
+ const edges = items
+ .filter((a) => a.duck !== undefined && a.duck < 1)
+ .map((a) => ({ start: a.start, end: a.start + itemDur(a), gain: Math.max(0, a.duck!) }))
+ .filter((w) => w.end > w.start)
+ .sort((a, b) => a.start - b.start);
+ const merged: { start: number; end: number; gain: number }[] = [];
+ for (const w of edges) {
+ const last = merged[merged.length - 1];
+ if (last && w.start <= last.end) {
+ last.end = Math.max(last.end, w.end);
+ last.gain = Math.min(last.gain, w.gain);
+ } else {
+ merged.push({ ...w });
+ }
+ }
+ return merged;
+}
+
+/** Schedule a duck envelope onto a gain node: 1 everywhere except inside the
+ * windows, where it steps down and back. The steps are ramps a few
+ * milliseconds long so the drop doesn't click. */
+const DUCK_RAMP = 0.08;
+
+function scheduleDuck(gain: GainNode, windows: { start: number; end: number; gain: number }[]) {
+ gain.gain.value = 1;
+ for (const w of windows) {
+ gain.gain.setValueAtTime(1, Math.max(0, w.start - DUCK_RAMP));
+ gain.gain.linearRampToValueAtTime(w.gain, w.start);
+ gain.gain.setValueAtTime(w.gain, Math.max(w.start, w.end - DUCK_RAMP));
+ gain.gain.linearRampToValueAtTime(1, w.end);
+ }
+}
+
+/**
+ * Render `spec` to a buffer, or null when nothing in it makes a sound.
+ *
+ * A clip that plays at a speed other than 1 is time-stretched to fit, so it
+ * keeps its pitch — the same thing ffmpeg's atempo does for the engine and the
+ * browser's `preservesPitch` does for the preview.
+ */
+export async function renderMix(spec: MixSpec, opts: MixOptions): Promise<AudioBuffer | null> {
+ const { sampleRate, channels, resolve } = opts;
+ const length = Math.max(1, Math.ceil(spec.duration * sampleRate));
+ const ctx = new OfflineAudioContext(channels, length, sampleRate);
+
+ // Only the spans that are actually heard are decoded, and only for entries
+ // that can be heard at all. Decoding whole sources instead would mean a
+ // ten-second trim of a ninety-minute recording pulling the entire recording
+ // into memory — around 1.4 GB an hour at 48 kHz stereo — and several of them
+ // at once.
+ const wanted = new Map<string, { file: string; from: number; to: number }>();
+ const spanKey = (c: { file: string; in: number; out: number }) =>
+ `${c.file}|${c.in.toFixed(3)}|${c.out.toFixed(3)}`;
+ for (const c of spec.clips) {
+ if (!c.file || c.muted) continue;
+ wanted.set(spanKey(c), { file: c.file, from: Math.max(0, c.in), to: c.out });
+ }
+ for (const a of spec.items) {
+ if (!a.file || a.muted) continue;
+ wanted.set(spanKey(a), { file: a.file, from: Math.max(0, a.in), to: a.out });
+ }
+
+ const buffers = new Map<string, AudioBuffer>();
+ await Promise.all(
+ [...wanted].map(async ([key, span]) => {
+ // A source with no audio track at all — a silent recording, a still —
+ // reads back null and mixes as silence, like the engine's hasStream
+ // check. A source that could not be *read* is a different thing and is
+ // allowed to fail the render: silently dropping it would hand the user a
+ // finished file with a clip, or a whole voiceover, missing its sound.
+ const buf = await decodeAudioSpan(resolve(span.file), span.from, span.to);
+ if (buf) buffers.set(key, buf);
+ })
+ );
+
+ if (buffers.size === 0) return null;
+
+ // Everything that can be ducked passes through one node; the voiceovers doing
+ // the ducking connect past it, so they never duck themselves.
+ const ducked = ctx.createGain();
+ scheduleDuck(ducked, duckWindows(spec.items));
+
+ // The project fade is the last thing on the way out, matching the export's
+ // fade on the final mix.
+ const master = ctx.createGain();
+ const fadeIn = Math.max(0, spec.fadeIn ?? 0);
+ const fadeOut = Math.max(0, spec.fadeOut ?? 0);
+ master.gain.value = 1;
+ if (fadeIn > 0) {
+ master.gain.setValueAtTime(0, 0);
+ master.gain.linearRampToValueAtTime(1, fadeIn);
+ }
+ if (fadeOut > 0 && spec.duration > fadeOut) {
+ master.gain.setValueAtTime(1, spec.duration - fadeOut);
+ master.gain.linearRampToValueAtTime(0, spec.duration);
+ }
+ ducked.connect(master);
+ master.connect(ctx.destination);
+
+ /**
+ * Fit a span to the time its clip occupies, keeping its pitch.
+ *
+ * `playbackRate` would do the fitting for free, and resample while it did it —
+ * a clip at 1.5× would come back seven semitones high, which neither the
+ * preview nor the engine's `atempo` does. So the buffer is stretched to the
+ * length it needs first, and then played at its own rate.
+ */
+ const stretched = new Map<string, AudioBuffer>();
+ const fitted = (key: string, buf: AudioBuffer, speed: number): AudioBuffer => {
+ if (speed === 1) return buf;
+ // A span used by more than one clip at the same speed is stretched once.
+ const memo = `${key}@${speed}`;
+ const hit = stretched.get(memo);
+ if (hit) return hit;
+ const channels = Array.from({ length: buf.numberOfChannels }, (_, c) =>
+ buf.getChannelData(c)
+ );
+ const fit = timeStretch(channels, buf.sampleRate, 1 / speed);
+ const out = new AudioBuffer({
+ length: Math.max(1, fit[0].length),
+ numberOfChannels: buf.numberOfChannels,
+ sampleRate: buf.sampleRate,
+ });
+ fit.forEach((data, c) => out.getChannelData(c).set(data));
+ stretched.set(memo, out);
+ return out;
+ };
+
+ // Each buffer holds exactly the span its entry plays, already fitted to the
+ // time that entry occupies, so it starts at its own zero and runs at 1.
+ const play = (
+ buf: AudioBuffer,
+ at: number,
+ duration: number,
+ into: AudioNode,
+ shape: (gain: GainNode) => void
+ ) => {
+ const src = ctx.createBufferSource();
+ src.buffer = buf;
+ const gain = ctx.createGain();
+ shape(gain);
+ src.connect(gain);
+ gain.connect(into);
+ src.start(Math.max(0, at), 0, Math.max(0, duration));
+ };
+
+ for (const g of foldClips(spec.clips)) {
+ const c = g.clip;
+ const buf = !c.muted && c.file ? buffers.get(spanKey(c)) : undefined;
+ if (!buf) continue; // muted, silent, or a gap spacer: only shapes time
+ play(fitted(spanKey(c), buf, speedOf(c.speed)), g.at, g.dur, ducked, (gain) => {
+ const level = Math.max(0, c.volume ?? 1);
+ gain.gain.value = level;
+ if (g.fadeIn > 0) {
+ gain.gain.setValueAtTime(0, g.at);
+ gain.gain.linearRampToValueAtTime(level, g.at + g.fadeIn);
+ }
+ if (g.fadeOut > 0) {
+ gain.gain.setValueAtTime(level, g.at + g.dur - g.fadeOut);
+ gain.gain.linearRampToValueAtTime(0, g.at + g.dur);
+ }
+ });
+ }
+
+ for (const a of spec.items) {
+ const buf = a.muted ? undefined : buffers.get(spanKey(a));
+ if (!buf) continue;
+ const dur = itemDur(a);
+ // A voiceover that ducks everything else is not itself ducked.
+ const into = a.duck !== undefined && a.duck < 1 ? master : ducked;
+ play(fitted(spanKey(a), buf, speedOf(a.speed)), a.start, dur, into, (gain) => {
+ const level = Math.max(0, a.volume);
+ gain.gain.value = level;
+ const fIn = Math.min(a.fadeIn ?? 0, dur);
+ const fOut = Math.min(a.fadeOut ?? 0, dur);
+ if (fIn > 0) {
+ gain.gain.setValueAtTime(0, a.start);
+ gain.gain.linearRampToValueAtTime(level, a.start + fIn);
+ }
+ if (fOut > 0) {
+ gain.gain.setValueAtTime(level, a.start + dur - fOut);
+ gain.gain.linearRampToValueAtTime(0, a.start + dur);
+ }
+ });
+ }
+
+ return ctx.startRendering();
+}
diff --git a/site/src/cut/lib/cloudTranscribe.ts b/site/src/cut/lib/cloudTranscribe.ts
index 810f3d19..30951370 100644
--- a/site/src/cut/lib/cloudTranscribe.ts
+++ b/site/src/cut/lib/cloudTranscribe.ts
@@ -10,6 +10,7 @@
// timeline time, and interpolates per-word timings. Mic dictation reuses the
// same chunk/post/stitch core on a MediaRecorder capture.
+import { renderMix as mixAudio } from "./audioMix";
import { apiFetch } from "./backend";
import { mediaUrl, type SubtitleCue } from "./types";
@@ -38,96 +39,25 @@ const SILENCE_PEAK = 1e-3;
const uid = () => crypto.randomUUID().slice(0, 8);
const round = (n: number) => Math.round(n * 1000) / 1000;
-const speedOf = (s?: number) => (s && s > 0 ? s : 1);
-/** Timeline length of one spec clip: source span over speed. A gap spacer
- * (no file) keeps its exact length — flooring it would land later cues late. */
-const clipDur = (c: CloudTranscribeSpec["clips"][number]) =>
- c.file ? Math.max(0.1, (c.out - c.in) / speedOf(c.speed)) : Math.max(0, c.out - c.in);
-
-/** Render the cut's audible mix to a 16 kHz mono buffer, mirroring the engine's
- * ffmpeg graph: clip audio folds sequentially with cross-dissolves overlapping
- * (linear crossfade ≈ acrossfade's tri curve), soundtrack/voiceover items land
- * at their absolute starts with their volumes, and speed rides playbackRate
- * (pitch shifts where atempo would preserve it — timing, which is what cue
- * placement needs, is identical). Returns null when nothing audible exists. */
-export async function renderMix(
+/** Render the cut's audible mix to a 16 kHz mono buffer — the wire format the
+ * speech models read. The fold itself is the shared one (audioMix.ts), so the
+ * audio a caption is timed against is the same audio an export writes, at a
+ * different rate. Returns null when nothing audible exists. */
+export function renderMix(
projectId: string,
spec: CloudTranscribeSpec
): Promise<AudioBuffer | null> {
- const ctx = new OfflineAudioContext(1, Math.max(1, Math.ceil(spec.duration * RATE)), RATE);
- const files = [...new Set([...spec.clips, ...spec.audio].map((c) => c.file).filter(Boolean))];
- const buffers = new Map<string, AudioBuffer>();
- await Promise.all(
- files.map(async (f) => {
- try {
- const res = await fetch(mediaUrl(projectId, f));
- if (!res.ok) return;
- buffers.set(f, await ctx.decodeAudioData(await res.arrayBuffer()));
- } catch {
- // No decodable audio stream (e.g. a silent video) — mixes as silence,
- // like the engine's hasStream check.
- }
- })
+ return mixAudio(
+ {
+ duration: spec.duration,
+ clips: spec.clips,
+ // Transcription hears the soundtrack the way the viewer will, minus the
+ // shaping it does not change the timing of.
+ items: spec.audio,
+ },
+ { sampleRate: RATE, channels: 1, resolve: (file) => mediaUrl(projectId, file) }
);
-
- const hasSpeechSource =
- spec.clips.some((c) => !c.muted && buffers.has(c.file)) ||
- spec.audio.some((a) => buffers.has(a.file));
- if (!hasSpeechSource) return null;
-
- // First pass: the timeline geometry of the sequential clip fold. Each
- // cross-dissolve pulls the next clip back by the (clamped) overlap, exactly
- // like the engine's acrossfade chain.
- const geo = spec.clips.map((c) => ({ clip: c, at: 0, dur: clipDur(c), fadeIn: 0, fadeOut: 0 }));
- let acc = 0;
- geo.forEach((g, j) => {
- const d =
- j > 0 ? Math.min(spec.clips[j - 1].transition ?? 0, acc * 0.9, g.dur * 0.9) : 0;
- const fade = d > 0.01 ? d : 0;
- g.at = j === 0 ? 0 : acc - fade;
- g.fadeIn = fade;
- if (j > 0) geo[j - 1].fadeOut = fade;
- acc = g.at + g.dur;
- });
-
- for (const g of geo) {
- const c = g.clip;
- const buf = !c.muted && c.file ? buffers.get(c.file) : undefined;
- if (!buf) continue; // muted / silent clips and gap spacers only shape time
- const src = ctx.createBufferSource();
- src.buffer = buf;
- src.playbackRate.value = speedOf(c.speed);
- const gain = ctx.createGain();
- if (g.fadeIn > 0) {
- gain.gain.setValueAtTime(0, g.at);
- gain.gain.linearRampToValueAtTime(1, g.at + g.fadeIn);
- }
- if (g.fadeOut > 0) {
- gain.gain.setValueAtTime(1, g.at + g.dur - g.fadeOut);
- gain.gain.linearRampToValueAtTime(0, g.at + g.dur);
- }
- src.connect(gain);
- gain.connect(ctx.destination);
- // start()'s offset/duration are source seconds; playbackRate stretches
- // them onto the timeline, matching the engine's atrim + atempo.
- src.start(g.at, Math.max(0, c.in), Math.max(0, c.out - c.in));
- }
-
- for (const a of spec.audio) {
- const buf = buffers.get(a.file);
- if (!buf) continue;
- const src = ctx.createBufferSource();
- src.buffer = buf;
- src.playbackRate.value = speedOf(a.speed);
- const gain = ctx.createGain();
- gain.gain.value = a.volume;
- src.connect(gain);
- gain.connect(ctx.destination);
- src.start(Math.max(0, a.start), Math.max(0, a.in), Math.max(0, a.out - a.in));
- }
-
- return ctx.startRendering();
}
/** 16-bit PCM WAV (RIFF) from mono 16 kHz float samples. */
diff --git a/site/src/cut/lib/timeStretch.test.ts b/site/src/cut/lib/timeStretch.test.ts
new file mode 100644
index 00000000..0d8fbc29
--- /dev/null
+++ b/site/src/cut/lib/timeStretch.test.ts
@@ -0,0 +1,107 @@
+import { describe, expect, test } from "bun:test";
+import { timeStretch } from "./timeStretch";
+
+const RATE = 16000;
+
+/** A pure tone, so pitch is something a test can measure. */
+function sine(hz: number, seconds: number, rate = RATE): Float32Array {
+ const data = new Float32Array(Math.round(seconds * rate));
+ for (let i = 0; i < data.length; i++) data[i] = Math.sin((2 * Math.PI * hz * i) / rate);
+ return data;
+}
+
+/**
+ * Dominant frequency by zero crossings, measured over the interior only — the
+ * first and last half-frame are windowed down, and counting crossings through
+ * near-silence would report noise rather than the tone.
+ */
+function pitchOf(data: Float32Array, rate = RATE): number {
+ const from = Math.floor(data.length * 0.25);
+ const to = Math.floor(data.length * 0.75);
+ let crossings = 0;
+ for (let i = from + 1; i < to; i++) {
+ if (data[i - 1] <= 0 && data[i] > 0) crossings++;
+ }
+ return crossings / ((to - from) / rate);
+}
+
+describe("timeStretch", () => {
+ test("measures its own fixture correctly", () => {
+ expect(pitchOf(sine(440, 1))).toBeCloseTo(440, -1);
+ });
+
+ test("halves the length of a clip played at double speed", () => {
+ const [out] = timeStretch([sine(440, 1)], RATE, 0.5);
+ expect(out.length).toBe(RATE / 2);
+ });
+
+ test("doubles the length of a clip played at half speed", () => {
+ const [out] = timeStretch([sine(440, 1)], RATE, 2);
+ expect(out.length).toBe(RATE * 2);
+ });
+
+ test("keeps the pitch when it compresses", () => {
+ const [out] = timeStretch([sine(440, 1)], RATE, 0.5);
+ // Resampling instead would put this an octave up, at 880.
+ expect(pitchOf(out)).toBeCloseTo(440, -1);
+ });
+
+ test("keeps the pitch when it expands", () => {
+ const [out] = timeStretch([sine(440, 1)], RATE, 2);
+ // Resampling instead would put this an octave down, at 220.
+ expect(pitchOf(out)).toBeCloseTo(440, -1);
+ });
+
+ test("keeps the pitch at the speeds an editor actually uses", () => {
+ for (const speed of [1.25, 1.5, 2, 0.5, 0.75]) {
+ const [out] = timeStretch([sine(300, 1.5)], RATE, 1 / speed);
+ expect(pitchOf(out)).toBeCloseTo(300, -1);
+ expect(out.length).toBe(Math.round((1.5 * RATE) / speed));
+ }
+ });
+
+ test("passes audio through untouched at speed 1", () => {
+ const input = sine(440, 0.5);
+ const [out] = timeStretch([input], RATE, 1);
+ expect(out.length).toBe(input.length);
+ expect(Array.from(out.slice(0, 64))).toEqual(Array.from(input.slice(0, 64)));
+ });
+
+ test("cuts every channel at the same points, so stereo stays put", () => {
+ // Identical channels must come back identical: choosing offsets per channel
+ // would slide them against each other and smear the image.
+ const left = sine(440, 1);
+ const right = sine(440, 1);
+ const [outL, outR] = timeStretch([left, right], RATE, 0.5);
+ expect(Array.from(outL)).toEqual(Array.from(outR));
+ });
+
+ test("keeps silence silent", () => {
+ const [out] = timeStretch([new Float32Array(RATE)], RATE, 0.5);
+ expect(out.every((v) => v === 0)).toBe(true);
+ });
+
+ test("holds its amplitude rather than fading through the middle", () => {
+ const [out] = timeStretch([sine(440, 1)], RATE, 0.5);
+ const interior = out.subarray(Math.floor(out.length * 0.25), Math.floor(out.length * 0.75));
+ let peak = 0;
+ for (const v of interior) peak = Math.max(peak, Math.abs(v));
+ expect(peak).toBeGreaterThan(0.9);
+ });
+
+ test("survives audio too short to frame", () => {
+ const tiny = sine(440, 0.005);
+ const [out] = timeStretch([tiny], RATE, 0.5);
+ expect(out.length).toBe(Math.round(tiny.length * 0.5));
+ });
+
+ test("returns the input unchanged for a nonsense factor", () => {
+ const input = sine(440, 0.1);
+ expect(timeStretch([input], RATE, 0)[0].length).toBe(input.length);
+ expect(timeStretch([input], RATE, NaN)[0].length).toBe(input.length);
+ });
+
+ test("has nothing to do with no channels", () => {
+ expect(timeStretch([], RATE, 0.5)).toEqual([]);
+ });
+});
diff --git a/site/src/cut/lib/timeStretch.ts b/site/src/cut/lib/timeStretch.ts
new file mode 100644
index 00000000..ecb2449a
--- /dev/null
+++ b/site/src/cut/lib/timeStretch.ts
@@ -0,0 +1,134 @@
+/**
+ * Changing how long audio lasts without changing how it sounds.
+ *
+ * Playing a buffer faster is the obvious way to speed a clip up, and it is the
+ * wrong one: resampling moves every frequency with the rate, so a voice at 1.5×
+ * comes back about seven semitones high. Both of Cut's other renderers avoid
+ * that — ffmpeg through `atempo`, and the preview through the browser's own
+ * `preservesPitch` — so an export that resampled would be the only place the
+ * cut sounds different.
+ *
+ * This is WSOLA: overlap-add, where each frame is taken from wherever nearby it
+ * best continues the waveform already written. Cutting and re-laying the signal
+ * at those points changes its length while leaving its periods — and so its
+ * pitch — alone. It is the same family of algorithm `atempo` uses.
+ */
+
+/** Analysis/synthesis frame, in seconds. Long enough to hold a pitch period of
+ * a low voice, short enough that a transient is not smeared across it. */
+const FRAME_SECONDS = 0.03;
+/** How far on either side of the ideal position a frame may be taken from. */
+const SEARCH_SECONDS = 0.008;
+/** How much of the frame the similarity match compares. */
+const MATCH_SECONDS = 0.01;
+/** The match samples every Nth value. Alignment only needs the shape of the
+ * waveform, not every sample of it, and the search runs for every output frame
+ * — so this is most of what keeps stretching a long clip from costing more than
+ * the encode it feeds. */
+const MATCH_STRIDE = 4;
+
+/** Periodic Hann. At 50% overlap successive windows sum to exactly 1, so the
+ * overlap-add needs no normalising pass. */
+function hann(length: number): Float32Array {
+ const w = new Float32Array(length);
+ for (let i = 0; i < length; i++) w[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / length);
+ return w;
+}
+
+/** Straight linear resample to `length` — the pitch-shifting behaviour, used
+ * only where there is too little audio for a frame-based stretch to mean
+ * anything. */
+function resampleLinear(input: Float32Array, length: number): Float32Array {
+ const out = new Float32Array(length);
+ if (input.length === 0 || length === 0) return out;
+ const ratio = (input.length - 1) / Math.max(1, length - 1);
+ for (let i = 0; i < length; i++) {
+ const at = i * ratio;
+ const j = Math.floor(at);
+ const frac = at - j;
+ const a = input[Math.min(j, input.length - 1)];
+ const b = input[Math.min(j + 1, input.length - 1)];
+ out[i] = a + (b - a) * frac;
+ }
+ return out;
+}
+
+/**
+ * Stretch `channels` so the result is `factor` times as long, at the same pitch.
+ *
+ * `factor` is the output length over the input length: 0.5 makes a clip play in
+ * half the time (a 2× speed-up), 2 makes it take twice as long. Every channel is
+ * cut at the same points — choosing them per channel would move the two sides of
+ * a stereo image independently and collapse it.
+ */
+export function timeStretch(
+ channels: Float32Array[],
+ sampleRate: number,
+ factor: number
+): Float32Array[] {
+ if (channels.length === 0) return [];
+ if (!(factor > 0) || !Number.isFinite(factor)) return channels.map((c) => c.slice());
+ if (factor === 1) return channels.map((c) => c.slice());
+
+ const inLength = channels[0].length;
+ const outLength = Math.max(1, Math.round(inLength * factor));
+ // An even frame keeps the synthesis hop exactly half of it, which is what
+ // makes the windows sum to one.
+ const frame = Math.max(4, Math.round(FRAME_SECONDS * sampleRate) & ~1);
+ if (inLength < frame * 2) {
+ return channels.map((c) => resampleLinear(c, outLength));
+ }
+
+ const hop = frame >> 1;
+ const analysisHop = Math.max(1, Math.round(hop / factor));
+ const search = Math.max(1, Math.round(SEARCH_SECONDS * sampleRate));
+ const match = Math.max(2, Math.min(hop, Math.round(MATCH_SECONDS * sampleRate)));
+ const window = hann(frame);
+
+ // Overlap-add runs a frame past the end and is trimmed back after.
+ const out = channels.map(() => new Float32Array(outLength + frame));
+ // The match runs against one channel so every channel is cut alike.
+ const guide = channels[0];
+
+ /** The samples that followed the frame just used — what the next frame should
+ * continue from if the waveform is to stay unbroken. */
+ let expected: Float32Array | null = null;
+ let analysis = 0;
+ let outPos = 0;
+
+ while (outPos < outLength && analysis + frame <= inLength) {
+ let offset = 0;
+ if (expected && expected.length >= MATCH_STRIDE) {
+ let bestScore = -Infinity;
+ const lo = Math.max(-search, -analysis);
+ const hi = Math.min(search, inLength - frame - analysis);
+ for (let d = lo; d <= hi; d++) {
+ const at = analysis + d;
+ let score = 0;
+ for (let i = 0; i < expected.length; i += MATCH_STRIDE) score += guide[at + i] * expected[i];
+ if (score > bestScore) {
+ bestScore = score;
+ offset = d;
+ }
+ }
+ }
+ const from = Math.min(Math.max(0, analysis + offset), inLength - frame);
+
+ for (let c = 0; c < channels.length; c++) {
+ const src = channels[c];
+ const dst = out[c];
+ for (let i = 0; i < frame; i++) dst[outPos + i] += src[from + i] * window[i];
+ }
+
+ const nextFrom = from + hop;
+ expected =
+ nextFrom + match <= inLength ? guide.subarray(nextFrom, nextFrom + match) : null;
+ outPos += hop;
+ analysis += analysisHop;
+ }
+
+ // The first and last half-frame are only covered by one window, so they fade
+ // in and out over about fifteen milliseconds. That is short enough to be
+ // inaudible and is what lets the interior need no normalising.
+ return out.map((o) => o.subarray(0, outLength));
+}