Ugacomp

How to use HLS and DASH Protocols in Nginx RTMP streaming

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

HLS and DASH protocols are powerful technologies for delivering modern video streaming with minimal latency. These protocols prioritize giving a smooth end-user streaming experience while limiting video buffering scenarios that could frustrate your target audience.

Integrating HLS and DASH protocols into your Nginx RTMP streaming server is one of the best alternatives you need to implement if you’re to optimize the performance of your video streaming projects.

Now. in this article, we would like to see how powerful DASH & HLS protocols are in supporting Nginx streaming capabilities.

RECOMMENDED READING: How are Protocols implemented in applications?

What are HLS & DASH protocols and how do they work?

Protocols such as HLS and DASH have been mainstreamed into the world of high-quality live streaming to catch up with the modern streaming experiences end-users expect to get. These protocols solve key issues that always bottlenecked the efficient delivery of streams to the target audiences.

So, to understand properly what HLS & DASH protocols mean, let’s break them down in detail below:

What is DASH?

DASH is an acronym for Dynamic Adaptive Streaming over HTTP. It’s one of the common streaming protocols used to deliver video content over the internet. Many popular streaming platforms such as Netflix, Hulu, and YouTube are using DASH to deliver robust streaming infrastructure.

Now, the basic idea behind DASH is that it allows the video stream to adapt to the quality of the viewer’s internet connection through a mechanism known as adaptive bitrate streaming.

This means that if a viewer has a slow internet connection, the video will automatically adjust to a lower quality, which requires less bandwidth. On the other hand, if a viewer has a faster internet connection, the video will adjust to a higher quality, which provides a better viewing experience.

RECOMMENDED READING: How can I enable Adaptive Bitrate streaming in Ant Media Server?

The way this works is that the video is broken up into small segments, and each segment is encoded at multiple different bitrates. The information about each video segment is stored in a manifest file called Media Presentation Description (MPD).

The MPD file is an XML file that contains information about the multimedia content, such as;

  • The location of the media segments.
  • The available bitrates.
  • The codecs used.
  • The timing information.

The MPD file also specifies the rules for switching between different representations based on the available bandwidth and the playback buffer level.

For example, a sample DASH manifest file or MPD looks like this below;

<?xml version="1.0" encoding="UTF-8"?>

<MPD
 
xmlns="urn:mpeg:dash:schema:mpd:2011"
 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 
xsi:schemaLocation="urn:mpeg:dash:schema:mpd:2011 MPD.xsd" profiles="urn:mpeg:dash:profile:isobtt:2011" minBufferTime="PT1.5S">
  <Period duration="[Duration]">
    <AdaptationSet mimeType="video/mp4" segmentAlignment="true">
      <Representation bandwidth="[Bandwidth]" id="[RepresentationID]">
        <BaseURL uri="[BaseURL]" />
        <SegmentList>
          <Segment duration="[SegmentDuration]" mediaInitializationPosition="[MediaInitializationPosition]" startNumber="[StartNumber]">
            <Initialization uri="[Initialization]" />
            <RepresentationIndex>[RepresentationIndex]" />
          </Segment>
        </SegmentList>
      </Representation>
    </AdaptationSet>
    <AdaptationSet mimeType="audio/mp4" segmentAlignment="true">
      <Representation bandwidth="[Bandwidth]" id="[RepresentationID]">
        <BaseURL uri="[BaseURL]" />
        <SegmentList>
          <Segment duration="[SegmentDuration]" mediaInitializationPosition="[MediaInitializationPosition]" startNumber="[StartNumber]">
            <Initialization uri="[Initialization]" />
            <RepresentationIndex>[RepresentationIndex]" />
          </Segment>
        </SegmentList>
      </Representation>
    </AdaptationSet>
  </Period>
</MPD>

Now in this article, we will not go into detail explaining every line of code in the Media Presentation Description file, but the most important thing here is to understand that this manifest file is crucial in segmenting different versions of the video. These segments are then made available to the viewer’s device, which chooses the version that best matches their internet connection speed while mitigating buffering issues.

In other words, as the connection speed changes, the device can switch to a different version of the video, so that the viewer always gets the best possible quality for their connection.

RECOMMENDED READING: How does Alibaba Cloud Free trial work?

What is HLS?

HLS is an acronym for HTTP Live Streaming, and it’s a streaming protocol that also enables the delivery of audio and video content over the Internet. It was first developed by Apple in 2009 and has since become one of the most popular streaming protocols, widely adopted by many content providers.

The HLS streaming process begins with the encoder compressing the audio and video content into small data packets using codecs like H.264 and AAC. During this process, the streaming content is divided into small segments, typically 10 seconds in length, and a playlist file, typically in the M3U8 format is created, which contains a list of URLs for each segment of the content.

HLS uses a variant file called the “M3U8 playlist” that contains information about the available video or audio streams, their bitrates, and the URLs where they can be accessed. Here is an example of this file:

