1.核心配置
rtmp
保存所有RTMP设置的块
server
声明RTMP服务实例,语法server { ... }
rtmp {server {}
}
listen
为NGINX添加监听套接字以接受RTMP连接。语法: listen (addr[:port]|port|unix:path) [bind] [ipv6only=on|off][so_keepalive=on|off|keepidle:keepintvl:keepcnt|proxy_protocol]
server {listen 1935;
}
application
创建RTMP应用。语法:application name { ... }
server {listen 1935;application myapp {}
}
timeout
套接字超时。该值主要用于写。大多数时候,RTMP模块不期望在除发布者套接字之外的所有套接字上有任何活动。如果你想让损坏的套接字快速断开连接,请使用keepalive或RTMP ping等活动工具。默认值为1分钟。语法: timeout value
timeout 60s;
ping|ping_timeout
RTMP ping间隔。0关闭ping。RTMP ping是用于主动连接检查的协议功能。一个特殊的数据包被发送到远程对等端,预计会在用ping_timeout指令指定的超时内收到回复。如果在此时间内未收到ping回复,则关闭连接。ping的默认值为1分钟。默认ping超时为30秒。
ping 3m;
ping_timeout 30s;
max_streams
设置RTMP流的最大数量。数据流被复用为单个数据流。不同的通道用于发送命令、音频、视频等。默认值为32,这在许多情况下是够用的。
max_streams 32;
ack_window
设置RTMP确认窗口大小。它是接收到的字节数,在该字节数之后,对等方应向远程侧发送确认包。默认值为5000000。
ack_window 5000000;
chunk_size
流多路复用的最大块大小,此值不能小于128,默认值为4096。值越大,CPU开销越低。
chunk_size 4096;
max_queue|max_message
输入数据消息的最大大小。所有输入数据都被拆分为消息(并进一步拆分为块)。部分消息在等待完成时保留在内存中。理论上,传入消息可能非常大,这可能会对服务器稳定性造成问题。默认值1M在许多情况下就足够了。
max_message 1M;
buflen
设置默认缓冲区长度。通常客户端在播放之前发送RTMP set_buflen命令并重置此设置。默认值为1000毫秒。
buflen 5s;
out_queue|out_cork
2.访问
allow|deny
允许从指定地址或所有地址发布/播放。允许/拒绝指令按出现顺序进行检查。语法: allow|deny [play|publish] address|subnet|all
allow publish 127.0.0.1;
deny publish all;
allow play 192.168.0.0/24;
deny play all;
3.执行指令
exec_push
语法:exec_push command arg*
指定要在每个发布的流上执行的带有参数的外部命令。发布停止时,进程终止。第一个参数为二进制文件的完整路径。对于这个过程应该做什么,没有任何假设。这个功能在ffmpeg流转码中很有用。FFmpeg应该作为客户端连接到nginx-rtmp,并将转码后的流作为发布者输出回nginx rtmp。可以在命令行中使用$var/${var}形式的替换:
- $name - stream name
- $app - application name
- $addr - client address
- $flashver - client flash version
- $swfurl - client swf url
- $tcurl - client tc url
- $pageurl - client page url
Shell脚本重定向可以在exec_push指令中指定,用于写入输出和接受输入。确保重定向字符和流名称/编号之间没有空格。
支持的有
- truncating output
>file
- appending output
>>file
- descriptor redirects like
1>&2
- input
<file
Make sure there's no space between redirection character and stream name/number.
您可以指定要执行的命令的完整路径或短命令名。在后一种情况下,在PATH环境变量指定的目录中查找二进制文件。默认情况下,nginx会清除环境,这通常会使rtmp模块仅运行位于/bin和/usr/bin等标准目录中的二进制文件。要使其始终有效,请使用以下nginx指令保留原始PATH变量值。
env PATH;
以下ffmpeg调用将传入流转码为HLS就绪流(H264/AAC)
application src {live on;exec_push ffmpeg -i rtmp://localhost/src/$name -vcodec libx264 -vprofile baseline -g 10 -s 300x200 -acodec aac -ar 44100 -ac 1 -f flv rtmp://localhost/hls/$name 2>>/var/log/ffmpeg-$name.log;
}application hls {live on;hls on;hls_path /tmp/hls;hls_fragment 15s;
}
exec_pull
语法:exec_pull command arg*
指定要在播放事件上执行的带有参数的外部命令。当第一个客户端连接到流时执行该命令,当最后一个客户端断开连接时终止该命令。此指令允许为本地客户端提取任何格式的远程流。
该功能仅在单工模式下可靠工作。原因是我们无法确保外部进程始终连接到正确的worker。它显然会连接到一个随机的。虽然这在大多数情况下仍然有效,但它不是一个推荐的架构,它将是不稳定和有缺陷的。
application myapp {live on;exec_pull ffmpeg -i http://example.com/video_$name.ts -c copy -f flv rtmp://localhost/$app/$name;
}
在上述配置中,exec_pull指令为所有流提供服务。这导致了远程流名称格式的某些限制。应该可以使用$app、$name等可用变量构造远程url。当不可能时,您可以在指令上添加exec_options,这允许在exec系列指令中设置其他流选项。现在唯一支持的选项是名称选项。
application myapp {live on;exec_options on;exec_pull ffmpeg -i http://example.com/tv1.ts -c copy -f flv rtmp://localhost/$app/$name name=mystream;exec_pull ffmpeg -i http://another.example.com/video_plus.ts -c copy -f flv rtmp://localhost/$app/$name name=anotherstream;
}
exec
exec是exec_push的别名
exec_options
该指令切换exec选项模式。激活后,您可以添加exec家族指令选项。唯一支持的exec选项是name。此选项允许仅对指定流应用exec。默认设置为禁用。语法: exec_options on|off
exec_options on;
# call my_on_publish_command only for "mystream"
exec_publish my_on_publish_command name=mystream;# call my_on_play_command only for "another"
exec_play my_on_play_command name=another;# execute different ffmpeg's for different streams
exec_pull ffmpeg -i http://example.com/abc.ts -c copy -f flv rtmp://localhost/$name/$app name=mystream;
exec_pull ffmpeg -i http://my.example.com/tele.ts -c copy -f flv rtmp://localhost/$name/$app name=tv;
exec_pull ffmpeg -i http://another.example.com/hello/f.ts -c copy -f flv rtmp://localhost/$name/$app name=fun;
exec_static
语法: exec_static command arg*
类似于exec,但在nginx启动时运行指定的命令。不支持替换,因为没有会话上下文。
exec_static ffmpeg -i http://example.com/video.ts -c copy -f flv rtmp://localhost/myapp/mystream;
exec_kill_signal
语法: exec_kill_signal signa
设置进程终止信号。默认值为kill(SIGKILL),可以指定数字或符号名称。
exec_kill_signal term;
exec_kill_signal usr1;
exec_kill_signal 3;
respawn
语法:respawn on|off
当终止子进程时,如果发布处于打开状态时,将启用respawns子进程。默认值为打开;
respawn off;
respawn_timeout
语法: respawn_timeout timeout
将
respawn超时设置为在启动新的子实例之前等待。默认值为5秒。
respawn_timeout 10s;
exec_publish
语法: exec_publish command arg*
指定在发布事件时,执行的带有参数的外部命令。不分析返回代码。这里也支持exec的替换。此外,支持args变量保存查询字符串参数。
exec_play
语法: exec_play command arg*
指定要在播放事件上执行的带有参数的外部命令。不分析返回代码。
exec_play_done
语法: exec_play_done command arg*
指定要在play_done事件上执行的带参数的外部命令。不分析返回代码。
exec_publish_done
语法: exec_publish_done command arg*
指定要在publish_done事件上执行的带参数的外部命令。不分析返回代码。
exec_record_done
语法: exec_record_done command arg*
指定录制完成时要执行的带参数的外部命令。这里支持替换exec_publish以及其他变量
recorder
- recorder namepath
- 录制文件完整路径 (/tmp/rec/mystream-1389499351.flv
)filename
-省略目录的路径 (mystream-1389499351.flv
)basename
- 省略扩展名的文件名 (mystream-1389499351
)dirname
- 目录的路径 (/tmp/rec
)
例子
# track client info
exec_play bash -c "echo $addr $pageurl >> /tmp/clients";
exec_publish bash -c "echo $addr $flashver >> /tmp/publishers";# convert recorded file to mp4 format
exec_record_done ffmpeg -y -i $path -acodec libmp3lame -ar 44100 -ac 1 -vcodec libx264 $dirname/$basename.mp4;
4.直播
live
语法: live on|off
切换直播模式,即一对多广播。
live on;
meta
语法:meta on|copy|off
设置元数据发送模式。on的值使订阅者接收到包含预定义字段(如宽度、高度等)的重建元数据包。copy的值使客户端收到发布者元数据块的精确副本,包括标准和特定字段。off的值将关闭向订阅者发送任何RTMP元数据的功能。默认为on。
meta copy;
interleave
语法: interleave on|off
切换交错模式。在此模式下,音频和视频数据在同一RTMP块流上传输。默认为关闭。
interleave on;
wait_key
语法: wait_key on|off
使视频流从关键帧开始,默认为关闭。
wait_key on;
wait_video
语法: wait_video on|off
在发送第一个视频帧之前禁用音频。默认为关闭。可以与wait_key结合使用,使客户端接收视频关键帧及其后的所有其他数据。但是,这通常会增加连接延迟。您可以调整编码器中的关键帧间隔以减少延迟。
注意:最近版本的IE需要启用此选项才能正常播放。
wait_video on;
publish_notify
语法: publish_notify on|off
发送NetStream.Play.PublishNotify
和 NetStream.Play.UnpublishNotify
通知订阅者。默认为关闭。
publish_notify on;
drop_idle_publisher
语法: drop_idle_publisher timeout
断开在指定时间内处于空闲状态(没有音频/视频数据)的发布者连接。默认设置为关闭。请注意,这仅在连接处于发布模式时(发送发布命令后)有效。
drop_idle_publisher 10s;
sync
语法: sync timeout
同步音频和视频流。若订户带宽不足以以发布者速率接收数据,则服务器会丢弃一些帧。这会导致同步问题。当时间戳差异超过指定为同步参数的值时,会发送一个绝对帧来修复该问题。默认值为300ms
sync 10ms;
play_restart
语法: play_restart on|off
如果启用,在每次发布者发布或停止时,
nginx-rtmp将向订阅者发送
NetStream.Play.Start 和
NetStream.Play.Stop。如果禁用,则每个订阅者仅在播放开始和结束时收到这些通知。默认设置为off。
play_restart off;
idle_streams
语法: idle_streams on|off
如果禁用,nginx-rtmp会阻止订阅者连接到空闲/不存在的直播流,并在流发布者断开连接时断开所有订阅者的连接。默认设置为启用。
idle_streams off;
5.录制
record
语法: record [off|all|audio|video|keyframes|manual]*
切换录制模式。流可以记录在flv文件中。该指令详细说明了应记录的内容:
- off - 不录制
- all - audio & video (所有)
- audio - 音频
- video - 视频
- keyframes - 仅仅关键视频帧
- manual - 不自动启动录制,使用控制界面启动/停止
在单个记录指令中可以有任何兼容的键组合。
record all;record audio keyframes;
record_path
指定录制flv文件的存放路径。
record_path /tmp/rec;
record_suffix
设置录制文件的后缀,默认为“.flv”。
record_suffix _recorded.flv;
记录后缀可以是strftime格式的模式。如以下指令将生成格式为mystream-24-Apr-13-18:23:38.flv的文件
record_suffix -%d-%b-%y-%T.flv;
record_unique
语法:record_unique on|off
如果启用,则会将当前时间戳附加到录制的文件中。否则,每次进行新的录制时,都会重写相同的文件。默认设置为关闭。
record_unique on;
record_append
语法:record_append on|off
切换文件追加模式。打开时,记录器会将新数据附加到旧文件中,或在丢失时创建新数据。文件中的旧数据和新数据之间没有时间间隔。默认设置为关闭。
record_append on;
record_lock
语法:record_lock on|off
打开时,当前录制的文件会被fcntl调用锁定。可以从其他地方检查,以找出正在录制的文件。默认设置为关闭。
record_lock on;
在FreeBSD上,你可以使用flock工具来检查这一点。在Linux上,flock和fcntl是不相关的,所以你只需要编写一个简单的脚本来检查文件锁定状态。这里有一个检测脚本isunlocked.py的例子。
#!/usr/bin/pythonimport fcntl, syssys.stderr.close()
fcntl.lockf(open(sys.argv[1], "a"), fcntl.LOCK_EX|fcntl.LOCK_NB)
record_max_size
设置录制的最大文件大小。
record_max_size 128K;
record_max_frames
设置每个录制文件的最大视频帧数。
record_max_frames 2;
record_interval
语法:record_interval time
在此(毫)秒数后重新开始录制。默认情况下为关闭。零表示录制之间没有延迟。如果record_unique处于关闭状态,则所有记录片段都将写入同一文件。否则,会附加时间戳,导致文件不同(给定的record_interval长于1秒)。
record_interval 1s;record_interval 15m;
recorder
语法: recorder name {...}
创建录制器块。可以在单个应用程序中创建多个记录器。上述所有与录制相关的指令都可以在记录器{}块中指定。所有设置都是从更高级别继承的。
application {live on;# default recorderrecord all;record_path /var/rec;recorder audio {record audio;record_suffix .audio.flv;}recorder chunked {record all;record_interval 15s;record_path /var/rec/chunked;}
}
record_notify
当特定录制器启动或停止录制文件时,向发布者发送NetStream.Record.Start和NetStream.Record.Stop状态消息(onStatus)。状态描述字段保存记录器名称(默认记录器为空)。默认情况下为关闭。
recorder myrec {record all manual;record_path /var/rec;record_notify on;
}
6.视频点播
play
语法: play dir|http://loc [dir|http://loc]*
从指定目录或HTTP位置播放flv或mp4文件。如果参数前缀为http://,则假定在播放之前应从远程http位置下载文件。在下载整个文件之前,不会开始播放。您可以使用本地nginx在本地计算机上缓存文件。
可以在单个播放指令中指定多个播放位置。当指定多个播放指令时,位置列表会合并并从更高的作用域继承。尝试播放每个位置,直到找到成功的位置。若未找到该位置,则向客户端发送错误状态。
索引FLV具有随机寻道功能。未索引的FLV在禁用寻道/暂停(仅重启模式)的情况下播放。使用FLV索引器(例如yamdi)进行索引。
如果您播放用记录指令录制的FLV,请不要忘记在播放前对其进行索引。因为它们创建时没有索引。
只有RTMP支持视频和音频编解,才能播放Mp4文件,最常见的是H264/AAC。
application vod {play /var/flvs;
}application vod_http {play http://myserver.com/vod;
}application vod_mirror {# try local location first, then access remote locationplay /var/local_mirror http://myserver.com/vod;
}
播放 /var/flvs/dir/file.flv。vod后的两个斜杠,使ffplay使用vod和应用程序名称,其余url作为播放路径。
ffplay rtmp://localhost/vod//dir/file.flv
play_temp_path
Syntax: play_temp_path dir
Context: rtmp, server, application
Sets location where remote VOD files are stored before playing. Default is /tmp
;
play_temp_path /www;
play http://example.com/videos;
play_local_path
Syntax: play_local_path dir
Context: rtmp, server, application
Sets location where remote VOD files copied from play_temp_path
directory after they are completely downloaded. Empty value disables the feature. By default it's empty. The feature can be used for caching remote files locally.
This path should be on the same device as play_temp_path
.
# search file in /tmp/videos.
# if not found play from remote location
# and store in /tmp/videosplay_local_path /tmp/videos;
play /tmp/videos http://example.com/videos;
Relay
pull
Syntax: pull url [key=value]*
Context: application
Creates pull relay. Stream is pulled from remote machine and becomes available locally. It only happens when at least one player is playing the stream locally.
Url syntax: [rtmp://]host[:port][/app[/playpath]]
. If application is missing then local application name is used. If playpath is missing then current stream name is used instead.
The following parameters are supported:
- app - explicit application name
- name - local stream name to bind relay to; if empty or non-specified then all local streams within application are pulled
- tcUrl - auto-constructed if empty
- pageUrl - page url to pretend
- swfUrl - swf url to pretend
- flashVer - flash version to pretend, default is 'LNX.11,1,102,55'
- playPath - remote play path
- live - toggles special behavior for live streaming, values: 0,1
- start - start time in seconds
- stop - stop time in seconds
- static - makes pull static, such pull is created at nginx start
If a value for a parameter contains spaces then you should use quotes around the WHOLE key=value pair like this : 'pageUrl=FAKE PAGE URL'
.
pull rtmp://cdn.example.com/main/ch?id=12563 name=channel_a;pull rtmp://cdn2.example.com/another/a?b=1&c=d pageUrl=http://www.example.com/video.html swfUrl=http://www.example.com/player.swf live=1;pull rtmp://cdn.example.com/main/ch?id=12563 name=channel_a static;
push
Syntax: push url [key=value]*
Context: application
Push has the same syntax as pull. Unlike pull push directive publishes stream to remote server.
push_reconnect
Syntax: push_reconnect time
Context: rtmp, server, application
Timeout to wait before reconnecting pushed connection after disconnect. Default is 3 seconds.
push_reconnect 1s;
session_relay
Syntax: session_relay on|off
Context: rtmp, server, application
Toggles session relay mode. In this mode relay is destroyed when connection is closed. When the setting is off relay is destroyed when stream is closed so that another relay could possibly be created later. Default is off.
session_relay on;
Notify
on_connect
Syntax: on_connect url
Context: rtmp, server
Sets HTTP connection callback. When clients issues connect command an HTTP request is issued asynchronously and command processing is suspended until it returns result code. If HTTP 2xx code is returned then RTMP session continues. The code of 3xx makes RTMP redirect to another application whose name is taken from Location
HTTP response header. Otherwise connection is dropped.
Note this directive is not allowed in application scope since application is still unknown at connection stage.
HTTP request receives a number of arguments. POST method is used with application/x-www-form-urlencoded MIME type. The following arguments are passed to caller:
- call=connect
- addr - client IP address
- app - application name
- flashVer - client flash version
- swfUrl - client swf url
- tcUrl - tcUrl
- pageUrl - client page url
In addition to the above mentioned items all arguments passed explicitly to connect command are also sent with the callback. You should distinguish connect arguments from play/publish arguments. Players usually have a special way of setting connection string separate from play/publish stream name. As an example here's how these arguments are set in JWPlayer
...
streamer: "rtmp://localhost/myapp?connarg1=a&connarg2=b",
file: "mystream?strarg1=c&strarg2=d",
...
Ffplay (with librtmp) example
ffplay "rtmp://localhost app=myapp?connarg1=a&connarg2=b playpath=mystream?strarg1=c&strarg2=d"
Usage example
on_connect http://example.com/my_auth;
Redirect example
location /on_connect {if ($arg_flashver != "my_secret_flashver") {rewrite ^.*$ fallback? permanent;}return 200;
}
on_play
Syntax: on_play url
Context: rtmp, server, application
Sets HTTP play callback. Each time a clients issues play command an HTTP request is issued asynchronously and command processing is suspended until it returns result code. HTTP result code is then analyzed.
- HTTP 2xx code continues RTMP session
- HTTP 3xx redirects RTMP to another stream whose name is taken from
Location
HTTP response header. If new stream name is started withrtmp://
then remote relay is created instead. Relays require that IP address is specified instead of domain name and only work with nginx versions greater than 1.3.10. See alsonotify_relay_redirect
. - Otherwise RTMP connection is dropped
Redirect example
http {...location /local_redirect {rewrite ^.*$ newname? permanent;}location /remote_redirect {# no domain name here, only iprewrite ^.*$ rtmp://192.168.1.123/someapp/somename? permanent;}...
}rtmp {...application myapp1 {live on;# stream will be redirected to 'newname'on_play http://localhost:8080/local_redirect;}application myapp2 {live on;# stream will be pulled from remote location# requires nginx >= 1.3.10on_play http://localhost:8080/remote_redirect;}...
}
HTTP request receives a number of arguments. POST method is used with application/x-www-form-urlencoded MIME type. The following arguments are passed to caller:
- call=play
- addr - client IP address
- clientid - nginx client id (displayed in log and stat)
- app - application name
- flashVer - client flash version
- swfUrl - client swf url
- tcUrl - tcUrl
- pageUrl - client page url
- name - stream name
In addition to the above mentioned items all arguments passed explicitly to play command are also sent with the callback. For example if stream is accessed with the url rtmp://localhost/app/movie?a=100&b=face&foo=bar
then a
, b
& foo
are also sent with callback.
on_play http://example.com/my_callback;
on_publish
Syntax: on_publish url
Context: rtmp, server, application
The same as on_play above with the only difference that this directive sets callback on publish command. Instead of remote pull push is performed in this case.
on_done
Syntax: on_done url
Context: rtmp, server, application
Sets play/publish terminate callback. All the above applies here. However HTTP status code is not checked for this callback.
on_play_done
Syntax: on_play_done url
Context: rtmp, server, application
Same behavior as on_done
but only for play end event.
on_publish_done
Syntax: on_publish_done url
Context: rtmp, server, application
Same behavior as on_done
but only for publish end event.
on_record_done
syntax: on_record_done url
context: rtmp, server, application, recorder
Set record_done callback. In addition to common HTTP callback variables it receives the following values
- recorder - recorder name in config or empty string for inline recorder
- path - recorded file path
Example
on_record_done http://example.com/recorded;
on_update
syntax: on_update url
context: rtmp, server, application
Set update callback. This callback is called with period of notify_update_timeout
. If a request returns HTTP result other than 2xx connection is terminated. This can be used to synchronize expired sessions. Two additional arguments time
and timestamp
are passed to this handler:
time
is the number of seconds since play/publish calltimestamp
is RTMP timestamp of the last audio/video packet sent to the client
You can use timestamp
argument to individually limit playback duration for each user.
on_update http://example.com/update;
notify_update_timeout
syntax: notify_update_timeout timeout
context: rtmp, server, application
Sets timeout between on_update
callbacks. Default is 30 seconds.
notify_update_timeout 10s;
on_update http://example.com/update;
notify_update_strict
syntax: notify_update_strict on|off
context: rtmp, server, application
Toggles strict mode for on_update
callbacks. Default is off. When turned on all connection errors, timeouts as well as HTTP parse errors and empty responses are treated as update failures and lead to connection termination. When off only valid HTTP response codes other that 2xx lead to failure.
notify_update_strict on;
on_update http://example.com/update;
notify_relay_redirect
syntax: notify_relay_redirect on|off
context: rtmp, server, application
Enables local stream redirect for on_play
and on_publish
remote redirects. New stream name is MD5 hash of RTMP URL used for remote redirect. Default is off.
notify_relay_redirect on;
notify_method
syntax: notify_method get|post
context: rtmp, server, application, recorder
Sets HTTP method for notifications. Default is POST with application/x-www-form-urlencoded
content type. In certain cases GET is preferable, for example if you plan to handle the call in http{}
section of nginx. In this case you can use arg_*
variables to access arguments.
notify_method get;
With GET method handling notifications in http{}
section can be done this way
location /on_play {if ($arg_pageUrl ~* localhost) {return 200;}return 500;
}
HLS输出
hls
语法: hls on|off
在应用程序上输出HLS协议,基本配置如下:
hls on;
hls_path /tmp/hls;
hls_fragment 15s;
在http{}部分中,为客户端设置以下配置,用来访问播放HLS流
http {...server {...location /hls {types {application/vnd.apple.mpegurl m3u8;}root /tmp;add_header Cache-Control no-cache;# To avoid issues with cross-domain HTTP requests (e.g. during development)add_header Access-Control-Allow-Origin *;}}
}
hls_path
语法:hls_path path
设置HLS播放列表和分片的存放目录。如果目录不存在,将自动创建。
hls_fragment
语法:hls_fragment time
设置HLS分片时长,默认为5秒。
hls_playlist_length
语法:hls_playlist_length time
设置HLS播放列表时长,默认为30秒。
hls_playlist_length 10m;
hls_sync
语法:hls_sync time
设置HLS时间戳同步阈值,默认值为2ms。此功能可防止从低分辨率RTMP(1KHz)转换为高分辨率MPEG-TS(90KHz)后出现爆裂噪声。
hls_sync 100ms;
hls_continuous
语法:hls_continuous on|off
切换为HLS连续模式,默认设置为off。在此模式下,HLS序列号从上次停止的位置开始,且旧碎片被保留下来。
Toggles HLS continuous mode. In this mode HLS sequence number is started from where it stopped last time. Old fragments are kept. Default is off.
hls_continuous on;
hls_nested
语法: hls_nested on|off
切换HLS嵌套模式,默认设置为off。在此模式下,将为每个流创建hls_path的子目录,播放列表和片段在该子目录中创建。
Toggles HLS nested mode. In this mode a subdirectory of hls_path
is created for each stream. Playlist and fragments are created in that subdirectory. Default is off.
hls_nested on;
hls_base_url
语法: hls_base_url url
为HLS播放列表项设置前缀url,默认为空。当为空时,播放列表项没有前缀,并且假设与父播放列表位于同一位置,或者在使用hls_nested时位于较低级别。
hls_base_url http://myserver.com/hls/;
hls_cleanup
语法: hls_cleanup on|off
启用HLS清理,默认为on。在这种模式下,nginx缓存管理器进程会从HLS目录中删除旧的HLS片段和播放列表。
hls_cleanup off;
hls_fragment_naming
语法:hls_fragment_naming sequential|timestamp|system
设置分片命名模式,默认为sequential
- sequential - 使用整数递增
- timestamp - 使用流时间戳
- system - 使用系统时间
hls_fragment_naming system;
hls_fragment_naming_granularity
语法:hls_fragment_naming_granularity number
设置hls分片ids的粒度,默认值为0。如果大于零,则更改ids以除以提供的值。
# use system time rounded to 500ms as fragment names
hls_fragment_naming system;
hls_fragment_naming_granularity 500;
hls_fragment_slicing
语法:hls_fragment_slicing plain|aligned
设置分片切片模式,默认为plain。
- plain -达到目标持续时间时切换片段
- aligned - 当传入的时间戳是片段持续时间的倍数时,切换片段。此模式可以在不同的nginx实例上生成相同的片段
hls_fragment_slicing aligned;
hls_variant
语法:hls_variant suffix [param*]
添加HLS变体条目。当流名称上的后缀匹配时,将为当前流创建变体播放列表,其中包含当前应用程序中hls_variant指令指定的所有条目。不带后缀的条带名称用作变体流名称。原始流照常处理。
后缀后的可选参数附加到m3u8播放列表中的EXT-X-STREAM-INF。见HLS规范3.3.10。EXT-X-STREAM-INF获取支持参数的完整列表。
rtmp {server {listen 1935;application src {live on;exec ffmpeg -i rtmp://localhost/src/$name-c:a aac -b:a 32k -c:v libx264 -b:v 128K -f flv rtmp://localhost/hls/$name_low-c:a aac -b:a 64k -c:v libx264 -b:v 256k -f flv rtmp://localhost/hls/$name_mid-c:a aac -b:a 128k -c:v libx264 -b:v 512K -f flv rtmp://localhost/hls/$name_hi;}application hls {live on;hls on;hls_path /tmp/hls;hls_nested on;hls_variant _low BANDWIDTH=160000;hls_variant _mid BANDWIDTH=320000;hls_variant _hi BANDWIDTH=640000;}}
}
hls_type
语法:hls_type live|event
在X-playlist-type播放列表指令中指定的HLS播放列表类型。直播HLS流通常从当前直播位置播放,该位置是播放列表末尾的几个片段。Event HLS流始终从播放列表的开头播放。在Event模式下,确保播放列表长度足以容纳整个Event。默认为live
;
Sets HLS playlist type specified in X-PLAYLIST-TYPE
playlist directive. Live HLS stream is usually played from the current live position which is several fragments to the end of playlist. Event HLS stream is always played from the start of playlist. When in event
mode make sure playlist length is enough for the whole event. Default is live
;
hls_type event;
hls_keys
语法:hls_keys on|off
启用HLS加密,加密方式为AES-128,默认情况下为off
。
hls_keys on;
以下是使用HLS加密的示例配置。此配置要求nginx使用--with-http_ssl_module构建以支持https。
...http {...server {listen 443 ssl;server_name example.com;ssl_certificate /var/ssl/example.com.cert;ssl_certificate_key /var/ssl/example.com.key;location /keys {root /tmp;}}server {listen 80;server_name example.com;location /hls {root /tmp;}}
}rtmp {server {listen 1935;application myapp {live on;hls on;hls_path /tmp/hls;hls_keys on;hls_key_path /tmp/keys;hls_key_url https://example.com/keys/;hls_fragments_per_key 10;}}
}
hls_key_path
语法:hls_key_path path
设置保存自动生成的HLS密钥的目录。密钥文件具有.key扩展名和使用OpenSSL RAND_bytes()例程创建的伪随机16字节内容。如果目录不存在,则在运行时创建。默认情况下,hls_path目录用于密钥文件。但是请记住,您通常应该限制对关键文件的访问,当这些文件与播放列表和片段分开存储时,访问会更容易。
hls_key_path /tmp/keys;
hls_key_url
语法: hls_key_url url
设置HLS密钥文件的前缀url,默认为空。当为空时,这些项目没有前缀,并且假设密钥与播放列表位于同一位置。
hls_key_url https://myserver.com/keys/;
具有上述设置的示例播放列表条目
#EXT-X-KEY:METHOD=AES-128,URI="https://myserver.com/keys/337.key",IV=0x00000000000000000000000000000151
hls_fragments_per_key
语法:hls_fragments_per_key value
设置使用相同密钥加密的HLS片段的数量,默认值为0。0意味着在发布开始时,只创建一个密钥,会话中的所有片段都使用此密钥进行加密。,
hls_fragments_per_key 10;
MPEG-DASH
dash
语法:dash on|off
在应用程序上输出MPEG-DASH。
dash on;
dash_path /tmp/dash;
dash_fragment 15s;
在http{}部分中,为客户端设置以下配置,用来访问播放DASH流
http {...server {...location /dash {root /tmp;add_header Cache-Control no-cache;# To avoid issues with cross-domain HTTP requests (e.g. during development)add_header Access-Control-Allow-Origin *;}}
}
dash_path
语法:dash_path path
设置MPEG-DASH播放列表和片段目录。如果目录不存在,将创建它。
dash_fragment
语法:dash_fragment time
设置MPEG-DASH片段长度,默认为5秒。
dash_playlist_length
语法: dash_playlist_length time
设置MPEG-DASH播放列表长度,默认为30秒。
dash_playlist_length 10m;
dash_nested
语法: dash_nested on|off
切换MPEG-DASH嵌套模式。在此模式下,将为每个流创建dash_path的子目录。播放列表和片段在该子目录中创建。默认设置为off
。
dash_nested on;
dash_cleanup
语法: dash_cleanup on|off
切换MPEG-DASH清理。默认情况下,该功能处于on
状态。在这种模式下,nginx缓存管理器进程会从MPEG-DASH目录中删除旧的MPEG-DASH片段和清单。删除流清单后,将删除初始化片段。
dash_cleanup off;
访问日志
access_log
Syntax: access_log off|path [format_name]
Context: rtmp, server, application
Sets access log parameters. Logging is turned on by default. To turn it off use access_log off
directive. By default access logging is done to the same file as HTTP access logger (logs/access.log
). You can specify another log file path in access_log
directive. Second argument is optional. It can be used to specify logging format by name. See log_format
directive for more details about formats.
log_format new '$remote_addr';
access_log logs/rtmp_access.log new;
access_log logs/rtmp_access.log;
access_log off;
log_format
Syntax: log_format format_name format
Context: rtmp
Creates named log format. Log formats look very much the same as nginx HTTP log formats. Several variables are supported within log format:
connection
- connection numberremote_addr
- client addressapp
- application namename
- last stream nameargs
- last stream play/publish argumentsflashver
- client flashVerswfurl
- client swfUrltcurl
- client tcUrlpageurl
- client pageUrlcommand
- play/publish commands sent by client:NONE
,PLAY
,PUBLISH
,PLAY+PUBLISH
bytes_sent
- number of bytes sent to clientbytes_received
- number of bytes received from clienttime_local
- local time at the end of client connectionsession_time
- connection duration in secondssession_readable_time
- connection duration in human-readable formatmsec
- current unix timestamp in SEC.MSEC format
Default log format has the name combined
. Here's the definition of this format
$remote_addr [$time_local] $command "$app" "$name" "$args" -
$bytes_received $bytes_sent "$pageurl" "$flashver" ($session_readable_time)
Limits
max_connections
Syntax: max_connections number
Context: rtmp, server, application
Sets maximum number of connections for rtmp engine. Off by default.
max_connections 100;
Statistics
Statistics module is NGINX HTTP module unlike all other modules listed here. Hence statistics directives should be located within http{} block.
rtmp_stat
Syntax: rtmp_stat all
Context: http, server, location
Sets RTMP statistics handler to the current HTTP location. RTMP statistics is dynamic XML document. To watch this document in browser as XHTML page use rtmp_stat_stylesheet directive.
http {server {location /stat {rtmp_stat all;rtmp_stat_stylesheet stat.xsl;}location /stat.xsl {root /path/to/stat/xsl/file;}}
}
rtmp_stat_stylesheet
Syntax: rtmp_stat_stylesheet path
Context: http, server, location
Adds XML stylesheet reference to statistics XML to make it viewable in browser. See rtmp_stat description and example for more information.
Multi-worker live streaming
Multi-worker live streaming is implemented through pushing stream to remaining nginx workers.
rtmp_auto_push
Syntax: rtmp_auto_push on|off
Context: root
Toggles auto-push (multi-worker live streaming) mode. Default is off.
rtmp_auto_push_reconnect
Syntax: rtmp_auto_push_reconnect timeout
Context: root
Sets auto-push reconnect timeout when worker is killed. Default is 100 milliseconds.
rtmp_socket_dir
Syntax: rtmp_socket_dir dir
Context: root
Sets directory for UNIX domains sockets used for stream pushing. Default is /tmp
.
rtmp_auto_push on;
rtmp_auto_push_reconnect 1s;
rtmp_socket_dir /var/sock;rtmp {server {listen 1935;application myapp {live on;}}
}
Control
Control module is NGINX HTTP module and should be located within http{} block.
rtmp_control
Syntax: rtmp_control all
Context: http, server, location
Sets RTMP control handler to the current HTTP location.
http {server {location /control {rtmp_control all;}}
}
More details about control moduleMore details about control moduleMore details about control module