Pidoku

TTS and Real-Time Voice

Module 26 Lesson 26.f 1h 10m Difficulty 4/5

Prerequisites 26.e, 12.d, 12.p, 20.b


Before you start: words you need#

WordPlain meaning
TTSText-to-speech: turning text into spoken audio.
Audio codec (neural)A model that compresses audio into a short sequence of discrete tokens and decodes them back. Its frame rate (for example 12.5 frames per second) sets how many tokens a second of speech costs.
CodebookOne of several parallel token streams per codec frame; more codebooks carry more audio detail.
VocoderThe network that turns acoustic features or codec tokens into a waveform.
Time to first audioDelay from “start speaking” to the first sound leaving the server. The TTS equivalent of TTFT.
Barge-inThe user interrupting while the agent is speaking; the agent must stop at once.
Cascaded vs speech-to-speechA cascade chains ASR, an LLM and TTS; a speech-to-speech model takes and produces audio in one model.
WebRTCThe browser standard for real-time audio and video over UDP, with jitter buffers and echo cancellation.

1. What is it?#

Modern TTS is mostly an autoregressive language model that writes audio tokens, followed by a codec decoder that turns tokens into a waveform. A real-time voice agent puts that at the end of a pipeline: voice activity detection and streaming ASR (26.e), an LLM, then TTS, all streaming, wired together so the user hears an answer within about a second of finishing their sentence. The alternative is a single speech-to-speech model (Moshi, Qwen3-Omni, commercial realtime APIs), covered with omni models in 26.h.

This lesson covers how TTS is served, and how to engineer the latency of the whole loop. Facts checked on 13 November 2026.


2. Why does it matter?#

  • Humans notice pauses. In conversation, the typical gap between one speaker stopping and the next starting is around 200 ms across languages (Stivers et al., PNAS 2009). Telephony guidance (ITU-T G.114) treats one-way delays above 150 ms as starting to hurt interactivity. A voice agent will not match that, but every 100 ms is felt.
  • Latency is a sum. Four streaming stages and two network hops must all be fast; one sequential stage ruins it (section 6).
  • TTS is real-time decode. Each stream needs a decode step every 80 ms (for a 12.5 Hz codec) forever. Miss it and the audio stutters, which users notice more than slowness.
  • Voice is a fast-growing workload. Support lines, tutors, companions and in-car assistants all run this loop at scale.

3. Simple analogy#

A relay race with four runners (listen, transcribe, think, speak). The team time is the sum of the legs plus the baton handovers. You win not by making one runner superhuman but by letting each runner start before the previous one has finished: the speaker starts the first sentence while the thinker is still composing the second.


4. Tiny example: one turn of a voice agent#

t = 0 ms       user stops speaking
t = 40         last audio packet reaches the server
t = 340        endpointing decides the turn is over (300 ms of silence)
t = 420        ASR final transcript
t = 670        LLM first token
t = 715        first 4 tokens ("Sure, your order")
t = 835        TTS first audio packet
t = 875        user hears the first sound
meanwhile      LLM keeps generating, TTS keeps synthesising ahead of playback
if the user speaks: stop playback, cancel LLM and TTS, keep what was actually played in history

5. Technical explanation#

TTS architectures in 2026#

FamilyHow it worksLatency profileExamples
Small non-autoregressivePredict acoustic features for the whole sentence in parallel, then a vocoderVery fast, cheap, limited expressivenessKokoro-82M (StyleTTS 2-based, Apache-2.0)
LM + flow matching + vocoderAn LM writes semantic speech tokens; a flow-matching model and vocoder render audioStreaming with chunked flow matchingCosyVoice 2/3, Voxtral TTS
LM over multi-codebook codec tokensAn LM predicts all codebooks of each codec frame (often a big model for the first codebook and a small one for the rest); a causal codec decoder renders audioLowest first-packet latencyQwen3-TTS (12.5 Hz, 16 codebooks), Fish Speech
Speech-to-speechOne model hears and speaksLowest overall latency, least controlMoshi, Qwen3-Omni, commercial realtime APIs (26.h)

Published latency figures are vendor claims under their own conditions: Qwen3-TTS reports end-to-end synthesis latency as low as 97 ms and first-packet emission after a single input character; CosyVoice 3 reports latency as low as 150 ms with text-in and audio-out streaming; Kokoro’s model card quotes API prices under $1 per million characters (April 2025).

Why the codec frame rate matters#