#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:10
#EXT-X-ALLOW-CACHE:YES
#EXT-X-MEDIA-SEQUENCE:1
#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=4000000,RESOLUTION=854x480
http://media.example.com/hls/playlist/chunk1.m4s
#EXT-X-ENDINF
#EXT-X-STREAM-INF:PROGRAM-ID=2,BANDWIDTH=1500000,RESOLUTION=640x360
http://media.example.com/hls/playlist/chunk2.m4s
#EXT-X-ENDINF
#EXT-X-STREAM-INF:PROGRAM-ID=3,BANDWIDTH=800000,RESOLUTION=426x240
http://media.example.com/hls/playlist/chunk3.m4s
#EXT-X-ENDINF

The server uses the M3U8 playlist to respond to client requests, allowing the download of the content segments. The client can request different bitrates and resolutions by changing the URL in the playlist, leading to seamless switching between different qualities based on the client’s available bandwidth and device capabilities.

HLS also includes support for subtitles and closed captions, which are delivered in a separate WebVTT (Web Video Text Tracks) file.

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

What is the difference between HLS and DASH?

Both protocols are important in the delivery of audio and video content over the Internet. While they share many similarities, there are some key differences between the two.

First, one of the main differences is the way the two protocols deliver content. For example, HLS uses a pull-based delivery model, where the client requests content segments from the server. The meaning of this is that the server responds by sending the requested segment to the client, which then decodes and plays the segment. Once the segment is played, the client requests the next segment and the process repeats. This process continues until the entire video has been streamed.

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

In contrast, DASH uses a push-based delivery model where a server continuously sends video segments to the client, even before the client requests them. The client is responsible for selecting the appropriate segment to play, based on factors such as network conditions and available bandwidth. This allows for more efficient and flexible streaming, as the client can adapt to changes in network conditions and select the optimal video quality in real time.

Another difference between HLS and DASH is in the way they handle adaptive bitrate streaming. HLS uses a file known as M3U8 playlist, where each bitrate and resolution is listed as a separate variant in the playlist. The client can switch between different variants by changing the URL in the playlist. On the other hand, DASH uses a manifest file called Media Presentation Description (MPD), where all the available bitrates and resolutions are listed in the manifest. The client can request different bitrates and resolutions by sending a request to the server.

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

Configuring HLS and DASH for Nginx RTMP

HLS and DASH protocols are necessary for creating modern streams for browsers. This means that once these protocols are properly configured, users will be able to access your streams directly through browsers. The good thing is that the Nginx RTMP module offers support for both protocols, allowing them to be integrated into the streaming server for efficient delivery of content.

Activate DASH and HLS in the configuration file

To activate both HLS and DASH, we will need to do some tweaking in the configuration file, nginx.conf. This means doing some modifications to the rtmp block section of the file. At this point, we’re assuming that you already have the Nginx RTMP module set up on your server. If you don’t know or if you haven’t set it up, then you can follow this guide to help you do it step-by-step.

It’s time to open the configuration file located on this path: /etc/nginx/nginx.conf. And in this case, we’re using nano as our preferred editor. You can choose your preferred editor and it doesn’t have to be nano in any way. Run the following command on your terminal if you’re using nano as your choice editor so you can open the configuration file.

sudo nano /etc/nginx/nginx.conf

Inside the configuration file, we need to add the following directives just after

rtmp {
        server {

                application live {
                    	live on;
                    	record off;  
                    	
// Add the following lines below to activate support for HLS and DASH

                        hls on;
                        hls_path /var/www/html/stream/hls;
                        hls_fragment 3;
                        hls_playlist_length 60;

                        dash on;
                        dash_path /var/www/html/stream/dash;
                }
        }
}

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

As you can see in the above code, there are two blocks. One activates the integration of HLS and the other triggers the DASH protocol in Nginx RTMP.

For HLS, let’s break down line by line below;

  • hls on; enables the HLS module for the specified server or location block in the NGINX configuration file.

  • hls_path; specifies the file system path where the HLS segments and playlists will be saved. In this case, the path is:

/var/www/html/stream/hls

  • hls_fragment 3; sets the duration of each HLS segment (in seconds) to 3 seconds. This means that the video will be divided into small segments of 3 seconds each.

  • hls_playlist_length 60; specifies the maximum duration of the HLS playlist, in seconds. In this case, the playlist will have a maximum duration of 60 seconds, after which it will start a new playlist

On the other hand, the meaning of the DASH block is explained below;

  • dash on;This line activates the DASH protocol in the Nginx RTMP configuration file.

  • dash_path;This line specifies the file path where the DASH video segments and manifest files will be stored on the server. In this case, it is set to:

/var/www/html/stream/dash

Once you’ve added the block successfully, you need to save the changes by pressing Ctrl + X key combination, then y, and finally press Enter. This only applies to those using nano editor.

RECOMMENDED READING: How to Point a Domain Name from Namecheap to Contabo VPS

How to configure HLS or DASH protocol independently?

If you’re not interested in activating both protocols and you only need to use one of them in the configuration, then here is how you go about it:

  • Only configure HLS in the Nginx RTMP configuration:

To only use HLS in Nginx, the configuration file would look as follows:

