windows环境下python使用ffmpeg rtmp推流

rtmp推流

参考文档:https://www.cnblogs.com/linuxAndMcu/p/12517787.html#_label4

坦白说这篇文档写的很好,但是我怕下次找不见,还是嫖一下吧

1 下载

开发工具:ffmpeg、nginx 1.7.11.3 Gryphon(nginx)

官方ffmpeg下载地址:http://www.ffmpeg.org

官方nginx下载地址:*http://nginx.org/en/download.html *(建议使用下面的自带rtmp模块的nginx

官方nginx 1.7.11.3 Gryphon下载地址:http://nginx-win.ecsds.eu/download/(原文中链接不能用了)
windows环境下python使用ffmpeg rtmp推流_第1张图片

官方nginx-rtmp-module下载地址:https://github.com/arut/nginx-rtmp-module

官方vlc media player下载地址:https://www.videolan.org/vlc(建议使用迅雷影音)

2 安装nginx、ffmpeg与启动nginx

1、下载好nginx 和 ffmpeg之后直接解压到想保存的文件夹中
2、配置环境变量 ~~~~(此处交给度娘

启动 nginx:

方法1、直接双击 nginx.exe,双击后一个黑色的弹窗一闪而过。

方法2、打开 cmd 命令窗口,切换到 nginx 解压目录下,输入命令 nginx.exe 或者 start nginx ,回车。

3 检查nginx是否启动成功

方法1、直接在浏览器地址栏输入网址 http://127.0.0.1:80 或者 http://localhost:80,回车,然后页面会告诉你欢迎使用nginx。

方法2、哈哈,就用方法1吧~

nginx 的配置文件是 conf 目录下的 nginx.conf,默认配置的 nginx 监听的端口为 80,如果 80 端口被占用可以修改为未被占用的端口即可,也因此 chrome 浏览器未显示端口。

检查 80 端口是否被占用的命令是:netstat -ano | findstr 0.0.0.0:80 或 netstat -ano | findstr “80”,如果打印出了一下内容则说明 80 端口被占用:

  TCP    0.0.0.0:80             0.0.0.0:0              LISTENING       6220

当我们修改了 nginx 的配置文件 nginx.conf 时,不需要关闭 nginx 后重新启动 nginx,只需要执行命令nginx -s reload即可让改动生效

4 配置nginx.conf文件

默认的 nginx.conf 文件并没有配置 RTMP 服务器,需要我们手动添加配置。具体步骤为:在 conf 目录中,复制粘贴 nginx.conf 文件并将其重名为 nginx-win.conf,修改其内容为:

#user  nobody;
# multiple workers works !
worker_processes  2;
 
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
 
#pid        logs/nginx.pid;
 
events {
    worker_connections  8192;
    # max value 32768, nginx recycling connections+registry optimization = 
    #   this.value * 20 = max concurrent connections currently tested with one worker
    #   C1000K should be possible depending there is enough ram/cpu power
    # multi_accept on;
}
 
rtmp {
    server {
        listen 1935;
        chunk_size 4000;
        application live {
             live on;
        }
    }
}
 
http {
    #include      /nginx/conf/naxsi_core.rules;
    include       mime.types;
    default_type  application/octet-stream;
 
    #log_format  main  '$remote_addr:$remote_port - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';
 
    #access_log  logs/access.log  main;
 
#     # loadbalancing PHP
#     upstream myLoadBalancer {
#         server 127.0.0.1:9001 weight=1 fail_timeout=5;
#         server 127.0.0.1:9002 weight=1 fail_timeout=5;
#         server 127.0.0.1:9003 weight=1 fail_timeout=5;
#         server 127.0.0.1:9004 weight=1 fail_timeout=5;
#         server 127.0.0.1:9005 weight=1 fail_timeout=5;
#         server 127.0.0.1:9006 weight=1 fail_timeout=5;
#         server 127.0.0.1:9007 weight=1 fail_timeout=5;
#         server 127.0.0.1:9008 weight=1 fail_timeout=5;
#         server 127.0.0.1:9009 weight=1 fail_timeout=5;
#         server 127.0.0.1:9010 weight=1 fail_timeout=5;
#         least_conn;
#     }
 
    sendfile        off;
    #tcp_nopush     on;
 
    server_names_hash_bucket_size 128;
 
## Start: Timeouts ##
    client_body_timeout   10;
    client_header_timeout 10;
    keepalive_timeout     30;
    send_timeout          10;
    keepalive_requests    10;
## End: Timeouts ##
 
    #gzip  on;
 
    server {
        listen       80;
        server_name  localhost;
 
 
        location /stat {
            rtmp_stat all;
            rtmp_stat_stylesheet stat.xsl;
        }
        location /stat.xsl {
            root nginx-rtmp-module/;
        }
        location /control {
            rtmp_control all;
        }
 
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
 
        ## Caching Static Files, put before first location
        #location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        #    expires 14d;
        #    add_header Vary Accept-Encoding;
        #}
 
# For Naxsi remove the single # line for learn mode, or the ## lines for full WAF mode
        location / {
            #include    /nginx/conf/mysite.rules; # see also http block naxsi include line
            ##SecRulesEnabled;
         ##DeniedUrl "/RequestDenied";
         ##CheckRule "$SQL >= 8" BLOCK;
         ##CheckRule "$RFI >= 8" BLOCK;
         ##CheckRule "$TRAVERSAL >= 4" BLOCK;
         ##CheckRule "$XSS >= 8" BLOCK;
            root   html;
            index  index.html index.htm;
        }
 
# For Naxsi remove the ## lines for full WAF mode, redirect location block used by naxsi
        ##location /RequestDenied {
        ##    return 412;
        ##}
 
## Lua examples !
#         location /robots.txt {
#           rewrite_by_lua '
#             if ngx.var.http_host ~= "localhost" then
#               return ngx.exec("/robots_disallow.txt");
#             end
#           ';
#         }
 
        #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;
        }
 
        # 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; # single backend process
        #    fastcgi_pass   myLoadBalancer; # or multiple, see example above
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  $document_root$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;
        #}
    }
 
    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;
 
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
 
    # HTTPS server
    #
    #server {
    #    listen       443 ssl spdy;
    #    server_name  localhost;
 
    #    ssl                  on;
    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;
    #    ssl_session_timeout  5m;
    #    ssl_prefer_server_ciphers On;
    #    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    #    ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:ECDH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!eNULL:!MD5:!DSS:!EXP:!ADH:!LOW:!MEDIUM;
 
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
}

