Nginx windows nginx rtmp module

NGINX-based Media Streaming Server

nginx-rtmp-module

Project blog

http://nginx-rtmp.blogspot.com

Wiki manual

https://github.com/arut/nginx-rtmp-module/wiki/Directives

Google group

https://groups.google.com/group/nginx-rtmp

https://groups.google.com/group/nginx-rtmp-ru (Russian)

Donation page (Paypal etc)

http://arut.github.com/nginx-rtmp-module/

Features

  • RTMP/HLS/MPEG-DASH live streaming

  • RTMP Video on demand FLV/MP4,
    playing from local filesystem or HTTP

  • Stream relay support for distributed
    streaming: push & pull models

  • Recording streams in multiple FLVs

  • H264/AAC support

  • Online transcoding with FFmpeg

  • HTTP callbacks (publish/play/record/update etc)

  • Running external programs on certain events (exec)

  • HTTP control module for recording audio/video and dropping clients

  • Advanced buffering techniques
    to keep memory allocations at a minimum
    level for faster streaming and low
    memory footprint

  • Proved to work with Wirecast, FMS, Wowza,
    JWPlayer, FlowPlayer, StrobeMediaPlayback,
    ffmpeg, avconv, rtmpdump, flvstreamer
    and many more

  • Statistics in XML/XSL in machine- & human-
    readable form

  • Linux/FreeBSD/MacOS/Windows

Build

cd to NGINX source directory & run this:

./configure --add-module=/path/to/nginx-rtmp-module
make
make install

Several versions of nginx (1.3.14 — 1.5.0) require http_ssl_module to be
added as well:

./configure --add-module=/path/to/nginx-rtmp-module --with-http_ssl_module

For building debug version of nginx add --with-debug

./configure --add-module=/path/to-nginx/rtmp-module --with-debug

Read more about debug log

Windows limitations

Windows support is limited. These features are not supported

  • execs
  • static pulls
  • auto_push

RTMP URL format

rtmp://rtmp.example.com/app[/name]

app — should match one of application {}
blocks in config

name — interpreted by each application
can be empty

Multi-worker live streaming

Module supports multi-worker live
streaming through automatic stream pushing
to nginx workers. This option is toggled with
rtmp_auto_push directive.

Example nginx.conf

rtmp {

    server {

        listen 1935;

        chunk_size 4000;

        # TV mode: one publisher, many subscribers
        application mytv {

            # enable live streaming
            live on;

            # record first 1K of stream
            record all;
            record_path /tmp/av;
            record_max_size 1K;

            # append current timestamp to each flv
            record_unique on;

            # publish only from localhost
            allow publish 127.0.0.1;
            deny publish all;

            #allow play all;
        }

        # Transcoding (ffmpeg needed)
        application big {
            live on;

            # On every pusblished stream run this command (ffmpeg)
            # with substitutions: $app/${app}, $name/${name} for application & stream name.
            #
            # This ffmpeg call receives stream from this application &
            # reduces the resolution down to 32x32. The stream is the published to
            # 'small' application (see below) under the same name.
            #
            # ffmpeg can do anything with the stream like video/audio
            # transcoding, resizing, altering container/codec params etc
            #
            # Multiple exec lines can be specified.

            exec ffmpeg -re -i rtmp://localhost:1935/$app/$name -vcodec flv -acodec copy -s 32x32
                        -f flv rtmp://localhost:1935/small/${name};
        }

        application small {
            live on;
            # Video with reduced resolution comes here from ffmpeg
        }

        application webcam {
            live on;

            # Stream from local webcam
            exec_static ffmpeg -f video4linux2 -i /dev/video0 -c:v libx264 -an
                               -f flv rtmp://localhost:1935/webcam/mystream;
        }

        application mypush {
            live on;

            # Every stream published here
            # is automatically pushed to
            # these two machines
            push rtmp1.example.com;
            push rtmp2.example.com:1934;
        }

        application mypull {
            live on;

            # Pull all streams from remote machine
            # and play locally
            pull rtmp://rtmp3.example.com pageUrl=www.example.com/index.html;
        }

        application mystaticpull {
            live on;

            # Static pull is started at nginx start
            pull rtmp://rtmp4.example.com pageUrl=www.example.com/index.html name=mystream static;
        }

        # video on demand
        application vod {
            play /var/flvs;
        }

        application vod2 {
            play /var/mp4s;
        }

        # Many publishers, many subscribers
        # no checks, no recording
        application videochat {

            live on;

            # The following notifications receive all
            # the session variables as well as
            # particular call arguments in HTTP POST
            # request

            # Make HTTP request & use HTTP retcode
            # to decide whether to allow publishing
            # from this connection or not
            on_publish http://localhost:8080/publish;

            # Same with playing
            on_play http://localhost:8080/play;

            # Publish/play end (repeats on disconnect)
            on_done http://localhost:8080/done;

            # All above mentioned notifications receive
            # standard connect() arguments as well as
            # play/publish ones. If any arguments are sent
            # with GET-style syntax to play & publish
            # these are also included.
            # Example URL:
            #   rtmp://localhost/myapp/mystream?a=b&c=d

            # record 10 video keyframes (no audio) every 2 minutes
            record keyframes;
            record_path /tmp/vc;
            record_max_frames 10;
            record_interval 2m;

            # Async notify about an flv recorded
            on_record_done http://localhost:8080/record_done;

        }


        # HLS

        # For HLS to work please create a directory in tmpfs (/tmp/hls here)
        # for the fragments. The directory contents is served via HTTP (see
        # http{} section in config)
        #
        # Incoming stream must be in H264/AAC. For iPhones use baseline H264
        # profile (see ffmpeg example).
        # This example creates RTMP stream from movie ready for HLS:
        #
        # ffmpeg -loglevel verbose -re -i movie.avi  -vcodec libx264
        #    -vprofile baseline -acodec libmp3lame -ar 44100 -ac 1
        #    -f flv rtmp://localhost:1935/hls/movie
        #
        # If you need to transcode live stream use 'exec' feature.
        #
        application hls {
            live on;
            hls on;
            hls_path /tmp/hls;
        }

        # MPEG-DASH is similar to HLS

        application dash {
            live on;
            dash on;
            dash_path /tmp/dash;
        }
    }
}

