Video streaming với Nginx HLS và ffmpeg trên linux
Nguồn: https://vnsys.wordpress.com/2019/02/28/streaming-media-voi-nginx-va-nginx-rtmp-module/
1. Về nginx-rtmp module
Nginx-rtmp là module mở rộng, mà kết hợp với Nginx để cho phép xây dựng máy chủ streaming media.
Một số tính năng mà nginx-rtmp hỗ trợ:
- RTMP/HLS/MPEG-DASH live streaming
RTMP Video on demand FLV/MP4, phát từ local file hoặc qua HTTP
Stream relay support for distributed streaming: push & pull models
Ghi streams vào nhiều tệp FLV
Hỗ trợ H264/AAC
Transcode trực tuyến với FFmpeg
HTTP callbacks (publish/play/record/update etc)
Module điều khiển HTTP để recording audio/video and dropping clients
Kỹ thuật buffer tiên tiến để giữ cho bộ nhớ được cấp ở mức thấp nhất mà streaming vẫn nhanh.
Kết hợp được với các ứng dụng như Wirecast, FMS, Wowza, JWPlayer, FlowPlayer, StrobeMediaPlayback, ffmpeg, avconv, rtmpdump, flvstreamer, ..
Thống kê stream với định dạng XML/XSL
Linux/FreeBSD/MacOS/Windows
2. Cài đặt Nginx với module nginx-rtmp
Step1: Download & unpack latest stable nginx & nginx-rtmp version
1 2 3 4 5 | cd /optsudo git clone git://github.com/arut/nginx-rtmp-module.gitsudo tar xzf nginx-1.14.1.tar.gzmv nginx-1.14.1 nginx |
Step2: Build nginx với nginx-rtmp
1 2 3 4 5 6 7 8 9 10 11 | sudo ./configure --prefix=/etc/nginx \--pid-path=/var/run/nginx.pid \--conf-path=/etc/nginx/nginx.conf \--sbin-path=/usr/sbin/nginx \--user=nginx \--group=nginx \--with-file-aio \--with-http_ssl_module \--add-module=nginx-rtmp-modulesudo makesudo make install |
Step3: Run Nginx với systemd
- Create tệp /lib/systemd/system/nginx.service với nội dung sau:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Description=nginx - high performance web serverDocumentation=http://nginx.org/en/docs/After=network-online.target remote-fs.target nss-lookup.targetWants=network-online.target[Service]Type=forkingExecStartPre=/usr/sbin/nginx -t -c /etc/nginx/nginx.confExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.confExecReload=/bin/kill -s HUP $MAINPIDExecStop=/bin/kill -s QUIT $MAINPID[Install]WantedBy=multi-user.target |
- Start Nginx service
1 2 | systemctl enable nginx.servicesystemctl start nginx.service |
3. VOD qua RTMP
Chúng ta sẽ cấu hình để cho phép các video player xem video qua giao thức RTMP.
3.1 Cấu hình Nginx
Step1: Tạo tệp tin cấu hình nginx với nội dung sau:
user nginx;
worker_processes 1;
pid /run/nginx.pid;
user nginx;
events {
worker_connections 1024;
}
rtmp {
server {
listen 1935;
chunk_size 4000;
# video on demand for mp4 files
application vod {
play /var/mp4s;
}
}
}
http {
access_log /var/log/nginx/access-streaming.log;
error_log /var/log/nginx/error-streaming.log;
server {
listen 80;
root /var/www/html;
# RTMP statistics in XML
location /stat {
# Copy stat.xsl put to root directory
rtmp_stat all;
rtmp_stat_stylesheet stat.xsl;
}
}
}Thông tin cấu hình tệp cấu như sau:
Khối rtmp { }
- listen port với 1935 (port default)
application với đường dẫn ảo là vod
Đường dẫn thư mục chứa các tệp video để phát là “/var/mp4s”.
Khi đó muốn sử dụng chúng ta truy cập kiểu như “rtmp://192.168.10.113:1935/vod/video-name.mp4”
Trong đó: Địa chỉ 192.168.10.113 là địa chỉ streaming server mà chúng ta sẽ sử dụng trong bài viết này.
Step2: Tạo thư mục chứa và copy tệp tin video
1 2 | mkdir /var/mp4scd /var/mp4s |
Chúng ta download hoặc copy một tin video vào thư mục /var/mp4s
3.2. Sử dụng Video Player để chạy video
Chúng ta có thể sử dụng một trình phát video có hỗ trợ giao thức rtmp để phát.
Ở đây, chúng ta có thể sử dụng VLC player
Mở player VLC → Nhấn Media → Chọn “Open Network Stream ..”. Sau đó vào thông tin đường dẫn tệp video vod với rtmp://192.168.10.113:1935/vod/vod.mp4

