nginx-rtmp-module實現mpeg-dash流直播服務(一)

前言

這個系列第一篇就來教如何把本地影片串流到網頁上。
nginx-rtmp-module是一套NGINX-based Media Streaming Server,不過nginx-rtmp-module不包含media decoder,故需要搭配ffmpeg把目標影片輸出成mpeg-dash流。

mpeg-dash(MPEG Dynamic Adaptive Streaming over HTTP)是MPEG設計的一個streaming of media content技術,類似的有Apple設計的HLS(Apple HTTP Live Streaming)。

local端若是用網頁呈現,由於mpeg-dash不是瀏覽器原生支援,所以需要載入dash.js來讀取前面輸出的mpeg-dash流。

使用套件

  1. nginx-rtmp-module
  2. ffmpeg
  3. dash.js

安裝nginx-rtmp-module

https://github.com/arut/nginx-rtmp-module/wiki/Installing-via-Build
nginx-rtmp-module安裝官方寫的很清楚,這邊就不再贅述。
git clone下來compile且安裝完,接下來就是config的配置。

nginx-rtmp-module config配置

簡單的配置可以參考官方doc
主要設定檔位於/usr/local/nginx/conf/nginx.conf

以下是我的配置nginx.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#user nobody;
worker_processes 1;
error_log logs/error.log debug;
events {
worker_connections 1024;
}
rtmp {
server {
listen 1935;
application myapp {
live on;
dash on;
dash_path /tmp/dash;
}
}
}
http {
server {
listen 8080;
location /dash {
root /tmp;
add_header Cache-Control no-cache;
add_header 'Access-Control-Allow-Origin' '*';
}
location /dash.js {
root /home/;
}
}
}

關閉/開啟nginx
sudo /usr/local/nginx/sbin/nginx -s stop
sudo /usr/local/nginx/sbin/nginx

影片轉換mpeg-dash流並推播

安裝ffmpeg套件
sudo apt-get install ffmpeg
mp4轉成mpeg-dash流並推播到rtmp://localhost/myapp/mystream
ffmpeg -re -i [video_path].mp4 -c copy -f flv rtmp://localhost/myapp/mystream

網頁接收mpeg-dash流畫面

根據上面config的設定,我們nginx有兩個輸出方式rtmp、http,所以我們可以透過這兩個方式來接收。

rtmp demo:

ffplay是ffmpeg裡的一個播放器,可以用他來接收rtmp流來做簡單的測試。
ffplay rtmp://localhost/myapp/mystream

http demo:

如果我們想要以網頁呈現就要走http protocol了

  1. 網頁端import dash.js
  2. 接收目標http url串流來呈現
    (http://localhost:8080/dash/mystream.mpd)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script src="https://cdn.dashjs.org/latest/dash.all.min.js"></script>
<style>
video {
width: 640px;
height: 360px;
}
</style>
<body>
<div>
<video data-dashjs-player autoplay src="http://localhost:8080/dash/mystream.mpd" controls></video>
</div>
</body>

NGinx Default public www location /usr/local/nginx/html
demo http://localhost:[port]/[file_path].html
類似 http://localhost:8080/test.html

參考

  1. http://blog.csdn.net/u011432426/article/details/54730581
  2. https://streamroot.readme.io/v1.8/docs/nginx-rtmp
  3. Enable CORS https://streamroot.readme.io/v1.8/docs/nginx-http
  4. Nice Youtube Video http://livestreamninja.com/live-streaming-with-nginx-and-ffmpeg/