Multimedia Sessions
Session and its subclasses handle the media exchange between call parties. They are created by the Dialog when a call is accepted or initiated.
Sessions can be audio, video, and more. However, this library currently only provides audio sessions via the AudioCall class. Video and other media types are fairly uncommon outside of consumer applications, and implementing them is on the roadmap but not yet a priority.
voip.rtp.Session
dataclass
One call leg managed by the RTP multiplexer.
Associates a SIP dialog with the RealtimeTransportProtocol media
stream. Subclass and override packet_received to process incoming
media, and use send_packet to transmit outbound media.
The rtp back-reference allows sending media; the dialog back-reference
carries the SIP dialog state and a reference to the SIP session
(dialog.sip) so that the transport can be closed when the call ends.
Subclass voip.audio.AudioCall for audio calls with codec
negotiation, buffering, and decoding.
Attributes:
| Name | Type | Description |
|---|---|---|
rtp |
RealtimeTransportProtocol
|
Shared RTP multiplexer socket that delivers packets to this handler. |
dialog |
Dialog
|
SIP dialog state for this call leg. |
media |
MediaDescription
|
Negotiated SDP media description for this call leg. |
caller |
CallerID
|
Caller identifier as received in the SIP From header. |
srtp |
SRTPSession | None
|
Optional SRTP session for encrypting and decrypting media. |
Source code in voip/rtp.py
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | |
hang_up()
async
Terminate the call by sending a SIP BYE request RFC 3261 §15.
Deregisters this call from the RTP multiplexer, then delegates the BYE signaling to Dialog.bye, which constructs and sends the BYE request, removes the dialog from the SIP session's registry, and awaits the 200 OK acknowledgment.
The method is a no-op when no dialog is associated with this call.
Source code in voip/rtp.py
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | |
negotiate_codec(remote_media)
classmethod
Negotiate a media codec from the remote SDP offer.
Override in subclasses to implement codec selection. The SIP layer calls this before sending a 200 OK; if the method raises the exception propagates and the call is not answered.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
remote_media
|
MediaDescription
|
The SDP |
required |
Returns:
| Type | Description |
|---|---|
MediaDescription
|
A |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
When not overridden by a subclass. |
Source code in voip/rtp.py
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | |
packet_received(packet, addr)
Handle a parsed RTP packet. Override in subclasses to process media.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
packet
|
RTPPacket
|
Parsed RTP packet. |
required |
addr
|
NetworkAddress
|
Remote |
required |
Source code in voip/rtp.py
118 119 120 121 122 123 124 | |
sdp_formats()
classmethod
Return the list of supported payload formats for outbound SDP offers.
Override in subclasses to advertise codec capabilities. AudioCall overrides this to return all supported codecs in priority order.
Returns:
| Type | Description |
|---|---|
list[RTPPayloadFormat]
|
List of RTPPayloadFormat |
list[RTPPayloadFormat]
|
objects describing the supported codecs. |
Source code in voip/rtp.py
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | |
send_packet(packet, addr)
Serialize packet and send it via the shared RTP socket.
Encrypts the packet with the call's SRTP session when one is set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
packet
|
RTPPacket
|
RTP packet to send. |
required |
addr
|
NetworkAddress
|
Destination |
required |
Source code in voip/rtp.py
126 127 128 129 130 131 132 133 134 135 136 137 138 | |
Audio Handling
voip.audio.AudioCall
dataclass
Bases: Session
RTP call handler for audio calls supporting Opus, G.722, PCMA, and PCMU.
Attributes:
| Name | Type | Description |
|---|---|---|
supported_codecs |
list[type[RTPCodec]]
|
Preferred codecs in priority order (highest first). |
rpt_packet_duration |
timedelta
|
Wall-clock spacing between outbound RTP packets in seconds. |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sampling_rate_hz
|
int
|
Target sample rate in Hz for decoded audio
delivered to |
16000
|
Source code in voip/audio.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | |
payload_type
property
Negotiated RTP payload type number.
sample_rate
property
SDP-negotiated audio sample rate in Hz.
Reflects the value from the remote a=rtpmap line. For G.722 this
is 8000 per RFC 3551 even though the codec runs at 16000 Hz
internally; use codec.sample_rate_hz to get the actual audio rate.
audio_received(*, audio, rms)
Handle decoded audio. Override in subclasses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Float32 mono PCM array at |
required |
rms
|
float
|
Root Mean Square of the decoded PCM, as a proxy for signal strength. |
required |
Source code in voip/audio.py
271 272 273 274 275 276 277 278 | |
cancel_outbound_audio()
Stop the current outbound audio while it is being sent.
Source code in voip/audio.py
199 200 201 202 203 204 205 206 | |
on_audio_sent()
Handle completion of an outbound audio stream.
Called once the last RTP packet of an outbound stream has been
dispatched (i.e. outbound_handle transitions to None).
The base implementation is a no-op. Override in subclasses to
trigger post-audio actions, for example hanging up after
SayCall finishes speaking.
Source code in voip/audio.py
208 209 210 211 212 213 214 215 216 | |
rms(audio)
staticmethod
Calculate the Root Mean Square (RMS) of an audio signal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Float32 mono PCM array. |
required |
Returns:
| Type | Description |
|---|---|
float
|
RMS value as a proxy for signal strength. |
Source code in voip/audio.py
186 187 188 189 190 191 192 193 194 195 196 197 | |
sdp_formats()
classmethod
Return all supported payload formats for outbound SDP offers.
Lists all codecs in supported_codecs priority order so the remote
can select the best available codec.
Returns:
| Type | Description |
|---|---|
list[RTPPayloadFormat]
|
List of RTPPayloadFormat |
list[RTPPayloadFormat]
|
objects for every codec in |
Source code in voip/audio.py
143 144 145 146 147 148 149 150 151 152 153 154 | |
send_audio(audio)
async
Encode audio with the negotiated codec and transmit via RTP.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Float32 mono PCM at |
required |
Source code in voip/audio.py
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 | |
voip.audio.VoiceActivityCall
dataclass
Bases: AudioCall
AudioCall with energy-based Voice Activity Detection (VAD) and speech buffering.
Full utterances are buffered and passed to voice_received. Silent chunks are dropped from the audio stream.
Override that method in subclasses to process complete speech segments (e.G. transcribe them, echo them back, etc.) instead of raw audio frames.
An utterance is considered complete when the RMS of the buffered audio
drops below voice_rms_threshold for at least [silence_gap] seconds.
Full utterances with an RMS sound power below utterances_rms_threshold
are discarded.
A full utterance must be separated from the previous one by at least the
silence_gap to be considered complete and passed to
voice_received.
Example
The following example shows how to use VoiceActivityCall to echo a caller's
voice back to them similar to EchoCall.
import dataclasses
from voip.audio import VoiceActivityCall
@dataclasses.dataclass(kw_only=True)
class EchoCall(VoiceActivityCall):
async def voice_received(self, audio: np.ndarray) -> None:
resampled = self.resample(
audio, self.sampling_rate_hz, self.codec.sample_rate_hz
)
await self.send_audio(resampled)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
voice_rms_threshold
|
float
|
Minimum RMS sound power voice detection. |
0.001
|
utterances_rms_threshold
|
float
|
Minimum RMS sound power for an utterance. |
0.01
|
silence_gap
|
timedelta
|
Minimum duration of silence to consider an utterance complete. |
timedelta(milliseconds=200)
|
Source code in voip/audio.py
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | |
voice_received(audio)
async
Handle the flushed speech buffer. Override in subclasses.
This base implementation is a no-op. Subclasses must override this method to process the buffered utterance (e.g. echo it back, transcribe it, etc.).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio
|
ndarray
|
Float32 mono PCM array at |
required |
Source code in voip/audio.py
373 374 375 376 377 378 379 380 381 382 383 | |
voip.audio.EchoCall
dataclass
Bases: VoiceActivityCall
Echo the caller's speech back after they finish speaking.
Buffers a full utterance and replays it once a sustained silence lasting
silence_gap seconds is detected. This gives the caller a natural echo
of their own voice, useful for network latency testing and call-flow
demonstrations.
Example
class MySession(SessionInitiationProtocol):
def call_received(self, request: Request) -> None:
self.answer(request=request, session_class=EchoCall)
Source code in voip/audio.py
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 | |
AI Calls
voip.ai.TranscribeCall
dataclass
Bases: VoiceActivityCall
Transcribe incoming call audio.
Audio is decoded by AudioCall on a per-packet
basis and delivered to audio_received,
which applies an energy-based voice activity detector (VAD) from
VoiceActivityCall. All audio frames
(speech and silence) are accumulated until silence is sustained for
silence_gap seconds, then the entire utterance is sent to Whisper as
one chunk. This avoids cutting sentences in the middle and prevents
background microphone noise from being passed to Whisper as spurious audio.
Example
Override transcription_received to handle the resulting text:
class MySession(SessionInitiationProtocol):
def call_received(self, request: Request) -> None:
self.answer(request=request, session_class=MyCall)
To share one model instance across multiple calls (recommended to avoid
loading it multiple times) pass a preloaded WhisperModel:
shared_model = WhisperModel("base")
class MyCall(TranscribeCall):
model = shared_model
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stt_model
|
WhisperModel
|
Whisper model to use for transcription. Defaults to "base". |
(lambda: WhisperModel('base'))()
|
Source code in voip/ai.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | |
transcription_received(text)
Handle a transcription result. Override in subclasses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Transcribed text for this audio chunk (already stripped). |
required |
Source code in voip/ai.py
91 92 93 94 95 96 | |
voip.ai.AgentCall
dataclass
Bases: TTSMixin, TranscribeCall
Respond to caller voice inputs with voice responses.
Uses Ollama to generate responses to transcribed text and Pocket TTS to synthesize voice replies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
system_prompt
|
str
|
Prompt to guide the language model. |
'You are a person on a phone call. Keep your answers very brief and conversational. YOU MUST NEVER USE NON-VERBAL CHARACTERS IN YOUR RESPONSES!'
|
llm_model
|
str
|
Ollama model to use for text generation. |
'ministral-3'
|
tts_model
|
TTSModel
|
Pocket TTS model to use for voice synthesis. |
(lambda: load_model())()
|
voice
|
Path | str | Tensor
|
Voice to use for synthesis. |
'azelma'
|
salutation
|
str
|
Opening message sent as soon as the call is established. |
'Hi.'
|
audio_interrupt_duration
|
timedelta
|
Time you have to talk over the agent to interrupt the outbound audio. |
timedelta(seconds=0.75)
|
Source code in voip/ai.py
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | |
voip.ai.SayCall
dataclass
Bases: TTSMixin, AudioCall
Dial a number, say a message using TTS, and hang up.
Source code in voip/ai.py
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | |