microscopic-dress-75199
12/10/2025, 12:05 AMtall-airline-16756
12/10/2025, 12:05 AMtall-airline-16756
12/10/2025, 12:05 AMmicroscopic-dress-75199
12/10/2025, 12:08 AM"""Helper utilities for LiveKit Egress recording.
This module provides functions for:
- Constructing egress file paths with phone normalization
- Starting room composite egress recordings (audio-only for telephony)
- Stopping egress recordings gracefully
"""
import logging
from datetime import datetime
from typing import Optional
from livekit import api
from livekit.protocol import egress
from ..state.session_state import ReceptionistState
from .fuzzy_matcher import normalize_phone
logger = logging.getLogger("egress_helper")
def construct_egress_filepath(caller_id: str, room_name: str) -> str:
"""Construct file path for egress recording.
File structure: calls/{normalized_phone}/{YYYY-MM-DD}/{room_name}.mp4
Args:
caller_id: Phone number from SIP (will be normalized)
room_name: LiveKit room name (unique identifier)
Returns:
Relative file path for recording
Examples:
>>> construct_egress_filepath("+1-416-555-1234", "RM_abc123")
"calls/4165551234/2025-12-09/RM_abc123.mp4"
>>> construct_egress_filepath("unknown", "RM_xyz789")
"calls/unknown/2025-12-09/RM_xyz789.mp4"
"""
# Normalize phone (e.g., "+1-416-555-1234" -> "4165551234")
normalized = normalize_phone(caller_id)
if not normalized:
normalized = "unknown"
# Canadian date format: YYYY-MM-DD
date_str = datetime.now().strftime("%Y-%m-%d")
# Result: calls/4165551234/2025-12-09/RM_abc123def456.mp4
return f"calls/{normalized}/{date_str}/{room_name}.mp4"
async def start_room_recording(
lkapi: api.LiveKitAPI,
room_name: str,
caller_id: str,
userdata: ReceptionistState,
) -> Optional[str]:
"""Start audio-only room composite egress recording.
Steps:
1. Construct file path using normalized phone and date
2. Create RoomCompositeEgressRequest with audio_only=True
3. Configure dual-channel recording (agent vs caller separation)
4. Call api.egress.start_room_composite_egress()
5. Update userdata with egress_id, status, and file_path
6. Return egress_id or None on error
Args:
lkapi: LiveKitAPI instance from JobContext
room_name: LiveKit room name
caller_id: Phone number from SIP
userdata: ReceptionistState to update with egress info
Returns:
egress_id string if successful, None if failed
Note:
Recording failures are logged but do NOT raise exceptions
to avoid breaking the call. Recording is best-effort.
Audio Configuration:
- audio_only=True: Records only audio (no video encoding)
- audio_mixing=DUAL_CHANNEL_AGENT: Separates agent audio (left)
from caller audio (right) for call quality analysis and compliance
"""
try:
# Step 1: Construct file path
filepath = construct_egress_filepath(caller_id, room_name)
logger.info(f"Starting egress recording: {filepath}")
# Step 2: Create RoomCompositeEgressRequest (audio-only for telephony)
request = api.RoomCompositeEgressRequest(
room_name=room_name,
audio_only=True, # ✓ Audio-only for telephony (no video)
audio_mixing=egress.AudioMixing.DUAL_CHANNEL_AGENT, # ✓ Separate agent/caller audio
file_outputs=[
api.EncodedFileOutput(
file_type=egress.EncodedFileType.MP4,
filepath=filepath,
)
],
)
# Step 3: Call egress API
egress_info = await lkapi.egress.start_room_composite_egress(request)
# Step 4: Update userdata
userdata.egress_id = egress_info.egress_id
userdata.egress_status = "recording"
userdata.egress_file_path = filepath
userdata.egress_started_at = datetime.now()
logger.info(
f"Egress recording started successfully | "
f"egress_id={egress_info.egress_id} | "
f"file={filepath} | "
f"mode=audio_only,dual_channel"
)
# Step 5: Return egress_id
return egress_info.egress_id
except Exception as e:
logger.error(f"Failed to start egress recording: {e}", exc_info=True)
userdata.egress_status = "failed"
return None
async def stop_room_recording(
lkapi: api.LiveKitAPI,
egress_id: str,
userdata: ReceptionistState,
) -> bool:
"""Stop active egress recording.
Steps:
1. Call api.egress.stop_egress(StopEgressRequest(egress_id=egress_id))
2. Update userdata status to "completed" or "failed"
3. Log final file path
4. Return success status
Args:
lkapi: LiveKitAPI instance from JobContext
egress_id: Egress session ID from start_room_recording
userdata: ReceptionistState to update with completion status
Returns:
True if successfully stopped, False otherwise
Note:
Errors are logged but do NOT raise exceptions to avoid
blocking call termination.
"""
try:
# Step 1: Stop egress
logger.info(f"Stopping egress recording: {egress_id}")
request = api.StopEgressRequest(egress_id=egress_id)
egress_info = await lkapi.egress.stop_egress(request)
# Step 2: Update userdata status
# EgressStatus enum values: https://docs.livekit.io/home/egress/api/#egressstatus
if egress_info.status == api.EgressStatus.EGRESS_COMPLETE:
userdata.egress_status = "completed"
logger.info(
f"Egress recording completed | "
f"egress_id={egress_id} | "
f"file={userdata.egress_file_path}"
)
return True
else:
userdata.egress_status = "failed"
logger.warning(
f"Egress stopped but status is not COMPLETE: {egress_info.status}"
)
return False
except Exception as e:
logger.error(f"Failed to stop egress recording: {e}", exc_info=True)
userdata.egress_status = "failed"
return False
below is how i am running egress self hosted :
egress:
image: livekit/egress:latest
restart: unless-stopped
network_mode: "host"
user: "1000:1000"
cap_add:
- SYS_ADMIN # Required for Chrome sandboxing
environment:
- EGRESS_CONFIG_FILE=/etc/egress.yaml
volumes:
- ./egress-config.yaml:/etc/egress.yaml:ro
- ./recordings:/out
depends_on:
- redis
- livekit
below is the error i am getting:
2025-12-10T00:03:15.116Z INFO egress info/io.go:269 egress_failed {"nodeID": "NE_fYj82MvY3rKj", "clusterID": "", "egressID": "EG_RCvnTaKt5ALs", "requestType": "room_composite", "outputType": "file", "error": "Local upload failed: mkdir /calls: permission denied", "code": 400, "details": "End reason: StopEgress API"}
why am i getting permission denied?
I am trying to save recordings inside recordings/calls/
i also have correct permission:
user_name@livekit-host:$ ls -la ./calls/
total 8
drwxrwxrwx 2 user_name user_name 4096 Dec 9 23:30 .
drwxrwxrwx 3 user_name user_name 4096 Dec 9 23:31 ..tall-airline-16756
12/10/2025, 12:08 AM/out (or adjust the egress image config) so relative paths resolve under /out.
• Ensure the target directories exist or allow the container user to create them:
◦ Create the directory tree inside the mounted volume from the host (chown/chmod) or ensure the container user (uid 1000) can write to the mount. Example on host:
i. mkdir -p ./recordings/calls
ii. chown -R 1000:1000 ./recordings
iii. chmod -R 755 ./recordings
• Confirm your egress config uses file outputs with the same base path (e.g., starts with /out/).
Why your host listing looked OK but the container still failed:
• Host permissions for ./calls do not guarantee the container can write to /calls — your container is attempting /calls at the container root, not the mounted ./recordings/calls. The mount maps host ./recordings to container /out, so you must write under /out from inside the container.
If you want, tell me:
• the contents of your egress-config.yaml file (file outputs paths), or
• whether you prefer to change the helper to produce /out/... paths or to change the egress container config so relative paths are resolved under /out.
I can give the exact code or config diff once you confirm which approach you prefer.