Cómo desarrollar un server de streaming con nginx

Cómo desarrollar un server de streaming con nginx

Hola amigos de la #nerditud.

En el día de hoy, quiero compartirles cómo instalar un servidor nginx y configurarlo para realizar streaming de audio y/o video vía RTM o HLS .

Instalar nginx

sudo apt update

sudo apt install nginx

configurar firewall

sudo ufw allow 'Nginx HTTP'

sudo ufw allow 'Nginx HTTPS'

sudo ufw status

Testear servidor

systemctl status nginx

localhost

Crear carpetas y permisos

sudo mkdir -p /cast/tv

sudo chown -R $USER:$USER /cast/tv

sudo chmod -R 755 /cast/tv

Modificar nginx.conf

/etc/nginx/nginx.conf

user www-data;
worker_processes 1;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections  1024;
}

rtmp {
    server {
        listen 1935;
        chunk_size 8192;
        application live {
            live on;
            meta copy;
            interleave on;
            hls on;
            hls_path /cast/tv;
            hls_fragment 15s;
        }
    }
}

http {
    default_type application/octet-stream;

    server {
        listen 80;

        location / {
            add_header 'Cache-Control' 'no-cache';
            add_header 'Access-Control-Allow-Origin' '*' always;
            add_header 'Access-Control-Expose-Headers' 'Content-Length';

            if ($request_method = 'OPTIONS') {
                add_header 'Access-Control-Allow-Credentials' 'true';
                add_header 'Access-Control-Allow-Methods' 'GET, OPTIONS';
                add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
                add_header 'Access-Control-Max-Age' 1728000;
                add_header 'Content-Type' 'text/plain charset=UTF-8';
                add_header 'Content-Length' 0;
                add_header 'Access-Control-Allow-Origin' '*';
                return 200;
            }

            if ($request_method = 'GET') {
                add_header 'Access-Control-Allow-Origin' '*';
                add_header 'Access-Control-Allow-Credentials' 'true';
                add_header 'Access-Control-Allow-Methods' 'GET, OPTIONS';
                add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
            }
        }

        try_files $uri = 404;

        types {
            application/vnd.apple.mpegurl m3u8;
            video/mp2t ts;
            text/html html;
        }

        root /cast;
    }
}

Corroborar sintaxis

sudo nginx -t

Reiniciar nginx

sudo systemctl restart nginx

Probar server

Desde OBS podemos emitir audio o video a rtmp://serverip:1935/live/canal Utilizando un reproductor de video como por ejemplo VLC presionamos CTRL+N (open network stream) y podemos ingresar las siguientes direcciones para testear