前言
搭建基于nginx
+ nginx-rtmp-module
的rtmp协议的推流服务器。
环境Centos 7 + Nginx
我平常nginx都是用yum安装的,这里需要编译安装
所以这篇文章最大可能和yum安装的nginx保持相同的配置
yum安装目录介绍
/usr/sbin/nginx
执行文件/usr/lib64/nginx/modules/
依赖模块目录/etc/nginx
配置文件路径/usr/share/nginx
默认的站点目录
安装Nginx和相关依赖
0、查看Nginx的版本和依赖
1 | nginx -V |
1、安装Nginx及其依赖库:
1 | #安装Nginx的编译环境gcc |
2、下载可编译的nginx
1 | cd /usr/local/ |
3、备份文件
1 | cp -r /etc/nginx /etc/nginx_bak |
下载rtmp模块
仓库地址:nginx-rtmp-module
1 | cd /usr/lib64/nginx/modules/ |
添加依赖
1 | cd /usr/local/nginx/ |
添加Nginx环境变量,可以在命令行直接输入Nginx命令
1 | vim /etc/profile |
在最后添加Nginx的路径
1 | export NGINX_HOME=/usr/local/nginx |
重新编译环境变量
1 | source /etc/profile |
配置Nginx的rtmp服务站点:1
vim /usr/local/nginx/conf/nginx.conf
在http内部添加
1 | include /etc/nginx/conf.d/*.conf; |
在文件底部(和http同级)添加下面内容:
1 | rtmp { |
启动nginx
1 | cd /usr/local/nginx/sbin |
查看端口是否能访问
1 | telnet 你的ip地址 1935 |
http-flv
nginx-rtmp-module
是不支持直接转换为http-flv
的,所以就没法在Web端不使用flash的前提下播放流。
所以就有基于nginx-rtmp-module
开发的nginx-http-flv-module
官方GitHub:https://github.com/winshining/nginx-http-flv-module/blob/master/README.CN.md
安装
nginx-http-flv-module
包含了 nginx-rtmp-module 所有的功能,所以不要将 nginx-http-flv-module
和 nginx-rtmp-module 一起编译。
下载 NGINX 和 nginx-http-flv-module
。
将它们解压到某一路径。
打开 NGINX 的源代码路径并执行:
将模块编译进NGINX
1 | ./configure --add-module=/path/to/nginx-http-flv-module |
或者
将模块编译为动态模块
1 | ./configure --add-dynamic-module=/path/to/nginx-http-flv-module |
注意
如果将模块编译为动态模块,那么 NGINX 的版本号必须大于或者等于 1.9.11。
配置
关于 nginx-rtmp-module 用法的详情,请参考 README.md。
注意
这里没有http-flv的配置 http-flv见下文
配置
1 | rtmp { |
发布
为了简单起见,不用转码:
1 | ffmpeg -re -i MEDIA_FILE_NAME -c copy -f flv rtmp://example.com[:port]/appname/streamname |
注意
一些旧版本的 FFmpeg 不支持选项 -c copy
,可以使用选项 -vcodec copy -acodec copy
替代。
appname
用于匹配 rtmp 配置块中的 application 块(更多详情见下文)。
streamname
可以随意指定,但是不能省略。
RTMP 默认端口为 1935,如果要使用其他端口,必须指定 :port
。
播放
HTTP-FLV 方式
1 | http://example.com[:port]/dir?[port=xxx&]app=appname&stream=streamname |
注意
- 如果使用 ffplay 命令行方式播放流,那么必须为上述的 url 加上引号,否则 url 中的参数会被丢弃(有些不太智能的 shell 会把 “&” 解释为”后台运行”)。
- 如果使用 flv.js 播放流,那么请保证发布的流被正确编码,因为 flv.js 只支持 H.264 编码的视频和 AAC/MP3 编码的音频。
参数 dir
用于匹配 http 配置块中的 location 块(更多详情见下文)。
HTTP 默认端口为 80, 如果使用了其他端口,必须指定 :port
。
RTMP 默认端口为 1935,如果使用了其他端口,必须指定 port=xxx
。
参数 app
的值(appname)用来匹配 application 块,但是如果请求的 app
出现在多个 server 块中,并且这些 server 块有相同的地址和端口配置,那么还需要用匹配主机名的 server_name
配置项来区分请求的是哪个 application 块,否则,将匹配第一个 application 块。
参数 stream
的值(streamname)用来匹配发布的流的名称。
例子
假设在 http
配置块中的 listen
配置项是:
1 | http { |
在 rtmp
配置块中的 listen
配置项是:
1 | rtmp { |
并且发布的流的名称是 mystream
,那么基于 HTTP 的播放 url 是:
1 | http://example.com:8080/live?port=1985&app=myapp&stream=mystream |
注意
由于一些播放器不支持 HTTP 块传输, 这种情况下最好在指定了 flv_live on;
的 location 中指定 chunked_transfer_encoding off
,否则播放会失败。
RTMP 方式
1 | rtmp://example.com[:port]/appname/streamname |
HLS 方式
1 | http://example.com[:port]/hls/streamname.m3u8 |
DASH 方式
1 | http://example.com[:port]/dash/streamname.mpd |
常见的播放器
flv.js 只支持 H.264 编码的视频和 AAC/MP3 编码的音频