I am making on telephony app. I am using Twilio si...
# ask-ai
f
I am making on telephony app. I am using Twilio sip trunk service for calling with US number. So my call will be routed from US to India. So my question is will this routing add some latency in calling experience? and also sometime it stuck at start and don't folllow instruction so what can be a problem? My network connection or anything else. How can I stabilise livekit?
t
Thanks for reaching out, Snehal. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking whether US→India routing via Twilio SIP trunk will add latency, why calls sometimes get stuck at start, and how to stabilize LiveKit. Short answers and next steps: 1) Latency • Yes — transcontinental routing adds measurable latency because of physical distance and network hops. Expect higher round‑trip times versus local calls. • You can reduce impact by pinning call routing to a region near the destination (set
destination_country
to
in
for India when creating outbound trunks) so media flows from a closer LiveKit region. 2) Why calls get stuck at start Common causes: • Incorrect SIP endpoint/trunk config (wrong domain can produce SIP errors). • Blocked or restricted network/firewall preventing UDP media or DTLS handshakes. • Missing TLS/SRTP or misconfigured secure trunking. • Client-side issues (device network quality, NAT, or TURN not used). Monitor
sip.callStatus
on the participant to see states like
dialing
,
ringing
,
active
to detect where it stops. 3) How to stabilize LiveKit (practical fixes) • Region pinning for outbound trunks to route closer to India. • Verify your SIP trunk endpoint and credentials are exactly as Twilio requires. • Enable TLS and SRTP on trunks and use
;transport=tls
in SIP URIs. • Ensure TURN over TLS is available and whitelist
*.turn.livekit.cloud
on TCP 443 if behind strict firewalls. • Enable client-side echo/noise cancellation (e.g.,
krisp_enabled
) to improve audio quality. • Add monitoring/logging of participant SIP states and call setup timing to identify failures. What I need to help further • Share the SIP trunk domain you use (mask any secrets), the typical error or SIP status code you see when it fails, and whether failures happen on specific networks (mobile vs corporate Wi‑Fi). Would you like steps to check your trunk config and firewall rules next? Sources: SIP cloud and region pinning | LiveKit docs | SIP outbound trunk | LiveKit docs | SIP troubleshooting guide | LiveKit docs | Secure trunking | LiveKit docs | Firewall Tips
f
will self hosted livekit server stabilse the performance and latency?
t
Short answer: Yes—self‑hosting can improve latency and stability, but only if you deploy and manage it correctly. Why it can help: • You control server location, so hosting the LiveKit server near your India endpoint (or your Twilio gateway) reduces network hops and round‑trip time. • You control instance types and networking, so you can choose non‑burstable, compute‑optimized machines and higher bandwidth to avoid CPU throttling and throughput limits. • You control TURN, external IPs, firewall rules, and TLS/SRTP settings, which improves connection reliability behind restrictive networks. Key trade‑offs and risks: • Self‑hosting is single‑home: you must handle scaling, redundancy, monitoring, and failover yourself. Rooms and participant capacity depend on your hardware. • If deployed far from users or on burstable/undersized instances, self‑hosting can worsen latency and cause spikes. Practical recommendations to get the benefit: 1. Host the server geographically close to the Indian destination (or your SIP/trunking edge). 2. Use non‑burstable, compute‑optimized instances (e.g., AWS c5/m5 class) to avoid CPU throttling. 3. Configure TURN and `use_external_ip: true`; provide TURN over TLS and whitelist
*.turn.livekit.cloud
on TCP 443 if needed. 4. Enable TLS/SRTP on SIP trunks and use
;transport=tls
in SIP URIs. 5. Monitor CPU, bandwidth, packet loss, and
sip.callStatus
to find bottlenecks. 6. If you need global reach or easier ops, consider LiveKit Cloud’s distributed mesh instead. If you want, I can help you pick server regions and instance types for your traffic pattern or provide a checklist for a self‑hosted deployment. Which would you prefer? Sources: LiveKit Cloud Architecture | LiveKit docs | Introducing LiveKit Phone Numbers: Zero to Ringing in 60 Seconds | LiveKit Cloud | LiveKit Docs | Troubleshooting Latency and Timeout Errors with Turn Detection on AWS | Deploying LiveKit | LiveKit docs
f
I am calling through telephony and then extracting transcription of that call from livekit.. now i had call starting time but i am not able extract the ending time of call. How can i get call ending time?
t
You're asking how to get the call ending time for telephony calls in LiveKit. Short answer: use LiveKit lifecycle events or participant status—these provide reliable end timestamps you can tie to your transcriptions. Options (pick one that fits your setup): • Webhooks (recommended) a. Listen for the participant lifecycle events
participant_left
or
room_finished
. b. Use the event's
createdAt
timestamp (UNIX seconds) as the call end time. • SIP participant attribute a. Monitor
sip.callStatus
for the SIP participant. b. When it becomes
hangup
, record that timestamp as the end time. • Analytics API (LiveKit Cloud) a. Query session details (
GET /api/project/{project_id}/sessions/{session_id}
). b. Read the
endTime
field (ISO format) for the call end. Recommended flow: 1. Enable webhooks and capture
participant_left
→ use
createdAt
. 2. Correlate that event to your transcription by room name or participant identity. 3. Optionally cross-check with
sip.callStatus == "hangup"
or Analytics
endTime
for verification. Do you want the webhook payload example and a short code snippet to parse
createdAt
for your language (Node/Python)? Sources: Webhooks | LiveKit docs | SIP participant | LiveKit docs | Analytics API | LiveKit docs
f
How can i use sip.callStatus in my code for status tracking?
t
You can track call progress by reading the
sip.callStatus
participant attribute and reacting when it changes. Below are concise examples and the recommended approach. How it works •
sip.callStatus
values include states like
dialing
,
ringing
,
active
, and
hangup
. • Watch for participant attribute changes (or poll attributes) and record the timestamp when the status becomes the value you care about (e.g.,
hangup
). Recommended flow 1. Subscribe to participant attribute changes in the room. 2. When
sip.callStatus
changes, log the timestamp and new value. 3. Correlate with room/participant identity to match transcripts. JavaScript / TypeScript (browser or Node using LiveKit SDK)
Copy code
room.on('participantUpdated', (participant) => {
  // for local SDKs this event fires when participant metadata/attributes change
  const attrs = participant.metadata ? JSON.parse(participant.metadata) : participant.attributes;
  const status = attrs?.['sip.callStatus'];
  if (status) {
    const now = new Date().toISOString();
    console.log(`Participant ${participant.identity} sip.callStatus=${status} at ${now}`);
    if (status === 'hangup') {
      // record end time, finalize transcription, etc.
    }
  }
});
Python (using SDK event hooks)
Copy code
def on_participant_updated(participant):
    attrs = participant.metadata or participant.attributes
    status = attrs.get('sip.callStatus')
    if status:
        now = datetime.utcnow().isoformat() + 'Z'
        print(f"Participant {participant.identity} sip.callStatus={status} at {now}")
        if status == 'hangup':
            # record end time, finalize transcription, etc.
            pass

