### Basic Handler Initialization in Go Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-handler.md Demonstrates the basic setup for initializing a handler, including loading configuration, creating a message bus, and starting the handler. This code should be used when setting up a new handler process. ```go // Load configuration conf, err := config.NewPipelineConfig(configYAML, startRequest) if err != nil { log.Fatal(err) } // Create message bus rc, err := redis.GetRedisClient(conf.Redis) if err != nil { log.Fatal(err) } bus := psrpc.NewRedisMessageBus(rc) // Create and run handler handler, err := handler.NewHandler(conf, bus) if err != nil { log.Fatal(err) } handler.Run() // Blocks until completion ``` -------------------------------- ### Minimal LiveKit Egress Configuration Source: https://github.com/livekit/egress/blob/main/_autodocs/quick-start.md Example configuration file for starting the LiveKit Egress service. Ensure you replace placeholders with your actual API key, secret, and WebSocket URL. ```yaml api_key: your-api-key api_secret: your-api-secret ws_url: wss://livekit.example.com redis: address: localhost:6379 ``` -------------------------------- ### Start Room Composite Egress Programmatically (Go) Source: https://github.com/livekit/egress/blob/main/_autodocs/quick-start.md Initiate a room composite egress request using the LiveKit Server SDK for Go. This example configures MP4 output to S3. ```go package main import ( "context" "log" lksdk "github.com/livekit/server-sdk-go/v2" "github.com/livekit/protocol/livekit" ) func main() { // Create LiveKit client client := lksdk.NewRoomServiceClient("https://livekit.example.com", "api-key", "api-secret") // Start room composite egress res, err := client.StartRoomCompositeEgress(context.Background(), &livekit.RoomCompositeEgressRequest{ RoomName: "my-room", Layout: "speaker", AudioCodec: livekit.AudioCodec_AAC, VideoCodec: livekit.VideoCodec_H264, Output: &livekit.EncodedFileOutput{ FileType: "mp4", Filepath: "recordings/{room_name}-{time}.mp4", S3: &livekit.S3Upload{ AccessKey: os.Getenv("AWS_ACCESS_KEY"), Secret: os.Getenv("AWS_SECRET_KEY"), Region: "us-east-1", Bucket: "my-bucket", }, }, }) if err != nil { log.Fatal(err) } log.Printf("Started egress: %s", res.EgressId) } ``` -------------------------------- ### Image Output Configuration Example Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-output-config.md Example of configuring image output with a specific codec, filename prefix, dimensions, frame rate, and S3 storage. ```protobuf image_outputs: [{ image_codec: "jpeg", filename_prefix: "thumbnail", width: 1280, height: 720, fps: 1.0, s3: { bucket: "my-thumbnails", region: "us-east-1" } }] ``` -------------------------------- ### Storage Configuration Example Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-output-config.md An example of a YAML configuration for storage, specifying bucket, region, and credentials for S3. ```yaml storage: prefix: "egress/2024-01" generate_presigned_url: true s3: bucket: my-recordings region: us-east-1 access_key: AKIAIOSFODNN7EXAMPLE secret: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY ``` -------------------------------- ### LiveKit Egress Configuration File Example Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-config.md An example YAML configuration file for LiveKit Egress, demonstrating required API credentials, WebSocket URL, Redis settings, and optional parameters for ports, storage, CPU cost, and latency tuning. ```yaml # Required api_key: your-api-key api_secret: your-api-secret ws_url: wss://livekit.example.com redis: address: localhost:6379 db: 0 # Optional health_port: 8081 template_port: 7980 prometheus_port: 8888 debug_handler_port: 9090 insecure: false enable_chrome_sandbox: false cluster_id: us-east-1 max_upload_queue: 60 disallow_local_storage: false # Session limits session_limits: file_output_max_duration: 1h stream_output_max_duration: 90m segment_output_max_duration: 3h image_output_max_duration: 30m # Storage storage: s3: region: us-east-1 bucket: my-bucket # CPU cost cpu_cost: max_cpu_utilization: 0.8 max_memory: 64 room_composite_cpu_cost: 4.0 web_cpu_cost: 4.0 track_composite_cpu_cost: 2.0 track_cpu_cost: 1.0 max_pulse_clients: 60 # Latency tuning (optional) latency: jitter_buffer_latency: 2s audio_mixer_latency: 2750ms pipeline_latency: 3s ``` -------------------------------- ### Start LiveKit Egress Service Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-server.md Loads configuration, initializes Redis client and message bus, sets up an I/O client for status reporting, and then starts the Egress server. Ensure Redis is accessible and configuration is valid. ```go // Load configuration conf, err := config.NewServiceConfig(configYAML) if err != nil { log.Fatal(err) } // Get Redis client rc, err := redis.GetRedisClient(conf.Redis) if err != nil { log.Fatal(err) } // Create message bus bus := psrpc.NewRedisMessageBus(rc) // Create I/O client for status reporting ioClient, err := info.NewSessionReporter(&conf.BaseConfig, bus) if err != nil { log.Fatal(err) } // Create server server, err := server.NewServer(conf, bus, ioClient) if err != nil { log.Fatal(err) } // Start service if err := server.Run(); err != nil { log.Fatal(err) } ``` -------------------------------- ### Server Shutdown Usage Examples Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-server.md Illustrates how to use the Shutdown method for both graceful and immediate server termination. ```go // Graceful shutdown: no new requests, finish active ones server.Shutdown(true, false) // Immediate shutdown server.Shutdown(true, true) ``` -------------------------------- ### Server.StartTemplatesServer Method Signature Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-server.md Signature for starting the HTTP server that serves room composite templates. Requires a filesystem containing template files. ```go func (s *Server) StartTemplatesServer(fs fs.FS) error ``` -------------------------------- ### Track Egress to Multiple Formats Example Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-output-config.md Example of configuring a track egress to multiple formats: file (S3), stream (SRT), and WebSocket. ```protobuf track_egress: { room_id: "my_room", track_id: "TR_SKasdXCVgHsei", output: { file: [{ filepath: "tracks/{track_id}-{time}.mp4", s3: { bucket: "my-bucket" } }], stream: [{ protocol: SRT, urls: ["srt://stream.example.com:10000"] }], websocket: [{ urls: ["ws://processor.local:8080/media"] }] } } ``` -------------------------------- ### Install Chrome in Dockerfile Source: https://github.com/livekit/egress/blob/main/build/chrome/README.md Add this to your Dockerfile to install Chrome. It copies the installer and runs it with the target platform argument. ```dockerfile ARG TARGETPLATFORM COPY --from=livekit/chrome-installer:124.0.6367.201 /chrome-installer /chrome-installer RUN /chrome-installer/install-chrome "$TARGETPLATFORM" ENV PATH=${PATH}:/chrome ENV CHROME_DEVEL_SANDBOX=/usr/local/sbin/chrome-devel-sandbox ``` -------------------------------- ### File Path Substitution Examples Source: https://github.com/livekit/egress/blob/main/_autodocs/quick-start.md Demonstrates dynamic filename generation using various templates for egress outputs. ```text "" → testroom-2024-01-15T143025.mp4 "{room_name}/{time}.mp4" → testroom/2024-01-15T143025.mp4 "{track_type}-{track_id}.mp4" → audio-TR_SKasdXCVgHsei.mp4 ``` -------------------------------- ### Get Output Type Compatible With Codecs Example Source: https://github.com/livekit/egress/blob/main/_autodocs/types.md Example usage of GetOutputTypeCompatibleWithCodecs to find a compatible output type for MP4. ```go audioCodecs := map[types.MimeType]bool{ types.MimeTypeAAC: true, } videoCodecs := map[types.MimeType]bool{ types.MimeTypeH264: true, } outputType := types.GetOutputTypeCompatibleWithCodecs( []types.OutputType{types.OutputTypeMP4, types.OutputTypeTS}, audioCodecs, videoCodecs, ) // Returns OutputTypeMP4 ``` -------------------------------- ### Start Room Composite Egress Programmatically (Node.js) Source: https://github.com/livekit/egress/blob/main/_autodocs/quick-start.md Initiate a room composite egress request using the LiveKit Server SDK for Node.js. This example configures MP4 output to S3. ```javascript const { AccessToken, RoomServiceClient } = require('livekit-server-sdk'); const roomService = new RoomServiceClient( 'https://livekit.example.com', 'api-key', 'api-secret' ); const options = { layout: 'speaker', audioCodec: 'AAC', videoCodec: 'H264', output: { fileType: 'mp4', filepath: 'recordings/{room_name}-{time}.mp4', s3: { accessKey: process.env.AWS_ACCESS_KEY, secret: process.env.AWS_SECRET_KEY, region: 'us-east-1', bucket: 'my-bucket', }, }, }; const res = await roomService.startRoomCompositeEgress('my-room', options); console.log('Started egress:', res.egressId); ``` -------------------------------- ### WebSocket Output Configuration Example Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-output-config.md Example of configuring track egress to a WebSocket endpoint, specifying the track ID and the WebSocket URLs. ```protobuf track_egress: { track_id: "TR_SKasdXCVgHsei", websocket_outputs: [{ urls: ["ws://localhost:8080/media"], disable_loopback_test: false }] } ``` -------------------------------- ### Start Room Composite Egress Programmatically (Python) Source: https://github.com/livekit/egress/blob/main/_autodocs/quick-start.md Initiate a room composite egress request using the LiveKit Server SDK for Python. This example configures MP4 output to S3. ```python from livekit.server_sdk import RoomServiceClient from livekit.protocol.egress import * room_service = RoomServiceClient( url="https://livekit.example.com", api_key="api-key", api_secret="api-secret" ) response = room_service.start_room_composite_egress( room="my-room", layout="speaker", audio_codec=AudioCodec.AUDIO_CODEC_AAC, video_codec=VideoCodec.VIDEO_CODEC_H264, output=EncodedFileOutput( file_type="mp4", filepath="recordings/{room_name}-{time}.mp4", s3=S3Upload( access_key=os.getenv("AWS_ACCESS_KEY"), secret=os.getenv("AWS_SECRET_KEY"), region="us-east-1", bucket="my-bucket", ), ), ) print(f"Started egress: {response.egress_id}") ``` -------------------------------- ### UpdateStream Go Example Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-output-config.md Example Go code demonstrating how to create and send an UpdateStreamRequest to add a fallback stream URL. ```go req := &livekit.UpdateStreamRequest{ EgressId: "EG_...", AddUrls: []string{ "rtmp://fallback.example.com/live/stream", }, } info, err := handler.UpdateStream(ctx, req) ``` -------------------------------- ### File Path Examples Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-output-config.md Illustrates various file path templates for dynamic filename generation in egress recordings. ```plaintext "" → testroom-2022-10-04T011306.mp4 "livekit-recordings/" → livekit-recordings/testroom-2022-10-04T011306.mp4 "{room_name}/{time}" → testroom/2022-10-04T011306.mp4 "{room_id}-{publisher_identity}.mp4" → 10719607-f7b0-4d82-afe1-06b77e91fe12-alice.mp4 "{track_type}-{track_source}-{track_id}" → audio-microphone-TR_SKasdXCVgHsei.ogg ``` -------------------------------- ### Start Room Recording (Go) Source: https://github.com/livekit/egress/blob/main/_autodocs/README.md Initiates a composite egress for a LiveKit room, saving the recording as an MP4 file to an S3 bucket. Requires the LiveKit Go SDK. ```go client := lksdk.NewRoomServiceClient("url", "key", "secret") client.StartRoomCompositeEgress(ctx, &livekit.RoomCompositeEgressRequest{ RoomName: "my-room", Layout: "speaker", Output: &livekit.EncodedFileOutput{ FileType: "mp4", Filepath: "{room_name}-{time}.mp4", S3: &livekit.S3Upload{ Bucket: "my-bucket", Region: "us-east-1", }, }, }) ``` -------------------------------- ### Start LiveKit Egress Service Source: https://github.com/livekit/egress/blob/main/_autodocs/quick-start.md Start the LiveKit Egress service using the configuration file. The EGRESS_CONFIG_FILE environment variable must be set. ```bash export EGRESS_CONFIG_FILE=/path/to/config.yaml ./egress ``` -------------------------------- ### Server.StartTemplatesServer Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-server.md Starts an HTTP server for serving room composite templates. This server is used by Chrome for rendering room composites and runs on a configured port. ```APIDOC ## Server.StartTemplatesServer ### Description Starts HTTP server for room composite templates. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **fs** (fs.FS) - Required - Filesystem containing template files ### Returns - `error` — Server startup error ### Description Serves HTML/CSS/JS templates used by Chrome for room composite rendering. Runs on configured template port (default 7980). ``` -------------------------------- ### RTMP Configuration Example Destinations Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-output-config.md Examples of destination URLs for RTMP and SRT streaming protocols. ```plaintext rtmp://stream.twitch.tv/live/your_stream_key rtmp://rtmp.youtube.com/live2/your_stream_key mux://your_mux_stream_id srt://streaming.example.com:10000?streamid=my_stream ``` -------------------------------- ### Track Composite with Multiple Output Types Example Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-output-config.md Example of configuring a track composite egress with multiple output types: file (S3), and image thumbnails (S3). ```protobuf track_composite_egress: { room_id: "my_room", audio_tracks: [ { participant_identity: "alice" }, { participant_identity: "bob" } ], video_track: { participant_identity: "alice" }, output: { file: { filepath: "composites/{room_name}-{time}.mp4", s3: { bucket: "my-bucket" } }, images: { filename_prefix: "thumbs/{time}", fps: 0.5, width: 320, height: 240, s3: { bucket: "my-bucket" } } } } ``` -------------------------------- ### Room Composite to Multiple Destinations Example Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-output-config.md Example of configuring a room composite egress to multiple destinations: file (S3), stream (RTMP), and segments (HLS). ```protobuf room_composite_egress: { room_id: "my_room", layout: "speaker", video_codec: H264, audio_codec: AAC, output: { file: { filepath: "recordings/{room_name}-{time}.mp4", s3: { bucket: "my-bucket", region: "us-east-1" } }, stream: { protocol: RTMP, urls: ["rtmp://twitch.tv/live/stream_key"] }, segments: { protocol: HLS, filename_prefix: "segments/part", playlist_name: "segments/playlist.m3u8" } } } ``` -------------------------------- ### Start Egress Service with Command Line Argument Source: https://github.com/livekit/egress/blob/main/_autodocs/deployment-and-operations.md Launches the egress service using the 'run' command, optionally specifying a configuration file path. ```bash $ egress run [--config /path/to/config.yaml] ``` -------------------------------- ### Server.Run Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-server.md Starts the egress service and blocks until shutdown is initiated. It registers the service, listens for requests, manages handler lifecycles, and monitors resources. ```APIDOC ## Server.Run ### Description Starts the service and blocks until shutdown. ### Method GET ### Endpoint / ### Parameters None ### Returns - `error` — Runtime error (if any) ### Behavior - Registers service with cluster for request routing - Listens for egress requests via PSRPC - Manages handler process lifecycle - Monitors resource utilization - Gracefully drains active requests on shutdown ``` -------------------------------- ### SetReplayTiming Function Source: https://github.com/livekit/egress/blob/main/_autodocs/pipeline-architecture.md Configures playback timing for concurrent live recording and playback. Specify start time in Unix nanoseconds and duration in milliseconds. ```go func (c *Controller) SetReplayTiming(startAt, durationMs int64) ``` -------------------------------- ### Start Egress RPC Method Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-server.md Initiates a new egress recording or streaming request. This RPC endpoint is used by clients to start egress jobs, specifying room, request type, and output configuration. ```protobuf rpc StartEgress(rpc.StartEgressRequest) returns (livekit.EgressInfo) ``` -------------------------------- ### Example Debug Log Output Source: https://github.com/livekit/egress/blob/main/_autodocs/deployment-and-operations.md An example of a structured JSON log message from the egress service, including level, timestamp, caller information, message, and version. ```json { "level": "info", "ts": 1696420800.123, "caller": "server/server.go:150", "msg": "service ready", "version": "v0.10.5" } ``` -------------------------------- ### StartEgress Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-server.md Starts a new egress request by initiating a handler process on the server. It takes a request object containing egress details and returns the initial EgressInfo. ```APIDOC ## StartEgress ### Description Starts a new egress request. ### Method RPC ### Endpoint /StartEgress ### Parameters #### Request Body - **egress_id** (string) - Required - Unique egress identifier - **room_id** (string) - Required - LiveKit room to record - **request** (rpc.StartEgressRequest) - Required - Type-specific request (room_composite, web, track, etc.) - **output** (rpc.EgressOutput) - Required - Output configuration (file, stream, segments, etc.) ### Response #### Success Response (200) - **egress_id** (string) - Egress identifier - **room_id** (string) - Room identifier - **status** (string) - Current status (STARTING, RUNNING, FINISHED, FAILED) - **error** (string) - Error message (if failed) - **started_at** (timestamp) - Start timestamp - **updated_at** (timestamp) - Last update timestamp - **result** (object) - Output result (file info, stream info, etc.) #### Error Handling - **Unavailable**: Server at max CPU/memory capacity - **InvalidArgument**: Invalid request configuration - **AlreadyExists**: Egress already running ``` -------------------------------- ### Install LiveKit Egress Docker Image Source: https://github.com/livekit/egress/blob/main/_autodocs/quick-start.md Pull the latest LiveKit Egress Docker image from Docker Hub. ```bash docker pull livekit/egress ``` -------------------------------- ### Run Egress Service with Configuration File Source: https://github.com/livekit/egress/blob/main/_autodocs/deployment-and-operations.md Starts the egress service using a configuration file mounted into the container. Ensure the EGRESS_CONFIG_FILE environment variable points to the correct path within the container. ```bash export EGRESS_CONFIG_FILE=/etc/egress/config.yaml docker run -v /etc/egress:/etc/egress livekit/egress ``` -------------------------------- ### Server.Run Method Signature Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-server.md Signature for the Run method, which starts the egress service and operates until shutdown. It handles request registration, listening, and resource monitoring. ```go func (s *Server) Run() error ``` -------------------------------- ### TimeProvider Interface Source: https://github.com/livekit/egress/blob/main/_autodocs/pipeline-architecture.md Defines the interface for providing current and start times within the pipeline. Used for synchronization and timing. ```go type TimeProvider interface { GetCurrentTime() time.Duration GetStartTime() time.Duration } ``` -------------------------------- ### Configure AWS S3 Storage Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-config.md Example configuration for storing egress output in AWS S3. Ensure credentials and bucket details are correctly set. ```yaml storage: s3: access_key: AWS_ACCESS_KEY_ID secret: AWS_SECRET_ACCESS_KEY session_token: AWS_SESSION_TOKEN region: us-east-1 bucket: my-bucket endpoint: s3.amazonaws.com force_path_style: false max_retries: 3 max_retry_delay: 5s min_retry_delay: 100ms proxy_config: url: http://proxy.example.com:8080 username: proxy_user password: proxy_pass ``` -------------------------------- ### Run Egress Service with Configuration Body Source: https://github.com/livekit/egress/blob/main/_autodocs/deployment-and-operations.md Starts the egress service using a configuration provided directly as an environment variable. The configuration is read from a local file and passed via EGRESS_CONFIG_BODY. ```bash export EGRESS_CONFIG_BODY="$(cat /path/to/config.yaml)" docker run -e EGRESS_CONFIG_BODY livekit/egress ``` -------------------------------- ### Example Usage of ErrArray Source: https://github.com/livekit/egress/blob/main/_autodocs/errors.md Demonstrates how to use the ErrArray to collect and check multiple errors. Use this pattern when performing several operations that might fail. ```go var errs errors.ErrArray errs.Check(validateCodec(codec1)) errs.Check(validateCodec(codec2)) if err := errs.ToError(); err != nil { return err } ``` -------------------------------- ### Launch Egress Handler Process Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-server.md Launches a new egress handler process. It creates an IPC listener, starts the process, and waits for the HandlerReady IPC call. Use this when initiating a new egress job. ```go func Launch(ctx context.Context, handlerID string, req *rpc.StartEgressRequest, info *livekit.EgressInfo, cmd *exec.Cmd) error ``` -------------------------------- ### Production Egress Configuration Source: https://github.com/livekit/egress/blob/main/_autodocs/deployment-and-operations.md A comprehensive configuration example for production environments, covering API credentials, cluster/node IDs, Redis, HTTP server ports, resource limits, session limits, storage settings, Chrome configuration, logging, and feature flags. ```yaml # API credentials api_key: your-api-key api_secret: your-api-secret ws_url: wss://livekit.example.com cluster_id: us-east-1 node_id: egress-1 # optional, auto-generated if omitted # Redis redis: address: redis-cluster.local:6379 username: redis password: redis-password db: 0 # HTTP Servers health_port: 8081 template_port: 7980 prometheus_port: 8888 debug_handler_port: 9090 # Resource Limits cpu_cost: max_cpu_utilization: 0.8 max_memory: 64 max_pulse_clients: 60 memory_source: cgroup memory_kill_grace_sec: 3 # Session Limits session_limits: file_output_max_duration: 24h stream_output_max_duration: 6h segment_output_max_duration: 12h image_output_max_duration: 6h # Storage storage: s3: bucket: livekit-egress-prod region: us-east-1 # Use IAM role if available # Otherwise provide credentials access_key: ${AWS_ACCESS_KEY_ID} secret: ${AWS_SECRET_ACCESS_KEY} # Chrome Configuration enable_chrome_sandbox: true template_base: http://templates.internal:7980/ # Logging logging: level: info json: true # Feature Flags enable_sync_engine: true enable_one_shot_sender_report_sync: false # Debugging debug: enable_profiling: true s3: bucket: livekit-debug-logs region: us-east-1 ``` -------------------------------- ### Configure Room Composite Egress to S3 Source: https://github.com/livekit/egress/blob/main/_autodocs/quick-start.md YAML configuration for starting a room composite egress to an S3 bucket. Specifies the room, layout, and S3 output details. ```yaml # Configuration room_composite_egress: room_id: "my-room" layout: "speaker" output: file: filepath: "recordings/{room_name}-{time}.mp4" s3: bucket: "my-bucket" ``` -------------------------------- ### Server Status Response Structure Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-server.md Example JSON structure for the server status response, including CPU load, active requests, process count, and available memory. ```json { "CpuLoad": 2.5, "ActiveRequests": 5, "ProcessCount": 3, "AvailableMemory": 28.5 } ``` -------------------------------- ### Configure Room Composite Egress to RTMP Stream Source: https://github.com/livekit/egress/blob/main/_autodocs/quick-start.md YAML configuration for starting a room composite egress to an RTMP stream, such as for Twitch. Includes the room ID and stream output URL. ```yaml room_composite_egress: room_id: "my-room" output: stream: protocol: RTMP urls: - "rtmp://live.twitch.tv/live/YOUR_STREAM_KEY" ``` -------------------------------- ### Prometheus Scrape Configuration for Egress Metrics Source: https://github.com/livekit/egress/blob/main/_autodocs/deployment-and-operations.md Example Prometheus configuration to scrape metrics from multiple egress instances. Assumes egress instances are accessible via their metrics port (8888). ```yaml scrape_configs: - job_name: 'egress-metrics' static_configs: - targets: ['egress-1:8888', 'egress-2:8888', 'egress-3:8888'] ``` -------------------------------- ### Create New Pipeline Controller with Custom Source Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-handler.md Initializes a new pipeline controller with a custom source builder. The source builder handles GStreamer callbacks for synchronization. ```go func NewWithSource( ctx context.Context, conf *config.PipelineConfig, ipcServiceClient ipc.EgressServiceClient, srcBuilder SourceBuilder, ) (*Controller, error) ``` -------------------------------- ### Build LiveKit Egress from Source Source: https://github.com/livekit/egress/blob/main/_autodocs/quick-start.md Clone the LiveKit Egress repository and build the server executable from source. ```bash git clone https://github.com/livekit/egress.git cd egress go build -o egress ./cmd/server ``` -------------------------------- ### New Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-handler.md Creates a new pipeline controller with a default LiveKit SDK source. This is suitable for standard egress scenarios. ```APIDOC ## New ### Description Creates a new pipeline controller with a default source. ### Method Signature ```go func New(ctx context.Context, conf *config.PipelineConfig, ipcServiceClient ipc.EgressServiceClient) (*Controller, error) ``` ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Context for pipeline initialization - **conf** (*config.PipelineConfig) - Required - Pipeline configuration - **ipcServiceClient** (ipc.EgressServiceClient) - Required - IPC client for status updates ### Returns - `*Controller` — Initialized pipeline controller - `error` — Initialization error ### Throws - **ErrGstPipelineError** - GStreamer pipeline creation failed - **ErrNoCompatibleCodec** - No codec compatible with all outputs ### Description Creates a pipeline controller with a standard LiveKit SDK source. For custom sources (testfeeder, replay export), use NewWithSource instead. ``` -------------------------------- ### Create New Pipeline Controller Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-handler.md Initializes a new pipeline controller with a default LiveKit SDK source. Use NewWithSource for custom sources. ```go func New(ctx context.Context, conf *config.PipelineConfig, ipcServiceClient ipc.EgressServiceClient) (*Controller, error) ``` -------------------------------- ### Controller.SetReplayTiming Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-handler.md Sets timing parameters for replay mode, controlling playback start and duration. ```APIDOC ## Controller.SetReplayTiming ### Description Sets timing parameters for replay mode. ### Method Signature ```go func (c *Controller) SetReplayTiming(startAt, durationMs int64) ``` ### Parameters #### Path Parameters - **startAt** (int64) - Required - Start timestamp (Unix nanos) - **durationMs** (int64) - Required - Duration in milliseconds ### Behavior Synchronizes pipeline with replay parameters for coordinated room playback scenarios. ``` -------------------------------- ### Controller Initialization Function Source: https://github.com/livekit/egress/blob/main/_autodocs/pipeline-architecture.md This Go function signature shows how to initialize the pipeline controller, taking context, configuration, and an IPC service client as arguments. ```go func New(ctx context.Context, conf *config.PipelineConfig, ipcServiceClient ipc.EgressServiceClient) (*Controller, error) ``` -------------------------------- ### Resource Sizing Guidelines for Egress Instances Source: https://github.com/livekit/egress/blob/main/_autodocs/deployment-and-operations.md Provides recommended CPU and RAM allocations per concurrent request for different egress job types (RoomComposite, TrackComposite, Track). ```text Per Instance: RoomComposite: 4 CPU, 1.5 GB RAM (1 concurrent) TrackComposite: 2 CPU, 1.0 GB RAM (2-4 concurrent) Track: 0.5 CPU, 0.5 GB RAM (8-16 concurrent) Calculation: ConcurrentRequests = min(MaxCPU / CostPerRequest, Memory / MemPerRequest) ``` -------------------------------- ### ErrNoConfig: Missing Configuration Source: https://github.com/livekit/egress/blob/main/_autodocs/errors.md This error indicates that no configuration file or config body was provided at service startup. It is an internal error. ```go var ErrNoConfig = psrpc.NewErrorf(psrpc.Internal, "missing config") ``` -------------------------------- ### HLS Playlist Structure Source: https://github.com/livekit/egress/blob/main/_autodocs/pipeline-architecture.md Example structure of an HLS M3U8 playlist manifest. Includes target duration and segment information. ```plaintext #EXTM3U #EXT-X-VERSION:3 #EXT-X-TARGETDURATION:4 #EXTINF:3.95, prefix-00000.ts #EXTINF:3.95, prefix-00001.ts ... #EXT-X-ENDLIST (added on EOS) ``` -------------------------------- ### Get Active Egress IDs Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-server.md Retrieves a list of all egress identifiers that are currently active on the server. Useful for monitoring and management. ```go func GetActiveEgressIDs() []string ``` -------------------------------- ### Get Output Type Compatible With Codecs Function Signature Source: https://github.com/livekit/egress/blob/main/_autodocs/types.md Signature for a function that finds the first output type compatible with provided codecs. ```go func GetOutputTypeCompatibleWithCodecs( types []OutputType, audioCodecs map[MimeType]bool, videoCodecs map[MimeType]bool, ) OutputType ``` -------------------------------- ### Record Entire Room to MP4 using LiveKit CLI Source: https://github.com/livekit/egress/blob/main/_autodocs/quick-start.md Use the LiveKit CLI to create a room composite egress, recording the entire room session to an MP4 file stored in S3. ```bash # Record entire room to MP4 livekit-cli egress create room-composite \ --room my-room \ --output-file s3://bucket/recording.mp4 ``` -------------------------------- ### Health Check Endpoint Source: https://github.com/livekit/egress/blob/main/_autodocs/README.md Example command to perform a health check on the LiveKit egress service using curl. This verifies if the service is running and responsive. ```bash curl http://localhost:8081/healthz ``` -------------------------------- ### Capture and Analyze CPU Profile Source: https://github.com/livekit/egress/blob/main/_autodocs/deployment-and-operations.md Generate a CPU profile for the egress service using the debug handler and analyze it with the Go pprof tool. This helps identify performance bottlenecks. ```bash # Via debug handler (30 seconds) curl http://localhost:9090/debug/pprof/profile?seconds=30 > cpu.pprof # Analyze go tool pprof cpu.pprof ``` -------------------------------- ### Signal Handler Initialization Complete Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-server.md Signals that an egress handler has finished its initialization. Call this after the handler process has successfully started and is ready to receive commands. ```go func HandlerStarted(egressID string) error ``` -------------------------------- ### Web Source Parameters Configuration Source: https://github.com/livekit/egress/blob/main/_autodocs/pipeline-architecture.md Defines the configuration parameters for using a web source, including display settings, layout, and URLs. Used for room composite and web egress. ```go type WebSourceParams struct { AwaitStartSignal bool // Wait for page signal before recording Display string // X display (for headless Chrome) Layout string // Template layout name Token string // LiveKit access token BaseUrl string // Template base URL WebUrl string // Web page URL for web egress } ``` -------------------------------- ### NewServer Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-server.md Creates and initializes the egress service. It sets up the process manager, resource monitor, IPC server, PSRPC server, and optional HTTP handlers for Prometheus and debugging. ```APIDOC ## NewServer ### Description Creates and initializes the egress service. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Returns - `*Server` — Initialized server instance - `error` — Initialization error ### Throws - `ErrGstPipelineError` - GStreamer initialization failed - `Network errors` - Listener setup failed ``` -------------------------------- ### Egress Test Configuration Source: https://github.com/livekit/egress/blob/main/README.md Create a `config.yaml` file to specify logging level, API keys, LiveKit WebSocket URL, Redis address, and output formats for testing. ```yaml 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 ``` -------------------------------- ### ErrHandlerFailedToStart Error Source: https://github.com/livekit/egress/blob/main/_autodocs/errors.md Signals that a handler process failed to start within the expected timeout. Use for internal service errors where a critical component did not initialize. ```go var ErrHandlerFailedToStart = psrpc.NewErrorf(psrpc.Internal, "handler failed to start") ``` -------------------------------- ### Construct GStreamer Media Pipeline Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-handler.md Builds the complete GStreamer media processing pipeline based on the current configuration. This includes setting up sources, decoders, encoders, and output sinks. ```go func (c *Controller) BuildPipeline() error ``` -------------------------------- ### NewWithSource Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-handler.md Creates a new pipeline controller with a custom source builder, allowing for flexible media source integration. ```APIDOC ## NewWithSource ### Description Creates a pipeline controller with a custom source builder. ### Method Signature ```go func NewWithSource( ctx context.Context, conf *config.PipelineConfig, ipcServiceClient ipc.EgressServiceClient, srcBuilder SourceBuilder, ) (*Controller, error) ``` ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Context for pipeline initialization - **conf** (*config.PipelineConfig) - Required - Pipeline configuration - **ipcServiceClient** (ipc.EgressServiceClient) - Required - IPC client for status updates - **srcBuilder** (SourceBuilder) - Required - Custom source builder function ### Returns - `*Controller` — Initialized pipeline controller - `error` — Initialization error ### Description Allows injection of custom media sources. The source builder receives GStreamer callbacks for synchronization with the pipeline's initialization state. ``` -------------------------------- ### Extract Track Source: https://github.com/livekit/egress/blob/main/_autodocs/README.md Starts an egress job to record a specific track (audio or video) from a room into a file. Supports various file types and storage backends. ```APIDOC ## StartTrackEgress ### Description Starts an egress job to record a specific track (audio or video) from a room into a file. ### Method POST ### Endpoint /egress/start ### Parameters #### Request Body - **room_name** (string) - Required - The name of the room containing the track. - **track_id** (string) - Required - The ID of the track to egress. - **output** (object) - Required - The output configuration for the file. - **file_type** (string) - Required - The desired file type (e.g., "mp4"). - **filepath** (string) - Required - The path or filename for the output file. - **s3** (object) - Optional - S3 upload configuration. - **bucket** (string) - Required - The S3 bucket name. ### Request Example ```json { "room_name": "my-room", "track_id": "TR_SKasdXCVgHsei", "output": { "file_type": "mp4", "filepath": "{track_id}.mp4", "s3": { "bucket": "my-bucket" } } } ``` ### Response #### Success Response (200) - **egress_id** (string) - The unique identifier for the egress job. #### Response Example ```json { "egress_id": "EG_abcdef12345" } ``` ``` -------------------------------- ### Enable Chrome Sandboxing with Docker Source: https://github.com/livekit/egress/blob/main/_autodocs/deployment-and-operations.md Run a Docker container with a custom seccomp profile to enable Chrome sandboxing. Ensure the seccomp profile file is accessible. ```bash docker run \ --security-opt seccomp=chrome-sandboxing-seccomp-profile.json \ livekit/egress ``` -------------------------------- ### ErrNoCompatibleCodec: Incompatible Codec for Outputs Source: https://github.com/livekit/egress/blob/main/_autodocs/errors.md This error indicates that the selected codecs are not compatible with all configured outputs. For example, an audio codec might not be supported by a specific container format. ```go var ErrNoCompatibleCodec = psrpc.NewErrorf(psrpc.InvalidArgument, "no supported codec is compatible with all outputs") ``` -------------------------------- ### CPU Admission Control Logic Source: https://github.com/livekit/egress/blob/main/_autodocs/pipeline-architecture.md Illustrates the admission control logic for CPU usage. Rejects new requests if they would exceed the maximum CPU utilization threshold. ```go if (currentCPU + requestCPU) / totalCPU > MaxCpuUtilization { return ErrNotEnoughCPU } ``` -------------------------------- ### Get Handler IPC Client Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-server.md Obtains an IPC client for communicating with a specific egress handler process. Use this to send commands or receive status updates from a handler. ```go func GetGRPCClient(egressID string) (ipc.EgressHandlerClient, error) ``` -------------------------------- ### Audio-Video File Output Types Source: https://github.com/livekit/egress/blob/main/_autodocs/types.md Lists output types that support both audio and video streams. ```go AudioVideoFileOutputTypes = []OutputType{ OutputTypeMP4, } ``` -------------------------------- ### Define StorageConfig for Cloud Providers Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-config.md Configuration for output storage, supporting multiple cloud providers like S3, Azure, GCP, and AliOSS. ```go type StorageConfig struct { Prefix string GeneratePresignedUrl bool S3 *storage.S3Config Azure *storage.AzureConfig GCP *storage.GCPConfig AliOSS *storage.AliOSSConfig } ``` -------------------------------- ### Get Egress Info Programmatically (Go) Source: https://github.com/livekit/egress/blob/main/_autodocs/quick-start.md Retrieve detailed information about a specific egress job using its ID in Go. Handles file and stream egress results. ```go info, err := client.GetEgress(context.Background(), &livekit.GetEgressRequest{ EgressId: "EG_...", }) if err != nil { log.Fatal(err) } switch info.Result.(type) { case *livekit.EgressInfo_File: file := info.GetFile() log.Printf("Recording: %s (%.2f MB)", file.Filename, float64(file.Size) / 1e6) case *livekit.EgressInfo_Stream: stream := info.GetStream() log.Printf("Streaming to %d destinations", len(stream.Info)) } ``` -------------------------------- ### Basic Docker Deployment of Egress Service Source: https://github.com/livekit/egress/blob/main/_autodocs/deployment-and-operations.md Deploys the egress service using Docker, setting necessary environment variables for LiveKit connection, configuration file path, and volume mounts for configuration and recordings. It also maps ports for health checks and metrics. ```bash docker run \ -e LIVEKIT_API_KEY="your-key" \ -e LIVEKIT_API_SECRET="your-secret" \ -e LIVEKIT_WS_URL="wss://livekit.example.com" \ -e EGRESS_CONFIG_FILE=/config/config.yaml \ -v /local/config:/config \ -v /local/recordings:/recordings \ -p 8081:8081 \ -p 8888:8888 \ livekit/egress ``` -------------------------------- ### Checking Error Type with errors.Is Source: https://github.com/livekit/egress/blob/main/_autodocs/errors.md Example of checking if an error matches a specific predefined error type using `errors.Is`. Use this for handling known error conditions gracefully. ```go import "github.com/livekit/egress/pkg/errors" resp, err := handler.StopEgress(ctx, req) if err != nil { if errors.Is(err, errors.ErrEgressNotFound) { log.Println("Egress not found") } else { log.Printf("Stop failed: %v", err) } } ``` -------------------------------- ### Controller.BuildPipeline Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-handler.md Constructs the GStreamer media pipeline based on the current configuration. ```APIDOC ## Controller.BuildPipeline ### Description Constructs the GStreamer media pipeline. ### Method Signature ```go func (c *Controller) BuildPipeline() error ``` ### Returns - `error` — Pipeline construction error ### Throws - **ErrGstPipelineError** - GStreamer element creation failed - **ErrNoCompatibleCodec** - No codec compatible with all configured outputs - **ErrPadLinkFailed** - Failed to connect pipeline elements ### Description Builds the complete media processing pipeline based on configuration, including: - Media source (SDK client or web browser) - Video decoding and transcoding (if needed) - Audio mixing and encoding (if needed) - Multiple output sinks (file, stream, segments, etc.) - Metadata tracking ``` -------------------------------- ### Image Sink Frame Rate Configuration Source: https://github.com/livekit/egress/blob/main/_autodocs/pipeline-architecture.md Configuration examples for the image sink's frames per second (fps) setting. Dictates the rate of JPEG thumbnail capture. ```plaintext fps: 1.0 → one JPEG per second fps: 0.5 → one JPEG every 2 seconds fps: 30.0 → 30 JPEGs per second ``` -------------------------------- ### Update Streaming Parameters Source: https://github.com/livekit/egress/blob/main/_autodocs/pipeline-architecture.md Demonstrates how to update streaming configurations, which may involve pausing and resuming the pipeline. This is used for live updates without full restarts. ```go controller.SetStreamingParams(urls) // May pause during update ``` -------------------------------- ### Stream to RTMP Source: https://github.com/livekit/egress/blob/main/_autodocs/README.md Starts an egress job to stream a room's composite output to an RTMP endpoint. This is useful for broadcasting live streams to platforms like Twitch or YouTube. ```APIDOC ## StartRoomCompositeEgress ### Description Starts an egress job to stream a room's composite output to an RTMP endpoint. ### Method POST ### Endpoint /egress/start ### Parameters #### Request Body - **room_name** (string) - Required - The name of the room to egress. - **output** (object) - Required - The output configuration for the stream. - **protocol** (enum) - Required - The streaming protocol, must be RTMP. - **urls** (array of strings) - Required - The list of RTMP ingest URLs. ### Request Example ```json { "room_name": "my-room", "output": { "protocol": "RTMP", "urls": ["rtmp://stream.twitch.tv/live/stream_key"] } } ``` ### Response #### Success Response (200) - **egress_id** (string) - The unique identifier for the egress job. #### Response Example ```json { "egress_id": "EG_abcdef12345" } ``` ``` -------------------------------- ### Handler.Run Method Source: https://github.com/livekit/egress/blob/main/_autodocs/api-reference-handler.md The main execution loop for the handler. It manages the handler lifecycle, including initialization, replay coordination, recording, and shutdown. ```go func (h *Handler) Run() ``` -------------------------------- ### Run Local Egress with Chrome Sandboxing Enabled Source: https://github.com/livekit/egress/blob/main/README.md Command to run the LiveKit Egress service with Chrome sandboxing enabled. Requires mounting a seccomp profile and setting the appropriate Docker security option. ```shell docker run --rm \ -e EGRESS_CONFIG_FILE=/out/config.yaml \ -v ~/egress-test:/out \ --security-opt seccomp=chrome-sandboxing-seccomp-profile.json \ livekit/egress ``` -------------------------------- ### SDK Source Parameters Configuration Source: https://github.com/livekit/egress/blob/main/_autodocs/pipeline-architecture.md Defines the configuration parameters for using an SDK source, including track IDs, participant identity, and codec preferences. Used for track and composite track egress. ```go type SDKSourceParams struct { TrackID string // Single track for track egress AudioTrackID string // Audio track for composite VideoTrackID string // Video track for composite Identity string // Participant identity TrackSource string // microphone, screenshare ScreenShare bool VideoInCodec types.MimeType AudioTracks []*TrackSource // Multiple audio for mixing VideoTrack *TrackSource AudioRoutes []AudioRouteConfig CaptureAudioAll bool // Capture all participants } ``` -------------------------------- ### Egress Prometheus Metrics Endpoint Source: https://github.com/livekit/egress/blob/main/_autodocs/deployment-and-operations.md Retrieves Prometheus metrics by sending a GET request to the /metrics endpoint. The response is in Prometheus text format and includes metrics like active handlers and available resources. ```bash GET /metrics Response: 200 OK with Prometheus text format ``` ```text # HELP livekit_egress_active_handlers Active handler count livekit_egress_active_handlers 3 # HELP livekit_egress_cpu_available Available CPU cores livekit_egress_cpu_available 12.5 # HELP livekit_egress_memory_available Available memory GB livekit_egress_memory_available 28.5 # HELP process_resident_memory_bytes Process RSS memory process_resident_memory_bytes 2048000000 # HELP process_cpu_seconds_total CPU time process_cpu_seconds_total 450.23 ``` ```bash $ curl http://localhost:8888/metrics | grep livekit_egress ``` -------------------------------- ### Egress Health Check Endpoint Source: https://github.com/livekit/egress/blob/main/_autodocs/deployment-and-operations.md Performs a GET request to the /healthz or /health endpoint to check the server's health status. Expects a 200 OK response if healthy, or 503 Service Unavailable if not. ```bash GET /healthz GET /health Response: 200 OK or 503 Service Unavailable ``` ```bash $ curl http://localhost:8081/healthz # Returns 200 if healthy ``` -------------------------------- ### Docker Deployment Configuration Source: https://github.com/livekit/egress/blob/main/_autodocs/README.md Shows the command to run the LiveKit egress service using Docker. It includes essential environment variables for API keys, WebSocket URLs, and configuration file paths, as well as port mappings. ```bash docker run \ -e LIVEKIT_API_KEY=key \ -e LIVEKIT_API_SECRET=secret \ -e LIVEKIT_WS_URL=wss://... \ -e EGRESS_CONFIG_FILE=/config/config.yaml \ -v /config:/config \ -p 8081:8081 \ -p 8888:8888 \ livekit/egress ``` -------------------------------- ### Egress Service Signal Handling for Shutdown Source: https://github.com/livekit/egress/blob/main/_autodocs/deployment-and-operations.md Demonstrates how to send OS signals to the egress service for graceful termination (SIGTERM), immediate shutdown (SIGINT), or force shutdown (SIGKILL). ```bash # Graceful termination # Finish active requests, no new requests accepted kill -TERM # Immediate shutdown # Kill all active handlers kill -INT # Force shutdown kill -9 ```