# HTTP can be used for accessing RTMP stats
http {

    server {

        listen      8080;

        # This URL provides RTMP statistics in XML
        location /stat {
            rtmp_stat all;

            # Use this stylesheet to view XML as web page
            # in browser
            rtmp_stat_stylesheet stat.xsl;
        }

        location /stat.xsl {
            # XML stylesheet to view RTMP stats.
            # Copy stat.xsl wherever you want
            # and put the full directory path here
            root /path/to/stat.xsl/;
        }

        location /hls {
            # Serve HLS fragments
            types {
                application/vnd.apple.mpegurl m3u8;
                video/mp2t ts;
            }
            root /tmp;
            add_header Cache-Control no-cache;
        }

        location /dash {
            # Serve DASH fragments
            root /tmp;
            add_header Cache-Control no-cache;
        }
    }
}

Multi-worker streaming example

rtmp_auto_push on;

rtmp {
    server {
        listen 1935;

        application mytv {
            live on;
        }
    }
}

Stream video in multiple formats, including Real-Time Messaging Protocol (RTMP), HLS, and DASH, with the RTMP dynamic module, supported by NGINX, Inc.

Installation

  1. Check the Technical Specifications page to verify that the module is supported by your operating system.

  2. Install the RTMP Media Streaming module package nginx-plus-module-rtmp.

    For Amazon Linux 2, CentOS, Oracle Linux, and RHEL:

    yum install nginx-plus-module-rtmp
    

    For Amazon Linux 2023, AlmaLinux, Rocky Linux:

    dnf install nginx-plus-module-rtmp
    

    For Debian and Ubuntu:

    apt-get install nginx-plus-module-rtmp
    

    For SLES:

    zypper install nginx-plus-module-rtmp
    

    For Alpine:

    apk add nginx-plus-module-rtmp
    

    For FreeBSD:

    pkg install nginx-plus-module-rtmp
    

Configuration

After installation you will need to enable and configure the module in NGINX Plus configuration file nginx.conf.

  1. Enable dynamic loading of the module with the load_module directive specified in the top-level (“main”) context:

    load_module modules/ngx_rtmp_module.so;
    
  2. Perform additional configuration as required by the module.

  3. Test the configuration and reload NGINX Plus to enable the module:

    nginx -t && nginx -s reload
    

More Info

  • NGINX RTMP Module Reference

  • NGINX Dynamic Modules

  • NGINX Plus Technical Specifications


Let’s take a closer look at NGINX RTMP Module in Windows. At Bobcares, with our Server Management Service, we can handle your NGINX RTMP Module issues.

NGINX RTMP Module in Windows

Nginx RTMP is an Nginx module which allows you to add RTMP and HLS streaming to your media server. Previously, the RTMP and HLS modules were seperate Nginx modules, but now they are a single module on Nginx.