room.on('participant_updated', on_participant_updated)
Server-side webhook alternative • If you prefer server-side reliable events, listen for
participant_left
or
participant_updated
webhooks and read `sip.callStatus`/`createdAt`. Webhooks give a server-verified timestamp. Notes • Some SDKs expose attributes differently (e.g.,
participant.attributes
vs
participant.metadata
). Inspect the participant object shape in your SDK and parse accordingly. • Use the timestamp from your server (or webhook
createdAt
) if client clocks aren’t trusted. If you tell me which SDK and language you’re using (browser JS, Node, Android, iOS, or Python backend), I’ll give a focused code snippet for that environment.
f
I am using python
t
Thanks — since you’re using Python, here’s a concise, practical way to track
sip.callStatus
and capture call end time. 1) Listen for participant attribute changes • Subscribe to the room’s
participant_attributes_changed
event and check for
sip.callStatus
in the changed attributes. 2) Example (Python)
Copy code
from datetime import datetime, timezone

call_end_times = {}  # map participant.sid -> end_time

@room.on("participant_attributes_changed")
def on_attributes_changed(changed_attrs: dict[str, str], participant):
    # only care about SIP participants
    if participant.kind.name != "PARTICIPANT_KIND_SIP":
        return

    status = changed_attrs.get("sip.callStatus")
    if not status:
        return

    now = datetime.now(timezone.utc)
    print(f"{now.isoformat()} - {participant.identity} sip.callStatus={status}")

    if status == "hangup":
        call_end_times[participant.sid] = now
        # finalize transcription / persist end time here
3) Optional server‑side verification • Also listen to
participant_left
or
room_finished
webhooks and use the webhook
createdAt
timestamp as the authoritative end time if you need server-verified timing. 4) Notes • Common
sip.callStatus
values:
dialing
,
ringing
,
active
,
automation
,
hangup
. • Use server timestamps (webhook
createdAt
) if client clocks aren’t trusted or you need audit-grade timestamps. • Correlate participant identity or room name with your transcription session to attach the end time. Would you like a ready-to-run example that also persists end times to a database (Postgres/Redis) or the webhook payload example to parse
createdAt
? Sources: SIP participant | LiveKit docs | Webhooks | LiveKit docs | Job lifecycle | LiveKit docs | SIP APIs | LiveKit docs
f
where should i put this function outside enntrypoint or inside entrypoint? and also its giving me error like room is not defined.
t
You're seeing "room is not defined" because the event handler needs the
room
object in scope and must be registered after you create/connect the room. Quick guidance and a minimal example showing where to put it. 1) Where to place the handler • Register the handler after you create/connect the
room
and before your main event loop or waiting logic. It can be in the same module as your entrypoint or imported from another module — just ensure the
room
instance is available when you register the callback. 2) Minimal runnable structure (connect → register handler → run)
Copy code
from datetime import datetime, timezone
from livekit import Room  # adjust import to your SDK package
# create/connect the room first
room = Room()
room.connect("wss://your-livekit-server", jwt="YOUR_TOKEN")  # sync or await as required

