Skip to content

Open source CapCut alternative.

TypeScript

feat(site): on-device live mic dictation in the Cut engine [rebuild]

David Le576b1f1400c1
diff --git a/site/src/cut/server/http/mic.ts b/site/src/cut/server/http/mic.ts
new file mode 100644
index 00000000..7e0eca30
--- /dev/null
+++ b/site/src/cut/server/http/mic.ts
@@ -0,0 +1,37 @@
+import { cancelMic, feedMic, getMicJob, startMicJob, stopMic } from "../mic";
+
+const err = (message: string, status: number) => Response.json({ error: message }, { status });
+
+/** Live mic dictation: start a job, stream PCM to it, poll the transcript. */
+export const micApi = {
+ async start(req: Request) {
+ try {
+ const body = (await req.json().catch(() => ({}))) as { locale?: string };
+ const job = await startMicJob(typeof body.locale === "string" ? body.locale : "en-US");
+ return Response.json({ id: job.id });
+ } catch (e) {
+ return err(e instanceof Error ? e.message : "Could not start dictation.", 500);
+ }
+ },
+
+ async feed(req: Request, { id }: { id: string }) {
+ const pcm = Buffer.from(await req.arrayBuffer());
+ return feedMic(id, pcm) ? new Response(null, { status: 204 }) : err("Dictation is not running.", 409);
+ },
+
+ poll(_req: Request, { id }: { id: string }) {
+ const job = getMicJob(id);
+ if (!job) return err("Unknown dictation.", 404);
+ return Response.json({ status: job.status, text: job.text, error: job.error });
+ },
+
+ async stop(_req: Request, { id }: { id: string }) {
+ const text = await stopMic(id);
+ if (text === null) return err("Unknown dictation.", 404);
+ return Response.json({ text });
+ },
+
+ cancel(_req: Request, { id }: { id: string }) {
+ return cancelMic(id) ? new Response(null, { status: 204 }) : err("Unknown dictation.", 404);
+ },
+};
diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.ts
index dacd04c0..1d850d45 100644
--- a/site/src/cut/server/http/routes.ts
+++ b/site/src/cut/server/http/routes.ts
@@ -2,6 +2,7 @@ import { aiApi } from "./ai";
import { engineApi } from "./engine";
import { exportApi } from "./export";
import { libraryApi } from "./library";
+import { micApi } from "./mic";
import { projectsApi } from "./projects";
type TableHandler = (req: Request, params: Record<string, string>) => Response | Promise<Response>;
@@ -66,6 +67,12 @@ export const CUT_ROUTES: CutRoute[] = [
{ method: "DELETE", path: "/api/cut/export/:jobId", handler: (req, p) => exportApi.cancel(req, { jobId: p.jobId }) },
{ method: "GET", path: "/api/cut/export/:jobId/file", handler: (req, p) => exportApi.file(req, { jobId: p.jobId }) },
+ { method: "POST", path: "/api/cut/mic/start", handler: (req) => micApi.start(req) },
+ { method: "POST", path: "/api/cut/mic/:id/feed", handler: (req, p) => micApi.feed(req, { id: p.id }) },
+ { method: "GET", path: "/api/cut/mic/:id", handler: (req, p) => micApi.poll(req, { id: p.id }) },
+ { method: "POST", path: "/api/cut/mic/:id/stop", handler: (req, p) => micApi.stop(req, { id: p.id }) },
+ { method: "POST", path: "/api/cut/mic/:id/cancel", handler: (req, p) => micApi.cancel(req, { id: p.id }) },
+
{ method: "POST", path: "/api/cut/ai/chat", handler: (req) => aiApi.chat(req) },
{ method: "POST", path: "/api/cut/ai/captions", handler: (req) => aiApi.captions(req) },
{ method: "POST", path: "/api/cut/ai/visual-subtitles", handler: (req) => aiApi.visualSubtitles(req) },
diff --git a/site/src/cut/server/mic.ts b/site/src/cut/server/mic.ts
new file mode 100644
index 00000000..a48f796f
--- /dev/null
+++ b/site/src/cut/server/mic.ts
@@ -0,0 +1,128 @@
+import { spawn, type ChildProcess } from "node:child_process";
+import { assertLocalRuntime } from "./local-only";
+import { createJobRegistry } from "./jobRegistry";
+import { ensureStt } from "./transcribe";
+
+// Live mic dictation for the AI chat composer. The browser captures the mic
+// (it already holds that permission) and streams 16 kHz mono s16le PCM to the
+// engine; this spawns `cut-stt --live`, forwards the PCM to its stdin, and
+// exposes the evolving transcript. On-device only — nothing leaves the Mac.
+
+export interface MicJob {
+ id: string;
+ status: "running" | "done" | "error" | "canceled";
+ /** Latest transcript: the evolving partial while running, the final text once done. */
+ text: string;
+ error?: string;
+ proc: ChildProcess;
+ /** Resolves once the process has emitted its final text (or died). */
+ finished: Promise<void>;
+}
+
+const MAX_RUNNING = 1; // on-device transcription is heavy; one dictation at a time
+const { jobs, runningCount, retire } = createJobRegistry<MicJob>("__cutMicJobs");
+
+export function getMicJob(id: string): MicJob | undefined {
+ return jobs.get(id);
+}
+
+export async function startMicJob(locale: string): Promise<MicJob> {
+ assertLocalRuntime();
+ if (runningCount() >= MAX_RUNNING) {
+ throw new Error("A dictation is already running — finish it first.");
+ }
+ const bin = await ensureStt();
+ const id = crypto.randomUUID().slice(0, 12);
+ const proc = spawn(bin, ["--live", locale], { stdio: ["pipe", "pipe", "pipe"] });
+
+ let resolveFinished!: () => void;
+ const finished = new Promise<void>((r) => (resolveFinished = r));
+ const job: MicJob = { id, status: "running", text: "", proc, finished };
+ jobs.set(id, job);
+
+ // Parse the process's NDJSON stdout line by line.
+ let buf = "";
+ proc.stdout?.on("data", (d: Buffer) => {
+ buf += d.toString();
+ let nl: number;
+ while ((nl = buf.indexOf("\n")) >= 0) {
+ const line = buf.slice(0, nl).trim();
+ buf = buf.slice(nl + 1);
+ if (!line) continue;
+ try {
+ const ev = JSON.parse(line) as { type: string; text?: string };
+ if (ev.type === "partial") job.text = ev.text ?? job.text;
+ else if (ev.type === "final") {
+ job.text = ev.text ?? job.text;
+ if (job.status === "running") job.status = "done";
+ } else if (ev.type === "error") {
+ job.error = ev.text || "Transcription failed.";
+ if (job.status === "running") job.status = "error";
+ }
+ } catch {
+ // Ignore a malformed line rather than tearing down a live dictation.
+ }
+ }
+ });
+
+ let stderr = "";
+ proc.stderr?.on("data", (d: Buffer) => (stderr += d.toString()));
+ proc.on("error", (e) => {
+ if (job.status === "running") {
+ job.status = "error";
+ job.error = e.message;
+ }
+ resolveFinished();
+ retire(job);
+ });
+ proc.on("close", (code) => {
+ if (job.status === "running") {
+ // Closed without a final line — surface whatever the process complained about.
+ job.status = code === 0 ? "done" : "error";
+ if (job.status === "error") job.error = stderr.trim().split("\n").slice(-2).join("\n") || `cut-stt exited ${code}`;
+ }
+ resolveFinished();
+ retire(job);
+ });
+
+ return job;
+}
+
+/** Forward a chunk of PCM to the running process. Returns false for an unknown/ended job. */
+export function feedMic(id: string, pcm: Buffer): boolean {
+ const job = jobs.get(id);
+ if (!job || job.status !== "running" || !job.proc.stdin?.writable) return false;
+ job.proc.stdin.write(pcm);
+ return true;
+}
+
+/** Close the input so the model flushes its final text, then wait for it. */
+export async function stopMic(id: string): Promise<string | null> {
+ const job = jobs.get(id);
+ if (!job) return null;
+ if (job.status === "running") job.proc.stdin?.end();
+ await withTimeout(job.finished, 8000);
+ return job.text;
+}
+
+/** Discard a dictation in progress. */
+export function cancelMic(id: string): boolean {
+ const job = jobs.get(id);
+ if (!job) return false;
+ if (job.status === "running") {
+ job.status = "canceled";
+ job.proc.kill("SIGKILL");
+ }
+ return true;
+}
+
+function withTimeout(p: Promise<void>, ms: number): Promise<void> {
+ return new Promise((resolve) => {
+ const t = setTimeout(resolve, ms);
+ t.unref();
+ void p.finally(() => {
+ clearTimeout(t);
+ resolve();
+ });
+ });
+}
diff --git a/site/src/cut/server/native/cut-stt.swift b/site/src/cut/server/native/cut-stt.swift
index 886810ab..58217f1f 100644
--- a/site/src/cut/server/native/cut-stt.swift
+++ b/site/src/cut/server/native/cut-stt.swift
@@ -6,6 +6,15 @@
//
// usage: cut-stt <audio-file> [locale]
// stdout: {"locale":"en-US","words":[{"t0":0.12,"t1":0.48,"w":"Hello"}]}
+//
+// usage: cut-stt --live [locale]
+// Streams live dictation: reads raw 16 kHz mono signed-16-bit little-endian
+// PCM from stdin (the browser captures the mic and pipes it in — this process
+// never touches the microphone itself) and emits one NDJSON line per update:
+// {"type":"partial","text":"Hello the"} // evolving, may still change
+// {"type":"final","text":"Hello there."} // on stdin EOF
+// {"type":"error","text":"…"}
+// The stream ends when stdin closes; the model then flushes its final text.
import AVFoundation
import Foundation
@@ -27,12 +36,27 @@ func fail(_ message: String) -> Never {
exit(1)
}
+/// One NDJSON event to stdout. FileHandle writes are unbuffered, so each line
+/// reaches the parent (and the polling client) the instant it is produced.
+func emit(_ type: String, _ text: String) {
+ guard let data = try? JSONEncoder().encode(["type": type, "text": text]) else { return }
+ FileHandle.standardOutput.write(data)
+ FileHandle.standardOutput.write(Data("\n".utf8))
+}
+
@main
struct Main {
static func main() async {
- guard CommandLine.arguments.count >= 2 else { fail("usage: cut-stt <audio-file> [locale]") }
- let path = CommandLine.arguments[1]
- let localeId = CommandLine.arguments.count >= 3 ? CommandLine.arguments[2] : "en-US"
+ let args = CommandLine.arguments
+ if args.count >= 2 && args[1] == "--live" {
+ let localeId = args.count >= 3 ? args[2] : "en-US"
+ await runLive(locale: Locale(identifier: localeId))
+ return
+ }
+
+ guard args.count >= 2 else { fail("usage: cut-stt <audio-file> [locale]") }
+ let path = args[1]
+ let localeId = args.count >= 3 ? args[2] : "en-US"
let locale = Locale(identifier: localeId)
do {
@@ -81,3 +105,131 @@ struct Main {
}
}
}
+
+// MARK: - Live streaming (stdin PCM → partial transcripts)
+
+@MainActor
+func runLive(locale: Locale) async {
+ // The browser pipes raw mic audio in this exact format; keep in sync with the
+ // client's downsampler in lib/micTranscribe.ts.
+ let liveSampleRate = 16000.0
+ do {
+ let transcriber = SpeechTranscriber(
+ locale: locale,
+ transcriptionOptions: [],
+ // Volatile results give us the evolving partial as the user speaks;
+ // finalized results are the stable prefix that will not change again.
+ reportingOptions: [.volatileResults],
+ attributeOptions: []
+ )
+
+ // First run per locale downloads the on-device model; no-op afterwards.
+ if let request = try await AssetInventory.assetInstallationRequest(supporting: [transcriber]) {
+ try await request.downloadAndInstall()
+ }
+
+ let analyzer = SpeechAnalyzer(modules: [transcriber])
+ guard let analyzerFormat = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [transcriber])
+ else {
+ emit("error", "No compatible audio format for on-device transcription.")
+ exit(1)
+ }
+
+ let inputFormat = AVAudioFormat(
+ commonFormat: .pcmFormatInt16, sampleRate: liveSampleRate, channels: 1, interleaved: true
+ )!
+ let converter = AVAudioConverter(from: inputFormat, to: analyzerFormat)
+
+ let (inputSequence, inputBuilder) = AsyncStream<AnalyzerInput>.makeStream()
+
+ // Blocking stdin reader on its own queue: it must not stall the actor or the
+ // results loop. Odd trailing bytes carry over so we only ever emit whole
+ // 16-bit samples.
+ let readerDone = DispatchSemaphore(value: 0)
+ DispatchQueue.global(qos: .userInitiated).async {
+ let handle = FileHandle.standardInput
+ var carry = Data()
+ while true {
+ let data = handle.availableData
+ if data.isEmpty { break } // EOF: browser stopped and the engine closed stdin.
+ carry.append(data)
+ let usable = carry.count - (carry.count % 2)
+ guard usable > 0 else { continue }
+ let chunk = carry.subdata(in: 0..<usable)
+ carry.removeSubrange(0..<usable)
+ if let buffer = makeInt16Buffer(chunk, format: inputFormat),
+ let converted = convertBuffer(buffer, using: converter, to: analyzerFormat)
+ {
+ inputBuilder.yield(AnalyzerInput(buffer: converted))
+ }
+ }
+ inputBuilder.finish()
+ readerDone.signal()
+ }
+
+ try await analyzer.start(inputSequence: inputSequence)
+
+ // Consume results concurrently with feeding: the loop only ends once the
+ // analyzer is finalized (below), so it cannot be awaited inline first.
+ let results = Task {
+ var finalized = ""
+ for try await result in transcriber.results {
+ let piece = String(result.text.characters)
+ if result.isFinal {
+ finalized += piece
+ emit("partial", finalized)
+ } else {
+ emit("partial", finalized + piece)
+ }
+ }
+ return finalized
+ }
+
+ // Wait for stdin EOF (reader finished the input stream), flush the model,
+ // then let the results loop drain to its final value.
+ await withCheckedContinuation { cont in
+ DispatchQueue.global().async { readerDone.wait(); cont.resume() }
+ }
+ try await analyzer.finalizeAndFinishThroughEndOfInput()
+ let finalText = try await results.value
+ emit("final", finalText)
+ } catch {
+ emit("error", "\(error)")
+ exit(1)
+ }
+}
+
+/// Wrap raw signed-16-bit little-endian PCM bytes as an AVAudioPCMBuffer.
+func makeInt16Buffer(_ data: Data, format: AVAudioFormat) -> AVAudioPCMBuffer? {
+ let frames = AVAudioFrameCount(data.count / 2)
+ guard frames > 0, let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frames)
+ else { return nil }
+ buffer.frameLength = frames
+ data.withUnsafeBytes { raw in
+ guard let src = raw.baseAddress, let dst = buffer.int16ChannelData?[0] else { return }
+ memcpy(dst, src, Int(frames) * 2)
+ }
+ return buffer
+}
+
+/// Resample/convert a buffer into the analyzer's required format.
+func convertBuffer(
+ _ input: AVAudioPCMBuffer, using converter: AVAudioConverter?, to outFormat: AVAudioFormat
+) -> AVAudioPCMBuffer? {
+ guard let converter else { return nil }
+ let ratio = outFormat.sampleRate / input.format.sampleRate
+ let capacity = AVAudioFrameCount(Double(input.frameLength) * ratio) + 1024
+ guard let output = AVAudioPCMBuffer(pcmFormat: outFormat, frameCapacity: capacity) else { return nil }
+ var supplied = false
+ var error: NSError?
+ converter.convert(to: output, error: &error) { _, status in
+ if supplied {
+ status.pointee = .noDataNow
+ return nil
+ }
+ supplied = true
+ status.pointee = .haveData
+ return input
+ }
+ return error == nil ? output : nil
+}
diff --git a/site/src/cut/server/transcribe.ts b/site/src/cut/server/transcribe.ts
index 7bdedad1..dba8567c 100644
--- a/site/src/cut/server/transcribe.ts
+++ b/site/src/cut/server/transcribe.ts
@@ -86,7 +86,7 @@ function run(cmd: string, args: string[], notFound?: string, timeoutMs = 600_000
* machine exercises the exact prod lookup; the plain dev server compiles the
* source on first use into ~/.cache/cut. Nothing ever leaves the machine.
*/
-async function ensureStt(): Promise<string> {
+export async function ensureStt(): Promise<string> {
const prebuilt = await findOnPath("cut-stt");
if (prebuilt) return prebuilt;
if (process.env.DONKEY_CUT_ENGINE) {