Steps to follow
  1. Firstly, download the nginx package.
  2. Then decompress the nginx_1.7.11.3 _Gryphon.zip, to get the Nginx_1.7.11.3_Gryphon folder.
  3. Then verify that Windows has unblocked all of the files so that we may run them.
  4. Be sure to look at the conf/nginx.conf file before running nginx.exe. Depending on the requirements or preferences, it could be necessary to alter parts of the content.
  5. Then use the command prompt to execute the command under the decompressed path.
    nginx.exe -v

    This command will display the NGINX version.

  6. Then, we create a new file called “nginx.conf” in the CONF directory of the NGINX 1.7.1.1.3 Gryphon folder.
  7. Enter the following information in nginx.conf, then save.
    Worker_processes 1; #nginx process number, recommended to be equal to the total number of CPU
    
    Events {
        Worker_connections 1024;#工 工作 工作 与
    }
    
    RTMP_AUTO_PUSH ON;
    
    #RTMP service
    RTMP {
        Server {
    Listen 1935;#service port
    CHUNK_SIZE 4096;#Data Transmission Block Size
    
    Application vod {
    Play./vod;#Video file storage location
    }
    Application Live {
    Live on;#Open live broadcast
    HLS ON;#Open HLS live. This parameter transforms live servers into real-time playback servers
    #Wait_Key on;#保护 视频 片 Slices, this will not produce mosaic
    HLS_PATH./M3U8FILE;#Slices Video File Storage Location (HLS, M3U8 file storage location)
    HLS_FRAGMENT 2S;#每 视频 片
    HLS_PLAYLIST_LENGTH 16S;
    Recorder mytribord {
    Record all manual;
    RECORD_SUFFIX _.FLV;
    RECORD_PATH./REC;
    }
    # hls_continuous on;#Continuous mode
    # hls_cleanup on;#多 多 切 切片
    #HLS_NESTED ON;#Nested mode
    }
    }
    }
    
    #Http service
    HTTP {
        Include mime.types;
        DEFAULT_TYPE Application/OCTET-stream;
        Sendfile on;
        Keepalive_Timeout 65;
    
        Server {
            Listen 80;
            Server_name localhost;
    
            Location/{
                Root HTML;
                Index index.html index.htm;
            }
    
            Location/Live_HLS {
    Types {
    # m3u8 Type settings
    Application/VND.Apple.mpegURL M3U8;
    #TS Split file settings
    VIDEO/MP2T TS;
    }
    # Point to access the M3U8 file directory
    Alias ​​./m3u8file;
    Add_header cache-control no-cache;#禁 缓 缓止
    }
    
            Location/Control {
    RTMP_CONTROL ALL;
    }
    
    Location/stat {
    RTMP_STAT ALL;
    RTMP_STAT_STYLESHEET STAT.XSL;
    }
    Location/stat.xsl {
    Root./nginx-rtmp-module-master;
    }
    
           #Redirect Server Error Pages to the static page/50x.html
            #
            Error_Page 500 502 503 504/50X.html;
            Location =/50X.html {
                Root HTML;
            }
        }
    }
    
  8. Then type the following command into the command prompt in the directory that contains Nginx.exe:
    nginx.exe -t

    This command’s purpose is to determine whether the NGINX configuration file is accurate. The configuration file nginx.conf is accurate when the information is output.

  9. By performing the above steps, we can confirm that the NGINX configuration file is correct before starting NGINX. Type the command into the command prompt  in the directory that contains nginx.exe:
    Start Nginx

Once the input is complete, enter the IP address of the machine hosting Nginx in the browser to show that Nginx has started successfully. Use the test-config.bat file to check for configuration errors each time you make a change to see if nginx picks them up. It is safe to (re)start Nginx if it detects no errors. If it does identify an error, it will inform us of it so we can quickly change the relevant setting before running test-config.bat once more.

Please make sure that OBS or any other live-streaming application is correctly configured before we test the setup. The live stream key should be “stream,” and the stream URL should be “rtmp:/localhost/live.”

We can create a stream and draw the test after launching NGINX. The act of transmitting data from the acquisition stage to the server is the “pushing through,” and in this case, the aaters pushed the locally acquired voice and video stream to the media server. It is the process of sending the site’s video signal to the network. The media file video3. Then push mp4 into nginx using FFMPEG and play it using VLC in the example below.

Run the following command in Windows command prompt:

ffmpeg -i video3.mp4 -f flv rtmp://127.0.0.1/live/test1

Pull Flow Test

Drawing alludes to the user’s end of the game, from the server to the client. We will use a video player like VLC to play the voice-over-video stream that Nginx passes through it. After following the instructions for the lightning described above, we launch VLC in Windows, click “Open Network Skestall,” and then click “Play.”

Then enter the network URL, rtmp://127.0.0.1/live/test1

The video screen can be seen in the VLC, proving that the draw was successful.

Play live state monitoring

