DubMochi

Low-Latency Live Stream Captions Architecture: Browser Silero VAD, Cloudflare Workers, and Soniox

An engineering deep dive into DubMochi's real-time streaming architecture: browser-side Silero VAD v5, Cloudflare Workers WebSocketPair proxying, Soniox stt-rt-v5 tuning, and 150 ms coalesced Convex writes to OBS.

SymphonyIceAttack

A mochi mascot at a studio desk views a streaming architecture diagram flowing from Silero VAD through Cloudflare Workers, Soniox, and Convex into a bilingual OBS Overlay.
On this page

End-to-end streaming architecture overview

Live streaming exposes every millisecond of caption lag. When a streamer lands a joke or reacts to an in-game play, international viewers reading translated subtitles need context while chat is still reacting—not seconds later. (For the motivation behind this constraint, see Why We Built DubMochi.)

To keep latency low without installing local GPU plugins or exposing speech API keys to the browser, DubMochi splits the real-time pipeline across four clear boundaries:

  1. Browser audio capture & local VAD: The Live captions workspace captures 16 kHz mono microphone audio via AudioWorklet, evaluates each 512-sample (32 ms) frame locally with Silero VAD v5 (silero_vad_v5.onnx on ONNX Runtime Web WASM), and gates silence through SpeechAudioGate before packing 64 ms pcm_s16le frames.
  2. Cloudflare Workers edge proxy: A Worker verifies a short-lived Convex ticket from Sec-WebSocket-Protocol, upgrades an upstream WebSocket to Soniox with the server-side SONIOX_API_KEY, and bridges traffic using WebSocketPair.
  3. Single-socket transcription and translation: Soniox stt-rt-v5 handles speech recognition, language identification, custom glossary hints, and one-way translation over one persistent WebSocket connection.
  4. Coalesced Convex sync to OBS: SonioxTranscript and SpeechCaptionWrites track concurrent in-flight utterances and coalesce provisional updates to Convex at 150 ms (while flushing key transitions immediately), pushing reactive queries straight to the /overlay OBS Browser Source.

For a user-facing overview of this flow, see How DubMochi Works. Below is how each layer is implemented and tuned to keep live captions responsive.

Client audio capture: 16 kHz mono frames and 64 ms PCM buffering

In the browser workspace, microphone audio is captured at 16,000 Hz mono (SPEECH_SAMPLE_RATE = 16_000) through a Web Audio AudioWorklet pipeline. Running capture off the main UI thread keeps frame extraction steady even while the browser repaints live transcript previews or the streamer runs a demanding game in the foreground.

Each frame extracted for VAD is 512 samples—exactly 32 ms of audio at 16 kHz. Once SpeechAudioGate confirms active speech, floating-point samples are accumulated into 64 ms packets (1,024 samples = 2,048 bytes of signed 16-bit little-endian PCM, pcm_s16le) before calling socket.send().

Halving client packet buffering down to 64 ms cuts wait time at the browser egress boundary while keeping WebSocket frame overhead reasonable. During encoding (encodePcm16), values are clamped to [-1, 1] and NaN samples are silenced to 0 so malformed audio frames never corrupt the upstream PCM stream.

Browser-side voice activity detection with Silero VAD v5

Shipping raw microphone silence continuously wastes bandwidth and forces upstream models to chew through room hum, keyboard clacks, and fan noise. Instead, DubMochi runs Silero VAD v5 (silero_vad_v5.onnx) directly inside the browser using ONNX Runtime Web with SIMD threaded WebAssembly (ort-wasm-simd-threaded).

One subtle startup bottleneck we eliminated was serial initialization: compiling WASM, instantiating the ONNX session, and opening the upstream WebSocket used to wait on one another. By parallelizing local Silero VAD initialization with the upstream WebSocket connection handshake, the model warms up concurrently while the Worker verifies the session ticket and connects to Soniox.

SpeechAudioGate: hysteresis, 320 ms pre-roll, and 480 ms trailing silence

Raw VAD probabilities fluctuate frame to frame—especially on soft consonants, quick breaths, or sudden desk bumps. Passing frames through a naive single threshold either clips the start of sentences or fires false triggers on keyboard noise.

