Total Pageviews

Saturday, 17 September 2016

基于nginx的流媒体服务器

NGINX-based Media Streaming Server

nginx-rtmp-module

Project blog

http://nginx-rtmp.blogspot.com

Wiki manual

https://github.com/arut/nginx-rtmp-module/wiki/Directives

Google group

https://groups.google.com/group/nginx-rtmp
https://groups.google.com/group/nginx-rtmp-ru (Russian)

Donation page (Paypal etc)

http://arut.github.com/nginx-rtmp-module/

Features

  • RTMP/HLS/MPEG-DASH live streaming
  • RTMP Video on demand FLV/MP4, playing from local filesystem or HTTP
  • Stream relay support for distributed streaming: push & pull models
  • Recording streams in multiple FLVs
  • H264/AAC support
  • Online transcoding with FFmpeg
  • HTTP callbacks (publish/play/record/update etc)
  • Running external programs on certain events (exec)
  • HTTP control module for recording audio/video and dropping clients
  • Advanced buffering techniques to keep memory allocations at a minimum level for faster streaming and low memory footprint
  • Proved to work with Wirecast, FMS, Wowza, JWPlayer, FlowPlayer, StrobeMediaPlayback, ffmpeg, avconv, rtmpdump, flvstreamer and many more
  • Statistics in XML/XSL in machine- & human- readable form
  • Linux/FreeBSD/MacOS/Windows

Build

cd to NGINX source directory & run this:
./configure --add-module=/path/to/nginx-rtmp-module
make
make install
Several versions of nginx (1.3.14 - 1.5.0) require http_ssl_module to be added as well:
./configure --add-module=/path/to/nginx-rtmp-module --with-http_ssl_module
For building debug version of nginx add --with-debug
./configure --add-module=/path/to-nginx/rtmp-module --with-debug
Read more about debug log

Windows limitations

Windows support is limited. These features are not supported
  • execs
  • static pulls
  • auto_push

RTMP URL format

rtmp://rtmp.example.com/app[/name]
app - should match one of application {} blocks in config
name - interpreted by each application can be empty

Multi-worker live streaming

Module supports multi-worker live streaming through automatic stream pushing to nginx workers. This option is toggled with rtmp_auto_push directive.

Example nginx.conf

rtmp {

    server {

        listen 1935;

        chunk_size 4000;

        # TV mode: one publisher, many subscribers
        application mytv {

            # enable live streaming
            live on;

            # record first 1K of stream
            record all;
            record_path /tmp/av;
            record_max_size 1K;

            # append current timestamp to each flv
            record_unique on;

            # publish only from localhost
            allow publish 127.0.0.1;
            deny publish all;

            #allow play all;
        }

        # Transcoding (ffmpeg needed)
        application big {
            live on;

            # On every pusblished stream run this command (ffmpeg)
            # with substitutions: $app/${app}, $name/${name} for application & stream name.
            #
            # This ffmpeg call receives stream from this application &
            # reduces the resolution down to 32x32. The stream is the published to
            # 'small' application (see below) under the same name.
            #
            # ffmpeg can do anything with the stream like video/audio
            # transcoding, resizing, altering container/codec params etc
            #
            # Multiple exec lines can be specified.

            exec ffmpeg -re -i rtmp://localhost:1935/$app/$name -vcodec flv -acodec copy -s 32x32
                        -f flv rtmp://localhost:1935/small/${name};
        }

        application small {
            live on;
            # Video with reduced resolution comes here from ffmpeg
        }

        application webcam {
            live on;

            # Stream from local webcam
            exec_static ffmpeg -f video4linux2 -i /dev/video0 -c:v libx264 -an
                               -f flv rtmp://localhost:1935/webcam/mystream;
        }

        application mypush {
            live on;

            # Every stream published here
            # is automatically pushed to
            # these two machines
            push rtmp1.example.com;
            push rtmp2.example.com:1934;
        }

        application mypull {
            live on;

            # Pull all streams from remote machine
            # and play locally
            pull rtmp://rtmp3.example.com pageUrl=www.example.com/index.html;
        }

        application mystaticpull {
            live on;

            # Static pull is started at nginx start
            pull rtmp://rtmp4.example.com pageUrl=www.example.com/index.html name=mystream static;
        }

        # video on demand
        application vod {
            play /var/flvs;
        }

        application vod2 {
            play /var/mp4s;
        }

        # Many publishers, many subscribers
        # no checks, no recording
        application videochat {

            live on;

            # The following notifications receive all
            # the session variables as well as
            # particular call arguments in HTTP POST
            # request

            # Make HTTP request & use HTTP retcode
            # to decide whether to allow publishing
            # from this connection or not
            on_publish http://localhost:8080/publish;

            # Same with playing
            on_play http://localhost:8080/play;

            # Publish/play end (repeats on disconnect)
            on_done http://localhost:8080/done;

            # All above mentioned notifications receive
            # standard connect() arguments as well as
            # play/publish ones. If any arguments are sent
            # with GET-style syntax to play & publish
            # these are also included.
            # Example URL:
            #   rtmp://localhost/myapp/mystream?a=b&c=d

            # record 10 video keyframes (no audio) every 2 minutes
            record keyframes;
            record_path /tmp/vc;
            record_max_frames 10;
            record_interval 2m;

            # Async notify about an flv recorded
            on_record_done http://localhost:8080/record_done;

        }


        # HLS

        # For HLS to work please create a directory in tmpfs (/tmp/hls here)
        # for the fragments. The directory contents is served via HTTP (see
        # http{} section in config)
        #
        # Incoming stream must be in H264/AAC. For iPhones use baseline H264
        # profile (see ffmpeg example).
        # This example creates RTMP stream from movie ready for HLS:
        #
        # ffmpeg -loglevel verbose -re -i movie.avi  -vcodec libx264
        #    -vprofile baseline -acodec libmp3lame -ar 44100 -ac 1
        #    -f flv rtmp://localhost:1935/hls/movie
        #
        # If you need to transcode live stream use 'exec' feature.
        #
        application hls {
            live on;
            hls on;
            hls_path /tmp/hls;
        }

        # MPEG-DASH is similar to HLS

        application dash {
            live on;
            dash on;
            dash_path /tmp/dash;
        }
    }
}