We can download the nginx-rtmp-module-master.zip file here: https://github.com/arut/nginx-rtmp-module/. After it has been compressed, copy it to the directory: nginx 1.7.11.3 Gryphon.

Then in the file stat.xsl can then be found in the Nginx-RTMP-MODULE-MASTER directory. This merely matches the configuration settings in the nginx.conf configuration file.

Then we type http://127.0.0.1/stat into the browser. On the page, there is a live status monitor.

Issues and Precautions

  1. Firstly, start NGINX error. The NGINX installation path contains the root of the issue.
  2. Then use VLC to extract the video after that; it will be extremely blurry. We can solve this issue by changing the FFMPEG command, as shown below, and pulling the stream playback.
    ffmpeg -re -i video3.mp4 -vcodec h264 -Acodec copy -f flv rtmp://127.0.0.1/live/test1
  3. 1935 (RTMP service port) and 80 are the default ports for NGINX servers (HTTP port). Use the “NetStat -ano” command in the command prompt to check if the two ports have been used before starting NGINX and to make sure that no other programs are using them.
  4. Finally, it’s best to disable the firewall where the computer is located before launching NGINX.

[Looking for a solution to another query? We are just a click away.]

Conclusion

To conclude, our Support team went over the NGINX RTMP Module in Windows details along with its setup.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

Обновлено Обновлено:
Опубликовано Опубликовано:

Вещание видео будет осуществляться с помощью модуля для nginx — nginx-rtmp-module.

Для этого необходимо собрать веб-сервер nginx из исходников, включив вышеназванный модуль.

Содержание:

Сборка программного обеспечения
Захват видео с камер
Несколько камер
Запись
HLS
MPEG-DASH
Директивы

Сборка NGINX + nginx-rtmp-module

Для удобства работы с nginx, сначала мы установим его из пакетов, хотя бы, чтобы создались скрипты автозапуска.

Установка nginx и пакетов для сборки

Ubuntu:

apt-get install nginx libpcre++-dev libssl-dev libxslt1-dev libgd2-xpm-dev libgeoip-dev

CentOS:

Настраиваем репозиторий:

vi /etc/yum.repos.d/nginx.repo