DubMochi's SpeechAudioGate solves this with dual-threshold hysteresis and a fixed-size circular ring buffer:

  • Confirmation before streaming: Incoming frames must stay at or above START_PROBABILITY (0.50) for 96 ms (1,536 samples) before transitioning to active speech. Transient clicks are discarded without ever hitting the network.
  • Zero-clipping 320 ms circular pre-roll: While idle, SpeechAudioGate continuously writes frames into a 320 ms ring buffer (5,120 samples). The instant speech is confirmed, the gate emits speech-start and flushes the entire pre-roll buffer once—preserving soft opening plosives and initial syllables without duplicating the triggering frame.
  • Hysteresis during speech: Once active, speech stays open as long as frame probability remains at or above CONTINUE_PROBABILITY (0.35), preventing quiet syllables from prematurely slicing a sentence in half.
  • 480 ms trailing silence finalize: When probability stays below 0.35 for 480 ms (7,680 samples), the gate flushes and emits speech-end, signaling the upstream stream to finalize promptly rather than lingering on trailing silence.
Gate parameterValuePurpose
START_PROBABILITY0.50Threshold to begin confirming a candidate speech onset
CONTINUE_PROBABILITY0.35Lower hysteresis threshold to avoid mid-sentence cutoffs
Speech confirmation window96 msFilters out brief non-speech transients such as key clicks
Circular pre-roll buffer320 msRetains recent audio so opening consonants are never clipped
Trailing silence finalize window480 msFinalizes completed utterances promptly once the speaker stops talking

Zero-trust WebSocket proxying with Cloudflare Workers

Putting a speech vendor's API key in client JavaScript is a non-starter, and routing live audio through a distant origin server adds avoidable network hops. DubMochi proxies WebSockets at the edge using Cloudflare Workers WebSockets and WebSocketPair.

When a streamer clicks Start captions in Live captions, the client requests a short-lived ticket from Convex and passes it during the WebSocket upgrade via Sec-WebSocket-Protocol: ["dubmochi", ticket]. Inside the Worker (speechStream):

  1. The Worker consumes the ticket through Convex (api.speech.consume), receiving the session's lease, language, targetLanguage, optional glossary entries, and quotaDeadline.
  2. It initiates the upstream upgrade to https://stt-rt.soniox.com/transcribe-websocket, injecting Authorization: Bearer <SONIOX_API_KEY> strictly on the server side.
  3. Because Cloudflare's fetch AbortSignal stays attached even after upgrade if left active, the Worker uses a 10-second AbortController scoped strictly to the handshake and clears the timer in a finally block right after the upgrade succeeds.
  4. Once open, WebSocketPair bridges binary PCM16 frames upstream and JSON token frames downstream. Account quota enforcement runs via an in-memory quotaDeadline timer and periodic lease checks (api.speech.maintain), keeping per-packet database overhead at zero.

Single-socket transcription and translation with Soniox stt-rt-v5

Rather than chaining a separate STT service into a second HTTP translation call—which adds serialization delay and extra round trips—DubMochi runs both transcription and one-way translation inside one Soniox real-time speech API session (stt-rt-v5).

During session initialization, the Worker sends a single configuration payload combining audio format, language hints (or open language identification in Multilingual mode), custom glossary context, and tuned endpointing parameters:

{
	"model": "stt-rt-v5",
	"audio_format": "pcm_s16le",
	"sample_rate": 16000,
	"num_channels": 1,
	"enable_language_identification": true,
	"enable_endpoint_detection": true,
	"max_endpoint_delay_ms": 600,
	"endpoint_latency_adjustment_level": 2,
	"translation": {
		"type": "one_way",
		"target_language": "en"
	}
}

Setting enable_endpoint_detection: true, max_endpoint_delay_ms: 600, and endpoint_latency_adjustment_level: 2 nudges the recognizer to commit sentence boundaries faster during lively commentary instead of waiting for long pauses. In single-language mode, strict language_hints narrow the decoder; when a creator supplies custom VTuber names or gaming terms, context forwards those glossary entries straight into the same session.

Tracking concurrent utterances with SonioxTranscript

Streaming bilingual captions creates a subtle ordering problem: a streamer often starts speaking Sentence 2 while the translated tokens for Sentence 1 are still arriving. A naive "single current caption" buffer either drops Sentence 1's late translation or overwrites Sentence 2's active draft.