# HTTP can be used for accessing RTMP stats
http {

    server {

        listen      8080;

        # This URL provides RTMP statistics in XML
        location /stat {
            rtmp_stat all;

            # Use this stylesheet to view XML as web page
            # in browser
            rtmp_stat_stylesheet stat.xsl;
        }

        location /stat.xsl {
            # XML stylesheet to view RTMP stats.
            # Copy stat.xsl wherever you want
            # and put the full directory path here
            root /path/to/stat.xsl/;
        }

        location /hls {
            # Serve HLS fragments
            types {
                application/vnd.apple.mpegurl m3u8;
                video/mp2t ts;
            }
            root /tmp;
            add_header Cache-Control no-cache;
        }

        location /dash {
            # Serve DASH fragments
            root /tmp;
            add_header Cache-Control no-cache;
        }
    }
}

Multi-worker streaming example

rtmp_auto_push on;

rtmp {
    server {
        listen 1935;

        application mytv {
            live on;
        }
    }
} 
 
from  https://github.com/arut/nginx-rtmp-module
------

How to set up your own private RTMP server using nginx

Most people who stream enjoy using services such as Twitch.tv or Ustream to deliver video to viewers, and that works well enough. But sometimes you want some more control over your stream, or you want other people to be able to stream to you, or you want to stream to multiple places, or any number of things that requires you to have access to an actual RTMP stream from an RTMP server. This guide will cover the very basics of setting up a simple RTMP server on a Linux computer. Don’t worry, it’s not too complicated, but having familiarity with Linux will certainly help.
A couple things you can do with your own RTMP server that you might be interested in:
  • Stream to multiple external channels
  • Import other people’s streams to incorporate for your own purposes
Alright, so how do you do these kinds of things?
Step 1: Get a Server Box
Believe it or not, RTMP is actually extremely light on system resources. Essentially it just grabs data from the input and forwards it on to the output, simple data transfer.
If you don’t have your own box, a VPS can also work. Just make sure you have enough bandwidth…remember that bandwidth usage will be (the size of a stream) * (the number of people uploading + the number of people downloading). So when I have 2 streamers stream to my server, and I download both of them, I can chew up 10GB of bandwidth in 2 hours.
I recommend using Ubuntu for the server software for the sake of ease, but you can obviously use whatever you want. As long as you get the dependencies for nginx somewhere besides apt, you can follow this guide just fine.
Note to Windows users: This guide focuses on using Linux. If you want to use Windows, you can find Windows binaries for nginx with the RTMP module already included here: http://nginx-win.ecsds.eu/download/
Note to Mac users: You can install nginx with the RTMP module via Homebrew: http://brew.sh/homebrew-nginx/
If you are hosting your server in your home, you will have to forward TCP port 1935 to the box…this varies by router, so look up how to set up port forwarding for your router. Also, I recommend using a dynamic DNS service to overcome dynamic IP issues that come up with residential hosting.
Step 2: Installing nginx with RTMP module
Log into your box, and make sure you have the necessary tools to build nginx using the following command:

Now a bit of info about nginx (pronounced “engine-X”). nginx is an extremely lightweight web server, but someone wrote a RTMP module for it, so it can host RTMP streams too. However, to add the RTMP module, we have to compile nginx from source rather than use the apt package. Don’t worry, it’s really easy. Just follow these instructions. 🙂
From your home directory, download the nginx source code:
As of this writing, the latest stable version of nginx is 1.13.1. You can find the latest version on the nginx download page.
Next, get the RTMP module source code from git:
Unpack/unzip them both, and enter the nginx directory:

Now we build nginx:

And nginx is installed! By default it installs to /usr/local/nginx, so to start the server run the following command:

And to test to make sure nginx is running, point your browser to http://<your server ip>/ and you should get the “Welcome to nginx!” page.
Step 3: Configuring nginx to use RTMP
Open your config file, located by default at /usr/local/nginx/conf/nginx.conf and add the following at the very end of the file:
Code
rtmp {
        server {
                listen 1935;
                chunk_size 4096;

                application live {
                        live on;
                        record off;
                }
        }
}
This is an extremely basic configuration with a “live” application that simply forwards the RTMP stream on to whoever requests it. You can play with it some more later. Here’s the whole configuration guide, which shows you how to forward streams to other places (such as Twitch), save recordings of uploads, output stats, etc.
Restart nginx with:

Step 4: Testing!
Your server should now be ready to accept RTMP streams! Let’s try it out.
Create a new profile in OBS, and change your Broadcast Settings thusly:

You may be wondering where that play path “test” came from. Well, we just made it up, just now. You can basically make up any play path and stream to it, and put that path into an RTMP player, and it will play back. For simple purposes, authentication isn’t necessary in my experience.
You should now be able to start streaming to your server. If you hit “Start Streaming” and don’t get an error from OBS, that’s a good sign.
So how do you watch it? The easiest way to do so is with VLC (v2.1.0 or later). Just Open a Network Stream and enter in rtmp://<your server ip>/live/test as the URL. If it all worked right, then you should now be seeing your stream in VLC!
You now have a working RTMP server! Congrats!
What now?
You can add the stream to OBS itself using the Media source or VLC source, or use something like JWPlayer to play back the RTMP stream on a web site you set up.
You can also use your RTMP server to forward to other streaming services and channels! Underneath the “record off;” line in your nginx.conf, add the following:

And any stream streamed to that application will be forwarded on to the other service, as well as being served up from the server! You can add multiple “pushes” to forward the stream to multiple locations.
FAQ
Q: Why nginx? Why not crtpmserver/Red5/Wowza? A: I’ve tried crtmpserver (aka rtmpd) before, and it works, but is harder to use. If you need to use RTSP, though, instead of RTMP, then I recommend it, since the nginx RTMP module doesn’t do RTSP. Red5 seemed overly complicated and heavy to me, and written in Java…you can use it if you want though. I haven’t investigated it deeply. Wowza is not free. You can use what you like, but so far nginx is lightweight, easy to use, and free, so you’re going to have to pry it from my cold, dead hands.
Q: How do I X? A: This FAQ is still in progress…ask questions so I can add them here!
-------------------------------------------------------------------------------------------------------
Demonstrates how to build a live broadcast app(Swift 3).

This project is to demonstrate how to build a live broadcast app. It include these features:
  • Create a room to broadcast your live stream
  • Join a room to watch the live
  • Send likes, gifts, and comments

Introduction

How to run

1. Nginx RTMP server

You need to can set up your own rtmp server, the guidance can be found here:

2. WebSocket server

Just go to the live-server folder, run npm install, then start the server by node app.js

3. iOS client