call_end_times = {}

@room.on("participant_attributes_changed")
def on_attributes_changed(changed_attrs: dict[str, str], participant):
    if participant.kind.name != "PARTICIPANT_KIND_SIP":
        return
    status = changed_attrs.get("sip.callStatus")
    if not status:
        return
    now = datetime.now(timezone.utc)
    print(f"{now.isoformat()} - {participant.identity} sip.callStatus={status}")
    if status == "hangup":
        call_end_times[participant.sid] = now
        # persist/finalize transcription here

# main loop or wait for events
room.wait()  # or your SDK's event loop / asyncio run
3) Common fixes for "room is not defined" • Ensure you import or create
room
in the same scope before using it. • If handler is in another module, export a function that accepts
room
and registers handlers:
Copy code
# handlers.py
def register_handlers(room):
    @room.on("participant_attributes_changed")
    def on_attributes_changed(...):
        ...
Then call
register_handlers(room)
after you construct/connect the room in your entrypoint. 4) If you're using asyncio • Use
await room.connect(...)
, register handlers after connect, and run the asyncio loop (e.g.,
asyncio.run(main())
). Handlers can be async functions if supported. If you share how you create/connect the room (sync vs async and a short snippet), I’ll show the exact placement and a corrected example for your setup.
f
can i pass the parameter in ctx.add_shutdown_callback(my_function) this?
t
Yes — you can pass parameters to a shutdown callback. ctx.add_shutdown_callback expects a callable; use a closure, lambda, or functools.partial to bind arguments. Examples: 1) Closure
Copy code
def make_cb(param):
    def cb():
        # uses param
        print("shutting down, param=", param)
    return cb

ctx.add_shutdown_callback(make_cb(my_param))
2) functools.partial
Copy code
from functools import partial

def my_cb(param):
    print("shutting down, param=", param)

ctx.add_shutdown_callback(partial(my_cb, my_param))
3) Lambda (for simple cases)
Copy code
ctx.add_shutdown_callback(lambda: my_cb(my_param))
Notes: • Callbacks should be zero-argument functions (or async zero-arg if the API supports async). If you need async cleanup, wrap it in a sync lambda that schedules the coroutine (e.g., asyncio.create_task). • Register the callback after you have the
ctx
and the parameter available. Tell me if your callback must be async or you want an example that persists the end time to a DB on shutdown.
f
how can i record telephony session in livekit?
t
You can record telephony sessions in two main ways: LiveKit Cloud egress (recommended for simplicity) or self‑hosted recording. Here’s how to do each and practical tips for telephony calls. LiveKit Cloud egress (recommended) • Use LiveKit’s recording/egress feature to produce audio (and optional mixed track) files for a room. • Start an egress job for the room where the SIP participant is present; egress will capture audio from participants and produce files (e.g., WAV/MP3). • For telephony, record the room that includes the SIP participant so the call audio and transcription mapping align. • Use the Analytics API or egress job response to get output URIs and timestamps. Self‑hosted recording • Run a recorder process that subscribes to the room and saves participant audio. This gives full control but requires you to manage scaling, storage, and failover. • Ensure your recorder subscribes to the SIP participant’s track(s) and writes encoded/PCM audio to files or streams them to storage. Practical steps and tips 1. Choose record target: ◦ Per-participant raw tracks (preferred if you need separate channels). ◦ Mixed output (single combined audio file) for simpler playback. 1. Start recording after the SIP participant is
active
(use
sip.callStatus == "active"
), and stop on
hangup
or
participant_left
(use webhook
createdAt
or
sip.callStatus == "hangup"
for end time). 2. File format: use lossless (WAV) if you need high-quality speech-to-text, or MP3/OGG for storage efficiency. 3. If using cloud egress, capture metadata (room, participant identity, start/end timestamps) and attach to the recording for transcription correlation. 4. For self-hosted recorder, ensure the recorder machine has enough CPU, bandwidth, and uses TURN when behind NAT to avoid dropped media. 5. Persist call start/end times (from
sip.callStatus
and webhooks) and link them to recording file names and transcription segments. Example (conceptual, using an egress API): 1. Detect SIP participant active. 2. Call egress start API with: ◦ room name ◦ output format and destination ◦ mix or individual tracks 1. When participant ends, stop egress (or let egress finish based on room empty) and retrieve output URL. Would you like a concrete example for: • starting/stopping LiveKit Cloud egress via HTTP API, or • a small Python recorder that subscribes and writes per‑participant WAV files?
f
I want to use livekit's cloud egress service.. can you provide me some code implementation for it?
t
Below is a concise, runnable Python example showing two ways to record telephony sessions with LiveKit Cloud egress: • Preferred (recommended): AutoEgress via SIP dispatch rule — records automatically when SIP calls are routed to rooms. • Manual: Start a Room Composite Egress job after a SIP participant becomes active. Replace placeholders (API URL, keys, trunk IDs, bucket/credentials) with your values. 1) AutoEgress via SIP dispatch rule (records calls automatically)
Copy code
from livekit import api
from livekit.api import CreateSIPDispatchRuleRequest, SIPDispatchRule, SIPDispatchRuleIndividual, RoomConfig, RoomEgress, RoomCompositeEgressRequest, EncodedFileOutput, EncodedFileType, GCPUpload

