This project provides a set of scripts to set up an Nginx server with RTMP module, optionally routing RTMP/RTMPS streams through Stunnel4. This allows you to restream to multiple platforms like Twitch, YouTube, and Kick.
Date Created/Last Updated: May 14, 2025
- Multi-Platform Restreaming: Configure Nginx to push your input stream to multiple RTMP/RTMPS endpoints.
- Stunnel4 for RTMPS: Securely stream to services requiring RTMPS by tunneling RTMP through Stunnel4.
- HLS Output: Configure Nginx to output HLS (HTTP Live Streaming) for playback in web browsers or media players.
- Flexible Configuration: Uses a
real.env/master.envfile for easy customization of stream keys, paths, and application names. - Helper Scripts: Includes scripts for initial setup, service management (start, stop, status), SSL certificate generation for Stunnel, and a full reset.
- WSL2 Support: Includes a PowerShell script (
WSL2-Setup/Install-RestreamWSL.ps1) to automate WSL2 setup, Linux distribution installation, and running the restream server setup on Windows. - WSL2 Management Scripts:
WSL2-Setup/WSL2-mgr.ps1: For backing up and restoring your WSL2 distribution.WSL2-Setup/WSL2-UFW.ps1: For managing Windows Firewall rules for WSL2.- These scripts are typically run from within their directory (e.g.,
NG-S4/WSL2-Setup/) using a command like:powershell.exe -ExecutionPolicy RemoteSigned -File .\\WSL2-mgr.ps1
NG-S4/
├── example.env/ # Example configuration files
│ ├── master.env
│ ├── nginx.conf
│ └── stunnel.conf
├── real.env/ # Your actual configuration files (copy from example.env)
│ ├── master.env # Main environment variables and stream keys
│ ├── nginx.conf # Your Nginx configuration
│ └── stunnel.conf # Your Stunnel4 configuration
├── UNIX-Scripts/ # Bash scripts for Linux setup and management
│ ├── setup-restream.sh
│ ├── generate-stunnel-cert.sh
│ ├── manage-services.sh
│ ├── reset-restream.sh
│ └── stream-gphoto2-webcam.sh
├── WSL2-Setup/ # PowerShell scripts for WSL2
│ ├── Install-RestreamWSL.ps1
│ ├── WSL2-mgr.ps1
│ └── WSL2-UFW.ps1
└── README.md # This file
Before running any setup scripts, you must configure your environment.
-
Copy Example Configuration: If the
real.env/directory does not containmaster.env,nginx.conf, andstunnel.conf, copy them from theexample.env/directory:mkdir -p real.env cp example.env/master.env real.env/master.env cp example.env/nginx.conf real.env/nginx.conf cp example.env/stunnel.conf real.env/stunnel.conf
(The
WSL2-Setup/Install-RestreamWSL.ps1script also attempts to do this copy if files are missing inreal.env) -
Edit
real.env/master.env: Openreal.env/master.envand update the following:XX_TW_KEY,XX_YT_KEY,XX_KI_KEY: Replace these with your actual stream keys.- Review other path variables like
NGINX_WEB_CONTENT_SRC,HLS_BASE_DIR,STUNNEL_SSL_SUBJECT, etc., and adjust if necessary. - The
envDrshould point to yourreal.envdirectory, andscriptsDrtoUNIX-Scripts. These should generally not need changing if you maintain the project structure.
-
Edit
real.env/nginx.conf: This is a critical step. Yournginx.confdefines how RTMP streams are handled, where they are pushed, and how HLS is generated. The fileexample.env/nginx.confcontains a comprehensive example incorporating common use cases like basic restreaming, HLS output, and applications for camera input (Cam1) and stream composition (MultiMain). You should: a. Copyexample.env/nginx.conftoreal.env/nginx.conf(if not already done). b. Carefully review and adaptreal.env/nginx.confto your specific needs.Key considerations for
nginx.conf:- Stream Keys: Replace placeholders like
YOUR_TWITCH_STREAM_KEY_HEREin yourreal.env/nginx.confwith your actual keys (ideally sourced frommaster.envif your setup scripts handle variable substitution, or hardcoded if not). The example applicationsXX_TW,XX_YT,XX_KIinexample.env/nginx.confshow placeholders. - Ingest URLs: Ensure all
push rtmp://...lines point to the correct ingest servers for each platform. - Stunnel Ports: If using Stunnel, make sure the Nginx
pushURLs for RTMPS services match theacceptports in yourstunnel.conf(e.g.,rtmp://127.0.0.1:19351). - HLS Paths: The
hls_pathin the RTMP block and therootin the HTTPlocation /hlsblock must correspond correctly. Thesetup-restream.shscript creates directories under$HLS_BASE_DIR(default/mnt/hls). - External Scripts (
pushCam1,pushM):- For
pushCam1-like functionality, your external script (usinggphoto2 | ffmpeg) should push its RTMP output to an application defined in Nginx (e.g.,rtmp://<nginx_server_ip>:1935/Cam1). - For
pushM-like functionality, your externalffmpegscript will pull from Nginx applications (e.g.,rtmp://localhost:1935/Main1) and push the combined output to another Nginx application (e.g.,rtmp://localhost:1935/MultiMain). Nginx simply provides the RTMP endpoints.
- For
- Stream Keys: Replace placeholders like
-
Edit
real.env/stunnel.conf:- If you are using Stunnel4 for RTMPS, configure the services here.
- For each service (e.g.,
[YT],[KI]):accept = 127.0.0.1:LOCAL_PORT(e.g.,127.0.0.1:19351for YouTube). This is the port Nginx will push to.connect = ACTUAL_RTMPS_INGEST_HOST:PORT(e.g.,a.rtmp.youtube.com:443). This is the actual RTMPS endpoint of the streaming service.
- The
certpath is typically/etc/stunnel/stunnel.pemand is generated byUNIX-Scripts/generate-stunnel-cert.sh.
Important .gitignore Note:
The .gitignore in this project is typically set up to ignore the contents of real.env/* (except for the directory itself and potentially placeholder files if you choose to commit them initially). This is to prevent accidental commitment of your personal stream keys. Ensure your personalized real.env files are not tracked by Git if you are pushing to a public repository.
This method uses PowerShell to set up WSL2, install a Linux distribution, and then run the Linux setup scripts.
-
Enable WSL & Virtual Machine Platform: You can do this via "Turn Windows features on or off" or by running PowerShell as Administrator:
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
A reboot is required after enabling these features.
-
Install a Linux Distribution from Microsoft Store (Optional if using
Install-RestreamWSL.ps1): If you don't use theWSL2-Setup/Install-RestreamWSL.ps1script to install a distro, you can install one like "Ubuntu" (e.g., Ubuntu 22.04 LTS) from the Microsoft Store and set up your user.
This script automates several steps:
- Checks and helps enable WSL features (requires reboot if not already enabled).
- Updates the WSL kernel.
- Installs a specified Linux distribution (default: Ubuntu-22.04) if not already present.
- Prompts you to copy/verify configuration files from
example.env/toreal.env/. - Executes the
UNIX-Scripts/setup-restream.shwithin the WSL distribution to install Nginx, Stunnel4, and configure them.
Steps:
- Configure
real.env/files as described in the "Configuration" section above. This is crucial before running the script. - Open PowerShell (preferably as Administrator, especially if WSL features need enabling).
- Navigate to the
NG-S4project directory. - Run the script:
.\\WSL2-Setup\\Install-RestreamWSL.ps1 - Follow any on-screen prompts. The script will execute
sudo bash UNIX-Scripts/setup-restream.shinside WSL.
WSL2 runs with a virtualized network. To access services running inside WSL2 from your local network (e.g., to send a stream from OBS on another machine to Nginx in WSL2), you'll need to:
- Find WSL2's IP Address:
Open your WSL2 terminal and run:
ip addr show eth0 | grep 'inet ' | awk '{print $2}' | cut -d/ -f1 - Port Forwarding / Firewall Rules:
The
WSL2-Setup/WSL2-UFW.ps1script can help create Windows Firewall rules to allow traffic to your WSL2 instance.- Review and edit
WSL2-Setup/WSL2-UFW.ps1to ensure the ports you want to open (e.g., 1935 for RTMP, 8080 for HLS HTTP) are correctly listed. - Run
WSL2-Setup/WSL2-UFW.ps1in an Administrator PowerShell. - You might need to update the firewall rules if your WSL2 IP address changes (it can change after a Windows reboot).
- Review and edit
The WSL2-Setup/WSL2-mgr.ps1 script provides functions to:
- Backup (Export): Create a
.tararchive of your WSL2 distribution. - Restore (Import): Restore a distribution from a
.tarfile, potentially as a new instance or overwriting an existing one. - Reset: Unregister and re-import a distribution from a backup.
Usage:
- Open PowerShell.
- Navigate to the
NG-S4/WSL2-Setup/directory. - Run the script:
.\WSL2-mgr.ps1 - Follow the prompts to choose an action.
This method is for setting up the restreaming server directly on a dedicated Linux machine or a VM.
- A Linux system (e.g., Ubuntu, Debian).
sudoaccess.gitinstalled (sudo apt install git).
git clone <repository_url> # Replace <repository_url> with the actual URL
cd NG-S4 # Or your chosen directory nameFollow the steps outlined in the main "Configuration (real.env/)" section at the beginning of this README to copy and edit your master.env, nginx.conf, and stunnel.conf files.
The main setup script will install Nginx, Stunnel4, libnginx-mod-rtmp, generate SSL certs for Stunnel, copy configurations, and start the services.
sudo bash UNIX-Scripts/setup-restream.shReview the output for any errors.
This script helps you manage Nginx and Stunnel4.
Usage: sudo bash UNIX-Scripts/manage-services.sh {start|stop|restart|status|enable|disable} [nginx|stunnel4|all]
Examples:
- Check status of all services:
sudo bash UNIX-Scripts/manage-services.sh status all - Restart Nginx:
sudo bash UNIX-Scripts/manage-services.sh restart nginx - Stop Stunnel4:
sudo bash UNIX-Scripts/manage-services.sh stop stunnel4
The setup-restream.sh script calls this automatically. However, if you need to regenerate the Stunnel SSL certificate manually (e.g., if it expires or you change the subject in master.env):
sudo bash UNIX-Scripts/generate-stunnel-cert.shThis will create/overwrite /etc/stunnel/stunnel.pem. Remember to restart Stunnel4 afterwards:
sudo bash UNIX-Scripts/manage-services.sh restart stunnel4
This script will stop services, purge Nginx and Stunnel4 packages, and remove their configuration files and related directories. Use with caution!
sudo bash UNIX-Scripts/reset-restream.shAfter resetting, you can re-run UNIX-Scripts/setup-restream.sh for a fresh installation. Logs for the reset operation are stored in the directory specified by LOG_DIR in master.env (default: /home/jnxlr/PROJECTS/LOG).
This script facilitates streaming video directly from a gphoto2-compatible camera (e.g., many DSLRs, mirrorless cameras) to your Nginx RTMP server.
Functionality:
- Uses
gphoto2to capture live video from the connected camera. - Pipes the video to
ffmpegfor encoding (H.264 video, AAC audio by default). - Adds a silent audio track if the camera doesn't provide one, for better compatibility with RTMP servers.
- Streams the final output to a specified RTMP URL, typically an input application on your Nginx server (e.g.,
rtmp://127.0.0.1:1935/Cam1/my_camera_feed).
Prerequisites:
gphoto2andffmpegmust be installed. Thesetup-restream.shscript now includes these in its installation process.- A
gphoto2-compatible camera connected to your Linux system.
Configuration:
- The script
UNIX-Scripts/stream-gphoto2-webcam.shhas configurable parameters at the top, such as default RTMP URL, video/audio bitrates, framerate, and ffmpeg preset.
FFmpeg Command Breakdown (Conceptual):
The stream-gphoto2-webcam.sh script uses ffmpeg to process the output from gphoto2 and stream it. While the exact command can be seen in the script, here's a breakdown of common options you might find or want to adjust:
- Input & Audio Generation:
-i pipe:0or similar: Tellsffmpegto read video data from standard input (piped fromgphoto2).-f lavfi -i anullsrc=channel_layout=stereo:sample_rate=44100: Generates a silent stereo audio track at 44.1kHz. This is crucial if your camera doesn't provide audio or for compatibility with some streaming platforms that require an audio track.
- Video Encoding (
libx264- H.264):-c:v libx264: Specifies the H.264 video codec.-preset ultrafast: A common preset for live streaming, prioritizing low CPU usage over quality/compression. Other presets includesuperfast,veryfast,faster,fast,medium(default),slow,slower,veryslow. Slower presets give better quality/compression at the cost of higher CPU.-b:v 2000k(e.g., 2 Mbps): Sets the target video bitrate. Adjust based on your internet upload speed and desired quality.-maxrate 2500k: Sets the maximum allowed video bitrate.-bufsize 4000k: Sets the decoder buffer size, often twice the maxrate.-vf "format=yuv420p": Sets the pixel format toyuv420p, which is widely compatible.-r 30: Sets the output video framerate (e.g., 30 frames per second).
- Audio Encoding (AAC):
-c:a aac: Specifies the AAC audio codec.-b:a 128k(e.g., 128 kbps): Sets the audio bitrate.-ar 44100: Sets the audio sample rate (e.g., 44.1 kHz).
- Output:
-f flv: Specifies the output format as FLV, suitable for RTMP."$RTMP_URL": The destination RTMP server URL (e.g.,rtmp://127.0.0.1:1935/Cam1/my_stream_key).
You can modify these parameters within the stream-gphoto2-webcam.sh script to fine-tune the output for your specific camera, network conditions, and streaming platform requirements.
Usage:
- Navigate to the scripts directory (e.g., if you are in
NG-S4):cd UNIX-Scripts/ - Run the script. You may need
sudoifgphoto2requires root permissions to access the camera hardware:sudo ./stream-gphoto2-webcam.sh [OPTIONAL_RTMP_URL]
- If
OPTIONAL_RTMP_URLis not provided, it will use theDEFAULT_RTMP_URLdefined inside the script (e.g.,rtmp://127.0.0.1:1935/Cam1/live_camera). - Example: To stream to the
Cam1application on your local Nginx server with a stream keymy_gphoto_feed:sudo ./stream-gphoto2-webcam.sh rtmp://127.0.0.1:1935/Cam1/my_gphoto_feed
- If
- Press
Ctrl+Cto stop the stream.
Note for WSL2 Users:
Using gphoto2 within WSL2 requires successful USB device passthrough from Windows to the WSL2 environment. This can sometimes be complex to configure (often involving usbipd-win). If you intend to use this script in WSL2, ensure your camera is accessible within the WSL2 Linux distribution.
- Check Service Status: Use
sudo bash UNIX-Scripts/manage-services.sh status all. - Nginx Logs: Typically found in
/var/log/nginx/error.logand/var/log/nginx/access.log. - Stunnel4 Logs: Check the
outputpath specified in your/etc/stunnel/stunnel.conf(e.g.,/var/log/stunnel4/stunnel.log). The debug level can also be adjusted instunnel.conf. - Permissions: Ensure file and directory permissions are correct, especially for Nginx PID files, web content, HLS directories, and Stunnel run/log directories. The setup script attempts to handle these.
- Firewall: On standalone Linux, ensure your system firewall (e.g.,
ufw) allows incoming connections on the necessary ports (e.g., 1935 for RTMP, or any ports Stunnel listens on if accessed externally, 8080 for HLS HTTP). - WSL2 Networking: If OBS or your streaming source can't connect to Nginx in WSL2, double-check the WSL2 IP address and your Windows Firewall rules (see WSL2 section).