How a Phone Call Reaches an AI Voice Agent: SIP, SDP, RTP and the 8 kHz Problem

15 min read

How a Phone Call Reaches an AI Voice Agent: SIP, SDP, RTP and the 8 kHz Problem

The problem

Someone dials a phone number and your AI agent answers. Between those two moments, two separate conversations happen. One is a text conversation between machines that agrees a call should exist, where its audio should go and in what format. The other is the audio itself, sliced into small packets and sent many times a second over a different path.

When a voice agent misbehaves on the phone, the cause is usually in one of those two conversations. The call never connects, because the first one failed. Or the call connects but the agent hears silence, hears garbage, or understands words badly, because the second one went wrong. That last case is sneaky: the audio arrives fine, but it is narrowband phone audio, and the speech recognizer was told it was something else.

This post walks through both conversations with real wire examples taken from the standards, then explains what an 8 kHz phone codec does to speech recognition according to the speech-to-text providers' own documentation.

This is part 4 of the Voice AI over SIP series. If a term is new to you, the glossary defines it in plain language and links to the part that covers it.

The path, from handset to agent

Here is the chain in plain terms:

  1. The phone network (PSTN). The public switched telephone network, the traditional phone system that ordinary phone numbers belong to.
  2. A SIP trunk. Your carrier converts the call to SIP (Session Initiation Protocol, RFC 3261) at a PSTN gateway and sends it to your server over the internet or a private link.
  3. Your SIP endpoint. This can be an SBC (session border controller), Asterisk, FreeSWITCH, or a framework with a built-in SIP side such as LiveKit SIP. Part 5 of this series covers that layer: the voice agent stack and its latency budget.
  4. The media bridge into the agent. The audio is decoded and handed to speech-to-text (STT), the language model and text-to-speech (TTS).

If you want to pick a carrier for step 2, see SIP trunk providers for voice AI in India compared.

Conversation one: SIP signaling

SIP is a text protocol that looks a lot like HTTP. A request has a method (INVITE, ACK, BYE, REGISTER, OPTIONS), a set of headers, and an optional body.

Animation: A SIP call message by message: INVITE, 100 Trying, 180 Ringing, 200 OK, ACK, RTP audio, then BYE.

A real INVITE

This is the example INVITE from RFC 3261, section 4. It is quoted as printed in the standard; the RFC omits Alice's SDP body at this point.

text
INVITE sip:bob@biloxi.com SIP/2.0
Via: SIP/2.0/UDP pc33.atlanta.com;branch=z9hG4bK776asdhds
Max-Forwards: 70
To: Bob <sip:bob@biloxi.com>
From: Alice <sip:alice@atlanta.com>;tag=1928301774
Call-ID: a84b4c76e66710@pc33.atlanta.com
CSeq: 314159 INVITE
Contact: <sip:alice@pc33.atlanta.com>
Content-Type: application/sdp
Content-Length: 142

