Ugacomp

How to set up Nginx RTMP Server on Ubuntu to Live stream videos

Where necessary, you may need to have access to a VPS server so you can follow how to implement the steps in this article.  You can get a cheaper VPS Server from Contabo with 4vCPU cores, 8GM RAM, and 32TB Bandwidth for less than $5.50 per month. Get this deal here now

Table of Contents

Cloud VPS S

$5.50 Monthly
  • 4 vCPU Cores | 8GB RAM

CLOUD VPS M

$15.50 Monthly
  • 6 vCPU Cores | 16GB RAM

CLOUD VPS L

$17.50 Monthly
  • 8 vCPU Cores | 24GB RAM

Ngnix is one of the most popular web servers in the world. Its incredible performance makes it suitable for handling 1000s of concurrent users while efficiently utilizing available resources. Although many out there may think Nginx is just for hosting websites, they should also know of its capabilities when it comes to the world of live streaming.

In this article, we will learn how to use Nginx so we can set up RTMP live streams on Ubuntu. As always, we will hold your hand to take you step-by-step through this process; to help you understand everything in detail while also simplifying for you the complex and technical jargon involved. Please don’t be afraid as we’re here for you 🙂

RECOMMENDED READING: How can I install an Open SSH Server on Ubuntu Linux?

Installing the Nginx RTMP module

Nginx can support live streaming using its RTMP module. The Nginx RTMP module works as a plugin, extending and triggering Nginx’s ability to act as a streaming server. This means that once the module is configured, you will be able to stream video and audio content to users across the internet.

Nginx itself doesn’t ship with the RTMP module by default, so to use it, we have to install and configure the necessary settings. The following commands will update the system and then install the Nginx RTMP module:

sudo apt update
sudo apt install libnginx-mod-rtmp

Edit Configuration file

Once we’ve installed Nginx on our system, we need to edit the Nginx configuration file, nginx.conf. This file is located in the following directory:

 /etc/nginx/nginx.conf

So, we will use the nano editor to edit the nginx.conf file using the following command;

sudo nano /etc/nginx/nginx.conf

We need to add the following block to the nginx.conf file;

.
rtmp {
        server {
                listen 1935;
                chunk_size 4096;
                allow publish 127.0.0.1;
                deny publish all;

                application live {
                        live on;
                        record off;
                }
        }
}

Let’s try to quickly break down the meaning of the above code we’ve just added in the configuration file:

RECOMMENDED READING: How to Secure HLS & DASH Streams in Ant Media Server?

  • listen 1935: This means that Nginx RTMP streams use TCP port: 1935, which by the way is the standard port for Real-time Messaging Protocol (RTMP).

  • Chunk_size 4096: The Chunk Size is the amount of data that is sent in a single message from the server to the client during a Real-Time Messaging Protocol (RTMP) session. In this context, we use the directive Chunhk_size to define and specify the maximum size of a chunk in bytes, which is 4096 in this example. In other words, the Ngnix RTMP will be sending data in 4KB blocks, which is also the acceptable standard

  • allow publish 127.0.0.1 and deny publish all: This means that Nginx RTMP will only allow a video stream to be published from the same server, preventing unauthorized users from pushing their own streams to the server.

  • application live: This defines the default application block that can be accessed via the /live URL path. In this context, an application provides the logical grouping of RTMP streams and the associated configurations. When a client (such as a streaming software or device) connects to an Nginx RTMP server, it specifies the name of the application it wishes to use. If the specified application exists on the server, the client can then publish or play streams within that application.

RECOMMENDED READING: How to Install WordPress on a VPS Server using Cloudron?

  • live on: This parameter activates the live mode, allowing multiple users to connect to your stream concurrently.

  • record off: This prevents Nginx-RTMP’s recording functionality, and streams cannot be separately saved to disk by default.

Now, that you’ve understood the defined parameters in the Nginx configuration file, the next step is to save the changes, and because we’re using nano in this example, we will just press Ctrl+X, then y, and Enter

RECOMMENDED READING: How to use Alibaba Cloud Free credit to Set up an Ubuntu server