SonioxTranscript solves this with a bounded state machine that tracks up to 4 concurrent in-flight utterances (pendingLimit = 4):

  • Each incoming token carries is_final and translation_status ("original", "translation", or "none"). Final prefixes append monotonically, while each result replaces the current provisional suffix cleanly.
  • Semantic <end> and <fin> boundary tokens close the source or target side of an utterance independently, allowing the next utterance to start capturing original speech while the previous utterance finishes receiving its translation.
  • Orphan translation tokens without a parent utterance are ignored, and speech already spoken in the target language (translation_status: "none") passes through directly so bilingual code-switching stays aligned.

Coalescing writes to Convex at 150 ms for reactive OBS overlays

Every live caption update ultimately needs to reach the streamer's /overlay page running inside an OBS Browser Source. Subscribing /overlay to Convex reactive queries eliminates manual polling and pushes state updates over Convex's real-time WebSocket directly to OBS.

However, forwarding every single streaming token straight into a database mutation would multiply write volume unnecessarily, while throttling too aggressively makes subtitles feel choppy. SpeechCaptionWrites balances responsiveness and write efficiency:

  • 150 ms write coalescing (WRITE_INTERVAL_MS = 150): Rapid provisional draft updates are batched at 150 ms intervals.
  • Immediate flushes on latency-critical transitions: Three events bypass the 150 ms timer and write immediately:
    1. The first streamed partial translation for an utterance (firstStreamedTranslation), so international viewers see translated text appear as soon as the first translated tokens arrive.
    2. The first finalized transcript (firstFinal), locking in the spoken line without waiting for another tick.
    3. Translation completion (justCompleted), immediately committing the finished translated line.
  • Preserving late translations across in-flight utterances: SpeechCaptionWrites tracks per-sequence translation slots (matching SonioxTranscript's 4-utterance window) so late translations for earlier utterances still update the workspace log, preview, and OBS /overlay cleanly.

Resilience under real-world streaming conditions

Real broadcasts run for hours while the streamer's focus stays on a full-screen game, not the browser tab hosting DubMochi. Three client-side safeguards keep the pipeline stable without building up lag:

  • Bounded send queue (never replay stale audio): Before calling socket.send(), the client checks socket.bufferedAmount against a 2-second cap (maxBufferedBytes = 64 KB at 16 kHz PCM16). If a network stall fills the send buffer past that cap, DubMochi intentionally resets the gate (gate.reset()), drops stale queued audio, and reconnects with exponential backoff (up to 4 retries) using a fresh ticket—because in a live stream, catching up to "right now" beats replaying 10-second-old captions.
  • Web Worker heartbeat ticker: Browsers aggressively throttle setInterval inside background tabs. Running a lightweight Web Worker ticker keeps keep-alive heartbeats firing reliably even when the DubMochi workspace sits behind a full-screen game.
  • Automatic audio context recovery: createSpeechVad listens to AudioContext state changes, track unmute, page visibility, and user gestures so temporary OS audio interruptions recover cleanly without requiring a full page reload.

Want to see the end result in action? Watch the DubMochi live demo, explore DubMochi features, or follow our Japanese-to-English OBS setup tutorial to add the overlay to your next stream.

Frequently asked questions

Why run Silero VAD v5 in the browser instead of on the server?

Running silero_vad_v5.onnx locally in the browser filters out silence, fan hum, and brief clicks before audio leaves the streamer's machine. That avoids sending empty PCM frames through the Cloudflare Worker and keeps upstream speech recognition focused on actual vocal segments.

How does DubMochi avoid clipping the first word when speech begins?

SpeechAudioGate continuously buffers the most recent 320 ms of 16 kHz audio in a circular pre-roll ring buffer. Once incoming frames stay above START_PROBABILITY (0.50) for 96 ms, the gate flushes that 320 ms pre-roll ahead of the live stream so opening consonants are preserved intact.

Why use a Cloudflare Worker to proxy WebSockets to Soniox?

The Worker keeps SONIOX_API_KEY strictly on the server while validating short-lived Convex connection tickets in Sec-WebSocket-Protocol and enforcing account quota leases at the edge. Using WebSocketPair lets the Worker pipe 64 ms binary PCM16 frames directly upstream without per-packet database lookups.

Why coalesce Convex writes at 150 ms instead of writing every token?

Coalescing provisional draft updates at 150 ms bounds database mutation load during rapid speech while still feeling smooth on screen. Because SpeechCaptionWrites flushes immediately on the first streamed partial translation, the first finalized transcript, and translation completion, viewers see key caption transitions right away in the OBS /overlay.