nginx rtmp module directives翻译和注释

这个我称之为 『段批』 nginx-rtmp-module使用指南

原文在 nginx-rtmp-module Directives 是最后修改于2014年12月17日的版本。

网上也有几个翻译的版本,但都比较老了,我这个主要参考了这篇 还有闯闯自己翻译珍藏的版本。

中英文对照形式的,有的解释其实看英文更好理解,所以这样编排。

最主要的特色是在部分指令后加入了提示,把我们在最近几个月里使用nginx-rtmp-module的方法,或是遇到的问题以及解决方法记录了一下。

Ready? GO!

Table of Contents

Core

rtmp

syntax: rtmp { ... }
context: root
The block which holds all RTMP settings
此块包含所有RTMP设置

提示: 这是必须用到的参数

server

syntax: server { ... }
context: rtmp
Declares RTMP server instance
声明RTMP服务器实例

rtmp {
  server {
  }
}

提示: 这是必须用到的参数

listen

syntax: listen (addr[:port]|port|unix:path) [bind] [ipv6only=on|off] [so_keepalive=on|off|keepidle:keepintvl:keepcnt|proxy_protocol]
context: server

Adds listening socket to NGINX for accepting RTMP connections
设置RTMP服务的监听端口

server {
    listen 1935;
}

提示: 这是必须用到的参数,一般RTMP服务器监听1935端口,但也可以修改

application

syntax: application name { ... }
context: server

Creates RTMP application. Unlike http location application name cannot be a pattern.

建立RTMP应用,与HTTP的location不同,不能是一个匹配模式(pattern),我理解就是必须是一个固定的字符串。

server {
    listen 1935;
    application myapp {
    }
}

提示: 这是必须用到的参数,application是一个重要的参数,每个application{}块都是一个比较独立的配置块,一个server{}块中可以配置多个application{}块,每个可配成不同的行为,同时这个application的名字就是我们用推流工具往rtmp服务器上推流时用到的appid:

例如: rtmp://localhost:1935/appid/streamid

其中appid就是你想往哪个application上推就填写哪个appid。
streamid一般是随便填,只要推流时和播放时一致就行。

timeout

syntax: timeout value
context: rtmp, server

Socket timeout. This value is primarily used for writing. Most of time RTMP module does not expect any activity on all sockets except for publisher socket. If you want broken socket to get quickly disconnected use active tools like keepalive or RTMP ping. Default is 1 minute.

Socket超时,默认值是1分钟。主要用于写入。多数时候,除了RTMP的发布连接所使用的socket,RTMP module并不希望在其他的socket上有活动连接。如果希望快速断开错误连接,使用keepalive或RTMP ping。

timeout 60s;

提示: 用默认值就行,我们没有特殊设置。

ping

syntax: ping value
context: rtmp, server

RTMP ping interval. Zero turns ping off. RTMP ping is a protocol feature for active connection check. A special packet is sent to remote peer and a reply is expected within a timeout specified with ping_timeout directive. If ping reply is not received within this time then connection is closed. Default value for ping is 1 minute. Default ping timeout is 30 seconds.

RTMP ping间隔。设置为0时,表示关闭ping。RTMP ping是一个用于检查活动连接的协议功能,发送一个特殊的包到远程连接,然后在ping_timeout指令指定的时间内期待一个回复。如果在这个时间里没有收到ping回复,连接断开。默认值是30秒。

ping 3m;
ping_timeout 30s;

提示: 用默认值就行,我们没有特殊设置。

ping_timeout

syntax: ping_timeout value
context: rtmp, server

See ping description above.
见上

max_streams

syntax: max_streams value
context: rtmp, server

Sets maximum number of RTMP streams. Data streams are multiplexed into a single data stream. Different channels are used for sending commands, audio, video etc. Default value is 32 which is usually ok for many cases.

设置RTMP流的最大数目。数据流被复用到一个单一的数据流里。不同的频道用于发送命令、音频、视频等。 默认32,通常够用了。

max_streams 32;

提示: 用默认值就行,我们没有特殊设置。

ack_window

syntax: ack_window value
context: rtmp, server

Sets RTMP acknowledge window size. It’s the number of bytes received after which peer should send acknowledge packet to remote side. Default value is 5000000.

设置RTMP确认的Window size, Window size就是一次发送数据,接收方可不作应答的最大长度。默认 5000000。

ack_window 5000000;

提示: 用默认值就行,我们没有特殊设置。

chunk_size

syntax: chunk_size value
context: rtmp, server

Maximum chunk size for stream multiplexing. Default is 4096. The bigger this value the lower CPU overhead. This value cannot be less than 128.

RTMP协议中chunk的大小。默认值为4096。这个值设置的越大CPU负载就越小。这个值不能低于128。

chunk_size 4096;

提示: 用默认值就行,我们没有特殊设置。

max_queue

提示: 无解释

max_message

syntax: max_queue value
context: rtmp, server

Maximum size of input data message. All input data comes split into messages (and further in chunks). A partial message is kept in memory while waiting for it to complete. In theory incoming message can be very large which can be a problem for server stability. Default value 1M is enough for many cases.

输入数据报文最大尺寸。所有输入数据会被分割成报文(然后进一步分割为块)。报文在处理结束之前会放在内存里。理论上讲,接收到的报文很大的话对于服务器的稳定性可能会有影响。默认值 1M 对于大多数情况就足够了。

max_message 1M;

提示: 用默认值就行,我们没有特殊设置。

buflen

syntax: buflen time
context: rtmp, server

Sets default buffer length. Usually client sends RTMP set_buflen command before playing and resets this setting. Default is 1000 ms.

缓冲区时长,默认1s。通常客户端在播放前,发送 RTMP set_buflen命令重设此值。

buflen 5s;

提示: 为了减小延迟,我们可以尝试适当减小这个值,比如设成200ms。

out_queue

提示: 无解释

out_cork

提示: 无解释

Access

allow

Syntax: allow [play|publish] address|subnet|all
Context: rtmp, server, application

Allow publishing/playing from addresses specified or from all addresses. Allow/deny directives are checked in order of appearance.

设置允许发布或播放的地址或地址范围。

allow publish 127.0.0.1;
deny publish all;
allow play 192.168.0.0/24;
deny play all;

提示: 我们没有设置这个值

deny

Syntax: deny [play|publish] address|subnet|all
Context: rtmp, server, application

See allow for description.

提示: 我们没有设置这个值

Exec

exec_push

Syntax: exec_push command arg*
Context: rtmp, server, application

Specifies external command with arguments to be executed on every stream published. When publishing stops the process is terminated. Full path to binary should be specified as the first argument. There are no assumptions about what this process should do. However this feature is useful with ffmpeg for stream transcoding. FFmpeg is supposed to connect to nginx-rtmp as a client and output transcoded stream back to nginx-rtmp as publisher. Substitutions of form $var/${var} can be used within command line:

当每个流发布时执行提前指定的带参数的外部命令。当这个流发布停止时这个外部命令的进程也随之终止。注意外部命令的第一个参数要指定绝对路径(不然找不到这个外部程序)。这个功能通常被用于转码,ffmpeg首先被当做client接收数据流,转码之后又被成为publisher来发布流。外部命令行中可以使用如下变量:

Shell-style redirects can be specified in exec_push directive for writing output and accepting input. Supported are

可以在exec指令中定义Shell格式的转向符用于写输出和接收输入。支持如下:

Make sure there’s no space between redirection character and stream name/number. 确保重定向符号和流名/号之间没有空格。

You can specify full path to the command to execute or short command name. In the latter case binary is looked up in directories specified by the PATH environment variable. By default nginx clears the environment which will usually make rtmp module run only binaries located in standard directories like /bin and /usr/bin. To make this always work please keep the original PATH variable value with the following nginx directive.

你可以在命令行写完整路径或只写命令名。如果是后者,会在PATH环境变量路径查找。 默认nginx会清理环境变量,rtmp模块会去/bin和/usr/bin查找可执行程序。请按下面命令设置PATH变量。

env PATH; 

The following ffmpeg call transcodes incoming stream to HLS-ready stream (H264/AAC). FFmpeg should be compiled with libx264 & libfaac support for this example to work.

下面的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 libfaac -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;
}

提示: 这个最后的例子,就是有2个application,首先推流工具往第一个application ‘src’推原始流,原始流经过ffmpeg转码后推倒第二个application ‘hls’上去。

另外我们也使用了这种方式进行转码。

exec_pull

Syntax: exec_pull command arg*
Context: rtmp, server, application

Specifies external command with arguments to be executed on play event. The command is executed when first client connects to the stream and is killed when the last one disconnects. This directive makes it possible to pull remote stream in any format for local clients.

当播放时执行提前指定的带参数的外部命令。外部程序在第一个客户端连接时开始执行,直到最后一个客户端断开连接时终止。这个参数使为本地客户端拉取任意格式的远程流成为可能。

The feature works reliably only in single-worker mode. The reason for this is we cannot make sure external process always connects to the right worker. It will obviously connect to a random one. While this will still work in most cases it’s not a recommended architecture, it will be unstable and buggy.

此特性只在单worker模式下工作稳定。因为外部进程连接到随机的worker。虽然通常都能工作,但不推荐这么用(好坑爹)。

Directive arguments are the same as for exec_push.

可以使用的变量和exec_push中提到的一样。

application myapp {
    live on;
    exec_pull ffmpeg -i http://example.com/video_$name.ts -c copy -f flv rtmp://localhost/$app/$name;
}

In the above configuration exec_pull directive serves all streams. That leads to certain limitations on remote stream name format. It should be possible to construct the remote url using available variables like $app, $name etc. When it’s not possible you can add exec_options on directive which permits setting additional stream options in exec-family directives. The only option supported now is name option.

上面的exec_pull配置服务所有流,这导致远程流的名称格式有一定的限制,也就是必须可以使用诸如$app $name等变量来构成其url。 你也可以使用exec_options on来许可额外的流选项,目前只支持name选项。

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_pull的场景,也没有做过多测试。

exec

Syntax: exec command arg*
Context: rtmp, server, application

exec is an alias of exec_push

同exec_push

exec_options

Syntax: exec_options on|off
Context: rtmp, server, application

The directive toggles exec options mode. When activated you can add exec-family directive options. The only exec option supported is name. This option makes it possible to apply exec only to specified stream. Default if off.

设置执行可选模式。你可以添加执行群可选方案。目前只支持name。此选项可以针对特定流执行。默认关。

exec_options on;
# call on_publish only for "mystream"
exec_publish http://localhost/on_publish name=mystream;

# call on_play only for "another"
exec_play http://localhost/on_play name=another;

# execute different ffmpeg's for different streams
exec_pull http://example.com/abc.ts -c copy -f flv rtmp://localhost/$name/$app name=mystream;
exec_pull http://my.example.com/tele.ts -c copy -f flv rtmp://localhost/$name/$app name=tv;
exec_pull http://enother.example.com/hello/f.ts -c copy -f flv rtmp://localhost/$name/$app name=fun;

提示: 默认关闭,我们没有用到这个参数。

exec_static

Syntax: exec_static command arg*
Context: rtmp, server, application

Similar to exec but runs specified command at nginx start. Does not support substitutions since has no session context.

类似exec,但是在启动nginx时运行,不支持变量替换。

exec_static ffmpeg -i http://example.com/video.ts -c copy -f flv rtmp://localhost/myapp/mystream;

提示: 我们没有用到这个参数。

exec_kill_signal

Syntax: exec_kill_signal signal
Context: rtmp, server, application

Sets process termination signal. Default is kill (SIGKILL). You can specify numeric or symbolic name (for POSIX.1-1990 signals).

设置进程结束信号,默认SIGKILL,也可以设置数字或符号名。(POSIX.1-1990)

exec_kill_signal term;
exec_kill_signal usr1;
exec_kill_signal 3;

提示: 我们没有用到这个参数。

respawn

Syntax: respawn on|off
Context: rtmp, server, application

If turned on respawns child process when it’s terminated while publishing is still on. Default is on;

当发布进行时,子进程被终止会重启子进程,默认开启

respawn off;

提示: 我们没有用到这个参数。

respawn_timeout

Syntax: respawn_timeout timeout
Context: rtmp, server, application