Allow RTMP through the Firewall

In this example, we’re using ufw firewall. If you don’t have it installed on your system, you can run the following command on your terminal

sudo apt install ufw

Confirm if ufw is active by running the following command;

sudo ufw status

Every time you activate a firewall on your Linux system, make sure to first allow SSH so you don’t get locked out. Use the following command:

RECOMMENDED READING: How to deploy WordPress on a Ubuntu LAMP Server

sudo ufw allow 22/tcp

Now, let’s open RTMP port: 1935 using the following command:

sudo ufw allow 1935/tcp

Okay, let’s reload Nginx so the changes we’ve made can be captured. We can use the following command;

sudo systemctl reload nginx.service

Using FFmpeg and Nginx RTMP

FFmpeg is a powerful open-source command-line tool that can be used to record, convert, and stream audio and video files in various formats.

RECOMMENDED READING: How to download and install Ubuntu Linux on a Laptop

In the context of Nginx RTMP, FFmpeg plays a critical role in several ways:

  • It is used to ingest audio and video streams from external sources, such as webcams, video cameras, and other media servers. FFmpeg can be used to transcode these incoming streams into different formats, resolutions, or bitrates, depending on the needs of the downstream clients.

  • It is used to create output streams that can be delivered to clients over the Internet. These output streams can be delivered in a variety of formats, such as H.264, AAC, MP3, and others, depending on the client’s requirements. FFmpeg can also be used to apply filters, add logos, or perform other processing on the output streams before they are delivered to clients.

  • It can also be used to record audio and video streams to disk, either in real-time or after the fact. This can be useful for archiving purposes, or for creating on-demand versions of previously-recorded events.

RECOMMENDED READING: How to install an SSL Certificate on Ant Media Server

Installing FFmpeg on Ubuntu

To use FFmpeg on your system, you need to run the following command;

sudo apt install ffmpeg

Before we dive into FFmpeg configuration, we also need to make sure we have a sample video file on our system we can use to set up a test stream using Nginx RTMP.

Alternatively, we can just download a video from YouTube using the youtube-dl command line utility tool. But to use this tool, we have to first install it using Python’s package manager, pip.

RECOMMENDED READING: How to host a Laravel application on Ubuntu using Apache

To simplify this process, follow these steps:

  • Install python3-pip: This will install python3 and the pip package manager using the following command;
sudo apt install python3-pip
  • Install the youtube-dl tool using pip with the following command:
sudo pip install youtube-dl

Now we can download any YouTube video using the youtube-dl utility tool. For example, the following command will download one of our videos on our YouTube Channel;

youtube-dl https://www.youtube.com/watch?v=5BntOkS-aTU

The video will be downloaded in the current directory with a title like my-video.mkv

Sending stream using ffmpeg

We can now send our downloaded video which is my-video.mkv to the Nginx RTMP server by running the following command:

ffmpeg -re -i "Imy-video.mkv" -c:v copy -c:a aac -ar 44100 -ac 1 -f flv rtmp://localhost/live/stream

Here is the breakdown of what the above command means:

  • -re: This parameter stands for “real-time” or “live stream in real-time“. It is used to tell the program to read the input at its native frame rate, without any optimization or delay. This is useful when processing live video streams that are being generated in real-time, such as those coming from a webcam or a network camera.

RECOMMENDED READING: How can I download files from Google Drive using Linux Terminal?

  • -i: This parameter is used to specify the path to our input file, which in this case is called my-video.mkv

  • -c:v is set to copy. This means that you’re using the same video format you got from YouTube natively. In other words, It copies the video stream from the input file to the output file without re-encoding it. Generally, the -c:v parameter is used to specify the video codec that should be used for the encoding or decoding of video streams. When used in conjunction with Nginx, it allows you to specify the video codec for video streaming over HTTP.

  • -c:a This is the general FFmpeg parameter to specify the audio codec to be used for encoding audio streams. In this example, parameters aac -ar 44100 -ac 1, specify the audio codec (aac), the audio sampling rate (-ar 44100), and the number of audio channels (-ac 1) for an audio stream.

  • -f flv: This indicates that the output format of the video stream should be FLV (Flash Video), a container format developed by Adobe Systems for streaming audio and video content over the internet. An flv format container is used in this example for maximum compatibility with RTMP.

