fancy-kitchen-89125
12/04/2025, 5:17 PMtall-airline-16756
12/04/2025, 5:17 PMtall-airline-16756
12/04/2025, 5:17 PMdestination_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 Tipsfancy-kitchen-89125
12/04/2025, 5:43 PMtall-airline-16756
12/04/2025, 5:44 PM*.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 docsfancy-kitchen-89125
12/05/2025, 7:56 AMtall-airline-16756
12/05/2025, 7:56 AMparticipant_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 docsfancy-kitchen-89125
12/05/2025, 9:48 AMtall-airline-16756
12/05/2025, 9:48 AMsip.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)
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)
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.fancy-kitchen-89125
12/05/2025, 9:52 AMtall-airline-16756
12/05/2025, 9:53 AMsip.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)
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 docsfancy-kitchen-89125
12/05/2025, 10:11 AMtall-airline-16756
12/05/2025, 10:12 AMroom 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)
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:
# 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.fancy-kitchen-89125
12/05/2025, 11:13 AMtall-airline-16756
12/05/2025, 11:13 AMdef 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
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)
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.fancy-kitchen-89125
12/08/2025, 8:51 AMtall-airline-16756
12/08/2025, 8:51 AMactive (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?fancy-kitchen-89125
12/08/2025, 8:53 AMtall-airline-16756
12/08/2025, 8:53 AMfrom 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)
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 docsfancy-kitchen-89125
12/08/2025, 8:56 AMtall-airline-16756
12/08/2025, 8:56 AMfancy-kitchen-89125
12/08/2025, 9:01 AM