(Alice's SDP not shown)

What the headers do, according to RFC 3261:

HeaderJob
ViaWhere responses to this request must be sent. Each hop adds one.
Max-ForwardsA hop limit, so a looping request eventually dies.
From / ToWho is calling whom. The tags identify each side.
Call-IDA unique ID for this call. Call-ID plus the From tag and To tag identify the dialog (the ongoing call relationship).
CSeqA sequence number plus method, increased for each new request in the dialog.
ContactThe direct address to use for future requests in this call.
Content-TypeWhat the body is. For calls this is application/sdp.

When Bob answers, his 200 OK carries his own tag and his own direct address, To: Bob <sip:bob@biloxi.com>;tag=a6c85cf and Contact: <sip:bob@192.0.2.4>.

The call flow

RFC 3261 describes the basic flow through proxies (the "trapezoid") like this:

text
Caller                         Callee
  | INVITE (with SDP offer)      |
  |----------------------------->|
  |               100 Trying     |
  |<-----------------------------|
  |               180 Ringing    |
  |<-----------------------------|
  |     200 OK (with SDP answer) |
  |<-----------------------------|
  | ACK                          |
  |----------------------------->|
  |<========= RTP media ========>|
  | BYE                          |
  |----------------------------->|
  |               200 OK         |
  |<-----------------------------|

A few details from the RFC that matter in practice:

  • The dialog starts as "early" when a 1xx response with a To tag arrives, and becomes "confirmed" on the 2xx.
  • The ACK goes end to end, using the Contact address from the 200 OK, so it can skip the proxies.
  • Media usually takes a different path from signaling. The SIP messages may go through three servers while the audio goes straight between two media endpoints.
  • A re-INVITE inside an existing dialog changes the session, for example to put a call on hold or change codec.

If something goes wrong here, the response code tells you which side gave up and roughly why. I am not repeating the codes in this post; see the SIP response code chart.

sequenceDiagram
    autonumber
    participant C as Caller
    participant P as Proxy
    participant B as Callee
    C->>P: INVITE (SDP offer)
    P-->>C: 100 Trying
    P->>B: INVITE (SDP offer)
    B-->>P: 180 Ringing
    P-->>C: 180 Ringing
    Note over C,B: 1xx with To tag: dialog is early
    B-->>P: 200 OK (SDP answer)
    P-->>C: 200 OK (SDP answer)
    Note over C,B: 2xx: dialog is confirmed
    C->>B: ACK (direct, to Contact address)
    C<<->>B: RTP media, on its own path
    C->>B: BYE
    B-->>C: 200 OK

Diagram: Through a proxy: the ACK goes straight to the Contact address, and RTP takes its own path.

REGISTER versus IP authentication

How does the carrier know a call to or from your server is really yours? There are two common patterns.

Registration (REGISTER). RFC 3261 section 10 describes a registrar: a special server that binds an "address-of-record" (your SIP identity) to one or more contact addresses (where you can be reached right now). Registrations are soft state. They expire unless refreshed, and the expires value is in seconds. The RFC says a malformed expires value is treated as 3600 seconds, and that refreshes should reuse the same Call-ID with CSeq going up by one. REGISTER does not create a dialog.

Registration usually comes with digest authentication (RFC 3261 section 22). A registrar or user agent challenges with 401 and a WWW-Authenticate header; a proxy challenges with 407 and Proxy-Authenticate. The client retries with an Authorization header and a higher CSeq. The RFC's example challenge:

text
WWW-Authenticate: Digest realm="biloxi.com", qop="auth,auth-int",
    nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
    opaque="5ccc069c403ebaf9f0171e9517f40e41"

The RFC also says "Basic" authentication must not be used, and servers must not challenge ACK or CANCEL.

IP authentication. Many trunks skip REGISTER and simply trust traffic from known IP addresses. LiveKit's inbound trunk is a useful concrete example of both styles. Its documentation says an inbound trunk restricts calls to those coming from your provider, and that you can protect it with a username and password or with allowed_addresses, a list of IPs or CIDR ranges. Two caveats are written into that doc page: support for username and password auth varies by provider (the page says Twilio Elastic SIP Trunking does not support it), and allowed_addresses has to be enabled by LiveKit support, until which it is "saved but not enforced". The same page says that if the trunk's numbers list is empty, you must set auth or allowed_addresses. The setup itself is covered in LiveKit SIP trunk voice agent setup.

sequenceDiagram
    autonumber
    participant U as Your SIP endpoint
    participant R as Registrar
    U->>R: REGISTER (CSeq 1)
    R-->>U: 401 Unauthorized
    Note over U,R: WWW-Authenticate: Digest realm, nonce
    U->>R: REGISTER + Authorization (CSeq 2)
    R-->>U: 200 OK (binding, expires in seconds)
    Note over U,R: Soft state: refresh before it expires
    U->>R: REGISTER refresh (same Call-ID, CSeq 3)
    R-->>U: 200 OK
    Note over U,R: A proxy challenges with 407 instead

Diagram: REGISTER with digest auth: a 401 challenge, a retry with Authorization and a higher CSeq, then refreshes.

The body: SDP offer and answer

The INVITE body is SDP (Session Description Protocol). The current SDP spec is RFC 8866 from January 2021, which obsoletes RFC 4566. How two sides use SDP to agree is defined in RFC 3264, the offer/answer model: the offer lists the media streams, the codecs, and the IP address and port where the offerer wants to receive. The answer accepts or rejects each stream and gives its own receive address.

Here is a real offer and answer pair, quoted from RFC 4317 (SDP offer/answer examples), section 2.2. The offer:

text
v=0
o=alice 2890844526 2890844526 IN IP4 host.atlanta.example.com
s=
c=IN IP4 host.atlanta.example.com
t=0 0
m=audio 49170 RTP/AVP 0 8 97
a=rtpmap:0 PCMU/8000
a=rtpmap:8 PCMA/8000
a=rtpmap:97 iLBC/8000
m=video 51372 RTP/AVP 31 32
a=rtpmap:31 H261/90000
a=rtpmap:32 MPV/90000

The answer:

text
v=0
o=bob 2808844564 2808844564 IN IP4 host.biloxi.example.com
s=
c=IN IP4 host.biloxi.example.com
t=0 0
m=audio 49172 RTP/AVP 0 8
a=rtpmap:0 PCMU/8000
a=rtpmap:8 PCMA/8000
m=video 0 RTP/AVP 31
a=rtpmap:31 H261/90000

How to read it:

  • c= is the address where that side wants to receive media.
  • m=audio 49170 RTP/AVP 0 8 97 means "send my audio to port 49170 using RTP, and I can take payload types 0, 8 or 97", in order of preference.
  • a=rtpmap maps a payload type number to a codec and clock rate.
  • The answer keeps PCMU and PCMA and drops iLBC.
  • The answer's video line has port 0, which in offer/answer means "stream declined".

RFC 3264 also defines direction attributes, sendonly, recvonly and inactive, and names the case where both sides send an offer at the same moment "glare". RFC 4317 (section 2.3) notes that a dynamic payload type number can change between offer and answer, here from 97 to 99, as long as it refers to the same codec. IANA reserves 96 to 127 for dynamic types. So never hard-code "97 means X".

Two practical notes from LiveKit's codec negotiation doc: its SIP side supports PCMU, PCMA and G722 by default, ranks G722 first, then PCMU, then PCMA, and when answering it picks its highest-ranked codec present in the offer. RTP usually starts after the ACK, or earlier if the far side sends a 183 with early media. The same page says an INVITE with no SDP ("delayed offer") gets 400 Bad Request unless delayed offer was enabled on request, and it is inbound only.

Conversation two: RTP media

Once the call is up, audio flows as RTP (Real-time Transport Protocol, RFC 3550). RTP runs over UDP and does not guarantee delivery or order. What it adds is a payload type (which codec), a sequence number (to spot loss and reordering) and a timestamp (to play audio at the right time). Its companion, RTCP, sends periodic quality reports; IANA lists RTCP packet types 200 (sender report) and 201 (receiver report) among others.

RFC 3551, the audio and video profile, says audio packets should carry 20 ms by default, and that packetization time sets a floor on delay. Receivers should accept anything from 0 to 200 ms per packet.

A worked example, my arithmetic from those rules: G.711 takes 8000 samples per second at 8 bits each. A 20 ms packet holds 8000 x 0.020 = 160 samples, which is 160 bytes of audio. That is 50 packets per second in each direction, and 8000 x 8 = 64,000 bits per second of audio payload, before RTP, UDP and IP headers. LiveKit's codec page describes PCMU as about 64 kbps plus overhead, which matches.

SRTP

SRTP (Secure RTP, RFC 3711) adds encryption, message authentication and replay protection to RTP and RTCP. Authentication of SRTCP is mandatory in that RFC, and the default ciphers are AES in counter mode with HMAC-SHA1.

The codecs you will actually meet

All rows come from the IANA RTP parameters registry and the RFCs and ITU pages listed at the end.

CodecRTP payload typeSDP clock rateAudio band or sample rateBitrateNotes
G.711 mu-law (PCMU)0 (static)80008000 samples/s64 kbit/sITU G.711
G.711 A-law (PCMA)8 (static)80008000 samples/s64 kbit/sITU G.711 says international links use A-law
G.7229 (static)8000 (see note)16,000 samples/s, 50 to 7,000 Hz audio64, 56 or 48 kbit/sWideband
AMR (narrowband)dynamic80008000 Hz8 modes, 4.75 to 12.2 kbit/sRFC 4867, from GSM and 3G
AMR-WBdynamic1600016000 Hz9 modes, 6.6 to 23.85 kbit/sRFC 4867
Opusdynamicalways 48000/28 kHz (NB) to 48 kHz (FB)6 to 510 kbit/sRFC 7587
telephone-eventdynamic8000 in RFC 4317's examplesn/an/aDTMF digits, RFC 4733

Three traps in that table:

  • G.722's clock rate is a lie on purpose. RFC 3551 says G.722 samples at 16,000 Hz but its RTP clock rate is 8,000, an error from an older RFC kept for compatibility. LiveKit's codec page calls this a "known quirk". If your code computes durations from the SDP clock rate, G.722 audio will come out at the wrong speed.
  • Opus always says 48000/2 in SDP, even when it carries narrowband speech. RFC 7587 puts the real limits in fmtp parameters. Its example 2:
text
m=audio 54312 RTP/AVP 101
a=rtpmap:101 opus/48000/2
a=fmtp:101 maxplaybackrate=16000; sprop-maxcapturerate=16000;
    maxaveragebitrate=20000; stereo=1; useinbandfec=1; usedtx=0
a=ptime:40
a=maxptime:40

RFC 7587 gives typical speech bitrates at 20 ms frames of 8 to 12 kbit/s narrowband, 16 to 20 kbit/s wideband and 28 to 40 kbit/s fullband.

  • DTMF can travel as its own RTP payload (telephone-event) instead of tones inside the audio. Part 9 covers this in depth: AMD, DTMF and transfers.

8 kHz versus 16 kHz: what the STT providers say

G.711 samples at 8 kHz. That limits the audio to narrowband. G.722, AMR-WB and wideband Opus carry 16 kHz audio. What does that mean for speech recognition? Rather than guess, here is what each provider's documentation says.

Animation: The same wave sampled at 8 kHz and at 16 kHz: twice the samples, a closer copy of the voice.

Google Cloud Speech-to-Text (best practices page and RecognitionConfig reference):

  • Capture audio at 16,000 Hz or higher where you can. Lower rates may reduce accuracy.
  • Do not re-sample. If the source is telephony at its native 8000 Hz, that is "the rate that should be sent".
  • Lossy codecs such as mu-law and A-law may reduce accuracy. If you must use a lossy codec, the page prefers AMR_WB, then OGG_OPUS.
  • The sampleRateHertz field accepts 8000 to 48000, with 16000 described as optimal.
  • There is a phone_call model meant for phone audio "typically recorded at an 8khz sampling rate".
  • A 100 ms frame size is recommended for streaming, and the page advises against automatic gain control and noise reduction before sending.

AWS Transcribe (data input page):

  • Streaming accepts FLAC, Ogg Opus and PCM, and recommends signed 16-bit little-endian PCM.
  • Streaming requires you to state the sample rate.
  • Telephone audio is described as typically 8,000 Hz, with "high fidelity" at 16,000 to 48,000 Hz.
  • At most two channels, with channel identification available.

Deepgram (encoding and sample rate pages):

  • For raw, headerless audio, encoding is required, and then sample_rate is required too.
  • Accepted encodings include linear16, mulaw, alaw, amr-nb, amr-wb, opus, speex and g729.
  • Its Flux model supports linear16, linear32, mulaw, alaw, opus and ogg-opus for raw audio.
  • amr-nb requires sample_rate=8000 and amr-wb requires sample_rate=16000.

Put together, the documented advice is consistent:

  1. Wideband in, wideband to STT. If the trunk can negotiate G.722, AMR-WB or wideband Opus end to end, you get 16 kHz audio, which Google describes as optimal.
  2. Narrowband in, narrowband to STT. If the call arrives as G.711, upsampling to 16 kHz does not add information, and Google says plainly not to re-sample. Send 8 kHz and pick a telephony model where the provider has one.
  3. Declare exactly what you send. Raw RTP payload has no header. Deepgram and AWS both require you to state the format and rate for raw audio. A mismatch, such as declaring 16000 for 8000 Hz mu-law, is a classic cause of terrible transcripts on audio that sounds fine to a human.
  4. Watch the conversion steps in your bridge. Pipecat's Twilio serializer docs, for example, say Twilio Media Streams uses 8 kHz mu-law and the serializer converts to and from PCM, with input and output sample rates defaulting to 8000. Asterisk's AudioSocket dialplan application docs say it sends 16-bit, 8 kHz mono PCM. Every hop that changes format is a place where the declared rate can drift from the real one.

These pages do not publish a single "accuracy drops by X% at 8 kHz" number, so I am not giving one.

My own opinion, for what it is worth: I would start by checking what codec the trunk actually negotiates (look at the m= and a=rtpmap lines in a real 200 OK), then make the STT config match that, before spending any time on prompt or model changes.

A quick checklist

  • Read the SDP from a real call. Which codec won? What clock rate?
  • If G.722 is in use, is your code using 16,000 samples per second for timing despite the 8000 in SDP?
  • Does your STT request declare the same encoding and sample rate as the audio you send?

When audio connects but flows one way only, the cause is usually NAT or the firewall, not the codec. That has its own post: SIP voice AI production reliability and one-way audio. For Asterisk-specific settings, see the Asterisk reference chart.

Sources