Cuối cùng nhấn Play để phát video.

4. VOD qua HLS
Chúng ta sẽ cấu hình để cho phép video player phát video qua giao thức HLS (Apple HTTP Live Streaming).
4.1 Cài đặt Ffmpeg
Sử dụng script Installing FFmpeg on Linux
Nếu chỉ sử dụng một thư viện có sẵn thì cài đặt đơn giản như sau trên CentOS
yum install ffmpeg ffmpeg-devel ffmpeg-libpostproc
Trong phần Cài đặt FFmpeg, cũng đã giới thiệu và cách sử dụng cơ bản FFmpeg.
4.2 Convert tệp vod.mp4 sang HLS
Trước khi convert, chúng ta thực hiện copy/download tệp tin video lên server (ví dụ tệp tin là vod.mp4)
Sử dụng lệnh ffmpeg để convert vod.mp4 sang định dạng HLS (Apache HTTP Live Stream)
ffmpeg -i video.mp4 -profile:v baseline -level 3.0 -s 720x400 -start_number 0 -hls_time 10 -hls_list_size 0 -f hls /tmp/index.m3u8
Trong đó:
- vod.mp4 là tệp video đầu vào cần convert
index.m3u8 là tệp tin master đầu ra của HLS playlist
và một số tham số tùy chọn cho độ phân giải, thời gian phân đoạn, ..
4.3 Cấu hình nginx
Ở đây, Chúng ta sẽ cấu hình nginx làm web server, đồng thời cấu hình làm media server.
user nginx;
worker_processes 1;
error_log logs/rtmp_error.log debug;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
#serve the player for HLS
server {
listen 80;
root /var/www/html;
server_name localhost;
location /hls {
# CORS setup
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length';
# Allow CORS preflight requests
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
types {
application/vnd.apple.mpegurl m3u8;
video/mp2t ts;
}
add_header Cache-Control no-cache;
alias /tmp;
}
}
}- Listen với port default 80
URL của web server sẽ là http://192.168.10.113/; với root directory là /var/www/html
URL của stream server sẽ là http://192.168.10.113/hls
Playlist của stream là tệp tin m3u8, với các segment là tệp ts
Đường dẫn thư mục chứa các playlist là /tmp
4.4 Phát video trên web browser với videojs
Chúng ta có thể phát video trên web browser, mà sử dụng flash player như Flowplayer hay Jwplayer. Trong trường hợp này, tôi sẽ giới thiệu sử dụng videojs player cho phát video trên web browser.
Link về videojs: https://github.com/videojs/http-streaming
Trên Nginx web server, chúng ta sẽ tạo tệp tin index.html vào root directory:
Download mẫu tệp index.html
Trong tệp index.html chúng ta sẽ vào đường dẫn chứa tệp tin playlist mà đã convert ở Step2. Khi đó vào thông tin đường dẫn URL ở đây là http://192.168.10.113/hls/index.m3u8
Cuối cùng duyệt http://192.168.10.113/index.html và xem kết quả