Sets respawn timeout to wait before starting new child instance. Default is 5 seconds.

设置重启新子进程的等待时间。

respawn_timeout 10s;

提示: 我们没有用到这个参数。

exec_publish

Syntax: exec_publish command arg*
Context: rtmp, server, application

Specifies external command with arguments to be executed on publish event. Return code is not analyzed. Substitutions of exec are supported here as well. In addition args variable is supported holding query string arguments.

设置发布时执行外部命令带参数。不分析返回码。支持替换。另外参数支持查询字符串参数。
提示: 我们没有用到这个参数。

exec_play

Syntax: exec_play command arg*
Context: rtmp, server, application

Specifies external command with arguments to be executed on play event. Return code is not analyzed. Substitution list is the same as for exec_publish. 设置播放时执行外部命令带参数。不分析返回码。替换列表同exec_publish。
提示: 我们没有用到这个参数。

exec_play_done

Syntax: exec_play_done command arg*
Context: rtmp, server, application

Specifies external command with arguments to be executed on play_done event. Return code is not analyzed. Substitution list is the same as for exec_publish. 设置播放完调外部命令带参数。不分析返回码。替换列表同exec_publish。
提示: 我们没有用到这个参数。

exec_publish_done

Syntax: exec_publish_done command arg*
Context: rtmp, server, application

Specifies external command with arguments to be executed on publish_done event. Return code is not analyzed. Substitution list is the same as for exec_publish. 设置发布完时调用外部命令带参数。不分析返回码。替换列表同exec_publish。
提示: 我们没有用到这个参数。

exec_record_done

Syntax: exec_record_done command arg*
Context: rtmp, server, application, recorder

Specifies external command with arguments to be executed when recording is finished. Substitution of exec_publish are supported here as well as additional variables

设置录制完时执行外部命令。替换列表包含exec_publish的那些,同时支持额外的变量:

Examples

# 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;

提示: 除了这个参数之前的exec_family的其他参数都是写在application{}配置块中,而这个是写在application{}下recorder{}配置块中的,它是针对recorder{}中定义的录制行为执行完之后触发的一个动作。

比如我们可以在record结束之后触发ffmpeg从record到的文件中截图:

recorder rec {
    record keyframes;
    record_max_frames 4;
    record_path /tmp/snapshot;
    record_interval 30s;
    exec_record_done /usr/local/ffmpeg/2.8/bin/ffmpeg -i /tmp/snapshot/$name.flv -vframes 1 -an -f rawvideo -ss 00:00:00 -y -f image2 /tmp/snapshot/$name.jpg;
}

Live

live

Syntax: live on|off
Context: rtmp, server, application

Toggles live mode i.e. one-to-many broadcasting.

开启直播功能。

live on;

提示:

meta

Syntax: meta on|copy|off
Context: rtmp, server, application

Sets metadata sending mode. The value of on makes subscribers receive reconstructed metadata packets containing predefined fields like width, height etc. The value of copy makes clients receive exact copy of publisher metadata block including both standard and specific fields. The value of off turns off sending any RTMP metadata to subscribers. Defaults to on.

设置元数据发送方式。on:发送重组过的元数据给客户端,其中包含一些预定义的参数,如宽,高等。copy:元数据完全不变的发给客户端。off:不发送元数据给客户端。默认为on

meta copy;

提示: 用默认值就行,我们没有特殊设置。

interleave

Syntax: interleave on|off
Context: rtmp, server, application

Toggles interleave mode. In this mode audio and video data is transmitted on the same RTMP chunk stream. Defaults to off.

设置交错模式。如果打开,音视频数据会在同一个chunk流中传输。默认off

interleave on;

提示: 用默认值就行,我们没有特殊设置。如果要获得更好的音视频同步效果,可以试着打开。
参见 nginx-rtmp-module issue 241

wait_key

Syntax: wait_key on|off
Context: rtmp, server, application

Makes video stream start with a key frame. Defaults to off.

设置视频流从关键帧起播,默认off

wait_key on;

提示: 使用默认值,因为从关键帧起播会增加延迟。

wait_video

Syntax: wait_video on|off
Context: rtmp, server, application

Disable audio until first video frame is sent. Defaults to off. Can be combined with wait_key to make client receive video key frame with all other data following it. However this usually increases connection delay. You can tune keyframe interval in your encoder to reduce the delay.

在发送视频帧之前不发音频数据。默认off。可以和wait_key配合使用,可以使客户端在收到视频关键帧后才收到随之而来的其他数据(而不是先收到音频数据,这时用户可以听到声音了,但画面还是黑的)。 这样玩通常会增加延迟,但是你可以通过调整编码器的关键帧间隔参数来减小延迟(比如使用ffmpeg的-g参数,就是用来调整关键帧间隔,也就是GOP长度的)。

Recent versions of IE need this option to be enabled for normal playback.

最近版本的IE需要打开这个参数才能正常播放。(不知是哪年的IE,现在应该没问题了,没测过,好久不用IE了。。。)

wait_video on;

提示: 使用默认值,我们不希望增加延迟。

publish_notify

Syntax: publish_notify on|off
Context: rtmp, server, application

Send NetStream.Play.PublishNotify and NetStream.Play.UnpublishNotify to subscribers. Defaults to off.

发送NetStream.Publish.Start和NetStream.Publish.Stop给用户。默认为off。

publish_notify on;

提示: 用默认值就行,我们没有特殊设置。

drop_idle_publisher

Syntax: drop_idle_publisher timeout
Context: rtmp, server, application

Drop publisher connection which has been idle (no audio/video data) within specified time. Default is off. Note this only works when connection is in publish mode (after sending publish command).

终止指定时间内闲置(没有音频/视频数据)的发布连接。默认为 off。注意这个仅仅对于发布模式的连接起作用(发送 publish 命令之后)。

drop_idle_publisher 10s;

提示: 我们设置这个参数为20s,表示当一个发布连接上不发送任何数据到20s后就断掉这个连接。
参见 nginx-rtmp-module issue 374

sync

Syntax: sync timeout
Context: rtmp, server, application

Synchronize audio and video streams. If subscriber bandwidth is not enough to receive data at publisher rate, some frames are dropped by server. This leads to synchronization problem. When timestamp difference exceeds the value specified as sync argument an absolute frame is sent fixing that. Default is 300ms.

