ComusThumbz Documentation
Admin Login

Video Streaming Setup

Video Streaming Server Setup

Page Location: N/A (Server Configuration)
Menu Path: N/A - Server-side setup
Access Level: System Administrator / Server Root Access
Last Updated: 2026-01-02


Overview

This guide covers the complete setup of the LiveKit WebRTC streaming server for ComusThumbz's live webcam streaming feature. LiveKit enables ultra-low-latency (sub-second) browser-to-browser video streaming, allowing creators to broadcast live directly from their webcams without requiring third-party streaming software.

The live streaming feature enables:

  • Creators to broadcast live from settings/golive.php
  • Viewers to watch streams at watchstream.php
  • Interactive chat with real-time messaging and tips
  • Private shows with per-minute token billing
  • Access control (free, password, subscribers-only, PPV, tip goals)

State: Diagram showing: Browser → LiveKit Server → Viewers
Annotations: Show WebRTC flow from broadcaster to server to viewers
-->


System Requirements

Configuration Required:
LiveKit requires a dedicated server or VPS with specific ports and resources. It cannot run on shared hosting.

Server Requirements

Requirement Minimum Recommended Notes
OS Ubuntu 20.04 / Debian 10 Ubuntu 22.04 / Debian 12 Linux only
RAM 2 GB 4+ GB Scales with concurrent viewers
CPU 2 cores 4+ cores Video transcoding is CPU-intensive
Storage 20 GB 50+ GB For logs and temporary files
Network 100 Mbps 1 Gbps Bandwidth scales with viewers

Required Ports

Warning:
These ports MUST be open in your firewall for LiveKit to function:
Port Protocol Purpose Required
7880 TCP WebSocket signaling Yes
7881 TCP RTC over TCP fallback Yes
50000-60000 UDP WebRTC media transport Yes
443 TCP HTTPS (production) Recommended

PHP Requirements (ComusThumbz Server)

Requirement Minimum Notes
PHP Version 8.0+ Required for JWT token generation
hashhmac() Required For HS256 JWT signing
jsonencode() Required For token payload
randombytes() Required For stream key generation

Required PHP Extensions

Extension Required Purpose
json Yes JWT encoding
openssl Yes Random key generation
mbstring Yes String handling

External Tools

Tool Required Version Check Command
Docker Yes 20.10+ docker --version
Docker Compose Yes 2.0+ docker compose version
curl Yes Any curl --version
openssl Yes Any openssl version

Installation Requirements

Config Settings (dat/config.inc.php)

Variable Type Default Description
LIVEKITHOST string wss://your-domain/livekit/ LiveKit WebSocket URL
LIVEKITAPIKEY string (generated) API key for token signing
LIVEKITAPISECRET string (generated) Secret for token signing

Example config entries:

// LiveKit WebRTC Streaming Configuration
define('LIVEKITHOST', 'wss://streaming.yourdomain.com/livekit/');
define('LIVEKITAPIKEY', 'APIxxxxxxxxxxxxx');
define('LIVEKITAPISECRET', 'your-secret-key-here');

File Dependencies

File Path Dependency Type Required Notes
ct/api/v1/controllers/LiveStreamController.php API Endpoint Yes Main streaming API
ct/api/v1/helpers/LiveKitHelper.php Helper Class Yes JWT token generation
ct/includes/TokenBalanceManager.php Include Yes Token transactions
settings/golive.php Frontend Page Yes Creator broadcast page
watchstream.php Frontend Page Yes Viewer page
livestreams.php Frontend Page Yes Stream directory
livekit-client.umd.min.js CDN Script Yes LiveKit browser SDK

Folders Required

Folder Path Permission Created By Notes
ct/config/ 755 Setup Script LiveKit config file
ct/logs/livekit/ 755 Install Script LiveKit logs

Architecture Overview

How LiveKit Streaming Works

