Search code examples
nginxflaskherokurtmp

Nginx RTMP with Flask


I have followed along the documentation/tutorial on how to set up the config file for RTMP streaming from here: https://www.nginx.com/blog/video-streaming-for-remote-learning-with-nginx/ and it is pretty straight forward. However, I am not sure how I can have my backend built on Flask to redirect the stream to some HLS/DASH video player that is embedded in an HTML template that is sent in response to a client that requested for a specific HTTP endpoint. The tutorial shows how to view locally in a VLC media player but not how to embed it in an HTML file that gets sent to the client. How would I go about doing this? For reference, I am hosting my website on Heroku that is set up with its Nginx buildpack from here, https://github.com/heroku/heroku-buildpack-nginx, and I am not sure if I need to have Heroku install additional dependencies to set up an RTMP server and listen for a stream.


Solution

  • Use the HLS protocol (HTTP Live Streaming). Nginx knows how to render HTTP perfectly. So, you just need to create and update the playlist and fragments of the HLS stream, as well as monitor the removal of old fragments. To do this, there is a nginx-rtmp-hls module. It is located in the hls directory, but it is not collected by default since requires the libavformat library included in the ffmpeg package. To build nginx with HLS support, you need to add this module explicitly during configuration:

    ./configure --add-module=/path/to/nginx-rtmp-module --add-module=/path/to/nginx-rtmp-module/hls
    

    To generate HLS, just specify the following directives:

    application myapp {
        live on;
        hls on;
        hls_path /tmp/hls;
        hls_fragment 5s;
    }
    

    And finally, in the http {} section, configure the return of everything related to HLS:

    location /hls {
        root /tmp;
    }
    

    To show stream in browser create html page with such content (example):

    <video width="600" height="300" controls="1" autoplay="1" src="http://example.com/hls/mystream.m3u8"></video>
    

    Update 1:

    You attached link on Nginx setup tutorial, so i'm referencing on their "Compiling NGINX with the RTMP Module" step with changes related to HLS module:

    $ cd /path/to/build/dir
    $ git clone https://github.com/arut/nginx-rtmp-module.git
    $ git clone https://github.com/nginx/nginx.git
    $ cd nginx
    $ ./auto/configure --add-module=../nginx-rtmp-module --add-module=../nginx-rtmp-module/hls
    $ make
    $ sudo make install