同步音频和视频流。如果用户带宽不足以以发布端的码率来接收数据,服务器会丢弃一些帧。这将导致同步问题。当时间戳差超过 sync 指定的值,将会发送一个绝对帧来解决这个问题。默认为 300 ms。

sync 10ms;

提示: 用默认值就行,我们没有特殊设置。但是隐隐感觉以后会用上 x_x

play_restart

Syntax: play_restart on|off
Context: rtmp, server, application

If enabled nginx-rtmp sends NetStream.Play.Start and NetStream.Play.Stop to each subscriber every time publisher starts or stops publishing. If disabled each subscriber receives those notifications only at the start and end of playback. Default is off.

使nginx-rtmp能够在发布启动或停止时发送 NetStream.Play.Start 和 NetStream.Play.Stop 到每个用户。如果关闭的话,那么每个用户就只能在回放的开始和结束时收到这些通知了。默认为 on。

play_restart off;

提示: 用默认值就行,我们没有特殊设置。
参见 nginx-rtmp-module issue 397

idle_streams

Syntax: idle_streams on|off
Context: rtmp, server, application

If disabled nginx-rtmp prevents subscribers from connecting to idle/nonexistent live streams and disconnects all subscribers when stream publisher disconnects. Default is on.

当设置为off时,nginx-rtmp禁止客户端连接闲置(idle)或不存在(nonexistent)的直播流,并且在发布者连接断开后会把所有接收者连接也都断掉。默认是on。

idle_streams off;

提示: 用默认值就行,我们没有特殊设置。

Record

record

syntax: record [off|all|audio|video|keyframes|manual]*
context: rtmp, server, application, recorder

Toggles record mode. Stream can be recorded in flv file. This directive specifies what exactly should be recorded:

切换录制模式。流可以被记录到 flv 文件。本指令指定应该被记录的:

There can be any compatible combination of keys in a single record directive.
在单个记录指令中可以有任何兼容的组合键。

record all;

record audio keyframes;

提示: record{}配置中的参数都是实实在在的,可以测试观察到效果的,不像前面好多参数看完还特么云里雾里的。

我们可以使用record指定只录制关键帧,然后用于生成截图,可以定期自动生成截图,也可以通过设置成manual,然后通过http control给nginx-rtmp发送命令来手工获取截图。

recorder snapshot {
    record keyframes manual;
    record_max_frames 1;
    record_path /tmp/snapshot;
    exec_record_done /usr/local/ffmpeg/2.8/bin/ffmpeg -i /tmp/snapshot/$name.flv -vframes 1 -an -f rawvideo -ss 00:00:00 -y -f image2 /tmp/snapshot/$name.jpg;
}

record_path

syntax: record_path path
context: rtmp, server, application, recorder

Specifies record path to put recorded flv files to.
指定录制flv文件的路径。

record_path /tmp/rec;

提示: 根据需要设置。

record_suffix

syntax: record_suffix value
context: rtmp, server, application, recorder

Sets record file suffix. Defaults to ‘.flv’.

record_suffix _recorded.flv;

Record suffix can be a pattern in strftime format. The following directive

record_suffix -%d-%b-%y-%T.flv;

will produce files of the form mystream-24-Apr-13-18:23:38.flv. All supported strftime format options can be found on strftime man page.

设置录制文件名后缀,默认 flv。录制后缀可以是strftime格式。 如下格式生成类似-24- Apr-13-18:23:38.flv。 strftime格式可以从手册 strftime man page 找到

提示: 根据需要设置。

record_unique

syntax: record_unique on|off
context: rtmp, server, application, recorder

If turned on appends current timestamp to recorded files. Otherwise the same file is re-written each time new recording takes place. Default is off.

开启追加当前时间戳到录制文件中。否则同一个文件多次录制时会被覆盖。默认off。

record_unique on;

提示: 根据需要设置。

record_append

syntax: record_append on|off
context: rtmp, server, application, recorder

Toggles file append mode. When turned on recorder appends new data to the old file or creates it when it’s missing. There’s no time gap between the old data and the new data in file. Default is off.

设置文件追加模式。如果打开,是将新录制的数据追加到已有文件的末尾或者没有就创建这个文件。在文件中新老数据之间没有间隔。默认off。

record_append on;

提示: 根据需要设置。

record_lock

syntax: record_lock on|off
context: rtmp, server, application, recorder

When turned on currently recorded file gets locked with fcntl call. That can be checked from elsewhere to find out which file is being recorded. Default is off.

开启时文件会被fcntl调用锁定,可以在其他地方发现哪个文件正在被录制。默认off。

record_lock on;

On FreeBSD you can use flock tool to check that. On Linux flock and fcntl are unrelated so you are left with writing a simple script checking file lock status. Here’s an example of such script isunlocked.py.

在 FreeBSD 上你可以使用 flock 工具检查。在 Linux 上 flock 和 fcntl 无关,因此你需要去写一个简单的脚本来检查文件的锁定状态。以下 isunlocked.py 是一个这样的脚本的示例。

#!/usr/bin/python

import fcntl, sys

sys.stderr.close()
fcntl.lockf(open(sys.argv[1], "a"), fcntl.LOCK_EX|fcntl.LOCK_NB)

提示: 不知道什么情况下需要,用默认值就好。

record_max_size

syntax: record_max_size size
context: rtmp, server, application, recorder

Set maximum recorded file size.

设置录制文件最大值。

record_max_size 128K;

提示: 根据需要设置。

record_max_frames

syntax: record_max_frames nframes
context: rtmp, server, application, recorder

Sets maximum number of video frames per recorded file.

设置每个录制文件的视频帧的最大数量。

record_max_frames 2;

提示: 根据需要设置。

record_interval

syntax: record_interval time
context: rtmp, server, application, recorder

Restart recording after this number of (milli)seconds. Off by default. Zero means no delay between recordings. If record_unique is off then all record fragments are written to the same file. Otherwise timestamp is appended which makes files differ (given record_interval is longer than 1 second).

设置录制的间隔。默认off。如果设为0表示连续录制。同时,如果record_unique设为off的话,那每次录制都会写入同一个文件,而如果record_unique设为on时,每次录制都会生成一个以时间戳为后缀的新文件(间隔设置要大于1s)。

record_interval 1s;

record_interval 15m;

提示: 根据需要设置,一般配合record_unique on一起使用。

recorder

syntax: recorder name {...}
context: application

Create recorder block. Multiple recorders can be created withing single application. All the above mentioned recording-related directives can be specified in recorder{} block. All settings are inherited from higher levels.

创建录制配置块。一个application{}中可以创建多个recorder{}块,所有上边提到的指令都可以设置在recorder{}块里。继承高层次中的所有设置。

application {
    live on;

    # default recorder
    record 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

syntax: record_notify on|off
context: rtmp, server, application, recorder

Toggles sending NetStream.Record.Start and NetStream.Record.Stop status messages (onStatus) to publisher when specific recorder starts or stops recording file. Status description field holds recorder name (empty for default recorder). Off by default.

切换当定义录制启动或停止文件时发送 NetStream.Record.Start 和 NetStream.Record.Stop 状态信息(onStatus)到发布者。状态描述字段保存录制的名字(默认录制的话为空)。默认为 off。

recorder myrec {
    record all manual;
    record_path /var/rec;
    record_notify on;
}

提示: 目前没用到,用默认值。

Video on demand

play

Syntax: play dir|http://loc [dir|http://loc]*
Context: rtmp, server, application

Play flv or mp4 file from specified directory or HTTP location. If the argument is prefixed with http:// then it is assumed that file should be downloaded from remote http location before playing. Note playing is not started until the whole file is downloaded. You can use local nginx to cache files on local machine.

播放指定文件夹或HTTP路径上的FLV或MP4文件,http://表示下载播放远程地址的文件。 注意当整个文件下载完之后才会开始播放。你可以在本地使用nginx来缓存。

Multiple play locations can be specified in a single play directive. When multiple play directives are specified the location lists are merged and inherited from higher scopes. An attempt to play each location is made until a successful location is found. If such location is not found error status is sent to client.

同一个 play 指令可以定义多个播放地址。当多个 play 指令定义时,地址列表将被合并,并进行从更高域中继承。尝试播放每一个地址,直到发现一个成功的地址。如果没有找到成功地址,将发送错误状态到客户端。

Indexed FLVs are played with random seek capability. Unindexed FLVs are played with seek/pause disabled (restart-only mode). Use FLV indexer (for example, yamdi) for indexing.

索引的 FLV 播放具有随机查找能力。没有索引的 FLV 则不具备查找/暂停能力(重播模式)。使用 FLV 索引器(比如 yamdi)来编索引。

If you play FLVs recorded with the record directive please do not forget to index them before playing. They are created unindexed.

record模块录制出来的flv文件是未经index处理的,如果你要想播放这些文件(随机拖动),请别忘了自己index一下。

Mp4 files can only be played if both video and audio codec are supported by RTMP. The most common case is H264/AAC.

mp4 文件只有在音频和视频编码都被 RTMP 支持时才可以播放。最常见的情况是 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 location
    play /var/local_mirror http://myserver.com/vod;
}

Playing /var/flvs/dir/file.flv:

ffplay rtmp://localhost/vod//dir/file.flv

The two slashes after vod make ffplay use vod and application name and the rest of the url as playpath.

播放vod时,自己试试吧,可能需要在application名字后加两个反斜线才能播。

栗子:

# Video on demand
application vod {
    play /tmp/Videos;
}

# Video on demand over HTTP
application vod_http {
    play http://localhost:8080/vod/;
}

将flv文件拷贝到/tmp/Videos目录下,
播放/tmp/Videos/test.flv 用 rtmp://localhost/vod/test.flv
播放/tmp/Videos/subfolder/test.flv的话用rtmp://localhost/vod//subfolder/test.flv

提示: VOD是一个古老而现在又没什么卵用的模块,你喜欢就好。

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;

在播放之前设置远程存储的 VOD 文件路径。默认为 /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.

设置远程点播文件存储路径,从临时路径拷贝过来。空值的话禁用此功能。默认为空值。这个功能可以用于缓存远程文件在本地。
这一路径应该和 play_temp_path 处于同一设备。

# search file in /tmp/videos.
# if not found play from remote location
# and store in /tmp/videos

play_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.

创建 pull 中继。流将从远程服务器上拉下来,成为本地可用的。仅当至少有一个播放器正在播放本地流时发生。

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.

Url 语法:[rtmp://]host[:port][/app[/playpath]]。如果不指定 application 名字那么将会使用本地 application 名。如果不指定 playpath 那么就是用当前流的名字。

The following parameters are supported: * app - explicit application name 明确指定application名 * name - local stream name to bind relay to; if empty or non-specified then all local streams within application are pulled 捆绑到 relay 的本地流名字。如果为空或者没有定义,那么将会使用 application 中的所有本地流。 * tcUrl - auto-constructed if empty 如果为空的话自动构建。 * pageUrl - page url to pretend 模拟页面 url。 * swfUrl - swf url to pretend 模拟 swf url。 * flashVer - flash version to pretend, default is ‘LNX.11,1,102,55’ 模拟 flash 版本,默认为 ‘LNX.11,1,102,55’。 * playPath - remote play path 远程播放地址。 * live - toggles special behavior for live streaming, values: 0,1 切换直播特殊行为,值:0,1。 * start - start time in seconds 开始时间。 * stop - stop time in seconds 结束时间。 * static - makes pull static, such pull is created at nginx start 创建静态 pull,这样的 pull 在 nginx 启动时创建。

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'.

如果某参数的值包含空格,那么你应该在整个 key=value 对周围使用引号,比如:'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;

提示: 这组中继指令在nginx-rtmp组网时应该会用到,但是一直听说nginx-rtmp对于大规模组网支持的不够好,自己也没机会测试,以后如果有机会测试,会补上。

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 的语法和 pull 一样。不同于 pull 指令的是 push 推送发布流到远程服务器。

提示: 根据需要设置。

push_reconnect

Syntax: push_reconnect time
Context: rtmp, server, application

Timeout to wait before reconnecting pushed connection after disconnect. Default is 3 seconds.

在断开连接后,在 push 重新连接前等待的时间。默认为 3 秒。

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.

切换会话 relay 模式。在这种模式下连接关闭时 relay 销毁。当设置为 off 时,流关闭,relay 销毁,这样子以后另一个 relay 可以被创建。默认为 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.

设置 HTTP 连接回调。当客户端发起一个连接命令时,一个 HTTP 请求异步发送,命令处理将被暂停,直到它返回结果代码。当 HTTP 2XX 码(成功状态码)返回时,RTMP 会话继续。返回码 3XX (重定向状态码)会使 RTMP 重定向到另一个从 HTTP 响应头的 Location 里获取到的 application。否则(其他状态码)连接丢弃。

Note this directive is not allowed in application scope since application is still unknown at connection stage.

注意这一指令在 application 域是不允许的,因为 application 在连接阶段还是未知的。

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:

HTTP 请求接收到一些参数。使用MIME的 application/x-www-form-urlencoded 编码方式的POST方法。以下参数将被传给调用者:

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

除了上述参数以外,所有显式传递给连接命令的参数也由回调发送。你应该将连接参数和 play/publish 参数区分开。播放器常常有独特的方式设置连接字符串不同于 play/publish 流名字。这里是 JWPayer 是如何设置这些参数的一个示例:

...
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 播放回调。每次一个客户分发播放命令时,一个 HTTP 请求异步发送,命令处理会挂起 - 直到它返回结果码。之后再解析 HTTP 结果码。

Redirect example

http {
    ...
    location /local_redirect {
        rewrite ^.*$ newname? permanent;
    }
    location /remote_redirect {
        # no domain name here, only ip
        rewrite ^.*$ 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.10
        on_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.

除了上述参数之外其他所有播放命令参数显式地发送回调。例如如果一个流由 url rtmp://localhost/app/movie?a=100&b=face&foo=bar 访问,然后呢 a,b 和 foo 发送回调。

on_play http://example.com/my_callback;

提示: 我们在on_play设置了回调。

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_play 一样,唯一的不同点在于这个指令在发布命令设置回调。不同于远程 pull,push 在这里是可以的。

提示: 我们在on_publish设置了回调。

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.

设置播放/发布禁止回调。上述所有适用于此。但这个回调并不检查 HTTP 状态码。

提示: 我们没有用到这个。

on_play_done

Syntax: on_play_done url
Context: rtmp, server, application

Same behavior as on_done but only for play end event.

等同于 on_done 的表现,但只适用于播放结束事件。

提示: 我们没有用到这个。

on_publish_done

Syntax: on_publish_done url
Context: rtmp, server, application

Same behavior as on_done but only for publish end event.

等同于 on_done 的表现,但只适用于发布结束事件。

提示: 我们在on_publish_done设置了回调。

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

设置 record_done 回调。除了普通 HTTP 回调参数它还接受:recorder名字和录制文件路径这两个参数。

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 call * timestamp is RTMP timestamp of the last audio/video packet sent to the client

设置 update 回调。这个回调会在 notify_update_timeout 期间调用。如果一个请求返回结果不是 2XX,连接禁止。这可以用来同步过期的会话。追加 time 参数即播放/发布调用后的秒数会被发送给处理程序。

You can use timestamp argument to individually limit playback duration for each user.

on_update http://example.com/update;

提示: 我们设置了on_update回调。

notify_update_timeout

syntax: notify_update_timeout timeout
context: rtmp, server, application

Sets timeout between on_update callbacks. Default is 30 seconds.

在 on_update 回调之间的超时设置。默认为 30 秒。

notify_update_timeout 10s;
on_update http://example.com/update;

提示: 我们设置为1s。

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.

切换 on_update 回调严格模式。默认为 off。当设置为 on 时,所有连接错误,超时以及 HTTP 解析错误和空返回会被视为更新失败并导致连接终止。当设置为 off 时只有 HTTP 返回码不同于 2XX 时导致失败。

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.

使本地流可以重定向为 on_play 和 on_publish 远程重定向。新的流名字是 RTMP URL 用于远程重定向。默认为 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.

设置 HTTP 方法通知。默认是带有 application/x-www-form-urlencoded 的 POST 内容类型。在一些情况下 GET 更好,例如如果你打算在 nginx 的 http{} 部分处理调用。在这种情况下你可以使用 arg_* 变量去访问参数。

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

Syntax: hls on|off
Context: rtmp, server, application

Toggles HLS on the application.

打开HLS直播功能

hls on;
hls_path /tmp/hls;
hls_fragment 15s;

In http{} section set up the following location for clients to play HLS.

为了开启HLS直播功能,要在nginx的http{}配置块进行如下配置: 主要是指定MIME类型;指定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

Syntax: hls_path path
Context: rtmp, server, application

Sets HLS playlist and fragment directory. If the directory does not exist it will be created.

设置 HLS 播放列表和分段目录。这一目录必须在 NGINX 启动前就已存在。

提示: 根据需要设置。

hls_fragment

Syntax: hls_fragment time
Context: rtmp, server, application

Sets HLS fragment length. Defaults to 5 seconds.

设置HLS分段长度。默认为5秒。

提示: 我们设置为10秒。

hls_playlist_length

Syntax: hls_playlist_length time
Context: rtmp, server, application

Sets HLS playlist length. Defaults to 30 seconds.

设置 HLS 播放列表长度。默认为 30 秒钟。

hls_playlist_length 10m;

提示: 我们设置为10分钟,这样索引文件中只包含10分钟的分片信息。

hls_sync

Syntax: hls_sync time
Context: rtmp, server, application

Sets HLS timestamp synchronization threshold. Default is 2ms. This feature prevents crackling noises after conversion from low-resolution RTMP (1KHz) to high-resolution MPEG-TS (90KHz).

设置 HLS 时间戳同步阈值。默认为 2 ms。这一功能可以防止由低分辨率 RTMP (1KHz) 转换到高分辨率 MPEG-TS (90KHz) 之后出现噪音。

hls_sync 100ms;

提示: 我们目前没有设置这个指令。

hls_continuous

Syntax: hls_continuous on|off
Context: rtmp, server, application

Toggles HLS continuous mode. In this mode HLS sequence number is started from where it stopped last time. Old fragments are keeped. Default is off.

设置HLS连续模式。设成on时,每次往同一个application上推流时,切出来的新分片的序号是接着之前老分片的序号的。设成off时,分片序号每次都重新开始。

hls_continuous on;

提示: 我们设置为on。

hls_nested

Syntax: hls_nested on|off
Context: rtmp, server, application

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 嵌套模式。这一模式下为每个流创建了一个 hls_path 的子目录。播放列表和分段在那个子目录中创建。默认为 off。

hls_nested on;

提示: 我们设置为on。

hls_base_url

Syntax: hls_base_url url
Context: rtmp, server, application

Sets base url for HLS playlist items. When empty those items have no prefix and assumed to be at the same location as parent playlist or one level lower when hls_nested is used. This feature applies both to master (variant) and slave HLS playlists. It can let you download the playlist and play it locally since it contains full references to child playlists or fragments. Empty by default.

设置索引文件中的分片的base url。不设置时,索引文件中分片位置就是单独的一个分片名字,当用这个指令设置一个base url后,索引文件中每个分片的名字前都会加上同样的前缀。

hls_base_url http://myserver.com/hls/;

提示: 我们没有设置base url,因为我们会自己生成需要的点播索引文件。

hls_cleanup

Syntax: hls_cleanup on|off
Context: rtmp, server, application

Toggles HLS cleanup. By default the feature is on. In this mode nginx cache manager process removes old HLS fragments and playlists from HLS directory.

设置是否删除老的分片。默认是on,删除。

hls_cleanup off;

提示: 为了防止时间一长服务器硬盘被HLS分片挤爆,所以一定设置成on。

hls_fragment_naming

Syntax: hls_fragment_naming sequential|timestamp|system
Context: rtmp, server, application

Sets fragment naming mode. * sequential - use increasing integers * timestamp - use stream timestamp * system - use system time

设置分片的命名方式,有三种命名方式:序列号,流时间戳,当前系统时间。

Default is sequential. 默认使用序列号。

hls_fragment_naming system;

提示: 根据业务需要一般都是使用第三种命名方式,system。

hls_fragment_naming_granularity

Syntax: hls_fragment_naming_granularity number
Context: rtmp, server, application

Sets granularity for hls fragment ids. If above zero, changes ids to divide the provided value. Default is zero.

当分片命名方式设置为system时,再设置这个参数,比如设置成500,那所有分片的名字都是以500取整,不会出现其他零碎的时间值。

# use system time rounded to 500ms as fragment names
hls_fragment_naming system;
hls_fragment_naming_granularity 500;

提示: 感觉没什么卵用,没设置。

hls_fragment_slicing

Syntax: hls_fragment_slicing plain|aligned
Context: rtmp, server, application

Sets fragment slicing mode. * plain - switch fragment when target duration is reached * aligned - switch fragment when incoming timestamp is a multiple of fragment duration. This mode makes it possible to generate identical fragments on different nginx instances

设置切片模式。plain:普通切法。aligned: 当传入的时间戳是分片周期的整数倍时分片。这种模式可以在不同nginx实例上切出一致的分片。

Default is plain.

hls_fragment_slicing aligned;

提示: 目前我们没有设置。

hls_variant

Syntax: hls_variant suffix [param*]
Context: rtmp, server, application

Adds HLS variant entry. When suffix is matched on stream name then variant playlist is created for the current stream with all entries specified by hls_variant directives in current application. Stripped name without suffix is used as variant stream name. The original stream is processed as usual.

Optional parameters following the suffix are appended to EXT-X-STREAM-INF in m3u8 playlist. See HLS spec. 3.3.10. EXT-X-STREAM-INF for the full list of supported parameters.

增加HLS多码流入口。前缀匹配上流的名字,建立多码流。

当前应用hls_variant命令, 去除名字前缀作为流名字使用。原始流按通常处理。 前缀后边的可选参数追加到 m3u8列表的EXT-X-STREAM-INF后面。

rtmp {
    server {
        listen 1935;

        application src {
            live on;

            exec ffmpeg -i rtmp://localhost/src/$name
              -c:a libfdk_aac -b:a 32k  -c:v libx264 -b:v 128K -f flv rtmp://localhost/hls/$name_low
              -c:a libfdk_aac -b:a 64k  -c:v libx264 -b:v 256k -f flv rtmp://localhost/hls/$name_mid
              -c:a libfdk_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;
        }
    }
}

提示: src中ffmpeg转出多路码率的码流,然后传入hls中,通过hls_variant设置多码率,这样就会生成一个masterplaylist和每个码率一个自己的mediaplaylist。从而可以支持HLS多码率的功能。

hls_type

Syntax: hls_type live|event
Context: rtmp, server, application

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;

用于设置在生成的索引文件中X-PLAYLIST-TYPE显示的类型。

LIVE : 流通常从索引文件中倒数几片开始播放。

EVENT: 流从头播放(使用此种模式需确认playlist的长度够长)。

hls_type event;

提示: 我们一定是用live的。

hls_keys

Syntax: hls_keys on|off
Context: rtmp, server, application

Enables HLS encryption. AES-128 method is used to encrypt the whole HLS fragments. Off by default.

开启HLS加密。 AES-128方法加密整个切片。默认关

hls_keys on;

Here’s the example configuration using the HLS encryption. This configuration requires that nginx is built with --with-http_ssl_module for https support.

...

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

Syntax: hls_key_path path
Context: rtmp, server, application

Sets the directory where auto-generated HLS keys are saved. Key files have .key extension and pseudo-random 16-byte content created with the OpenSSL RAND_bytes() routine. If the directory does not exist it’s created in runtime. By default, hls_path directory is used for key files. Remember however you should normally restrict access to key files which is easier when these files are stored separately from playlist and fragments.

设置自动生成HLS秘钥存放路径。key文件后缀.key,内容16位伪随机数。路径不存在会自动建立。 默认,hls_path 目录用于key文件。记住把key放在不同于切片和索引的目录,限制访问。

hls_key_path /tmp/keys;

提示: 目前我们不支持切片加密,所以没设置这个。

hls_key_url

Syntax: hls_key_url url
Context: rtmp, server, application

Sets url for HLS key file entries. When empty those items have no prefix and keys are assumed to be at the same location as the playlist. Empty by default.

为HLS秘钥文件设置URL入口。为空时没有前缀,假定秘钥存放在索引路径。默认空。

hls_key_url https://myserver.com/keys/;

Example playlist entry with the above setting

示例为如上设置的列表入口

#EXT-X-KEY:METHOD=AES-128,URI="https://myserver.com/keys/337.key",IV=0x00000000000000000000000000000151

提示: 目前我们不支持切片加密,所以没设置这个。

hls_fragments_per_key

Syntax: hls_fragments_per_key value
Context: rtmp, server, application

Sets the number of HLS fragments encrypted with the same key. Zero means only one key is created at the publish start and all fragments within the session are encrypted with this key. Default is zero.

设置HLS切片用相同key加密的片数。0意味着发布时有1 个秘钥生成,会话所有的切片被此秘钥加密。默认为 0。

hls_fragments_per_key 10;

提示: 目前我们不支持切片加密,所以没设置这个。

MPEG-DASH

dash

Syntax: dash on|off
Context: rtmp, server, application

Toggles MPEG-DASH on the application. 开始DASH直播功能。

dash on;
dash_path /tmp/dash;
dash_fragment 15s;

In http{} section set up the following location for clients to play MPEG-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目前没有多少人在用,所以没有研究,但应该跟HLS也是差不多的。

dash_path

Syntax: dash_path path
Context: rtmp, server, application

Sets MPEG-DASH playlist and fragment directory. If the directory does not exists it will be created.

设置MPEG-DASH列表和切片路径。如果存在自动建立。

dash_fragment

Syntax: dash_fragment time
Context: rtmp, server, application

Sets MPEG-DASH fragment length. Defaults to 5 seconds.

设置MPEG-DASH切片时 长。默认5s。

dash_playlist_length

Syntax: dash_playlist_length time
Context: rtmp, server, application

Sets MPEG-DASH playlist length. Defaults to 30 seconds.

设置播放列表时长,默认30s。

dash_playlist_length 10m;

dash_nested

Syntax: dash_nested on|off
Context: rtmp, server, application

Toggles MPEG-DASH nested mode. In this mode a subdirectory of dash_path is created for each stream. Playlist and fragments are created in that subdirectory. Default is off.

设置 MPEG-DASH 嵌套模式。这一模式下为每个流创建了一个 dash_path 的子目录。播放列表和分段在那个子目录中创建。默认为 off

dash_nested on;

dash_cleanup

Syntax: dash_cleanup on|off
Context: rtmp, server, application

Toggles MPEG-DASH cleanup. By default the feature is on. In this mode nginx cache manager process removes old MPEG-DASH fragments and manifests from MPEG-DASH directory. Init fragments are deleted after stream manifest is deleted.

设置是否删除老的MPEG-DASH的分片。默认是删除。

dash_cleanup off;

Access log

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相关参数。log默认是打开的,内容被输出到了nginx本身的logs/access.log中去了。我们可以通过设置把跟rtmp-module相关的输出到一个单独的log文件中。

log_format new '$remote_addr';
access_log logs/rtmp_access.log new;
access_log logs/rtmp_access.log;
access_log off;

提示: log_format可以定义Log的输出内容和格式,并把这个log形式组合起一个名字,比如上例的new, 然后在access_log就可以指定要输出的log位置,后边带上刚刚定义的log组合名字。

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 number * remote_addr - client address * app - application name * name - last stream name * args - last stream play/publish arguments * flashver - client flashVer * swfurl - client swfUrl * tcurl - client tcUrl * pageurl - client pageUrl * command - play/publish commands sent by client: NONE, PLAY, PUBLISH, PLAY+PUBLISH * bytes_sent - number of bytes sent to client * bytes_received - number of bytes received from client * time_local - local time at the end of client connection * session_time - connection duration in seconds * session_readable_time - connection duration in human-readable format * msec - current unix timestamp in SEC.MSEC format

上面是在定义log组合时可以用到的变量,自己可以自由组合。

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)

默认输出的log组合是上边这些内容,命名为combined

提示: 我们可以通过在application中指定

access_log logs/rtmp_accesss.log combined;

将rtmp log输出到rtmp_access.log文件中。

Limits

max_connections

Syntax: max_connections number
Context: rtmp, server, application

Sets maximum number of connections for rtmp engine. Off by default.

设置RTMP连接最大数。默认off

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{}中的,而是定义在http{}中,这个没有什么好说的,就按照下面那样配置就可以。

提示: 但是。。。。这个模块有一个大坑,就是只能在nginx单worker的模式下正常工作,一旦设置为多worker模式,这个统计信息就完全不准了, 所以将来我们如果要做统计还要另想办法。

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;
        }
    }
}

