Skip to content

Open source CapCut alternative.

TypeScript

feat(cut): snap transcribed cues onto the speech in the mix [rebuild]

David Le54785449b1cf
diff --git a/site/src/cut/lib/cueAlign.test.ts b/site/src/cut/lib/cueAlign.test.ts
new file mode 100644
index 00000000..29f8f7a3
--- /dev/null
+++ b/site/src/cut/lib/cueAlign.test.ts
@@ -0,0 +1,141 @@
+import { describe, expect, test } from "bun:test";
+import { alignCues, speechSpans } from "./cueAlign";
+
+/**
+ * Cue alignment reads the audio it was transcribed from. These build that
+ * audio: noise bursts where speech happens, quiet everywhere else, and cues
+ * whose times are wrong in the ways transcribers get them wrong — a constant
+ * lag, and edges that miss by a fraction of a second.
+ */
+
+const RATE = 16000;
+
+/** A mix of `duration` seconds carrying a noise burst over each span. */
+function mix(duration: number, spans: [number, number][]): Float32Array {
+ const samples = new Float32Array(Math.round(duration * RATE));
+ // A quiet, steady room tone under everything — the floor the envelope reads.
+ let seed = 1;
+ const rnd = () => {
+ seed = (seed * 1103515245 + 12345) % 2147483648;
+ return seed / 2147483648 - 0.5;
+ };
+ for (let i = 0; i < samples.length; i++) samples[i] = rnd() * 0.002;
+ for (const [from, to] of spans) {
+ const start = Math.round(from * RATE);
+ const stop = Math.min(samples.length, Math.round(to * RATE));
+ for (let i = start; i < stop; i++) samples[i] += rnd() * 0.6;
+ }
+ return samples;
+}
+
+const cue = (start: number, end: number, text = "hello there") => ({
+ id: `${start}`,
+ start,
+ end,
+ text,
+});
+
+describe("speechSpans", () => {
+ test("finds the bursts and skips the quiet", () => {
+ const spans = speechSpans(mix(10, [[1, 2.5], [5, 7]]), RATE);
+ expect(spans?.length).toBe(2);
+ expect(spans![0].start).toBeCloseTo(1, 1);
+ expect(spans![0].end).toBeCloseTo(2.5, 1);
+ expect(spans![1].start).toBeCloseTo(5, 1);
+ });
+
+ test("has nothing to say about silence or a flat wall of sound", () => {
+ expect(speechSpans(new Float32Array(RATE * 5), RATE)).toBe(null);
+ expect(speechSpans(mix(6, [[0, 6]]), RATE)).toBe(null);
+ });
+});
+
+describe("alignCues", () => {
+ test("takes out a systematic lag", () => {
+ const audio = mix(12, [[1, 2.5], [4, 5.5], [8, 9.5]]);
+ // Every cue reported a quarter second late — the shape is right, the
+ // placement is not.
+ const late = [cue(1.25, 2.75), cue(4.25, 5.75), cue(8.25, 9.75)];
+ const fixed = alignCues(late, audio, RATE);
+ expect(fixed[0].start).toBeCloseTo(1, 1);
+ expect(fixed[1].start).toBeCloseTo(4, 1);
+ expect(fixed[2].end).toBeCloseTo(9.5, 1);
+ });
+
+ test("takes out a lag wider than any single edge may travel", () => {
+ const audio = mix(14, [[1, 2.5], [4, 5.5], [8, 9.5], [11, 12.5]]);
+ // 0.6s early, further than the per-edge snap window: only the global pass
+ // can find this.
+ const early = [cue(0.4, 1.9), cue(3.4, 4.9), cue(7.4, 8.9), cue(10.4, 11.9)];
+ const fixed = alignCues(early, audio, RATE);
+ expect(fixed[0].start).toBeCloseTo(1, 1);
+ expect(fixed[3].start).toBeCloseTo(11, 1);
+ });
+
+ test("leaves cues that already sit on the speech", () => {
+ const audio = mix(12, [[1, 2.5], [4, 5.5], [8, 9.5]]);
+ const good = [cue(1, 2.5), cue(4, 5.5), cue(8, 9.5)];
+ for (const [i, c] of alignCues(good, audio, RATE).entries()) {
+ expect(c.start).toBeCloseTo(good[i].start, 1);
+ expect(c.end).toBeCloseTo(good[i].end, 1);
+ }
+ });
+
+ test("snaps each edge that misses on its own", () => {
+ const audio = mix(12, [[1, 2.5], [4, 5.5], [8, 9.5]]);
+ const off = [cue(1.14, 2.4), cue(3.86, 5.6), cue(8.2, 9.4)];
+ const fixed = alignCues(off, audio, RATE);
+ expect(fixed[0].start).toBeCloseTo(1, 1);
+ expect(fixed[0].end).toBeCloseTo(2.5, 1);
+ expect(fixed[1].start).toBeCloseTo(4, 1);
+ expect(fixed[2].start).toBeCloseTo(8, 1);
+ });
+
+ test("carries word timings into the cue's new span", () => {
+ const audio = mix(6, [[1, 2.5]]);
+ const withWords = [
+ {
+ ...cue(1.25, 2.75),
+ words: [
+ { t0: 1.25, t1: 2.0, w: "hello" },
+ { t0: 2.0, t1: 2.75, w: "there" },
+ ],
+ },
+ ];
+ const [fixed] = alignCues(withWords, audio, RATE);
+ // The cue slid back onto the burst, and its words slid with it.
+ expect(fixed.start).toBeCloseTo(1, 1);
+ expect(fixed.words![0].t0).toBeCloseTo(fixed.start, 2);
+ expect(fixed.words![1].t1).toBeCloseTo(fixed.end, 1);
+ expect(fixed.words![0].t1).toBeGreaterThan(fixed.words![0].t0);
+ for (const w of fixed.words!) {
+ expect(w.t0).toBeGreaterThanOrEqual(fixed.start);
+ expect(w.t1).toBeLessThanOrEqual(fixed.end);
+ }
+ });
+
+ test("keeps cues in order and never overlaps them", () => {
+ const audio = mix(12, [[1, 2.5], [2.7, 4], [8, 9.5]]);
+ const packed = [cue(1.2, 2.6), cue(2.6, 4.2), cue(8.3, 9.3)];
+ const fixed = alignCues(packed, audio, RATE);
+ for (let i = 1; i < fixed.length; i++) {
+ expect(fixed[i].start).toBeGreaterThanOrEqual(fixed[i - 1].end);
+ expect(fixed[i].end).toBeGreaterThan(fixed[i].start);
+ }
+ });
+
+ test("leaves the cues alone when the audio cannot answer", () => {
+ const cues = [cue(1, 2.5), cue(4, 5.5)];
+ expect(alignCues(cues, new Float32Array(RATE * 8), RATE)).toBe(cues);
+ // Speech nowhere near the transcript: the overlap gate refuses the read.
+ expect(alignCues(cues, mix(12, [[9, 11.5]]), RATE)).toBe(cues);
+ expect(alignCues([], mix(6, [[1, 2]]), RATE)).toEqual([]);
+ });
+
+ test("reads 16-bit samples the same way as floats", () => {
+ const floats = mix(12, [[1, 2.5], [4, 5.5], [8, 9.5]]);
+ const ints = Int16Array.from(floats, (v) => Math.round(v * 32767));
+ const late = [cue(1.25, 2.75), cue(4.25, 5.75), cue(8.25, 9.75)];
+ expect(alignCues(late, ints, RATE)).toEqual(alignCues(late, floats, RATE));
+ });
+});
diff --git a/site/src/cut/lib/cueAlign.ts b/site/src/cut/lib/cueAlign.ts
new file mode 100644
index 00000000..d989fa4d
--- /dev/null
+++ b/site/src/cut/lib/cueAlign.ts
@@ -0,0 +1,277 @@
+// Snap transcribed cues onto the speech they describe.
+//
+// Every transcriber mistimes a caption in its own way. The on-device model
+// hands the silence before a sentence to that sentence's first word, so a cue
+// opening an utterance can appear a full second before anyone speaks; the
+// hosted model reads times off the audio by ear and misses by a beat either
+// way. The mix they transcribed is right here, so the times get checked against
+// it: a 10 ms energy envelope marks where speech runs, and each cue edge moves
+// to the speech edge it belongs to. Pure arithmetic over the samples — the
+// engine runs it on the wav it just rendered, the browser on the mix it posted,
+// and neither needs a model or the network.
+//
+// Only what the audio can testify to moves. An edge counts as evidence when
+// real quiet sits on its far side, so a cue boundary in the middle of a
+// sentence — where nothing audible says one caption ends and the next begins —
+// keeps the time the transcriber gave it, and a mix that never goes quiet (a
+// wall of music) supplies no edges at all. A start may travel a long way
+// forward to meet the voice it captions and only a little way back, because
+// silence proves nobody was speaking yet and proves nothing about a word that
+// came earlier.
+
+/** Word timings as the transcriber and the editor both carry them. */
+export interface AlignWord {
+ t0: number;
+ t1: number;
+ w: string;
+}
+
+/** The part of a cue this cares about; cue ids, text, and lanes ride through. */
+export interface AlignCue {
+ start: number;
+ end: number;
+ words?: AlignWord[];
+}
+
+/** Envelope frame length, seconds — the resolution every time here lands on. */
+const HOP = 0.01;
+/** How far an edge may travel backward (and a cue end either way) to meet a
+ * speech edge. */
+const SNAP = 0.35;
+/** How far a cue start may travel forward to meet the voice it captions — the
+ * silence a transcriber hands to a sentence's first word runs this long. */
+const LEAD = 1.5;
+/** A run of speech shorter than this is a click; a gap shorter than this sits
+ * inside a word rather than between two of them. */
+const MIN_RUN = 0.06;
+const BRIDGE = 0.12;
+/** An edge is evidence when this much quiet sits on its far side, within this
+ * many dB of the mix's own floor. A drum hit under a music bed says nothing
+ * about where a sentence starts, and this is what keeps it from being read
+ * that way. */
+const QUIET_RUN = 0.15;
+const QUIET_MARGIN = 6;
+/** A cue never collapses below this while being snapped. */
+const MIN_CUE = 0.2;
+/** Speech and cues must overlap at least this well before any of this is
+ * trusted — below it the envelope is describing something other than the
+ * transcript (music, noise, a bad read) and the cues are left alone. */
+const MIN_IOU = 0.35;
+
+const round = (n: number) => Math.round(n * 1000) / 1000;
+
+/** A stretch of audio carrying speech. `cleanStart`/`cleanEnd` mark the edges
+ * that quiet sits against — the ones a cue boundary may be snapped to. */
+export interface SpeechSpan {
+ start: number;
+ end: number;
+ cleanStart: boolean;
+ cleanEnd: boolean;
+}
+
+/** The stretches of the audio that carry speech, in seconds. Frames whose
+ * energy rises well above the mix's own noise floor open a run and quiet ones
+ * close it (two thresholds, so a wavering syllable can't chatter the run open
+ * and shut). Null when the audio has nothing to say about where speech is:
+ * digital silence, or a level so flat that every frame looks alike. */
+export function speechSpans(samples: ArrayLike<number>, rate: number): SpeechSpan[] | null {
+ const hop = Math.max(1, Math.round(rate * HOP));
+ const frames = Math.floor(samples.length / hop);
+ if (frames < 4) return null;
+
+ // Frame energy after pre-emphasis: speech lives above the low rumble a music
+ // bed or room tone carries, and differencing the samples leans the envelope
+ // that way. Levels stay relative to the loudest frame, so this reads the same
+ // whether the caller hands over floats or 16-bit integers.
+ const db = new Float32Array(frames);
+ let peakRms = 0;
+ let prev = 0;
+ let i = 0;
+ for (let f = 0; f < frames; f++) {
+ let sum = 0;
+ const stop = (f + 1) * hop;
+ for (; i < stop; i++) {
+ const x = samples[i];
+ const v = x - 0.97 * prev;
+ prev = x;
+ sum += v * v;
+ }
+ const rms = Math.sqrt(sum / hop);
+ db[f] = rms;
+ if (rms > peakRms) peakRms = rms;
+ }
+ if (peakRms <= 0) return null;
+ for (let f = 0; f < frames; f++) db[f] = 20 * Math.log10(db[f] / peakRms + 1e-6);
+
+ const sorted = Float32Array.from(db).sort();
+ const at = (q: number) => sorted[Math.min(frames - 1, Math.floor(q * frames))];
+ const floor = at(0.1);
+ const loud = at(0.9);
+ if (loud - floor < 12) return null; // no dynamics to read edges from
+
+ const enter = floor + (loud - floor) * 0.45;
+ const exit = floor + (loud - floor) * 0.25;
+ const runs: { from: number; to: number }[] = [];
+ let open = -1;
+ for (let f = 0; f < frames; f++) {
+ if (open < 0) {
+ if (db[f] >= enter) open = f;
+ } else if (db[f] < exit) {
+ runs.push({ from: open, to: f });
+ open = -1;
+ }
+ }
+ if (open >= 0) runs.push({ from: open, to: frames });
+
+ const merged: { from: number; to: number }[] = [];
+ for (const run of runs) {
+ const last = merged[merged.length - 1];
+ if (last && (run.from - last.to) * HOP <= BRIDGE) last.to = run.to;
+ else merged.push({ ...run });
+ }
+ const kept = merged.filter((r) => (r.to - r.from) * HOP >= MIN_RUN);
+ if (kept.length === 0) return null;
+ // Speech everywhere means no edges worth snapping to — a bed of music under
+ // the whole cut reads this way.
+ const covered = kept.reduce((n, r) => n + (r.to - r.from) * HOP, 0);
+ if (covered > 0.95 * frames * HOP) return null;
+
+ // Quiet is what makes an edge readable. A run of frames near the floor
+ // before a span means its first word really does start there; audio that
+ // merely dips (a bed under the whole cut) leaves the edge unusable.
+ const quietBefore = floor + QUIET_MARGIN;
+ const span = Math.round(QUIET_RUN / HOP);
+ const isQuiet = (from: number, to: number) => {
+ for (let f = Math.max(0, from); f < Math.min(frames, to); f++) {
+ if (db[f] > quietBefore) return false;
+ }
+ return true;
+ };
+ return kept.map((r) => ({
+ start: r.from * HOP,
+ end: r.to * HOP,
+ cleanStart: r.from === 0 || isQuiet(r.from - span, r.from),
+ cleanEnd: r.to === frames || isQuiet(r.to, r.to + span),
+ }));
+}
+
+/** A frame-level 0/1 mask of the spans, over `frames` frames. */
+function maskOf(spans: readonly { start: number; end: number }[], frames: number): Uint8Array {
+ const mask = new Uint8Array(frames);
+ for (const s of spans) {
+ const from = Math.max(0, Math.floor(s.start / HOP));
+ const to = Math.min(frames, Math.ceil(s.end / HOP));
+ for (let f = from; f < to; f++) mask[f] = 1;
+ }
+ return mask;
+}
+
+/** How well the transcript and the audible speech describe the same thing:
+ * intersection over union of the two masks. A low score means the envelope is
+ * about something other than these cues, and nothing should be moved on it. */
+function overlap(cues: Uint8Array, speech: Uint8Array): number {
+ let cueTotal = 0;
+ let speechTotal = 0;
+ let hit = 0;
+ for (let f = 0; f < cues.length; f++) {
+ cueTotal += cues[f];
+ speechTotal += speech[f];
+ if (cues[f] === 1 && speech[f] === 1) hit++;
+ }
+ if (cueTotal === 0 || speechTotal === 0) return 0;
+ return hit / (cueTotal + speechTotal - hit);
+}
+
+/** The value in `sorted` closest to `t` within [`t - back`, `t + ahead`], and
+ * inside [`floor`, `ceil`]. Null when the audio offers no edge there. */
+function nearest(
+ sorted: number[],
+ t: number,
+ back: number,
+ ahead: number,
+ floor: number,
+ ceil: number
+): number | null {
+ let best: number | null = null;
+ let bestGap = Infinity;
+ for (const v of sorted) {
+ if (v < t - back || v < floor) continue;
+ if (v > t + ahead) break;
+ if (v > ceil) break;
+ const gap = Math.abs(v - t);
+ if (gap < bestGap) {
+ bestGap = gap;
+ best = v;
+ }
+ }
+ return best;
+}
+
+/**
+ * Re-time cues against the audio they were transcribed from. Cues come back in
+ * the same order with their ids, text, and lanes intact, and word timings ride
+ * along with them. A cue the audio has nothing to say about arrives unchanged,
+ * as does every cue when the mix as a whole disagrees with the transcript.
+ *
+ * `snap` widens the backward search for a transcriber whose times are guesses
+ * (the hosted model) over one that reports real word ranges.
+ */
+export function alignCues<T extends AlignCue>(
+ cues: T[],
+ samples: ArrayLike<number>,
+ rate: number,
+ opts: { snap?: number } = {}
+): T[] {
+ if (cues.length === 0 || rate <= 0) return cues;
+ const spans = speechSpans(samples, rate);
+ if (!spans) return cues;
+
+ const frames = Math.max(1, Math.ceil(samples.length / rate / HOP));
+ const fit = overlap(
+ maskOf(cues.map((c) => ({ start: c.start, end: c.end })), frames),
+ maskOf(spans, frames)
+ );
+ if (fit < MIN_IOU) return cues; // the audio is describing something else
+
+ const back = opts.snap ?? SNAP;
+ const onsets = spans.filter((s) => s.cleanStart).map((s) => s.start);
+ const offsets = spans.filter((s) => s.cleanEnd).map((s) => s.end);
+ const roomFor = (cue: AlignCue) => Math.min(MIN_CUE, Math.max(0.05, cue.end - cue.start));
+
+ // Starts first: each looks for the voice its caption belongs to, reaching
+ // well ahead to cross the silence a transcriber hands to a sentence's first
+ // word, stopping short of the cue's own end so the caption keeps a life on
+ // screen, and never opening before the cue in front of it.
+ const starts: number[] = [];
+ for (const [i, cue] of cues.entries()) {
+ const floor = i > 0 ? starts[i - 1] : 0;
+ const ceil = cue.end - roomFor(cue);
+ starts.push(
+ Math.max(floor, nearest(onsets, cue.start, back, LEAD, floor, ceil) ?? cue.start)
+ );
+ }
+
+ // Ends then close inside the room the next cue's start leaves, which is what
+ // keeps captions on a track from ever overlapping.
+ return cues.map((cue, i) => {
+ const start = starts[i];
+ const ceil = i + 1 < cues.length ? starts[i + 1] : Infinity;
+ const minLen = Math.max(0.01, Math.min(roomFor(cue), ceil - start));
+ const end = Math.max(
+ start + minLen,
+ Math.min(ceil, nearest(offsets, cue.end, back, back, start, ceil) ?? cue.end)
+ );
+
+ // Word timings follow the edge that moved. A cue that slid whole carries
+ // its cadence along; one whose start met a later onset keeps every interior
+ // word where the transcriber put it and pulls in only the leading word —
+ // the one the silence was wrongly attached to.
+ const shift = start - cue.start;
+ const slid = Math.abs(end - start - (cue.end - cue.start)) <= 3 * HOP;
+ const words = cue.words?.map((w) => {
+ const at = (t: number) => round(Math.min(end, Math.max(start, slid ? t + shift : t)));
+ return { ...w, t0: at(w.t0), t1: at(w.t1) };
+ });
+ return { ...cue, start: round(start), end: round(end), ...(words ? { words } : {}) };
+ });
+}
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 6ddefa34..bfb535da 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -38,6 +38,7 @@ import {
writeCachedMediaLinks,
} from "./docCache";
import { renderMix, transcribeSamples, type CloudTranscribeSpec } from "./cloudTranscribe";
+import { alignCues } from "./cueAlign";
import { engineTranscribeSamples } from "./localStt";
import { trackLocale } from "./subtitles";
import { ANIM_STYLE_IDS, emptySubtitles, IMAGE_CLIP_SECONDS, LOOK_IDS, MAX_SUBTITLE_LANES, mediaUrl, migrateLegacyTransitions, normalizeAspect, SPEED_FLOOR, SPEED_MIN, TRANSITION_MAX } from "./types";
@@ -671,7 +672,10 @@ export async function runTranscription(projectId: string, spec: object): Promise
// The hosted route still works, so the user never sees the difference.
}
}
- return transcribeSamples(samples, s.locale, stale);
+ // The hosted model reads cue times off the audio by ear, so they land near
+ // the speech rather than on it; the mix is right here to settle it.
+ const cues = await transcribeSamples(samples, s.locale, stale);
+ return cues && alignCues(cues, samples, mix.sampleRate, { snap: 0.6 });
}
const res = await apiFetch(`/api/cut/projects/${projectId}/transcribe`, {
method: "POST",
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index 9963dfba..f9d2a274 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -487,7 +487,7 @@ export const AI_TOOLS: AiToolDef[] = [
{
name: "subtitles_generate",
description:
- "Transcribe the cut on-device (Apple speech) and create subtitle captions on a subtitle track (the active one unless `track` says otherwise; other tracks keep their captions) — it WRITES captions the user sees, so call it only when they asked for subtitles; to just hear what an audio asset says, listen_audio. Runs in the background; returns when finished. If no speech is found, no subtitles are added.",
+ "Transcribe the cut on-device (Apple speech) and create subtitle captions on a subtitle track (the active one unless `track` says otherwise; other tracks keep their captions) — it WRITES captions the user sees, so call it only when they asked for subtitles; to just hear what an audio asset says, listen_audio. Cue times come back snapped to the audio, so treat them as in sync — retime a cue only when the user points at one. Runs in the background; returns when finished. If no speech is found, no subtitles are added.",
inputSchema: obj({
locale: str("Speech language as BCP-47 like en-US (default: the track's language)"),
track: num("Subtitle track to write, 0-based (default: the active track)"),
diff --git a/site/src/cut/server/transcribe.ts b/site/src/cut/server/transcribe.ts
index 4cabd267..cc0f39bb 100644
--- a/site/src/cut/server/transcribe.ts
+++ b/site/src/cut/server/transcribe.ts
@@ -1,7 +1,8 @@
import { spawn } from "node:child_process";
-import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises";
+import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
+import { alignCues } from "../lib/cueAlign";
import { assertLocalRuntime } from "./local-only";
import { createJobRegistry } from "./jobRegistry";
import { mediaPath, readProject } from "./projects";
@@ -148,6 +149,56 @@ export function groupWords(words: Word[]): Cue[] {
return cues;
}
+/** Mono 16-bit samples out of a canonical PCM wav (what the mix render and the
+ * browser's uploads both are), for reading where the speech actually sits.
+ * Null for anything else — alignment is an improvement, so an unreadable file
+ * costs the caller nothing. */
+async function readWavMono(file: string): Promise<{ samples: Int16Array; rate: number } | null> {
+ const buf = await readFile(file);
+ if (buf.length < 44 || buf.toString("ascii", 0, 4) !== "RIFF") return null;
+ if (buf.toString("ascii", 8, 12) !== "WAVE") return null;
+ let pos = 12;
+ let rate = 0;
+ let channels = 0;
+ let bits = 0;
+ let data: Uint8Array | null = null;
+ while (pos + 8 <= buf.length) {
+ const id = buf.toString("ascii", pos, pos + 4);
+ const size = buf.readUInt32LE(pos + 4);
+ const body = pos + 8;
+ if (id === "fmt " && body + 16 <= buf.length) {
+ channels = buf.readUInt16LE(body + 2);
+ rate = buf.readUInt32LE(body + 4);
+ bits = buf.readUInt16LE(body + 14);
+ } else if (id === "data") {
+ data = buf.subarray(body, Math.min(buf.length, body + size));
+ break;
+ }
+ pos = body + size + (size % 2); // chunks are word-aligned
+ }
+ if (!data || bits !== 16 || channels < 1 || rate <= 0) return null;
+ // An odd byte offset can't back an Int16Array view; copying realigns it.
+ const bytes = data.byteOffset % 2 === 0 ? data : new Uint8Array(data);
+ const pcm = new Int16Array(bytes.buffer, bytes.byteOffset, Math.floor(bytes.length / 2));
+ if (channels === 1) return { samples: pcm, rate };
+ const mono = new Int16Array(Math.floor(pcm.length / channels));
+ for (let i = 0; i < mono.length; i++) {
+ let sum = 0;
+ for (let c = 0; c < channels; c++) sum += pcm[i * channels + c];
+ mono[i] = sum / channels;
+ }
+ return { samples: mono, rate };
+}
+
+/** The finished cues for a run: grouped from the model's words, then snapped
+ * onto the speech in the very wav it transcribed, so captions land on the
+ * audio instead of a few frames off it. */
+async function cuesFromRun(out: string, wav: string, duration: number): Promise<Cue[]> {
+ const cues = cuesFromStt(out, duration);
+ const pcm = await readWavMono(wav).catch(() => null);
+ return pcm ? alignCues(cues, pcm.samples, pcm.rate) : cues;
+}
+
/** Cues from one cut-stt run: drop what the model emits degenerate, clamp to
* the audio's own length, and group the words into caption-sized cues. */
function cuesFromStt(out: string, duration: number): Cue[] {
@@ -201,7 +252,7 @@ async function runAudioTranscribe(
const bin = await ensureStt();
job.stage = "transcribe";
const out = await run(bin, [wav, locale ?? "en-US"]);
- job.cues = cuesFromStt(out, duration && duration > 0 ? duration : Infinity);
+ job.cues = await cuesFromRun(out, wav, duration && duration > 0 ? duration : Infinity);
job.status = "done";
} finally {
void rm(tmpDir, { recursive: true, force: true });
@@ -385,7 +436,7 @@ async function runTranscribe(job: TranscribeJob, spec: TranscribeSpec) {
job.stage = "transcribe";
const out = await run(bin, [wav, spec.locale ?? "en-US"]);
- job.cues = cuesFromStt(out, spec.duration);
+ job.cues = await cuesFromRun(out, wav, spec.duration);
job.status = "done";
} finally {
void rm(tmpDir, { recursive: true, force: true });