┌─────────────────┐     ┌──────────────────┐     ┌─────────────────┐
│   BROADCASTER   │     │  LIVEKIT SERVER  │     │    VIEWERS      │
│  (Creator)      │────▶│  (Media Server)  │────▶│  (Subscribers)  │
│  golive.php    │     │  Docker Container│     │ watchstream.php│
└─────────────────┘     └──────────────────┘     └─────────────────┘
        │                        │                        │
        │                        │                        │
        ▼                        ▼                        ▼
   WebRTC Publish          SFU Routing            WebRTC Subscribe

Video Track - Room Management - Video TrackAudio Track - Participant Auth - Audio Track

  • Data Channel - Media Relay - Chat Messages

Component Overview

Component Location Purpose
LiveKit Server Docker (Port 7880) WebRTC media routing
LiveStreamController ct/api/v1/ Stream management API
LiveKitHelper ct/api/v1/helpers/ JWT token generation
golive.php settings/ Creator broadcast interface
watchstream.php Project root Viewer interface
livestreams.php Project root Stream directory

Installation Methods

Tip:
The automated script handles Docker installation, configuration, and API key generation automatically.

Step 1: Upload the Setup Script

Upload tools/setuplivekitserver.sh to your streaming server.

Step 2: Make Executable and Run

# Make the script executable
chmod +x setuplivekitserver.sh

Run with sudo

sudo ./setuplivekitserver.sh

Step 3: Follow Interactive Prompts

The script will:

  1. Detect your OS (Ubuntu/Debian)
  2. Install Docker if not present
  3. Configure firewall rules
  4. Auto-detect your public IP
  5. Generate API keys
  6. Create LiveKit configuration
  7. Start the LiveKit container
  8. Update your PHP configuration

Step 4: Note Your Credentials

At the end, the script outputs:

API Credentials:

  API Key: APIxxxxxxxxxxxxxxxx

  API Secret: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Warning:
Save these credentials immediately! You'll need them for PHP configuration.

Method 2: Manual Installation (Debian 12)

For manual control or troubleshooting, follow these steps:

Step 1: Install Docker

# Update system
sudo apt update && sudo apt upgrade -y

Install prerequisites

sudo apt install -y apt-transport-https ca-certificates curl gnupg lsb-release

Add Docker GPG key

curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg

Add Docker repository

echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/debian $(lsbrelease -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

Install Docker

sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin

Start and enable Docker

sudo systemctl start docker
sudo systemctl enable docker

Verify installation

docker --version

Step 2: Configure Firewall

# UFW (Ubuntu/Debian)
sudo ufw allow 7880/tcp comment "LiveKit WebSocket"
sudo ufw allow 7881/tcp comment "LiveKit RTC TCP"
sudo ufw allow 50000:60000/udp comment "LiveKit WebRTC Media"

Or iptables directly

sudo iptables -A INPUT -p tcp --dport 7880 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 7881 -j ACCEPT
sudo iptables -A INPUT -p udp --dport 50000:60000 -j ACCEPT

Step 3: Generate API Keys

# Generate API Key (16 bytes, base64)
APIKEY=$(openssl rand -base64 16 | tr -d '/' | tr '+' '-')
echo "API Key: $APIKEY"

Generate API Secret (32 bytes, base64)

APISECRET=$(openssl rand -base64 32 | tr -d '/' | tr '+' '-')
echo "API Secret: $APISECRET"

Step 4: Create LiveKit Configuration

Create /opt/livekit/livekit-config.yaml:

# LiveKit Media Server Configuration
port: 7880
rtc:
portrangestart: 50000
portrangeend: 60000
tcpport: 7881
nodeip: YOURPUBLICIP

keys:

YOURAPIKEY: YOURAPISECRET

room:

autocreate: true
emptytimeout: 300
maxparticipants: 1000

logging:
level: info
sample: false

Warning:
Replace YOUR
PUBLICIP, YOURAPIKEY, and YOURAPISECRET with your actual values!

Step 5: Create Docker Compose File

Create /opt/livekit/docker-compose.yml:

version: '3.9'

services:

livekit:
image: livekit/livekit-server:latest
containername: livekit
restart: unless-stopped
networkmode: host
command: --config /livekit.yaml
volumes:
  • ./livekit-config.yaml:/livekit.yaml:ro

Step 6: Start LiveKit

cd /opt/livekit
docker compose up -d

Verify it's running

docker ps
docker logs livekit

Production Configuration

SSL/TLS Setup with Nginx

Configuration Required:
For production, LiveKit MUST be accessed via HTTPS/WSS for WebRTC to work in modern browsers.

Step 1: Install Nginx and Certbot

sudo apt install -y nginx certbot python3-certbot-nginx

Step 2: Create Nginx Configuration

Create /etc/nginx/sites-available/livekit:

# LiveKit WebRTC Streaming Proxy

Place in /etc/nginx/sites-available/livekit

upstream livekit {
server 127.0.0.1:7880;
}

 

server {
listen 80;
servername streaming.yourdomain.com;
# Redirect HTTP to HTTPS
return 301 https://$host$requesturi;
}
server {
listen 443 ssl http2;
servername streaming.yourdomain.com;
# SSL certificates (Let's Encrypt)
sslcertificate /etc/letsencrypt/live/streaming.yourdomain.com/fullchain.pem;
sslcertificatekey /etc/letsencrypt/live/streaming.yourdomain.com/privkey.pem;
# SSL settings
sslprotocols TLSv1.2 TLSv1.3;
sslpreferserverciphers on;
sslciphers XXXXX-XXXXX-AES128-XXX-SHA256:XXXXX-RSA-AES128-GCM-SHA256;
# LiveKit WebSocket proxy
location /livekit/ {
proxypass http://livekit/;
proxyhttpversion 1.1;
# WebSocket upgrade headers
proxysetheader Upgrade $httpupgrade;
proxysetheader Connection "upgrade";
# Standard proxy headers
proxysetheader Host $host;
proxysetheader X-Real-IP $remoteaddr;
proxysetheader X-Forwarded-For $proxyaddxforwardedfor;
proxysetheader X-Forwarded-Proto $scheme;
# Timeouts for long-lived connections
proxyreadtimeout 86400s;
proxysendtimeout 86400s;
# Disable buffering for real-time
proxybuffering off;
}
}

Step 3: Enable and Obtain SSL Certificate

# Enable site
sudo ln -s /etc/nginx/sites-available/livekit /etc/nginx/sites-enabled/

Test configuration

sudo nginx -t

Obtain SSL certificate

sudo certbot --nginx -d streaming.yourdomain.com

Restart Nginx

sudo systemctl restart nginx

PHP Configuration

Update config.inc.php

Add these lines to ct/dat/config.inc.php:

// =====================================================
// LiveKit WebRTC Streaming Configuration
// =====================================================
// LiveKit WebSocket URL
// Development: ws://YOURIP:7880
// Production: wss://streaming.yourdomain.com/livekit/
define('LIVEKITHOST', 'wss://streaming.yourdomain.com/livekit/');

// API credentials (from setup script)
define('LIVEKITAPIKEY', 'APIxxxxxxxxxxxxx');
define('LIVEKITAPISECRET', 'your-32-byte-secret-key-here');

Enable Live Streaming Feature

Navigate to Admin Panel → Settings → Feature Toggles and enable:

  • featurelivestreaming - Enable/Disable live streaming

Or add directly to the database:

INSERT INTO tblFeatureToggles (featurekey, featureenabled, featuregroup)
VALUES ('featurelivestreaming', 1, 'creatorfeatures')
ON DUPLICATE KEY UPDATE featureenabled = 1;

API Endpoints

The live streaming system provides these API endpoints:

Stream Management

Method Endpoint Description
POST /api/v1/live/start Start a new stream
POST /api/v1/live/{id}/end End a stream
GET /api/v1/live/active List active streams
GET /api/v1/live/{id} Get stream details
POST /api/v1/live/{id}/join Join as viewer
POST /api/v1/live/{id}/leave Leave stream

Chat & Interactions

Method Endpoint Description
GET /api/v1/live/{id}/chat Get chat messages
POST /api/v1/live/{id}/chat Send chat message
POST /api/v1/live/{id}/tip Send tip
POST /api/v1/live/{id}/private-request Request private show

Access Control

Method Endpoint Description
POST /api/v1/live/{id}/unlock Unlock PPV stream
POST /api/v1/live/{id}/verify-password Verify stream password

Frontend Pages

Creator Broadcast Page (settings/golive.php)

Features:

  • Webcam preview and selection
  • Microphone selection
  • Stream title and description
  • Access type selection (free, password, subscribers, PPV, tip goal)
  • Real-time chat panel
  • Tip notifications
  • Private request management
  • Viewer count display

Access Requirements:

  • User must be logged in
  • User must have iscreator = 1 in tblCMSUsers
  • featurelivestreaming must be enabled

Viewer Page (watchstream.php)

Features:

  • Live video player
  • Real-time chat
  • Tip sending
  • Private show requests
  • Viewer count
  • Creator profile sidebar

Stream Directory (livestreams.php)

Features:

  • Grid of active streams
  • Viewer count badges
  • Creator avatars
  • Stream previews (snapshots)
  • Filter by category

Testing Your Setup

Step 1: Verify LiveKit Server

# Check container status
docker ps | grep livekit

Check logs

docker logs livekit

Test WebSocket (should return error, which means it's responding)

curl http://localhost:7880

Expected: {"code":"InvalidArgument"...}

Step 2: Test from Browser Console

Open browser dev tools and run:

// Test WebSocket connection
const ws = new WebSocket('wss://streaming.yourdomain.com/livekit/');
ws.onopen = () => console.log('Connected to LiveKit');
ws.onerror = (e) => console.error('Connection error:', e);

Step 3: Test Full Workflow

Log in as a creator account

  1. Navigate to settings/golive.php
  2. Click "Go Live" to start broadcasting
  3. Open a second browser/incognito window
  4. Navigate to livestreams.php
  5. Click on your stream to watch

Common Tasks

Restarting LiveKit

# Restart container
docker restart livekit

Or full restart

docker compose down
docker compose up -d

Viewing Logs

# Real-time logs
docker logs -f livekit

Last 100 lines

docker logs --tail 100 livekit

Updating LiveKit

# Pull latest image
docker pull livekit/livekit-server:latest

Restart with new image

docker compose down
docker compose up -d

Checking Active Rooms

# Using LiveKit CLI (if installed)
livekit-cli list-rooms --url ws://localhost:7880 --api-key YOURKEY --api-secret YOURSECRET

Troubleshooting

Common Errors

Error:
Error: "LiveKit API key and secret must be configured"

Cause: LIVEKITAPIKEY or LIVEKITAPISECRET not defined in config.inc.php

Solution: Add the LiveKit configuration to your config.inc.php file:

define('LIVEKITHOST', 'wss://streaming.yourdomain.com/livekit/');

define('LIVEKITAPIKEY', 'your-api-key');

define('LIVEKITAPISECRET', 'your-api-secret');

 

Error:
Error: "WebSocket connection failed" or "Connection refused"

Cause: Firewall blocking ports or LiveKit not running

Solution:

  1. Verify LiveKit is running: docker ps | grep livekit
  2. Check firewall: sudo ufw status
  3. Open required ports: sudo ufw allow 7880/tcp
  4. Check Nginx proxy configuration

 

Error:
Error: "Only active creators can go live"

Cause: User doesn't have creator status

Solution:

  1. Check user has iscreator = 1 in tblCMSUsers
  2. Check tblCreatorProfiles has an entry with status = 'active'

 

Error:
Error: "Stream not connecting" (video not appearing)

Cause: Usually SSL/WSS mismatch or CORS issues

Solution:

  1. Ensure LIVEKITHOST uses wss:// for HTTPS sites
  2. Check Nginx WebSocket headers are configured
  3. Verify SSL certificate is valid
  4. Check browser console for specific errors

 

Error:
Error: "Token expired" or authentication failures

Cause: Server time drift or incorrect API secret

Solution:

  1. Sync server time: sudo ntpdate pool.ntp.org
  2. Verify APISECRET matches in both config.yaml and config.inc.php
  3. Regenerate tokens by restarting stream

Debug Checklist

  1. LiveKit Container Running?
docker ps | grep livekit
  1. Ports Open?
sudo netstat -tlnp | grep -E '7880|7881'
  1. Config Values Match?
  • Check livekit-config.yaml API key/secret
  • Check config.inc.php API key/secret
  • They MUST be identical
  1. Nginx Proxying Correctly?
curl -v https://streaming.yourdomain.com/livekit/
  1. SSL Certificate Valid?
openssl sclient -connect streaming.yourdomain.com:443

Performance Tuning

For High Concurrent Viewers

Modify livekit-config.yaml:

# Increased limits for production
rtc:
  portrangestart: 40000
  portrangeend: 50000  # 10,000 ports for more viewers

room:
maxparticipants: 5000 # Increase from 1000

 

logging:
level: warn # Reduce logging overhead

Docker Resource Limits

Update docker-compose.yml:

services:
  livekit:
    image: livekit/livekit-server:latest
    containername: livekit
    restart: unless-stopped
    networkmode: host
    command: --config /livekit.yaml
    volumes:
  • ./livekit-config.yaml:/livekit.yaml:ro
    deploy:
      resources:
        limits:
          cpus: '4'
          memory: 4G
        reservations:
          cpus: '2'
          memory: 2G

Security Considerations

Warning:
Live streaming involves real-time video - security is critical.

Best Practices

  1. Always use HTTPS/WSS in production
  • WebRTC requires secure contexts in modern browsers
  • Use Let's Encrypt for free SSL certificates
  1. Protect API credentials
  • Never expose LIVEKITAPISECRET in frontend code
  • Tokens are generated server-side only
  1. Implement rate limiting
  • Prevent chat spam
  • Limit stream start attempts
  1. Monitor for abuse
  • Log stream metadata
  • Review reported streams
  1. Firewall configuration
  • Only open required ports
  • Consider geo-blocking if needed

  • Live Streaming Implementation - .docs/LIVESTREAMINGIMPLEMENTATION.md
  • LiveKit Setup Quick Start - .docs/LIVEKITSETUP.md
  • Debian 12 Install Guide - .docs/LIVEKITINSTALLDEBIAN12.md
  • Streaming Fixes - .docs/LIVESTREAMINGFIXES.md
  • Setup Script - tools/setuplivekitserver.sh

Translatable Strings

The following translation keys are used by the live streaming feature:

Key Default English Used In
livestreaming.title "Go Live" golive.php title
livestreaming.watchtitle "Watch Live" watchstream.php title
livestreaming.browsetitle "Live Streams" livestreams.php title
livestreaming.startstream "Start Streaming" Start button
livestreaming.endstream "End Stream" End button
livestreaming.viewers "Viewers" Viewer count label
livestreaming.chatplaceholder "Type a message..." Chat input
livestreaming.sendtip "Send Tip" Tip button
livestreaming.privaterequest "Request Private Show" Private button
livestreaming.accessfree "Free" Access type
livestreaming.accesspassword "Password Protected" Access type
livestreaming.accesssubscribers "Subscribers Only" Access type
livestreaming.accessppv "Pay-Per-View" Access type
livestreaming.accesstipgoal "Tip Goal" Access type

Install Script Checklist

  • [ ] Docker installed and running
  • [ ] Firewall ports opened (7880, 7881, 50000-51000) --- For the 50000-51000, this may need adjusted as opening so many ports not only a security issue, but it will cause the streaming server to fail on load.
  • [ ] LiveKit configuration file created
  • [ ] Docker Compose file created
  • [ ] LiveKit container started
  • [ ] API credentials added to config.inc.php
  • [ ] Database migration 018 applied
  • [ ] Database migration 019 applied (LiveKit fields)
  • [ ] Nginx reverse proxy configured (production)
  • [ ] SSL certificate obtained (production)
  • [ ] Feature toggle enabled
  • [ ] Test stream successful

Changelog

Date Version Changes
2026-01-02 1.0 Initial guide created