RECOMMENDED READING: What you need to know before deploying Ant Media in AWS Cluster

If you’ve set up everything correctly, video, my-video.mkv will be sent to the following URL:

rtmp://localhost/live/stream 

This URL can be justified because that’s how we defined it in the live configuration block as seen below;

.
rtmp {
        server {
                listen 1935;
                chunk_size 4096;
                allow publish 127.0.0.1;
                deny publish all;

                application live {
                        live on;
                        record off;
                }
        }
}

You will notice that the RTMP publish parameter is set to localhost or 127.0.0.1 . On the other hand, the stream URL parameter is an arbitrarily chosen URL for this video.

RECOMMENDED READING: How to Easily Create and Add Users in Linux

When FFmpeg is running, you will be able to see the following printout on the terminal

frame=  127 fps= 25 q=-1.0 size= 405kB time=00:00:05.00 bitrate= 662.2kbits/s speed=frame=  140 fps= 25 q=-1.0 size=628kB time=00:00:05.52 bitrate= 931.0kbits/s speed=frame=  153 fps= 25 q=-1.0 size= 866kB time=00:00:06.04 bitrate=1173.1kbits/s speed=

Please refer to the following table for the interpretation of these parameters:

ParameterDescription
frame=The current processing speed of the conversion process, is measured in frames per second.
fps=The number of frames per second being processed.
q=The current frame number is being processed.
size=The current output size of the encoded video.
time=The quantization parameter is used for encoding the video. A value of -1.0 indicates that the encoding is using a constant quality mode.
bitrate=The current bitrate of the encoded video.
speed=The current processing speed of the conversion process is measured in frames per second.

Playing the stream

to play your stream, you have to make sure that FFmpeg is running. Then you will have to connect to your RTMP stream using any supported video player like VLC, MPV, or another media player installed locally on your machine.

From your video player, you will have to use the following URL format to stream:

 rtmp://your_domain/live/stream

For our case in this article, the following is our streaming URL:

rtmp://localhost/live/stream 

RECOMMENDED READING: How to use DASH & HLS Protocols in Nginx RTMP streaming

Loop the stream

Now, it’s important to note that your stream will terminate immediately after ffmpeg completes playing the video. If you want to turn your stream into a loop so it can play indefinitely, you can add -stream_loop -1 to the beginning of your ffmpeg command. as seen below;

ffmpeg -stream_loop -1 -re -i "Imy-video.mkv" -c:v copy -c:a aac -ar 44100 -ac 1 -f flv rtmp://localhost/live/stream

Run FFmpeg in the background

To run FFmpeg in the background, you can use the standard method for running a process in the background in your operating system.

On Linux or macOS, you can use the nohup command to run FFmpeg in the background and prevent it from being terminated when you log out. Here’s an example command:

nohup ffmpeg -stream_loop -1 -re -i "Imy-video.mkv" -c:v copy -c:a aac -ar 44100 -ac 1 -f flv rtmp://localhost/live/stream

More related articles to explore

Hire us to handle what you want

Hire us through our Fiverr Profile and leave all the complicated & technical stuff to us. Here are some of the things we can do for you:

  • Website migration, troubleshooting, and maintenance.
  • Server & application deployment, scaling, troubleshooting, and maintenance
  • Deployment of Kubernetes, Docker, Cloudron, Ant Media, Apache, Nginx,  OpenVPN, cPanel, WHMCS, WordPress, and more
  • Everything you need on AWS, IBM Cloud, GCP, Azure, Oracle Cloud, Alibaba Cloud, Linode, Contabo, DigitalOcean, Ionos, Vultr, GoDaddy, HostGator, Namecheap, DreamHost, and more.
 

We will design, configure, deploy, or troubleshoot anything you want. Starting from $10, we will get your job done in the shortest time possible. Your payment is safe with Fiverr as we will only be paid once your project is completed.