提示: 其中/stat.xsl下指定的root路径下一定要有stat.xsl这模板文件,这个文件就在nginx-rtmp-module源码包的根目录下,拷贝过去就行了。

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.

多worker模式支持。通过推流给持续的nginx workers实现多worker直播流。

rtmp_auto_push

Syntax: rtmp_auto_push on|off
Context: root

Toggles auto-push (multi-worker live streaming) mode. Default is off.

设置自动推模式(多worker 直播流)。默认关。设置为on时,开启支持多worker模式。

提示: 我们会用多worker模式,所以我们把这项设为on

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.

设置worker被杀掉时自动重 连超时。默认100ms。

rtmp_socket_dir

Syntax: rtmp_socket_dir dir
Context: root

Sets directory for UNIX domains sockets used for stream pushing. Default is /tmp.

为推流设置UNIX域名 socket路径。默认是/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.

控制模块是NGINX HTTP模块, 位于http{}配置块中。

提示: 这个模块和统计模块问题是一样的,只在单worker下能稳定正常工作,在多worker下就完蛋了,说这句话容易,但这都是自己踩过坑之后才知道的。

rtmp_control

Syntax: rtmp_control all
Context: http, server, location

Sets RTMP control handler to the current HTTP location.

为当前HTTP location设置RTMP控制器。

http {
    server {
        location /control {
            rtmp_control all;
        }
    }
}

More details about control module

comments powered by Disqus