An LM-based TTS produces one decode step per codec frame. At 12.5 Hz that is 12.5 steps per second of speech; a 50 Hz codec needs four times as many. Fewer frames per second mean fewer sequential steps, fewer tokens of KV cache and cheaper real-time decode, at the cost of more information per frame (hence several codebooks). The codec decoder must also be causal to stream: it may only use past frames to render the next audio packet.

Serving TTS#

  • It looks like LLM decode, so the same engines apply: continuous batching, KV cache, CUDA graphs. vLLM-Omni v0.32.0 serves TTS models (Qwen3-TTS, CosyVoice3, Fish Speech, Voxtral TTS and others) behind an OpenAI-style /v1/audio/speech endpoint with streaming, and added an optional single-stage Qwen3-TTS with streaming codec decoding inside the generation loop.
  • The real-time constraint replaces the throughput goal. Each stream must receive a frame every 80 ms (at 12.5 Hz). Batch size is bounded by the step time that still beats real time with margin (section 6).
  • Stream text in. Agents feed TTS from a streaming LLM. Some models accept streaming text (CosyVoice’s “bi-streaming”); others need whole sentences, which adds the time to generate the first sentence.
  • Voices and cloning. Reference audio for a cloned voice is a prompt prefix. Cache its encoding, as you would a prefix (12.m), and keep it per tenant for privacy.

Engineering the voice loop#

  • Endpointing is the biggest single cost. Waiting 300–800 ms of silence to be sure the user has finished is common. Semantic or model-based turn detection lowers it but risks interrupting people mid-thought.
  • Overlap every stage. Stream ASR partials, start the LLM on a confident partial (speculatively, cancel if the final differs), stream LLM tokens into TTS, stream TTS audio out.
  • Barge-in. Detect user speech during playback, stop audio within tens of milliseconds, cancel in-flight LLM and TTS work (free their batch slots), and truncate the conversation history to what the user actually heard.
  • Transport. WebRTC (UDP, jitter buffer, echo cancellation, opus) for browsers and apps; WebSocket for server-to-server and simple clients; SIP gateways for phone calls (8 kHz audio).
  • Orchestration frameworks. Open-source frameworks such as Pipecat (v1.16.0, November 2026) and LiveKit Agents (1.8.11) provide the pipeline, VAD, turn detection, interruption handling and transport, and plug in any ASR, LLM and TTS.
  • Co-locate. Put ASR, LLM and TTS in one region (ideally one cluster) near users; each cross-region hop costs tens of milliseconds twice per turn.

6. Under the hood: the latency sum and the real-time limit#

The program adds up one turn of a cascaded agent under four designs, then shows how many TTS streams one replica can keep real time. Every stage time and the TTS step-time model are assumptions; replace them with your measurements.

Go
package main

import "fmt"

// Part 1: when does the user hear the first sound of the reply?
// All stage numbers are assumptions for a cascaded voice agent in one region.
const (
	netIn      = 40.0  // ms, user audio to server
	endpoint   = 300.0 // ms of silence before we decide the user has finished
	asrFinal   = 80.0  // ms to finalise the transcript after the endpoint
	llmTTFT    = 250.0 // ms to first LLM token
	msPerTok   = 15.0  // ms per LLM output token
	replyToks  = 150.0 // whole reply
	firstSent  = 15.0  // tokens in the first sentence
	firstWords = 4.0   // tokens before an incremental TTS can start
	ttsFirst   = 120.0 // ms from TTS input to first audio packet (streaming TTS)
	ttsWhole   = 900.0 // ms to synthesise the whole reply non-streaming
	netOut     = 40.0  // ms, first audio packet to the user's speaker
)

// Part 2: how many speech streams can one TTS replica keep real time?
// A 12.5 Hz codec needs one generation step (all codebooks) per 80 ms of audio per stream.
// Assumption: one batched step takes 12 ms + 0.1 ms per stream in the batch.
func stepMs(batch float64) float64 { return 12 + 0.1*batch }

func main() {
	front := netIn + endpoint + asrFinal
	cases := []struct {
		name string
		ms   float64
	}{
		{"sequential: full reply, then full TTS", front + llmTTFT + (replyToks-1)*msPerTok + ttsWhole + netOut},
		{"stream LLM, TTS per sentence", front + llmTTFT + (firstSent-1)*msPerTok + ttsFirst + netOut},
		{"stream LLM, incremental TTS", front + llmTTFT + (firstWords-1)*msPerTok + ttsFirst + netOut},
		{"  ... and a 150 ms smart endpoint", front - endpoint + 150 + llmTTFT + (firstWords-1)*msPerTok + ttsFirst + netOut},
	}
	fmt.Println("end of user speech -> first audio heard")
	for _, c := range cases {
		fmt.Printf("  %-38s %6.0f ms\n", c.name, c.ms)
	}

	fmt.Println("\nTTS replica, 12.5 Hz codec (80 ms of audio per step)")
	fmt.Printf("  %8s %10s %16s\n", "streams", "step ms", "x real time")
	for _, b := range []float64{1, 64, 256, 512, 680, 800} {
		s := stepMs(b)
		fmt.Printf("  %8.0f %10.1f %15.2fx\n", b, s, 80/s)
	}
}