Chúng ta thấy videojs cho khung nhìn tuyệt đẹp.
5. Cấu hình Live Streaming
Live Streaming là tính năng chính của nginx-rtmp module, và quá trình thực hiện live streaming sẽ qua giao thức RTMP.
Các bước cho thực hiện quá trình Live Streaming như sau:
5.1 Cấu hình Nginx để làm live streaming server
Step1: Tạo tệp tin nginx.conf với nội dung sau
user nginx;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
#RTMP configuration
rtmp {
server {
listen 1935;
application live {
live on;
# Push the stream to the local HLS application
push rtmp://localhost:1935/hls;
}
application hls {
live on;
# Only accept publishing from localhost.
allow publish 127.0.0.1;
deny publish all;
# Streams as HLS
hls on;
hls_path /tmp/hls;
hls_fragment 3s;
hls_nested on;
hls_fragment_naming system;
}
}
}
#HTTP Configuration
http {
sendfile off;
tcp_nopush on;
aio on;
directio 512;
default_type application/octet-stream;
server {
listen 80;
root /var/www/html;
server_name localhost;
location /hls {
# Disable cache
add_header 'Cache-Control' 'no-cache';
# CORS setup
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length
# allow CORS preflight requests
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
# MIME type for HLS
types {
application/dash+xml mpd;
application/vnd.apple.mpegurl m3u8;
video/mp2t ts;
}
alias /tmp/hls;
}
# RTMP statistics in XML
location /stat {
rtmp_stat all;
rtmp_stat_stylesheet stat.xsl;
}
}
}Ở đây, chúng ta sẽ cấu hình nginx làm nhiệm vụ là web server và live streaming server.
- Block http { } : Dựng nginx làm web server với mục đích thống kê số liệu, cho phép người dùng xem live streaming. Nếu không cần dùng các chức năng này, chúng ta có thể qua bỏ block này. Quá trình tạo server cho xem live streaming có thể thực hiện ở server khác.
Block rtmp { } : Dựng nginx làm live streaming server, để thực hiện quá trình thu phát live streaming từ client và publish luồng
Diễn giải một số directive cho cấu hình nginx trên như sau:
- live on: Bật tính năng live stream.
push rtmp://localhost:1935/hls : Thực hiện push streaming vào /hls
allow publish 127.0.0.1; Khai báo server từ xa được phép push stream đến hệ thống. Ở đây chúng ta sẽ khai báo localhost được phép push stream đến hệ thống localhost. Kết hợp với
deny publish all, nhằm hạn chế remote server nào đó push stream vào hệ thống của mình.deny publish all;
hls on: Bật chế độ HLS, cho phép client có thể sử dụng chế độ này
hls_path /tmp/hls: Thiết lập đường dẫn thư mục chứa playlist và fragments của HLS. Nếu không chỉ định thì nó tự động tạo.
hls_fragment 3s: Thực hiện tạo mỗi fragment với 03 second (fragment *.ts). Thường thì mỗi tệp ts được sinh ra gồm 3s + time decode)
hls_nested on; Bật chế độ lồng. Dùng để tạo ra một subdirectory của “hls_path” cho mỗi stream. Playlist và fragments sẽ được tạo ra cùng thư mục đó. Ví dụ /tmp/hls/
stream-name. Mặc định chế độ này là off, vì vậy stream sẽ tạo ra playlist và fragments ở thư mục của của đường dẫn hls_path, với kiểu tên là stream-name-..ts và stream-name.m3u8hls_fragment_naming system: Tên của fragment, có thể định dạng với các kiểu “system, sequential, timestamp”
Step2: Tạo thư mục và copy tệp statistics dạng xml
1 2 3 4 | mkdir /tmp/hlschown -R nginx:nginxcopy /opt/nginx/nginx-rtmp-module/stat.xsl /var/www/htmlsystemctl restart nginx |
Step3: Tạo tệp tin index.html
Chúng ta thực hiện tạo tệp tin tĩnh live.html để tạo web player cho xem live streaming qua web browser
Download tệp mẫu tại: live.html
Note: Thay đường dẫn http://192.168.10.113/hls/stream/index.m3u8 với đường dẫn chứa thông tin tệp stream phù hợp.
5.2 Thực hiện live streaming từ mobile
Sử dụng một phần mềm live streaming bất kỳ, hỗ trợ giao thức RTMP. Ở đây, tôi sử dụng android nên cài đặt soft Larix Broadcaster
- Mở Larix Broadcaster → Nhấn biểu tượng Setting → Connections → Sau đó vào các thông tin kết nối đến Live Streaming server.
rtmp://192.168.10.113:1935/live/stream
(Với tên “stream” là tên bất kỳ do mình đặt. Tên này sau khi lên live server, tương ứng với biến $name)
- Cuối cùng nhấn vào biểu tượng quay phát để live streaming thôi
5.3 Kiểm tra quá trình Live Streaming
Step1: Xem thông tin tệp streaming trên server
Dùng lệnh để list xem quá trình sinh ra luồng stream với tệp playlist và fragments

Step2: Thực hiện xem live stream qua web browser
Mở web browser và truy cập http://192.168.10.113/live.html để xem live streaming

Step3: Xem thống kê số liệu streaming
Truy cập http://192.168.10.113/stat

Một số trang tham khảo
Nhận xét
Đăng nhận xét