LiveKit Egress

repository·main·Indexed 43 days ago

https://github.com/livekit/egress

A service for exporting LiveKit media—including rooms, tracks, or web URLs—into formats such as MP4, HLS, or RTMP streams. It provides four primary egress types: Room composite, Web egress, Track composite, and Track egress, utilizing GStreamer for transcoding and supporting storage providers like S3, Azure, and GCP.

Tokens
4.7K
Snippets
13
Records
22
Agent score
52%

What's inside LiveKit Egress

  1. Overview of LiveKit Egress capabilities

    main

    LiveKit Egress provides APIs to export LiveKit sessions and tracks to various protocols and storage formats. It solves interoperability challenges by allowing you to store sessions for playback, relay streams to CDNs, or process tracks through external services.

    There are four primary egress types:

    1. Room composite: Exports an entire LiveKit room.
    2. Web egress: Recordings not attached to a single LiveKit room (uses a supplied URL).
    3. Track composite: Exports synchronized tracks of a single participant.
    4. Track egress: Exports individual tracks.

    Depending on the request, Egress uses either a Chrome instance with a web template (for room composite) or a supplied URL (for web requests), or the Go SDK directly (for track and track composite requests). The service uses GStreamer to automatically transcode streams when moving between protocols, containers, or encodings.

  2. Use Default LiveKit Recording Templates

    main
    The livekit-egress-web repository contains the default recording templates used by LiveKit Egress. These templates are designed to be deployed alongside and served by the egress service to provide standard layouts for room composite recordings. For detailed information on how to use these layouts, refer to the LiveKit documentation on room composite default layouts.
  3. Build custom Room Composite templates with the Egress Recording Template SDK

    main
    The Egress Recording Template SDK is a lightweight tool designed to help developers build custom Room Composite templates for LiveKit Egress. These templates allow you to define how a LiveKit room is composed (e.g., layout, overlays, branding) when recording or streaming a room to an external output.
  4. Use dynamic placeholders in filenames

    main

    When submitting an egress request, you can use specific placeholders in the filename or filepath parameters to generate dynamic names based on the session context.

    Supported Placeholders

    PlaceholderDescription
    {room_id}The unique ID of the room
    {room_name}The name of the room
    {time}Timestamp in 2006-01-02T150405 format
    {utc}Timestamp in 20060102150405789 format
    {publisher_identity}The identity of the publisher
    {track_id}The unique ID of the track
    {track_type}The type of track (e.g., audio, video)
    {track_source}The source of the track (e.g., microphone)

    Behavior Rules

    • Default Filename: If no filename is provided, it defaults to "{room_name}-{time}".
    • Directories: If the filename ends with a /, the file will be generated inside that directory.
    • Compatibility by Egress Type:
      • Room Composite: Supports {room_id}, {room_name}, {time}, {utc}.
      • Web: Supports {time}, {utc}.
      • Track Composite: Supports {room_id}, {room_name}, {time}, {utc}, {publisher_identity}.
      • Track: Supports all placeholders listed above.
    # Examples of resulting filenames
    "{room_name}/{time}" -> testroom/2022-10-04T011306.mp4
    "{room_id}-{publisher_identity}.mp4" -> 10719607-f7b0-4d82-afe1-06b77e91fe12-david.mp4
    "{track_type}-{track_source}-{track_id}" -> audio-microphone-TR_SKasdXCVgHsei.ogg
  5. Run integration tests for Egress

    main

    To test LiveKit Egress against your own LiveKit rooms, you must have a deployed LiveKit server with a secure websocket URL.

    1. Create a configuration file at egress/test/config.yaml containing your LiveKit credentials, Redis address, and desired test flags.
    2. Join a room using a LiveKit client (e.g., https://example.livekit.io or your own implementation).
    3. Execute the integration test using mage.

    This process validates recording different file types, output settings, and streams against your active room.

    log_level: debug
    api_key: your-api-key
    api_secret: your-api-secret
    ws_url: wss://your-livekit-url.com
    redis:
      address: 192.168.65.2:6379
    room_only: false
    web_only: false
    track_composite_only: false
    track_only: false
    file_only: false
    stream_only: false
    segments_only: false
    dot_files: false
    short: false
    mage integration test/config.yaml
  6. Run LiveKit Egress locally for development

    main

    To run Egress against a local LiveKit server, you must ensure the Egress container can communicate with your host's Redis and LiveKit server.

    Prerequisites

    1. Configure Redis: In your host's redis.conf:
      • Comment out bind 127.0.0.1.
      • Set protected-mode no.
    2. Identify Host IP: Find the IP address that Docker uses to reach your host (e.g., 172.17.0.1 on Linux, or use nslookup host.docker.internal on Mac/Windows).

    Setup Steps

    1. Create a local directory (e.g., ~/egress-test).
    2. Create a config.yaml in that directory. Use the host IP for ws_url and redis.address, and set insecure: true.
    3. Run the container using the following command:
    docker run --rm \
        -e EGRESS_CONFIG_FILE=/out/config.yaml \
        -v ~/egress-test:/out \
        livekit/egress
    # Example local config.yaml
    log_level: debug
    api_key: your-api-key
    api_secret: your-api-secret
    ws_url: ws://192.168.65.2:7880
    insecure: true
    redis:
      address: 192.168.65.2:6379
  7. Enable Chrome sandboxing in Egress

    main

    By default, Room Composite and Web egresses run with Chrome sandboxing disabled to avoid Docker security conflicts. To enable sandboxing, you must:

    1. Set enable_chrome_sandbox: true in your Egress configuration.
    2. Run the Docker container using the provided chrome-sandboxing-seccomp-profile.json security profile to allow the necessary clone and unshare system calls.

    Note: Kubernetes environments often disable seccomp by default, which may allow sandboxing to work without additional configuration.

    docker run --rm \
        -e EGRESS_CONFIG_FILE=/out/config.yaml \
        -v ~/egress-test:/out \
        --security-opt seccomp=chrome-sandboxing-seccomp-profile.json \
        livekit/egress
  8. Configure the LiveKit Egress service

    main

    The Egress service is configured using a YAML file. You can provide this file by setting the EGRESS_CONFIG_FILE environment variable to the file path (mounted via a volume) or by passing the configuration body directly via the EGRESS_CONFIG_BODY environment variable.

    Required Fields

    • api_key: LiveKit server API key (or use LIVEKIT_API_KEY env).
    • api_secret: LiveKit server API secret (or use LIVEKIT_API_SECRET env).
    • ws_url: LiveKit server websocket URL (or use LIVEKIT_WS_URL env).
    • redis:
      • address: The Redis address used by your LiveKit server.
      • username: Redis username.
      • password: Redis password.
      • db: Redis database index.

    Storage Configuration

    You must specify exactly one storage provider. Note that some S3 options can only be set in the global config and cannot be overridden per request.

    S3 Options:

    • access_key, secret, session_token, region, endpoint, bucket.
    • proxy_config: { url, username, password }.
    • max_retries (default: 3).
    • max_retry_delay (default: 5s).
    • min_retry_delay (default: 500ms).
    • aws_log_level (default: LogOff).

    Azure Options:

    • account_name, account_key, container_name.

    GCP Options:

    • credentials_json, bucket.
    • proxy_config: { url, username, password }.

    AliOSS Options:

    • access_key, secret, region, endpoint, bucket.
    # Example minimal config
    api_key: livekit-key
    api_secret: livekit-secret
    ws_url: ws://livekit.example.com
    redis:
      address: redis:6379
      db: 0
    storage:
      s3:
        bucket: my-egress-bucket
        region: us-east-1
  9. Troubleshoot Egress errors

    main

    "no response from egress service"

    • Cause: The LiveKit server cannot connect to the Egress instance via Redis.
    • Fix: Ensure both the LiveKit server and Egress instances can reach the same Redis database.
    • Scaling: If all Egress instances are currently full, you must deploy more instances or configure autoscaling.

    "different error" (General)

    • Fix: Ensure that your egress service, livekit server, server SDK, and livekit-cli are all updated to compatible versions.
  10. Supported output formats by Egress type

    main

    LiveKit Egress supports various output formats depending on the type of egress requested. Files can be uploaded to S3-compatible storage, Azure, or GCP.

    Egress TypeMP4 FileOGG FileWebM FileHLS (TS Segments)RTMP(s) StreamSRT StreamWebSocket StreamThumbnails (JPEGs)
    Room Composite✅✅✅✅✅✅
    Web✅✅✅✅✅✅
    Track Composite✅✅✅✅✅✅
    Track✅✅✅✅
  11. Start the Egress Server lifecycle with Run

    main

    Once initialized, call Run() to start the service. This method registers the StartEgressTopic with the cluster and blocks until the server is signaled to shut down. The server will enter a draining phase once the shutdown signal is received.

    err := s.Run()
    if err != nil {
    	// handle error
    }
  12. Use EgressHelper to manage web recording templates

    main

    The EgressHelper object provides utility methods for web-based LiveKit recording templates to extract necessary connection parameters from the URL and manage the recording lifecycle.

    When a recording starts using a web template, the LiveKit Egress service will point a browser instance to your template URL. You should use EgressHelper to:

    1. Extract the url (LiveKit server URL) and token (access token) from the query string to connect to the room.
    2. Manage the Room instance via setRoom.
    3. Handle layout changes triggered by participant metadata updates.
    4. Signal the start and end of recording via console logs (START_RECORDING and END_RECORDING).
    import EgressHelper from '@livekit/egress-sdk';
    import { Room } from 'livekit-client';
    
    // 1. Get connection details from the URL
    const livekitUrl = EgressHelper.getLiveKitURL();
    const token = EgressHelper.getAccessToken();
    
    // 2. Initialize the room and register it with the helper
    const room = new Room();
    await room.connect(livekitUrl, token);
    EgressHelper.setRoom(room);
    
    // 3. Listen for layout changes (e.g., switching from grid to speaker view)
    EgressHelper.onLayoutChanged((newLayout) => {
      console.log('Switching to layout:', newLayout);
      // Apply your CSS or UI logic here
    });
    
    // 4. Start recording logic
    EgressHelper.startRecording();