Output:

end of user speech -> first audio heard
  sequential: full reply, then full TTS    3845 ms
  stream LLM, TTS per sentence             1040 ms
  stream LLM, incremental TTS               875 ms
    ... and a 150 ms smart endpoint         725 ms

TTS replica, 12.5 Hz codec (80 ms of audio per step)
   streams    step ms      x real time
         1       12.1            6.61x
        64       18.4            4.35x
       256       37.6            2.13x
       512       63.2            1.27x
       680       80.0            1.00x
       800       92.0            0.87x

How to read it:

  • Streaming is worth seconds; tuning is worth hundreds of milliseconds. Going from sequential to streaming saves almost three seconds. After that, the endpoint wait (300 ms) and LLM TTFT (250 ms) are the largest items, bigger than TTS itself.
  • Real time is a hard ceiling. At 680 streams a step takes exactly 80 ms: no slack for jitter, a long prompt arriving, or a garbage-collection pause. Below 1.0x, every stream stutters at once. Run with margin (here, around 256–400 streams, 2x to 1.5x real time) and admit new streams by step time, not GPU utilisation.
  • Time to first audio for a new stream also includes its prefill (text plus voice prompt) inside a busy batch; chunked prefill (12.k) keeps that from stalling everyone else’s next frame.

7. Performance implications#

  • Step time is the metric. Watch p99 decode step time against the frame period. Spikes become audible glitches; clients buffer a few hundred ms of audio to hide them, which adds latency.
  • Small models win on latency per stream. A 0.5–2B TTS model decodes in a few ms per step, so most of the budget is batching headroom.
  • Codec decode costs too. The waveform decoder runs per packet per stream; batch it on the GPU rather than per-stream on CPU.
  • The LLM in the loop is latency-critical. Short prompts, prefix caching of the system prompt and history (12.m), speculative decoding (13.n) and a model sized for TTFT, not leaderboard scores.

8. Production implications#

  • SLOs per turn: p50 and p95 time from end of user speech to first audio; interruption reaction time; audio glitch rate. Measure at the client, not the server.
  • Graceful overload: refuse new calls, or fall back to a smaller TTS voice, rather than degrade every live call.
  • Long sessions: calls last minutes; keep conversation KV cached between turns and route each call to the same replicas (21.h).
  • Telephony: 8 kHz μ-law audio, SIP trunks, DTMF, and carrier latency you do not control.
  • Voice cloning consent and abuse: require proof of consent for cloned voices, watermark generated speech where possible, and log usage.
  • Text normalisation: numbers, dates, currencies and abbreviations must be spoken correctly. It is often a separate step and a frequent source of bugs.

9. Common mistakes#

  1. Waiting for the full LLM reply before synthesising. Seconds lost.
  2. Tuning TTS while the endpoint waits 800 ms. Measure the whole budget first.
  3. Packing TTS replicas to exactly real time. Any spike becomes stutter for every stream.
  4. Not cancelling work on barge-in. The GPU keeps generating audio nobody will hear, and the history claims the agent said things it did not.
  5. Benchmarking on a fast office network. Mobile networks add jitter; test through WebRTC on real devices.

10. Hands-on exercise#

  1. Run the program. Which single change saves the most: halving LLM TTFT, halving TTS first-packet time, or halving the endpoint wait?
  2. Add a cross-region hop (+70 ms each way between the ASR and the LLM). How does it compare with the other items?
  3. Change the codec to 50 Hz (20 ms per step) with the same step-time model. How many streams fit at 1.5x real time?
  4. Build a minimal Pipecat or LiveKit Agents pipeline with any ASR, LLM and TTS. Log timestamps per stage for 20 turns and draw the budget.

11. Interview questions#

  1. Walk through the latency budget of a cascaded voice agent. Which items dominate and how do you cut each?
  2. Why does TTS have a hard real-time constraint that chat does not?
  3. How does the codec frame rate affect the cost of an LM-based TTS?
  4. What has to happen, end to end, when the user interrupts?
  5. When would you choose a speech-to-speech model over a cascade, and what do you give up?

12. Further reading#

Checked on 13 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in