这里监听端口未改动,仍然为 80,重点添加了 RTMP 服务器的相关配置,以搭建 RTMP 服务器,rtmp 协议的默认端口号是 1935。具体的配置详解请参考:菜鸟教程 - Nginx 配置详解

5 nginx方式启动服务器

按住 windows 键 +R,输入 cmd,进入 cmd 命令窗口,进入 nginx 目录:cd (你的nginx目录),然后启动 nginx rtmp 服务器:

nginx.exe -c conf\nginx-win.conf

使用其他版本nginx可能会出现以下错误:

nginx: [emerg] unknown directive "rtmp" in E:\technology\nginx-1.17.9/conf\nginx-win.conf:19

这时需要下载源码编译时加入rtmp模块(俺也不会,看人家说的~)
或者更换为带 rtmp 模块的 nginx 版本,如 nginx 1.7.11.3 Gryphon(下载链接在本文开头。)

6 rtmp视频代理转发

nginx启动成功之后就可以使用ffmpeg推流了。加油我们离成功又近了一步。

直接使用 ffmpeg 推流

ffmpeg.exe -re -i (你的视频文件 如 test.mp4)-f flv rtmp://127.0.0.1:1935/(你想加的路径,不加也可)

使用python,可以将接受的视频流处理后转发

#此处换为你自己的地址
rtmp_url = 'rtsp://127.0.0.1:1935/mv'
cap = cv2.VideoCapture((你的摄像头视频流地址))
fps = int(cap.get(cv2.CAP_PROP_FPS))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
command = ['ffmpeg',
               '-y',
               '-f', 'rawvideo',
               '-vcodec', 'rawvideo',
               '-pix_fmt', 'bgr24',
               '-s', "{}x{}".format(width, height),
               '-r', str(fps),
               '-i', '-',
               '-c:v', 'libx264',
               '-pix_fmt', 'yuv420p',
               '-preset', 'ultrafast',
               '-f', 'flv',
               rtmp_url]
p = sp.Popen(command, stdin=sp.PIPE)

while (cap.isOpened()):
    ret, frame = cap.read()
    if not ret:
        print("Opening camera is failed")
        break
    frame = 你的图像处理的函数(frame)
    p.stdin.write(frame.tostring())

7 测试

import cv2
cap = cv2.VideoCapture("rtsp://127.0.0.1:1935/mv")

while (cap.isOpened()):
    ret, frame = cap.read()
    if not ret:
        print("Opening camera is failed")
        break
    cv2.imshow('起个名字',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
            break

cap.release()
cv2.destroyAllWindows()

当然,如果这几行代码你也不愿意写的话~我只能教你一点别的办法了

迅雷影音 推荐
下载地址:算了自己找吧~
食用方法:打开之后在中间的 框框中输入rtsp推流的地址就ok了
在这里插入图片描述
VLC media player
下载地址:https://www.videolan.org/vlc/index.html
运行之后选择媒体----网络串流----网络----填写地址(刚刚rtsp推流的地址)----选择播放
请添加图片描述

在这里插入图片描述

qq影音
使用同迅雷影音

总有一款适合你

ok 大功告成~

你可能感兴趣的:(python小工具)