Go to the live-ios folder, run pod install(must use cocoapods 0.39.0)
In Config.swift, update the server url:
struct Config {
    static var rtmpPushUrl = "rtmp://139.196.179.230/mytv/"
    static var rtmpPlayUrl = "rtmp://139.196.179.230/mytv/"
    static var serverUrl = "http://139.196.179.230:3000"
}

The app can also run on a simulator, but to broadcast, you need to run it on a real device.

Tutorial

1. Live streaming

The basic live streaming flow is:
broadcaster -> rtmp -> media server -> cdn -> rtmp or hls -> audience
For the simplest case, we don't need a cdn server, then the flow will be:
broadcaster -> rtmp -> media server -> rtmp or hls -> audience
That is, the boadcaster push the live stream using the RTMP protocal to a media server, the audience pull the stream from the server using RTMP or HLS protocal.
Some explaination for RTMP and HLS:
  • RTMP: RTMP is used to stream audio, video or data and is originally a proprietary protocol introduced by Macromedia (owned by Adobe). The protocol is TCP-based and offers therefore persistent connections. In short, RTMP encapsulates MP3/AAC audio and MP4/FLV video multimedia streams.
  • HLS: HTTP Live Streaming is known as HLS. As the name implies, it is the media streaming communications protocol based on HTTP; developed by Apple as part of their QuickTime, Safari, OS X, and iOS products. How does it work? It breaks the overall stream into a sequence of small HTTP-based files (.ts: Transport Stream). These transport stream files are indexed in the file .m3u8. It is required to download first the .m3u8 playlist to play a live stream.
For the media server, there are serveral choices:
  • Adobe media server
  • Red5
  • Nginx RTMP module
  • crtmpserver
After setting up the server, you can test it using ffmpeg(install it by brew install ffmpeg).
  • push stream
ffmpeg -f avfoundation -framerate 30  -i "1:0" -f flv rtmp://server-url
p.s. Lots of live stream cloud already covers the media server and cdn parts. You just need to push/pull the stream from it.

2. iOS RTMP libs

There are serveral open source projects supporting RTMP, this project uses:
You can find the usage of these libs in their project pages.
frm  https://github.com/ltebean/Live
-----

RTSP, RTMP, and HTTP server in Node.js

  • Supports RTSP, RTMP/RTMPE/RTMPT/RTMPTE, and HTTP.
  • Supports only H.264 video and AAC audio (AAC-LC, HE-AAC v1/v2).

Installation without Docker

$ git clone https://github.com/iizukanao/node-rtsp-rtmp-server.git
$ cd node-rtsp-rtmp-server
$ npm install -d
Also, install CoffeeScript 1.x or 2.x.

Configuration

Edit config.coffee.

Starting the server

$ cd node-rtsp-rtmp-server
$ sudo coffee server.coffee
or use Node.js directly:
$ cd node-rtsp-rtmp-server
$ coffee -c *.coffee
$ sudo node server.js
If both serverPort and rtmpServerPort are >= 1024 in config.coffeesudo is not needed.

Docker Deploy Method

If you would prefer building and executing this code in a docker container, you can do so by first building the container and then running it.
$  make build
$  make console
You may also want to use just make run to run the container as a daemon. If you fiddle with the ports, you'll need to update the values in the Makefile as well to expose the desired ports to your system.

Serving MP4 files as recorded streams

MP4 files in file directory will be accessible at either:
  • rtsp://localhost:80/file/FILENAME
  • rtmp://localhost/file/mp4:FILENAME
For example, file/video.mp4 is available at rtmp://localhost/file/mp4:video.mp4

Publishing live streams

From Flash Media Live Encoder

Flash Media Live Encoder is a free live encoder from Adobe.
In the Encoding Options panel, check "Stream to Flash Media Server" and set the URL to:
  • FMS URL: rtmp://localhost/live
  • Backup URL: (blank)
  • Stream: STREAM_NAME (whatever name you would like)
Press the "Connect" button. Set the video format to H.264, and the audio format to AAC. Press the "Start" button.
When you watch the stream over RTSP or RTMP, use the stream name specified above.

From FFmpeg

If you have an MP4 file with H.264 video and AAC audio:
$ ffmpeg -re -i input.mp4 -c:v copy -c:a copy -f flv rtmp://localhost/live/STREAM_NAME
Or if you have an MP4 file that is encoded in other audio/video format:
$ ffmpeg -re -i input.mp4 -c:v libx264 -preset fast -c:a libfdk_aac -ab 128k -ar 44100 -f flv rtmp://localhost/live/STREAM_NAME
Replace input.mp4 with live audio/video sources.