LIVEKIT_URL = "https://your-project.livekit.cloud"
API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
TRUNK_ID = "your-trunk-id"
GCP_BUCKET = "your-gcp-bucket"
GCP_CREDENTIALS_JSON = '{"type":"service_account", ... }'  # full JSON key

client = api.LiveKitAPI(url=LIVEKIT_URL, api_key=API_KEY, api_secret=API_SECRET)

req = CreateSIPDispatchRuleRequest(
    trunk_ids=[TRUNK_ID],
    rule=SIPDispatchRule(
        dispatch_rule_individual=SIPDispatchRuleIndividual(
            room_prefix="call-"
        )
    ),
    room_config=RoomConfig(
        egress=RoomEgress(
            room=RoomCompositeEgressRequest(
                audio_only=True,
                file_outputs=[
                    EncodedFileOutput(
                        filepath="recordings/{room_name}-{time}.ogg",
                        filetype=EncodedFileType.OGG,
                        gcp=GCPUpload(
                            bucket=GCP_BUCKET,
                            credentials=GCP_CREDENTIALS_JSON
                        )
                    )
                ]
            )
        )
    )
)

resp = client.sip.create_sip_dispatch_rule(request=req)
print("Dispatch rule created:", resp)
Notes: • AutoEgress starts recording when rooms are created by SIP dispatch rules. Use
{room_name}
and
{time}
in filepath templates. • You can output to S3/Azure instead of GCP by switching the output config. 2) Manual start of a Room Composite Egress (start/stop programmatically)
Copy code
from livekit import api
from livekit.api import RoomCompositeEgressRequest, EncodedFileOutput, EncodedFileType, S3Upload
import asyncio

LIVEKIT_URL = "https://your-project.livekit.cloud"
API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
S3_BUCKET = "your-s3-bucket"
ROOM_NAME = "call-abc123"

client = api.LiveKitAPI(url=LIVEKIT_URL, api_key=API_KEY, api_secret=API_SECRET)

async def start_recording(room_name: str):
    req = RoomCompositeEgressRequest(
        room_name=room_name,
        audio_only=True,
        file_outputs=[
            EncodedFileOutput(
                filepath=f"recordings/{room_name}.ogg",
                filetype=EncodedFileType.OGG,
                s3=S3Upload(
                    bucket=S3_BUCKET,
                    access_key="AWS_ACCESS_KEY",
                    secret="AWS_SECRET",
                    region="us-east-1"
                )
            )
        ]
    )
    resp = await client.egress.start_room_composite_egress(req)
    print("Egress started, id:", resp.egress_id)
    return resp.egress_id

# Example invocation
asyncio.run(start_recording(ROOM_NAME))
Notes: • Call this after you detect the SIP participant is
active
(e.g., via
sip.callStatus
) and stop the egress when call ends or let it finish when the room empties. •
egress.start_room_composite_egress
returns an
egress_id
you can use to stop or query status. Helpful tips • Use audio-only egress for telephony to save bandwidth and storage. • Ensure your API token has egress permissions (`roomRecord`/egress). • For AutoEgress set at SIP dispatch rule level, you do not need per-call egress orchestration. • Store call start/end timestamps (webhook
participant_left
or
sip.callStatus == "hangup"
) and attach metadata to recordings. Would you like a curl example for the egress API or a version that also polls egress job status and downloads the final file? Sources: sip | livekit/livekit_composite | DeepWiki | Egress examples | LiveKit docs | Egress output types | LiveKit docs | Egress API | LiveKit docs | Auto egress | LiveKit docs
f
how can i integrate this function with my session?
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
f
I am running my code like below mention: if name == "_main_": cli.run_app( WorkerOptions(...) ) in entrypoint function i have agent session which will run when sip dispatch request will come.. so how can i integrate the recording function in it?