[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1

yum install nginx pcre-devel openssl-devel

Сборка из исходников

Смотрим версию установленного пакета:

nginx -v

Теперь переходим по ссылке https://nginx.org/download и копируем ссылку на установленную версию nginx (архив tar.gz). В моем случае, это была версия 1.10.0.
* обратите внимание, что в данном списке версии идут не по порядку — ориентируйтесь по дате (средняя колонка).

Скачиваем исходник:

wget http://nginx.org/download/nginx-1.10.0.tar.gz

Скачиваем модуль:

wget https://github.com/arut/nginx-rtmp-module/archive/master.tar.gz

Распаковываем исходник nginx и модуль:

tar xzf nginx-1.10.0.tar.gz

tar xzf master.tar.gz

И переходим в распакованный каталог nginx:

cd nginx-1.10.0

Смотрим, с какими опциями собран уже установленный nginx:

nginx -V

Копируем текст, который идет после configure arguments:

Теперь конфигурируем nginx со скопированными опциями + —add-module=../nginx-rtmp-module-master. Получиться что-то на вроде:

./configure —with-cc-opt=’-g -O2 -fPIE -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2′ —with-ld-opt=’-Wl,-Bsymbolic-functions -fPIE -pie -Wl,-z,relro -Wl,-z,now’ —prefix=/usr/share/nginx —conf-path=/etc/nginx/nginx.conf —http-log-path=/var/log/nginx/access.log —error-log-path=/var/log/nginx/error.log —lock-path=/var/lock/nginx.lock —pid-path=/run/nginx.pid —http-client-body-temp-path=/var/lib/nginx/body —http-fastcgi-temp-path=/var/lib/nginx/fastcgi —http-proxy-temp-path=/var/lib/nginx/proxy —http-scgi-temp-path=/var/lib/nginx/scgi —http-uwsgi-temp-path=/var/lib/nginx/uwsgi —with-debug —with-pcre-jit —with-ipv6 —with-http_ssl_module —with-http_stub_status_module —with-http_realip_module —with-http_auth_request_module —with-http_addition_module —with-http_dav_module —with-http_geoip_module —with-http_gunzip_module —with-http_gzip_static_module —with-http_image_filter_module —with-http_v2_module —with-http_sub_module —with-http_xslt_module —with-stream —with-stream_ssl_module —with-mail —with-mail_ssl_module —with-threads —add-module=../nginx-rtmp-module-master

Собираем исходник:

make

И выполняем установку:

make install

Запускаем веб-сервер:

systemctl start nginx

Настройка захвата видео

Если используется брандмауэр, не забываем добавить в разрешения tcp порт 1935.

Установка утилит

Ubuntu:

apt-get install ffmpeg rtmpdump

CentOS:

Устанавливаем расширенный репозиторий пакетов EPEL:

yum install epel-release

Тянем дополнительный репозиторий:

rpm -Uvh http://li.nux.ro/download/nux/dextop/el7/x86_64/nux-dextop-release-0-5.el7.nux.noarch.rpm

Теперь можно устанавливать пакеты:

yum install ffmpeg rtmpdump

Настройка NGINX

Открываем на редактирование следующий файл:

vi /etc/nginx/nginx.conf

И дописываем следующее:

rtmp {
    server {
        listen 1935;
        application cam1 {
            live on;
        }
    }
}

* важно, чтобы данный блок шел не внутри, а отдельно от основного http.

Перезагружаем сервис:

systemcl restart nginx

На данном этапе мы настроили простейший rtmp-сервер, который сможет принимать запросы на передачу видео.

Чтобы проверить его работу, воспользуемся ранее установленной утилитой ffmpeg:

ffmpeg -i rtsp://admin:admin@192.168.0.12:554/Streaming/Channels/1/ -c copy -f flv rtmp://127.0.0.1/cam1/stream

* где admin:admin — логин и пароль на подключение к веб-камере; 192.168.0.12 — IP-адрес камеры; cam1 — имя application, которое мы задали в конфигурационном файле nginx; stream — произвольное название для потока.

В подтверждение правильного выполнения команды, мы увидим что-то наподобие:

frame= 1381 fps= 26 q=-1.0 size=   27586kB time=00:00:55.27 bitrate=4088.6kbits/
frame= 1394 fps= 26 q=-1.0 size=   27822kB time=00:00:55.79 bitrate=4085.1kbits/
frame= 1407 fps= 26 q=-1.0 size=   28131kB time=00:00:56.31 bitrate=4092.5kbits/
frame= 1420 fps= 26 q=-1.0 size=   28371kB time=00:00:56.83 bitrate=4089.6kbits/
frame= 1433 fps= 26 q=-1.0 size=   28609kB time=00:00:57.35 bitrate=4086.5kbits/
frame= 1446 fps= 26 q=-1.0 size=   28852kB time=00:00:57.87 bitrate=4084.1kbits/

Теперь можно запустить приложение воспроизведения видео, например, VLC плеер и подключиться к веб-серверу (МедиаОткрыть URL):

Открываем URL в VLC

Вводим URL: rtmp://192.168.0.100/cam1/stream

* где 192.168.0.100 — IP-адрес сервера nginx; cam1 — наш application; stream — наше произвольное название для потока.

Если мы увидим видео с камеры, значит все настроено верно.

Теперь прерываем работу ffmpeg и открываем конфиг nginx:

vi /etc/nginx/nginx.conf

И добавляем следующее:

rtmp {
    server {
        listen 1935;
        application cam1 {
            live on;
            exec_static ffmpeg -i rtsp://admin:admin@192.168.0.12:554/Streaming/Channels/1/ -c copy -f flv rtmp://127.0.0.1/cam1/stream;
        }
    }
}

Перезапускаем nginx:

systemctl restart nginx

И снова, но уже не запуская вручную ffmpeg, проверяем наличие видеопотока при помощи VLC.

Несколько камер

Открываем nginx.conf:

vi /etc/nginx/nginx.conf

Настраиваем автоматическое определение воркеров:

worker_processes auto;

* оптимальное число одновременных потоков, позволит nginx работать быстрее.

В корень конфига добавляем:

rtmp_auto_push on;

* включает локальные ретрансляции для использования нескольких воркеров.

Теперь переходим к настройкам rtmp и приводим наш конфиг к следующему виду:

rtmp {
    server {
        listen 1935;
        application cam1 {
            live on;
            exec_static ffmpeg -i rtsp://admin:admin@192.168.0.12:554/Streaming/Channels/1/ -c copy -f flv rtmp://127.0.0.1/cam1/stream;
        }
        application cam2 {
            live on;
            exec_static ffmpeg -i rtsp://admin:admin@192.168.0.13:554/Streaming/Channels/1/ -c copy -f flv rtmp://127.0.0.1/cam2/stream;
        }
    }
}

На самом деле, его можно также настроить так:

rtmp {
    server {
        listen 1935;
        application cam1 {
            live on;
        }
        application cam2 {
            live on;
        }
        exec_static ffmpeg -i rtsp://admin:admin@192.168.0.12:554/Streaming/Channels/1/ -c copy -f flv rtmp://127.0.0.1/cam1/stream;
        exec_static ffmpeg -i rtsp://admin:admin@192.168.0.13:554/Streaming/Channels/1/ -c copy -f flv rtmp://127.0.0.1/cam2/stream;
    }
}

Или так:

rtmp {
    server {
        listen 1935;
        application cams {
            live on;
        }
        exec_static ffmpeg -i rtsp://admin:admin@192.168.0.12:554/Streaming/Channels/1/ -c copy -f flv rtmp://127.0.0.1/cams/stream1;
        exec_static ffmpeg -i rtsp://admin:admin@192.168.0.13:554/Streaming/Channels/1/ -c copy -f flv rtmp://127.0.0.1/cams/stream2;
    }
}

И перезапускаем nginx:

systemctl restart nginx

Запись

Для хранения видео на сервер, есть также несколько варинатов настройки.

1-й вариант: использование нескольких application. В каждом из них своя папка для хранения видео:

rtmp {
    record all;
    live on;
    server {
        listen 1935;
        application cam1 {
            record_path /tmp/record1;
            exec_static ffmpeg -i rtsp://admin:admin@192.168.0.12:554/Streaming/Channels/1/ -c copy -f flv rtmp://127.0.0.1/cam1/stream;
        }
        application cam2 {
            record_path /tmp/record2;
            exec_static ffmpeg -i rtsp://admin:admin@192.168.0.13:554/Streaming/Channels/1/ -c copy -f flv rtmp://127.0.0.1/cam2/stream;
        }
    }
}

Создаем папки:

mkdir /tmp/record1 /tmp/record2

Задаем права (владельца):

chown nginx:nginx /tmp/record*

2-й вариант: один application с разными именами для потоков:

rtmp {
    server {
        listen 1935;
        application cams {
            live on;
            record all;
            record_path /tmp/record;
        }
        exec_static ffmpeg -i rtsp://admin:admin@192.168.0.12:554/Streaming/Channels/1/ -c copy -f flv rtmp://127.0.0.1/cams/stream1;
        exec_static ffmpeg -i rtsp://admin:admin@192.168.0.13:554/Streaming/Channels/1/ -c copy -f flv rtmp://127.0.0.1/cams/stream2;
    }
}

Необходимо также создать папку и задать владельца:

mkdir /tmp/record

chown nginx:nginx /tmp/record

и не забываем перезагрузить nginx:

systemctl restart nginx

Полезные опции для записи

record_suffix -%Y-%m-%d-%H-%M-%S.flv;
record_max_size 5120K;
record_interval 3m;

record_suffix — добавляет окончание к каждому созданному файлу.
record_max_size — ограничивает размер каждого файла определенным объемом (в данном примере, 5 Мб). При лимите, будет создан новый файл.
record_interval — ограничивает файл видеофрагментом в несколько минут (в нашем примере, 3).

HLS

Прежде, чем начать, убедитесь, что брандмауэр отключен или пропускает http-запросы. Selinux на момент проведения тестов, лучше отключить.

Протокол HLS позволяем транслировать потоковое видео поверх HTTP. Это позволит сэкономить ресурсы сервера при множественном обращении и создать более кроссплатформенную инфраструктуру.

Для его включения, приводим наш nginx.conf к следующему виду:

rtmp {
    live on;
    hls on;
    hls_fragment 5s;
    server {
        listen 1935;
        application cam1 {
            hls_path /tmp/cam1;
        }
        application cam2 {
            hls_path /tmp/cam2;
        }
        exec_static ffmpeg -i rtsp://admin:admin@192.168.0.12:554/Streaming/Channels/1/ -c copy -f flv rtmp://127.0.0.1/cam1/stream;
        exec_static ffmpeg -i rtsp://admin:admin@192.168.0.13:554/Streaming/Channels/1/ -c copy -f flv rtmp://127.0.0.1/cam2/stream;
    }
}

Перезапуск:

systemctl restart nginx

Ждем 4-5 секунд и смотрим содержимое папок в /tmp:

ls /tmp/cam1

ls /tmp/cam2

Внутри каждой из них мы должны увидеть файл с расширением m3u8 — это плейлист с видеонарезками. Если файлы есть, значит HLS заработал.

Осталось научить наш NGINX отдавать данные файлы. Для этого в секции http добавим:

    location / {
        root /tmp;
    }

И снова:

systemctl restart nginx

В том же VLC для проверки вводим следующий URL:

http://192.168.0.100/cam1/stream.m3u8

MPEG-DASH

Как альтернатива HLS, используется для видеотрансляции поверх HTTP. Его основные преимущества — поддержка со стороны большого количества браузеров и работа на javascript-плеере.

И так, его настройка сильно напоминает настройку HLS. В конфиге NGINX:

rtmp {
    live on;
    dash on;
    server {
        listen 1935;
        application cams {
            dash_path /tmp/cams;
        }
        exec_static ffmpeg -i rtsp://admin:admin@192.168.0.12:554/Streaming/Channels/1/ -c:v libx264 -profile:v baseline -c:a libfaac -ar 44100 -f flv rtmp://127.0.0.1/cams/stream1;
        exec_static ffmpeg -i rtsp://admin:admin@192.168.0.13:554/Streaming/Channels/1/ -c:v libx264 -profile:v baseline -c:a libfaac -ar 44100 -f flv rtmp://127.0.0.1/cams/stream2;
    }
}

* обратите внимание, здесь мы решили настроить все в одном application с разными потоками для каждой камеры. И не потому, что так нужно для MPEG-DASH — скорее для демонстрации возможности различных способов конфигурации.
** также можно заменить, что мы добавили опции конвертации потока при переводе его в RTMP — это важно для MPEG-DASH.

Перезапускаем nginx:

systemctl restart nginx

Проверяем появление файлов с расширением .mpd.

ls /tmp/cams

Если они есть, переходим в /tmp

cd /tmp

И выполняем следующую команду:

git clone https://github.com/arut/dash.js.git

* мы скачали js-плеер для просмотра dash-видео.
** по хорошему, в продуктивной среде следует создать отдельный виртуальный домен и хранить все файлы в специальной выделенной директории, а не в каталоге /tmp. Для теста это не принципиально.

И создаем новую ветку live:

cd dash.js

git checkout live

Проверим работу плеера. Открываем браузер и вводим следующий URL:

http://192.168.0.100/dash.js/baseline.html

* где 192.168.0.100 — IP-адрес нашего видео-сервера.

И нажимаем play — начнется показ демонстративного видео.

Теперь откроем файл baseline.html внутри папки dash.js:

vi /tmp/dash.js/baseline.html

Найдем строчку:

url = «http://dash.edgesuite.net/envivio/dashpr/clear/Manifest.mpd»,

И заменим ее на:

url = «http://192.168.0.100/cams/stream1.mpd»,

* где cams — наш application; stream1 — имя потока с первой камеры.

И снова открываем браузер и вводим:

http://192.168.0.100/dash.js/baseline.html

Полезные директивы

respawn_timeout 15s;
chunk_size 8192;

respawn_timeout — время ожидания перед повторным запуском дочернего процесса. По умолчанию, 5 секунд.
chunk_size — максимальный размер порции для мультиплексирования потока. По умолчанию, 4096.

Полный перечень директив опубликован Романом Арутюняном по ссылке:

https://github.com/arut/nginx-rtmp-module/wiki/Directives

🚀 Introduction

Welcome to our guide on setting up an Nginx RTMP server on Windows! If you’re looking to host live streaming events or pre-recorded videos, an Nginx RTMP server can be an excellent choice. In this article, we’ll walk you through the entire process step-by-step so you can set up your own server with ease. Let’s get started!

📌 What is Nginx RTMP Server?

Before we dive into the setup process, let’s first understand what Nginx RTMP server is. Nginx is a popular open-source web server used for hosting websites, load balancing, and serving as a reverse proxy, among other things. One of the many modules available for Nginx is RTMP, which stands for Real-Time Messaging Protocol.

Nginx RTMP module allows you to host live streaming events or pre-recorded videos, and it can handle multiple streams simultaneously. With an Nginx RTMP server, you can reach a larger audience and customize the streaming experience to your liking.

📌 Why Use Nginx RTMP Server?

There are many reasons why you might want to use an Nginx RTMP server. Here are some of the advantages:

👍 Advantages

Advantages

Description

Free and Open-Source

Nginx RTMP server is free to use and open-source, making it accessible to everyone.

High Performance

Nginx is known for its high performance and can easily handle multiple streams simultaneously.

Customizable

You can customize the streaming experience to your liking and control everything from the quality of the video to the audio output.

Scalable

With Nginx RTMP server, you can easily scale your streaming service as your audience grows.

👎 Disadvantages

Despite its advantages, there are some disadvantages to using an Nginx RTMP server:

Disadvantages

Description

Steep Learning Curve

The setup process for an Nginx RTMP server can be complicated, especially if you’re not familiar with the process.

Requires Technical Expertise

You need to have some technical knowledge of Nginx and server setup to use an Nginx RTMP server effectively.

Requires Resources

Nginx RTMP server requires a dedicated server with a good internet connection, which can be expensive.

🚀 Setting up Nginx RTMP Server on Windows: Step-by-Step Guide

Now that we’ve covered the basics and advantages and disadvantages of Nginx RTMP server, let’s dive into the setup process. Here’s a step-by-step guide:

📌 Step 1: Download and Install Nginx for Windows

The first step is to download and install Nginx for Windows. You can download the installer from the Nginx website. Once you’ve downloaded the installer, run it and follow the installation wizard to install Nginx on your Windows machine.

📌 Step 2: Download and Install RTMP Module for Nginx

After installing Nginx, you need to download and install the RTMP module for Nginx. You can download the module from the Nginx-rtmp GitHub repository.

Once you’ve downloaded the module, extract the files and copy them to the Nginx installation directory.

📌 Step 3: Configure Nginx and RTMP Module

Now that you’ve installed Nginx and the RTMP module, the next step is to configure them. Open the Nginx configuration file located in the conf folder of the Nginx installation directory.

Add the following code to the configuration file:

📌 Step 4: Start Nginx Server

After configuring Nginx and the RTMP module, you need to start the Nginx server. Open the Nginx command prompt and navigate to the Nginx installation directory. Then, type the following command:

📌 Step 5: Test Your RTMP Server

That’s it! Your Nginx RTMP server is now ready to use. To test your server, you can use a streaming software like OBS or VLC player. Simply enter the server URL and key, and you should be able to stream live events or pre-recorded videos.

🚀 Frequently Asked Questions (FAQs)

📌 What is Nginx RTMP module?

The Nginx RTMP module is a plugin for Nginx that allows you to host live streaming events or pre-recorded videos.

📌 Is Nginx RTMP server free?

Yes, Nginx RTMP server is free to use and open-source.

📌 What are the advantages of using Nginx RTMP server?

The advantages of using Nginx RTMP server include being customizable, scalable, and providing high performance.

📌 What are the disadvantages of using Nginx RTMP server?

The disadvantages of using Nginx RTMP server are that it requires technical expertise, a dedicated server, and has a steep learning curve.

📌 Can I use Nginx RTMP server on Windows?

Yes, you can use Nginx RTMP server on Windows.

📌 What is the recommended hardware and internet connection for Nginx RTMP server?

For optimal performance, it’s recommended to have at least an Intel Core i5 processor, 8GB of RAM, and a dedicated internet connection with at least 5 Mbps upload speed.

📌 Can I use Nginx RTMP server for on-demand video streaming?

Yes, you can use Nginx RTMP server to host on-demand video streaming.

📌 Can I use Nginx RTMP server for audio-only streaming?

Yes, you can use Nginx RTMP server to host audio-only streaming.

📌 Can I password protect my Nginx RTMP server?

Yes, you can password protect your Nginx RTMP server by adding a password to the configuration file.

📌 Can I use SSL for my Nginx RTMP server?

Yes, you can use SSL for your Nginx RTMP server by configuring it in the Nginx configuration file.

📌 Can I limit the bitrate for my Nginx RTMP server?

Yes, you can limit the bitrate for your Nginx RTMP server by adding a bitrate limit to the configuration file.

📌 Can I stream to multiple platforms using Nginx RTMP server?

Yes, you can stream to multiple platforms using Nginx RTMP server by setting up multiple RTMP endpoints in the configuration file.

📌 Can I use Nginx RTMP server for live streaming from mobile devices?

Yes, you can use Nginx RTMP server for live streaming from mobile devices by using a streaming app that supports RTMP protocol.

📌 Can I use Nginx RTMP server for live streaming games?

Yes, you can use Nginx RTMP server for live streaming games by using a game streaming software that supports RTMP protocol.

🚀 Conclusion

Congratulations! You’ve now learned how to set up an Nginx RTMP server on Windows. With this guide, you can now host live streaming events or pre-recorded videos for your audience to enjoy. Remember to keep in mind the advantages and disadvantages of using Nginx RTMP server and always ensure that you have the necessary resources and technical expertise to set it up effectively.

📌 Take Action

If you’re ready to get started with hosting your own live events or pre-recorded videos, download Nginx and the RTMP module today and follow our step-by-step guide to set up your server. Good luck!

🚀 Disclaimer

The information provided in this article is for educational purposes only. We do not guarantee the accuracy or completeness of the information in this article, and we are not responsible for any damages or losses that may arise from the use of this information. Always ensure that you have the necessary technical expertise and resources before attempting to set up an Nginx RTMP server.

Video:Setting up an Nginx RTMP Server on Windows: A Step-by-Step Guide

  • Nginx mysql php windows nginx
  • Nfs pro street тормозит на windows 10
  • Nfs pro street не нажимается продолжить windows 10
  • Nginx asp net core windows
  • Nfsu2 бесконечная загрузка windows 10