Camera Setup & MediaMTX Streaming Guide (End-to-End Walkthrough)
📌 What is this for?
In Simple Words:
When setting up live camera video for a new TuTr vehicle or project (referred to in this guide asabc), you need video to travel from the physical IP cameras on the vehicle to operators' web browsers in under 300 milliseconds.This guide is a complete, self-contained walkthrough. It provides the exact configuration files, scripts, and service definitions so you never have to search old repositories or guess parameters.
Architecture Overview
PART 1: Creating the Cloud Video Server (AWS EC2 + MediaMTX)
1.1 Launching the EC2 Instance
In the AWS Management Console (or using AWS CLI):
- AMI: Ubuntu Server 24.04 LTS or 22.04 LTS (64-bit x86_64 or arm64).
- Instance Type:
t3.small(for 1–2 camera streams) ort3.medium(for 4+ concurrent streams or heavy WebRTC fanout). - Storage: 20 GB gp3 root EBS volume.
- Elastic IP: Allocate an Elastic IP in
ap-south-1(Mumbai) and associate it with the EC2 instance so the public IP never changes upon reboot. - DNS Record: In Route 53 (or your DNS provider for
tutr.tech), create an A Record:- Record Name:
cam.abc.tutr.tech - Value:
<Your-EC2-Elastic-IP> - TTL: 300 seconds
- Record Name:
1.2 Security Group Firewall Rules
Configure the EC2 Security Group with the following inbound rules:
| Type | Protocol | Port Range | Source | Purpose |
|---|---|---|---|---|
| SSH | TCP | 22 | Your IP / VPN | Server administration |
| HTTP | TCP | 80 | 0.0.0.0/0 | Let's Encrypt standalone certificate verification |
| HTTPS | TCP | 443 | 0.0.0.0/0 | Standard secure web traffic |
| Custom TCP | TCP | 8554 | 0.0.0.0/0 (or Vehicle IP) | RTSP ingestion from Edge Device (cwc-stream / abc-stream) |
| Custom TCP | TCP | 8889 | 0.0.0.0/0 | WebRTC WHEP signaling over TLS/HTTPS (Dashboard connects here) |
| Custom TCP | TCP | 8888 | 0.0.0.0/0 | HLS streaming fallback |
| Custom UDP | UDP | 8189 | 0.0.0.0/0 | WebRTC ICE audio/video UDP packets |
[!IMPORTANT] If UDP port 8189 is blocked by your security group, the WebRTC handshake will succeed, but the video player will remain black with an infinite loading spinner because the underlying RTP media packets are dropped!
1.3 Step-by-Step Server Provisioning Script
SSH into your fresh EC2 instance as ubuntu:
ssh -i your-key.pem ubuntu@cam.abc.tutr.tech
Run the following commands to install prerequisites, obtain an SSL certificate, and install MediaMTX:
# 1. Update system and install tools
sudo apt update && sudo apt upgrade -y
sudo apt install -y curl wget tar jq certbot ffmpeg ca-certificates
# 2. Obtain Let's Encrypt SSL/TLS Certificate
# (Ensure DNS A record for cam.abc.tutr.tech already points to this instance's Elastic IP)
sudo certbot certonly --standalone \
-d "cam.abc.tutr.tech" \
--agree-tos \
--no-eff-email \
-m "dev@tutr.tech" \
--non-interactive
# 3. Download and install MediaMTX (v1.9.3)
MEDIAMTX_VER="v1.9.3"
ARCH="linux_amd64"
if [ "$(uname -m)" = "aarch64" ]; then ARCH="linux_arm64v8"; fi
cd /tmp
wget "https://github.com/bluenviron/mediamtx/releases/download/${MEDIAMTX_VER}/mediamtx_${MEDIAMTX_VER}_${ARCH}.tar.gz" -O mediamtx.tar.gz
tar -xzf mediamtx.tar.gz
sudo install -m 755 mediamtx /usr/local/bin/mediamtx
sudo mkdir -p /etc/mediamtx
rm -rf /tmp/mediamtx*
1.4 The Complete MediaMTX Configuration File (/etc/mediamtx/mediamtx.yml)
Create or update /etc/mediamtx/mediamtx.yml:
sudo nano /etc/mediamtx/mediamtx.yml
Paste the following complete configuration:
###############################################
# TuTr Hyperloop MediaMTX Production Configuration
# Project: abc
# Host: cam.abc.tutr.tech
###############################################
logLevel: info
logDestinations: [stdout]
# ---------------------------------------------
# RTSP Ingestion (Pushed from Raspberry Pi)
# ---------------------------------------------
rtsp: yes
rtspAddress: :8554
protocols: [tcp]
# ---------------------------------------------
# RTMP Configuration (Optional / Legacy)
# ---------------------------------------------
rtmp: yes
rtmpAddress: :1935
# ---------------------------------------------
# HLS Streaming Fallback
# ---------------------------------------------
hls: yes
hlsAddress: :8888
hlsAlwaysRemux: yes
# ---------------------------------------------
# WebRTC / WHEP Server (Ultra-Low Latency < 300ms)
# ---------------------------------------------
webrtc: yes
webrtcAddress: :8889
webrtcEncryption: yes
webrtcServerKey: /etc/letsencrypt/live/cam.abc.tutr.tech/privkey.pem
webrtcServerCert: /etc/letsencrypt/live/cam.abc.tutr.tech/fullchain.pem
webrtcAllowOrigin: '*'
webrtcLocalUDPAddress: :8189
webrtcAdditionalHosts: ["cam.abc.tutr.tech"]
# ---------------------------------------------
# Stream Path Definitions
# ---------------------------------------------
paths:
# Camera 1 (Forward Track View)
cam1:
source: publisher
# Camera 2 (Cabin / Rear View)
cam2:
source: publisher
# Catch-all for any extra dynamic feeds
all_others:
source: publisher
1.5 MediaMTX Systemd Service & Auto-Renewal Hook
Create the systemd service file:
sudo nano /etc/systemd/system/mediamtx.service
Paste the following unit configuration:
[Unit]
Description=MediaMTX Live Video Streaming Server (Project abc)
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/mediamtx /etc/mediamtx/mediamtx.yml
Restart=always
RestartSec=3
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
Enable and start the service:
sudo systemctl daemon-reload
sudo systemctl enable mediamtx
sudo systemctl start mediamtx
Set up an automated Certbot renewal hook so MediaMTX automatically reloads renewed SSL certificates:
sudo mkdir -p /etc/letsencrypt/renewal-hooks/post
sudo tee /etc/letsencrypt/renewal-hooks/post/restart-mediamtx.sh > /dev/null << 'EOF'
#!/bin/sh
systemctl restart mediamtx
EOF
sudo chmod +x /etc/letsencrypt/renewal-hooks/post/restart-mediamtx.sh
1.6 Verifying the MediaMTX Server
-
Check service status:
sudo systemctl status mediamtxYou should see:
Active: active (running). -
Verify WHEP endpoint over HTTPS:
curl -k -i -X OPTIONS https://cam.abc.tutr.tech:8889/cam1/whepYou should receive an HTTP
200 OKor204 No Contentresponse with WHEP capability headers.
PART 2: Configuring the Raspberry Pi Edge Device (Project abc)
2.1 Physical IP Camera Setup & IP Allocation
On the vehicle, IP cameras connect via Ethernet switches to the Raspberry Pi:
| Camera Name | Physical Position | Static IP Address | RTSP URL Format |
|---|---|---|---|
| CAM 1 | Forward / Nose View | 192.168.1.200:554 | rtsp://tutr:Tutr123!@192.168.1.200:554/cam/realmonitor?channel=1&subtype=0 |
| CAM 2 | Rear / Dock View | 192.168.1.201:554 | rtsp://tutr:Tutr123!@192.168.1.201:554/cam/realmonitor?channel=1&subtype=0 |
[!TIP] If your camera uses a different manufacturer format (e.g., Hikvision
rtsp://user:pass@192.168.1.200:554/Streaming/Channels/101or Dahua/Amcrestrtsp://user:pass@192.168.1.200:554/cam/realmonitor?channel=1&subtype=0), test connectivity directly from the Pi first:nc -zv 192.168.1.200 554
2.2 Installing Prerequisites on the Raspberry Pi
Log in to the Raspberry Pi terminal:
sudo apt update
sudo apt install -y ffmpeg python3-venv python3-pip fonts-dejavu-core
2.3 Creating the Camera Stream Project Structure
Create the project folder:
mkdir -p /home/tutr/abc_stream
cd /home/tutr/abc_stream
python3 -m venv venv
source venv/bin/activate
Create requirements.txt:
Flask==3.1.2
gunicorn==23.0.0
Install the dependencies:
pip install -r requirements.txt
2.4 The Complete Camera Stream Script (/home/tutr/abc_stream/app.py)
Create /home/tutr/abc_stream/app.py:
#!/usr/bin/env python3
"""
Autonomous Camera Stream Forwarder for Project: abc
- Reads physical RTSP feeds from onboard IP cameras.
- Autonomously probes camera socket availability every 3 seconds.
- Automatically falls back to synthetic SMPTE color bars with live timestamps if a camera is unplugged or offline.
- Encodes with low-latency WebRTC parameters (-g 15, -bf 0, -profile:v baseline).
- Pushes continuous RTSP feeds to the cloud MediaMTX server.
- Exposes local HTTP MJPEG preview routes for trackside debugging.
"""
import os
import shutil
import socket
import subprocess
import threading
import time
from flask import Flask, Response, abort
app = Flask(__name__)
# Camera RTSP URLs (Adjust IP or credentials to match physical camera hardware)
RTSP_LINKS = [
os.environ.get("CAM1_RTSP", "rtsp://tutr:Tutr123!@192.168.1.200:554/cam/realmonitor?channel=1&subtype=0"),
os.environ.get("CAM2_RTSP", "rtsp://tutr:Tutr123!@192.168.1.201:554/cam/realmonitor?channel=1&subtype=0"),
]
MEDIAMTX_HOST = os.environ.get("MEDIAMTX_HOST", "cam.abc.tutr.tech")
MEDIAMTX_PORT = int(os.environ.get("MEDIAMTX_PORT", "8554"))
PROJECT_NAME = os.environ.get("PROJECT_NAME", "ABC")
BOUNDARY = "frame"
FFMPEG = shutil.which("ffmpeg") or "/usr/bin/ffmpeg"
def get_font_arg():
"""Finds an available system TTF font to prevent fontconfig errors on headless Linux."""
candidates = [
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/usr/share/fonts/truetype/freefont/FreeSans.ttf",
"/usr/share/fonts/dejavu/DejaVuSans.ttf",
]
for c in candidates:
if os.path.isfile(c):
escaped = c.replace("\\", "/").replace(":", "\\:")
return f"fontfile={escaped}:"
return ""
def is_camera_reachable(url, timeout=1.2):
"""Parses host and port from RTSP URL and tests if TCP socket is accessible."""
try:
# Extract host and port from rtsp://user:pass@host:port/path
stripped = url.split("://")[-1].split("@")[-1].split("/")[0]
if ":" in stripped:
host, port = stripped.split(":")
port = int(port)
else:
host = stripped
port = 554
with socket.create_connection((host, port), timeout=timeout):
return True
except (socket.timeout, OSError, ValueError):
return False
def push_stream_to_mediamtx(cam_id, rtsp_source, dest_url):
"""
Autonomous forwarder thread:
- If camera is online: Transcodes/copies RTSP into destination MediaMTX channel.
- If camera is offline: Generates synthetic test pattern with live timestamp.
- Uses 1-second IDR keyframe cadence (-g 15, -bf 0) for zero-latency WebRTC decoding.
- Probes camera status every 3s to seamlessly cut over without service restarts.
"""
print(f"🚀 [{PROJECT_NAME}-Stream] Starting forwarder for CAM {cam_id} -> {dest_url}")
while True:
is_online = is_camera_reachable(rtsp_source)
proc = None
try:
if is_online:
print(f"✅ [{PROJECT_NAME}-Stream] CAM {cam_id}: Physical camera connected. Pushing live RTSP.")
cmd = [
FFMPEG,
"-loglevel", "warning",
"-re",
"-rtsp_transport", "tcp",
"-i", rtsp_source,
"-c:v", "libx264",
"-preset", "ultrafast",
"-tune", "zerolatency",
"-g", "15", # Mandatory: Keyframe every 1s for instant WebRTC locking
"-bf", "0", # Mandatory: Zero B-frames eliminates jitter buffer stalls
"-profile:v", "baseline", # Universal WebRTC decoder compatibility
"-pix_fmt", "yuv420p",
"-an",
"-f", "rtsp",
"-rtsp_transport", "tcp",
dest_url
]
else:
font_arg = get_font_arg()
text_filter = (
f"drawtext={font_arg}text='[{PROJECT_NAME}] CAM {cam_id} (OFFLINE SIMULATOR) %{{localtime}}':"
f"x=25:y=25:fontsize=32:fontcolor=white:box=1:boxcolor=black@0.65:boxborderw=8"
)
pattern = "testsrc=size=1280x720:rate=15" if cam_id == 1 else "smptebars=size=1280x720:rate=15"
cmd = [
FFMPEG,
"-loglevel", "warning",
"-re",
"-f", "lavfi",
"-i", pattern,
"-vf", text_filter,
"-c:v", "libx264",
"-preset", "ultrafast",
"-tune", "zerolatency",
"-g", "15",
"-bf", "0",
"-profile:v", "baseline",
"-pix_fmt", "yuv420p",
"-an",
"-f", "rtsp",
"-rtsp_transport", "tcp",
dest_url
]
proc = subprocess.Popen(cmd)
# Monitor process; if camera connection status changes, terminate and switch
while proc.poll() is None:
time.sleep(3)
current_state = is_camera_reachable(rtsp_source)
if current_state != is_online:
print(f"🔄 [{PROJECT_NAME}-Stream] CAM {cam_id}: Hardware status changed (online={current_state}). Switching stream...")
proc.terminate()
try:
proc.wait(timeout=2)
except subprocess.TimeoutExpired:
proc.kill()
break
except Exception as e:
print(f"⚠️ [{PROJECT_NAME}-Stream] CAM {cam_id} forwarder error: {e}")
if proc and proc.poll() is None:
proc.kill()
time.sleep(2)
def start_all_forwarders():
"""Starts background threads for CAM 1 and CAM 2."""
for cam_id in [1, 2]:
idx = cam_id - 1
dest = f"rtsp://{MEDIAMTX_HOST}:{MEDIAMTX_PORT}/cam{cam_id}"
t = threading.Thread(
target=push_stream_to_mediamtx,
args=(cam_id, RTSP_LINKS[idx], dest),
daemon=True,
name=f"Forwarder-CAM{cam_id}"
)
t.start()
# Launch forwarders on process boot
start_all_forwarders()
# ------------------------------------------------------------------------------
# LOCAL TRACKSIDE HTTP PREVIEWS
# ------------------------------------------------------------------------------
@app.route("/")
def index():
return f"""
<!DOCTYPE html>
<html>
<head><title>{PROJECT_NAME} Camera Status</title></head>
<body style="font-family: system-ui, sans-serif; background: #0b1120; color: #f8fafc; padding: 2rem;">
<h2>🎥 {PROJECT_NAME} Vehicle Camera Streams</h2>
<p>MediaMTX Cloud Destination: <code>rtsp://{MEDIAMTX_HOST}:{MEDIAMTX_PORT}</code></p>
<ul>
<li><a style="color: #38bdf8;" href="/cam1" target="_blank">CAM 1 Local Preview (/cam1)</a></li>
<li><a style="color: #38bdf8;" href="/cam2" target="_blank">CAM 2 Local Preview (/cam2)</a></li>
</ul>
</body>
</html>
"""
@app.route("/cam<int:cam_id>")
def local_mjpeg_preview(cam_id):
"""Local MJPEG stream generator for browser preview without WebRTC."""
idx = cam_id - 1
if idx < 0 or idx >= len(RTSP_LINKS):
abort(404)
is_online = is_camera_reachable(RTSP_LINKS[idx])
font_arg = get_font_arg()
if is_online:
cmd = [
FFMPEG, "-loglevel", "quiet",
"-rtsp_transport", "tcp",
"-i", RTSP_LINKS[idx],
"-an", "-vf", "scale=1280:720", "-r", "10",
"-f", "mpjpeg", "-boundary_tag", BOUNDARY, "pipe:1"
]
else:
text_filter = f"drawtext={font_arg}text='[{PROJECT_NAME}] CAM {cam_id} OFFLINE':x=25:y=25:fontsize=28:fontcolor=white"
cmd = [
FFMPEG, "-loglevel", "quiet",
"-f", "lavfi", "-i", "testsrc=size=1280x720:rate=10",
"-vf", text_filter,
"-f", "mpjpeg", "-boundary_tag", BOUNDARY, "pipe:1"
]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=0)
def generate():
try:
while True:
data = proc.stdout.read(4096)
if not data:
break
yield data
finally:
proc.kill()
return Response(generate(), mimetype=f"multipart/x-mixed-replace; boundary={BOUNDARY}")
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
2.5 Gunicorn Production Configuration (gunicorn.conf.py)
Create /home/tutr/abc_stream/gunicorn.conf.py:
bind = "0.0.0.0:5000"
workers = 1
threads = 4
timeout = 0
graceful_timeout = 0
keepalive = 2
loglevel = "info"
accesslog = "-"
errorlog = "-"
2.6 The Systemd Service (/etc/systemd/system/abc-stream.service)
Create the systemd service to ensure the camera streaming application starts automatically when the Raspberry Pi boots:
sudo nano /etc/systemd/system/abc-stream.service
Paste the following definition:
[Unit]
Description=TuTr Camera Streaming Service (Project abc)
After=network.target
[Service]
Type=simple
User=tutr
WorkingDirectory=/home/tutr/abc_stream
Environment="MEDIAMTX_HOST=cam.abc.tutr.tech"
Environment="MEDIAMTX_PORT=8554"
Environment="PROJECT_NAME=ABC"
Environment="CAM1_RTSP=rtsp://tutr:Tutr123!@192.168.1.200:554/cam/realmonitor?channel=1&subtype=0"
Environment="CAM2_RTSP=rtsp://tutr:Tutr123!@192.168.1.201:554/cam/realmonitor?channel=1&subtype=0"
ExecStart=/home/tutr/abc_stream/venv/bin/gunicorn -c gunicorn.conf.py app:app
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
Enable and start the service:
sudo systemctl daemon-reload
sudo systemctl enable abc-stream
sudo systemctl restart abc-stream
Check the live logs on the Raspberry Pi:
sudo journalctl -u abc-stream -f
You will see the forwarder initialize, probe the physical camera IP, and begin pushing the feed to cam.abc.tutr.tech:8554/cam1 and /cam2.
PART 3: Viewing the Stream in Frontend Dashboards
3.1 WebRTC WHEP Connection Code (React / JavaScript)
Modern browsers play WebRTC streams directly using the standard WebRTC HTTP Egress Protocol (WHEP). In your React component:
import React, { useEffect, useRef } from 'react';
export function LiveCameraPlayer({ streamUrl }) {
// Example streamUrl: "https://cam.abc.tutr.tech:8889/cam1/whep"
const videoRef = useRef(null);
useEffect(() => {
let pc = new RTCPeerConnection({
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
});
pc.ontrack = (event) => {
if (videoRef.current && event.streams[0]) {
videoRef.current.srcObject = event.streams[0];
}
};
pc.addTransceiver('video', { direction: 'recvonly' });
async function startStream() {
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
const response = await fetch(streamUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/sdp' },
body: offer.sdp
});
if (!response.ok) {
console.error('WHEP connection failed:', response.status);
return;
}
const answerSdp = await response.text();
await pc.setRemoteDescription({ type: 'answer', sdp: answerSdp });
}
startStream().catch(console.error);
return () => {
pc.close();
};
}, [streamUrl]);
return (
<video
ref={videoRef}
autoPlay
playsInline
muted
style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: '8px' }}
/>
);
}
Summary Checklist for Project abc
| Step | Action | Success Indicator |
|---|---|---|
| 1 | Point cam.abc.tutr.tech DNS A record to EC2 Elastic IP | ping cam.abc.tutr.tech resolves to Elastic IP |
| 2 | Open EC2 Security Group ports (80, 443, 8554, 8889, 8189/udp) | Ports respond to connection attempts |
| 3 | Install Let's Encrypt SSL certificate | /etc/letsencrypt/live/cam.abc.tutr.tech/fullchain.pem exists |
| 4 | Place /etc/mediamtx/mediamtx.yml and start mediamtx.service | systemctl is-active mediamtx reports active |
| 5 | Deploy /home/tutr/abc_stream/app.py on Raspberry Pi | journalctl -u abc-stream shows forwarder active |
| 6 | Open https://cam.abc.tutr.tech:8889/cam1/whep in dashboard | Video displays with < 300ms latency |