From RTSP client

You can publish streams from RTSP client such as FFmpeg.
$ ffmpeg -re -i input.mp4 -c:v libx264 -preset fast -c:a libfdk_aac -ab 128k -ar 44100 -f rtsp rtsp://localhost:80/live/STREAM_NAME
Or you can publish it over TCP instead of UDP, by specifying -rtsp_transport tcp option. TCP is favorable if you publish large data from FFmpeg.
$ ffmpeg -re -i input.mp4 -c:v libx264 -preset fast -c:a libfdk_aac -ab 128k -ar 44100 -f rtsp -rtsp_transport tcp rtsp://localhost:80/live/STREAM_NAME

From GStreamer

For an MP4 file with H.264 video and AAC audio:
$ gst-launch-0.10 filesrc location=input.mp4 ! qtdemux name=demux ! \
    flvmux name=mux streamable=true ! queue ! \
    rtmpsink location='rtmp://localhost/live/STREAM_NAME' demux. ! \
    multiqueue name=mq ! h264parse ! mux. demux. ! mq. mq. ! aacparse ! mux.
Replace input.mp4 with live audio/video sources.
For an RTSP source (at rtsp://192.168.1.1:5000/video1 in this example):
$ gst-launch-0.10 rtspsrc location=rtsp://192.168.1.1:5000/video1 ! decodebin ! \
    x264enc bitrate=256 tune=zerolatency  ! h264parse ! flvmux name=mux streamable=true ! \
    queue ! rtmpsink location='rtmp://localhost/live/STREAM_NAME' 

Accessing the live stream

Via RTSP

RTSP stream is for VLC media player or Android's VideoView.
RTSP URL: rtsp://localhost:80/live/STREAM_NAME
Note that the RTSP server runs on port 80 by default.

Via RTMP

RTMP stream is for Flash Player. Flowplayer and JW Player are both good free players.
RTMP URL: rtmp://localhost/live/STREAM_NAME
If you have rtmpdump installed, you can record the video with:
$ rtmpdump -v -r rtmp://localhost/live/STREAM_NAME -o dump.flv
from
https://github.com/iizukanao/node-rtsp-rtmp-server
------

CentOS7上,自建基于HLS的私人直播服务器

实现方法基于nginx和nginx的一个rtmp模块。因为epel源和nginx官方源里面安装的nginx是没有nginx-rtmp-module的,所以只能编译安装。

先新建一个www用户和组专门用来跑Nginx:

groupadd www
useradd www -g www -s /sbin/nologin

安装EPEL/开发工具包/以及编译Nginx所需的依赖:

yum -y install epel-release
yum -y groupinstall "Development Tools"
yum -y install wget openssl-devel pcre-devel zlib-devel geoip-devel gd-devel

进入到opt目录下载nginx-rtmp-module模块:

cd /opt
git clone https://github.com/arut/nginx-rtmp-module.git

同时下载解压Nginx并进入到Nginx的源码目录:

wget http://nginx.org/download/nginx-1.15.8.tar.gz
tar -xzvf nginx-1.15.8.tar.gz
cd nginx-1.15.8

虽然我们本次使用Nginx只是需要用到它的RTMP功能,但既然都编译了,就编译个全面一点的Nginx吧,所以这里我还是把Nginx常用的一些功能和模块都加上:

./configure --user=www --group=www --prefix=/usr/local/nginx --add-module=/opt/nginx-rtmp-module --with-http_ssl_module --with-http_v2_module --with-stream --with-stream_ssl_module --with-http_gzip_static_module --with-http_gunzip_module --with-http_flv_module --with-http_mp4_module --with-http_image_filter_module --with-http_geoip_module --with-http_sub_module --with-http_stub_status_module --with-http_realip_module --with-http_addition_module

如果配置没有错误,那么就可以编译并完成安装了:

make
make install

然后新建一个systemd服务:

vi /etc/systemd/system/nginx.service

写入:

[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID

[Install]
WantedBy=multi-user.target

现在创建hls视频文件存放的目录:

mkdir -p /opt/stream/hls

接着创建一个conf.d目录,专门用来存放Nginx的站点配置文件:

mkdir -p /usr/local/nginx/conf/conf.d

很多人配置的时候都喜欢直接在Nginx的主配置文件内去写http段,这是极其愚蠢的做法。为了可以让你的Nginx配置变的一目了然,更好的分类,正确的做法应该是在主配置文件内引用其他http段的配置,所以现在编辑Nginx的主配置文件:

vi /usr/local/nginx/conf/nginx.conf

引用我们之前创建的conf.d目录,所以在Nginx的主配置文件加入:

include /usr/local/nginx/conf/conf.d/*.conf;

位置如图:


接着我们还是在这个配置文件内加入RTMP的设置,基本上每个参数我都写了注释,你可以一目了然的知道这些配置都做了啥:

rtmp {
    server {
        listen 1935;
        chunk_size 4000;
        # POST请求改为GET用于鉴权验证
        notify_method get;

        application show {
            # 开启实时
            live on;
            # 鉴权验证
            on_publish http://你的服务器公网IP/auth;
            # 加密视频
            wait_key on;
            # 开启HLS
            hls on;
            # ts文件存放路径
            hls_path /opt/stream/hls;
            # 每个ts包含5秒视频
            hls_fragment 5;
            # hls可回放时间
            hls_playlist_length 60;
            # 连续模式,可解决libx264编码出现的缓冲问题
            hls_continuous on;
            # 创建子目录存放ts文件
            hls_nested on;
            # 直播结束清理所有视频文件
            hls_cleanup on;
        }
    }
}

上面这段配置加到events段的下面,如图所示:


接着我们新建一个站点配置文件:

vi /usr/local/nginx/conf/conf.d/stream.conf

写入:

server {
    listen       80;
    server_name  你的服务器公网IP;
    charset utf-8;

    location / {
        root   /usr/local/nginx/html;
        index  index.html index.htm;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/local/nginx/html;
    }

    # 简单的鉴权验证
    location /auth {
        if ($arg_psk = '设置你的直播密码') {
          return 201;
          }
          return 404;
    }

    # HTTP播放地址
    location /live {
        types {
            application/vnd.apple.mpegurl m3u8;
            video/mp2t ts;
        }
        alias /opt/stream/hls;   
        expires -1;
        add_header Cache-Control no-cache;
    }

    # 统计
    location /stat {
        rtmp_stat all;
        rtmp_stat_stylesheet stat.xsl;
    }

    location /stat.xsl {
        root /opt/nginx-rtmp-module/;
    }
}

Nginx的配置到这里就完成了,我们可以使用下面的命令检查一下配置是否正常:

/usr/local/nginx/sbin/nginx -t

有错误就按照错误的提示去排查,没错误就可以用systemd启动Nginx了:

systemctl start nginx
systemctl enable nginx

下面我用Dplayer简单弄个html页面用来测试是否可以正常直播:

cd /usr/local/nginx/html/

下载hls.min.js:

wget https://github.com/video-dev/hls.js/releases/download/v0.12.2/hls.min.js

编辑这个目录内的index.html:

vi index.html

把里面的内容替换成:

<link rel=”stylesheet” href=”https://cdn.bootcss.com/dplayer/1.25.0/DPlayer.min.css”>
<script src=”hls.min.js”></script>
<script src=”https://cdn.bootcss.com/dplayer/1.25.0/DPlayer.min.js”></script>
<div id=”dplayer”></div>
<script>
const dp = new DPlayer({
container: document.getElementById(‘dplayer’),
video: {
url: ‘http://你的服务器公网IP/live/imlala/index.m3u8’,
type: ‘hls’
}
});
</script>

这里还是具体说一下这个OBS的推流设置,首先URL就是:

rtmp://你的服务器公网IP:1935/show/

而下面这个流的名称,比如我是:

imlala?psk=233133xxx

这其中imlala是可以自定义的,你可以把这个理解成一个直播间名字(房间号)而后面的233133xxx就是你的直播密码,这个密码是在/usr/local/nginx/conf/conf.d/stream.conf内可以设置的。其次如果你修改了你的直接间名字(房间号)那么上面那个示例html中的播放地址也需要做修改:

http://你的服务器公网IP/live/imlala/index.m3u8

这样就可以实现一个私人的直播间,如果你不做这种鉴权验证的话,那只要有人知道你的rtmp地址就可以用你的服务器做直播,这样会造成滥用。

最后通过浏览器访问服务器IP,测试是否能够正常播放。 

----------------------

OpenStreamingPlatform:一个开源的视频直播平台


OpenStreamingPlatform是一个开源的视频直播平台,可以用来搭建自己的直播网站。

功能方面还是挺全的,视频上传/直播/录制/聊天/用户控制/后台面板等等都有,唯一的不足就是我觉得UI好丑。。

手动部署方法可以看官方的文档:

https://gitlab.com/Deamos/flask-nginx-rtmp-manager

下面使用docker来部署这个项目。

安装docker:

apt -y update
apt -y install curl
curl -sSL https://get.docker.com/ | sh
systemctl start docker
systemctl enable docker

安装docker-compose:

curl -L https://github.com/docker/compose/releases/download/1.25.4/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose

创建两个目录:

mkdir -p /opt/traefik
mkdir -p /opt/stream

创建acme.json:

touch /opt/traefik/acme.json && chmod 600 /opt/traefik/acme.json

新建traefik的traefik.toml

nano /opt/traefik/traefik.toml

写入如下配置:

defaultEntryPoints = ["https","http"]

[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
    entryPoint = "https"
  [entryPoints.https]
  address = ":443"
  [entryPoints.https.tls]

[acme]
email = "example@qq.com"
storage = "acme.json"
entryPoint = "https"
onHostRule = true
[acme.httpChallenge]
entryPoint = "http"

注:替换邮箱example@qq.com为你自己的。

新建traefik的docker-compose:

nano /opt/traefik/docker-compose.yml

写入如下配置:

version: '3.5'

services:
    reverse-proxy:
      container_name: traefik
      image: traefik:v1.7
      command: --api --docker
      ports:
        - "80:80"
        - "443:443"
        - "8080:8080"
      networks:
        - traefik
      volumes:
        - /var/run/docker.sock:/var/run/docker.sock
        - /opt/traefik/traefik.toml:/traefik.toml
        - /opt/traefik/acme.json:/acme.json

networks:
    traefik:
      name: imlala

新建openstreamingplatform的docker-compose:

nano /opt/stream/docker-compose.yml

写入如下配置:

version: '3.5'

services: 
    openstram:
        container_name: openstream
        image: deamos/openstreamingplatform:latest
        ports:
            - 1935:1935
        environment: 
            - REDIS_HOST=redis-osp
            - FLASK_SECRET=""
            - FLASK_SALT=""
            - OSP_REQUIREVERIFICATION=False
            - OSP_ALLOWREGISTRATION=False
        labels: 
            - "traefik.frontend.rule=Host:stream.233.fi"
        volumes: 
            - ./data:/var/www
            - ./db:/opt/osp/db 
    redis-osp:
        container_name: redis
        image: redis

networks:
    default:
        external:
            name: imlala

注:

1.FLASK_SECRET/FLASK_SALT自己随便填写一点随机字符。

2.OSP_REQUIREVERIFICATION是关闭注册,如果需要注册功能去掉这行env。

3.OSP_ALLOWREGISTRATION是关闭注册用户邮箱验证,如果打开的话需要配置SMTP服务,为方便建议关掉。

4.stream.233.fi的域名替换为你自己的。

最后进到这两个项目目录up起来即可:

docker-compose up -d

关于直播设置,首先要创建频道和直播key。

登录进去右上角点你的账户头像-My Channels-Create Channel

创建完成之后点下拉菜单-齿轮按钮,往下翻会有一个Stream Key。

OBS流设置如下图,rtsp/rtmp都可以.

---------------

Building your own live streaming site using Nginx RTMP & video.js


Previously I built a live stream service using my raspberry pi, and only use the most simple configuration of nginx, and it does not play very well. Now I have bought a shiny new VPS from CAT.NET with my partner onion, it’s awesomely fast and fluent, so I use this server to build my live stream service, including a frontend to play the stream.

The tutorial is here: https://docs.peer5.com/guides/setting-up-hls-live-streaming-server-using-nginx/

The following guide will show how to build one stream server on Archlinux (Yes, archilnux ONLY, but compatible with many other distro), Just follow the basic steps:

Setting up the RTMP Streaming Server with HLS

  1. Install nginx-rtmp from AUR (nginx-mainline + nginx-rtmp-module may also works, but I have problems when compiling the module using makepkg)
  2. If you have previous nginx configuration, install nginx-rtmp will conflict with nginx, just remove it, no worry about the configuration file you wrote, it will be stored at /etc/nginx/nginx.conf.pacsave
  3. If you have a previous installation of nginx, after install nginx-rtmp  exec the command mv /etc/nginx/nginx.conf /etc/nginx/nginx.conf.old and mv /etc/nginx/nginx.conf.pacsave /etc/nginx/nginx.conf
  4. Then restart the nginx server and reload the daemon systemctl daemon-reload  && systemctl restart nginx.conf
  5. This restart shouldn’t generate any error except you have error in your previous nginx config
  6. Then create the rtmp.conf file (or whatever you name it)  example configuration can be found here

Here is my rtmp.conf, remember to include it in nginx.conf OUTSIDE the http block like this:

http {
 ...
}

include rtmp.conf
rtmp {
        server {
                

                max\_connections 100;
                chunk\_size 4096;
                ping 30s;
                notify\_method get;

                application my\_live {
                        live on;
                        hls on;
                        hls\_path /tmp/hls;
                        hls\_fragment 3s;
                        hls\_playlist\_length 60s;

                }
        }
}

Then you can use OBS or anything else to push to the livestream, in this example, you should push to

rtmp://example.com/my\_live

In the key field just write something e.g: test

Remember to mkdir /tmp/hls before using the live stream.

Setting up the Live Stream data service

We need hls.js or videojs with hls supported, I choose the latter one.

create a config in /etc/nginx/sites-available

e.g: live.void-shana.moe.conf

put these lines in the config file

server {
    listen 80;

    location /stream {
        # 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;
        }

        types {
            application/vnd.apple.mpegurl m3u8;
            video/mp2t ts;
        }

        alias /tmp/hls;
    }
}

Then when you visit https://example.com/stream/test.m3u8 you will get the live stream playlist of live named “test”.

This *.m3u8 file is a text file that describes every segment to play (segments are named in -.ts format), here is a sample file

#EXTM3U         
#EXT-X-VERSION:3                 
#EXT-X-MEDIA-SEQUENCE:0          
#EXT-X-TARGETDURATION:8          
#EXT-X-DISCONTINUITY             
#EXTINF:8.333,  
test-0.ts       
#EXTINF:8.333,  
test-1.ts       
#EXTINF:8.334,  
test-2.ts

The videojs / hls.js will recognize format and parse it, fetch *.ts segments from server then play it one by one, making it looks like a live stream.

Create a webpage to show it

I use videojs with hls support for this, just take a look at view-source://live.void-shana.moe/ you can get a video player that works.

See https://github.com/videojs/videojs-contrib-hls#getting-started for more details.

TODO

I didn’t find any credential configuration when setting up rtmp stream, this will make it dangerous when someone know my rtmp URI. Bad guy can push nasty live stream / video to my site, currently the URI is complex, and cannot be fetched from frontend (I only expose the hls interface). Future i  will try to support auth.

---------------------------------------------------------

enhanced-rtmp

There have been ongoing requests from the media streaming industry to enhance the RTMP/FLV solution by bringing the protocol up to date with the current state of the art streaming technologies. RTMP was released over 20 years ago and many streaming solutions use it in their stack today. While RTMP has remained popular it has gone stale in its evolution. As an example RTMP/FLV did not have support for popular video codecs like VP9, HEVC, AV1. That is until now! The document enhanced-rtmp.pdf outlines new enhancements to the RTMP/FLV specification to help bring RTMP protocol inline with the current streaming media technologies. Furthermore Veovera and its members are working on a fast follow with additional capabilities to continue to modernize RTMP. What’s immediately on our roadmap is to complement the recent video codec enhancements with additional popular audio codecs. At the top of our list is Opus, AC-3 and E-AC-3. In addition to continued codec support we are looking to add support for a seamless reconnect command. Our goal is to continue to enhance RTMP while staying backwards compatible without breaking the internet or current tooling. Please stay tuned for the fast follow details and the continued enhancements that will come after that!

<Feedback may be provided by creating a new issue>

from https://github.com/veovera/enhanced-rtmp

https://raw.githubusercontent.com/veovera/enhanced-rtmp/main/enhanced-rtmp-v1.pdf 

----------


相关帖子: 
https://briteming.blogspot.com/2019/12/srs.html
https://briteming.blogspot.com/2020/05/nginx-rtmp-module.html