rtmp { 
    server { 
        listen 1935; 
        application live { 
            live on; 
            interleave on;
 
            hls on; 
            hls_path /tmp/hls; 
            hls_fragment 15s; 
        } 
    } 
} 
 
http { 
    default_type application/octet-stream;
 
    server { 
        listen 80; 
        location /tv { 
            root /tmp/hls; 
        } 
    }
 
    types {
        application/vnd.apple.mpegurl m3u8;
        video/mp2t ts;
        text/html html;
    } 
}

You also need to make sure you open ports 1935 and 80 through your server firewall to allow traffic to pass through.

  • Only configure DASH in the Nginx RTMP configuration

If you’re only interested in the DASH protocol, then your Nginx RTMP configuration file should look as follows:

rtmp { 
    server { 
        listen 1935; 
        application live { 
            live on; 
            dash on; 
            dash_path /tmp/dash; 
            dash_fragment 15s; 
        } 
    } 
} 
 
http { 
    server { 
        listen 80; 
        location /tv { 
            root /tmp/dash; 
        } 
    }
 
    types {
        text/html html;
        application/dash+xml mpd;
    } 
}

How to play HLS and DASH streams

After setting up the HLS and DASH configurations in the Nginx RTMP server, you need to understand how to play the streams using the appropriate URL structures. For example;

  • Playing HLS streams:

To play HLS streams, here is the URL structure you need to use:

http://NGINX_server/live/bbb.m3u8

You will need to input your appropriate values in the URL as per your HLS stream configuration. Make your stream file name end with the .m3u8 extension at the end of the URL.

  • Playing DASH streams:

Here is the DASH stream URL structure you will need to use in the player:

 http://NGINX_server/live/bbb.mpd

You have to make sure your stream name ends with the .mpd extension at the end.

Configure Access-Control-Allow-Origin Header (Optional)

In the context of Nginx RTMP, Access-Control-Allow-Origin is a response header that is used to indicate which origins are allowed to access a particular resource, such as an audio or video stream.

The Access-Control-Allow-Origin header is used in Cross-Origin Resource Sharing (CORS) to control access to resources from different domains. When a client (such as a web browser) requests a resource from a server with a different domain, the server needs to explicitly allow the client’s domain to access the resource.

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

In the context of Nginx RTMP streaming, the Access-Control-Allow-Origin header can be used to control access to RTMP streams from different domains. By specifying the allowed origins in this header, Nginx RTMP can ensure that only authorized clients can access the streams.

Now, we need to use the nano editor to add some configurations in the following file:

sudo nano /etc/nginx/sites-available/rtmp

And then, we need to add the following lines just at the bottom of sites-available/rtmp to activate the Access-Control-Allow-Origin header in Nginx RTMP:


server {
    listen 8088;

    location / {
        add_header Access-Control-Allow-Origin *;
        root /var/www/html/stream;
    }
}

types {
    application/dash+xml mpd;
}

In the above code, port 8088 is being used as the listening port for the server. The server is configured to listen on port 8088 for incoming requests.

The configuration file defines a location block that sets the root directory for serving content for the / location. In this case, the root directory is set to /var/www/html/stream, which means that any request that comes to the server with a URI that starts with / will be served from this directory.

RECOMMENDED READING: How to install Ant Media Server on VPS

The types block sets the MIME type for the DASH manifest file format, which is used for the adaptive streaming of video content. Using this file format enables the server to correctly identify and serve DASH manifests to clients who request them.

So, the server that serves content from the /var/www/html/stream directory allows requests from any origin by setting the Access-Control-Allow-Origin header to the wildcard asterisk * and it is listening on port 8088 for incoming requests. Using the wildcard character (*) means that any domain can access the resources from the server. This can be useful when you want to allow cross-origin resource sharing (CORS) for all domains, without specifying each domain explicitly.

After making this edit, you need to save the changes

Allow Port: 8088 through the firewall

We’re using port 8088 in this case as an arbitrary port to avoid conflicts with other services that could be using the default ports: 80 or 443.

To open this port, we will use ufw firewall or any other firewall platform of your choice. In this case, let’s use ufw by running the following command;

sudo ufw allow 8088/tcp

RECOMMENDED READING: How to install and configure UFW firewall on Ubuntu Linux

Create the root directory

The purpose of the directory /var/www/html/stream in this example is to serve as the root directory for the server’s content for the specified location /.

When a client requests a resource through the Nginx RTMP server, it will look for that resource in the directory specified by the root directive. In this case, the server will look for the requested resource in the /var/www/html/stream directory for requests that match the location.

This means that the Nginx server will be able to generate the necessary files for HLS and DASH in this directory. In this example, we’re calling the directory /stream and we the following command to create it:

sudo mkdir /var/www/html/stream

So, everything is set and we only need to reload the Nginx server by running the following command on the terminal:

sudo systemctl reload nginx

Conclusion

If you want to deliver low-latency and adjustable video streams based on the network bandwidth of the client devices, using DASH and HLS is one of the best choices you can explore. And finally, if you’ve enjoyed this article, please come back again for more. And as a show of support for our work, you can as well share this article on your social media, or send it to a friend who might be interested in content like this 🙂

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

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.