Nginx_Http_Flv_Module + JavaCV推流RTSP 直播流

懒驴 2021年10月14日 620次浏览
  • 推流与拉流的前提都是需要有流媒体服务器,所以第一步是进行搭建流媒体服务器,本文的流媒体服务器搭建方式使用的是Nginx_Http_Flv_Module +JavaCV流媒体方案。【基于Windows系统开发】

  • 环境准备:

    1. 下载并安装具有rtmp模块的Nginx,配置nginx.conf;
    2. 使用编程语言中调用推流方法。
  • 具体实现
    以下实现均为环境安装完成的情况是的具体实现过程

  1. Nginx的配置文件
#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  4096;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       8800;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            #root   E:/service/VideoMonitorWEB3.0;
			root  html;
            index  index.html index.htm;
        }

        location ^~ /uwb/ {
            proxy_pass http://127.0.0.1:18080;
            proxy_send_timeout 1800;
            proxy_read_timeout 1800;
            proxy_connect_timeout 1800;
            client_max_body_size 2048m;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded=-Proto $scheme;

            #proxy_http_version 1.1;
            #proxy_set_header Upgrade $http_upgrade;
            #proxy_set_header Connection "upgrade";
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }


        location /live {
            flv_live on; #打开HTTP播放FLV直播流功能
            chunked_transfer_encoding on; #支持'Transfer-Encoding: chunked'方式回复

            add_header 'Access-Control-Allow-Origin' '*'; #添加额外的HTTP头
            add_header 'Access-Control-Allow-Credentials' 'true'; #添加额外的HTTP头
        }

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

            root html/hls;
            add_header 'Cache-Control' 'no-cache';
        }

        location /dash {
            root html/dash;
            add_header 'Cache-Control' 'no-cache';
        }

        location /stat {
            #推流播放和录制统计数据的配置

            rtmp_stat all;
            rtmp_stat_stylesheet stat.xsl;
        }

        location /stat.xsl {
            root html/stat; #指定stat.xsl的位置
        }

        #如果需要JSON风格的stat, 不用指定stat.xsl
        #但是需要指定一个新的配置项rtmp_stat_format

        #location /stat {
        #    rtmp_stat all;
        #    rtmp_stat_format json;
        #}

        location /control {
            rtmp_control all; #rtmp控制模块的配置
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
}


rtmp_auto_push on;
rtmp_auto_push_reconnect 1s;
rtmp_socket_dir /tmp;

rtmp {
    out_queue           4096;
    out_cork            8;
    max_streams         128;
    timeout             15s;
    drop_idle_publisher 15s;

    log_interval 5s; #log模块在access.log中记录日志的间隔时间,对调试非常有用
    log_size     1m; #log模块用来记录日志的缓冲区大小

    server {
        listen 1935;
        # server_name www.test.*;  #当模块中,只有一个server时,可以不配置server_name,nginx对于请求,当找不到匹配的server_name时,会默认发给第一个server进行处理。

        application myapp {
            live on;
            gop_cache on; #打开GOP缓存,减少首屏等待时间
			#gop_cache off; 
        }

        application hls {
            live on;
            hls on;
			hls_playlist_length 1s; 
			hls_fragment 1s;
            hls_path D:/nginx-1.19.3/html/hls;
        }

        application dash {
            live on;
            dash on;
            dash_path D:/nginx-1.19.3/html/dash;
        }
    }

}

  1. Java Maven pom.xml需要配置

     <dependency>
         <groupId>net.bramp.ffmpeg</groupId>
         <artifactId>ffmpeg</artifactId>
         <version>0.6.2</version>
     </dependency>
    
     <dependency>
     	<groupId>org.bytedeco</groupId>
     	<artifactId>javacv-platform</artifactId>
     	<version>1.5.4</version>
     </dependency>
     <dependency>
         <groupId>org.bytedeco.javacpp-presets</groupId>
         <artifactId>ffmpeg-platform</artifactId>
         <version>4.0.2-1.4.3</version>
     </dependency>
    
  2. Nginx配置文件完成后启动,然后通过java代码推流代码如下:
    建议在线程中调用此方法

package com.video.httpflv.converttools;

import static org.bytedeco.ffmpeg.global.avcodec.av_packet_unref;

import java.io.IOException;

import org.bytedeco.ffmpeg.avcodec.AVPacket;
import org.bytedeco.ffmpeg.avformat.AVFormatContext;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.FrameGrabber.Exception;


/***
 * rtsp转rtmp工具类(转封装方式)
 * @author 懒驴
 *
 */
public class ConvertVideoPakcetTools {
	FFmpegFrameGrabber grabber = null;
	FFmpegFrameRecorder record = null;
	int width = -1, height = -1;
	
	// 视频参数
	protected int audiocodecid;
	protected int codecid;
	protected double framerate=30;// 帧率
	protected int bitrate=300000;// 比特率
	
	/**
	 * 选择视频源.
	 */
	public ConvertVideoPakcetTools from(String src) throws Exception {
	  // 采集/抓取器
	  grabber = new FFmpegFrameGrabber(src);
	  if(src.indexOf("rtsp")>=0) {
	    grabber.setOption("rtsp_transport","tcp");
	  }
	  grabber.start();// 开始之后ffmpeg会采集视频信息,之后就可以获取音视频信息
	  if (width < 0 || height < 0) {
	    width = grabber.getImageWidth();
	    height = grabber.getImageHeight();
	  }
	  // 视频参数
	  audiocodecid = grabber.getAudioCodec();
	  return this;
	}
	
	/**
	 * 选择输出.
	 */
	public ConvertVideoPakcetTools to(String out) throws IOException {
		// 录制/推流器
		record = new FFmpegFrameRecorder(out, width, height);
		record.setGopSize(2);
		record.setFrameRate(framerate);
		record.setVideoBitrate(bitrate);
		//record.recordSamples(bitrate, audiocodecid, null);
		AVFormatContext fc = null;
		if (out.indexOf("rtmp") >= 0 || out.indexOf("flv") > 0) {
		  // 封装格式flv
		  record.setFormat("flv");
		  record.setAudioCodecName("aac");
		  fc = grabber.getFormatContext();
		}
		record.start(fc);
		return this;
	}
	
	/**
	 * 转封装.
	 */
	public ConvertVideoPakcetTools go() throws IOException {
	  long err_index = 0;//采集或推流导致的错误次数test
	  //连续五次没有采集到帧则认为视频采集结束,程序错误次数超过1次即中断程序
	  for(int no_frame_index=0;no_frame_index<5||err_index>1;) {
	    AVPacket pkt=null;
	    try {
	      //没有解码的音视频帧
	      pkt=grabber.grabPacket();
	      if(pkt==null||pkt.size()<=0||pkt.data()==null) {
	        //空包记录次数跳过
	        no_frame_index++;
	        continue;
	      }
	      //不需要编码直接把音视频帧推出去
	      err_index+=(record.recordPacket(pkt)?0:1);//如果失败err_index自增1
	      av_packet_unref(pkt);
	    }catch (Exception e) {//推流失败
	      err_index++;
	    } catch (IOException e) {
	      err_index++;
	    }
	  }
	  return this;
	}
}