You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用FFmpeg推流至Nginx RTMP服务器遇Broken pipe错误

RTMP推流偶发Broken pipe崩溃问题排查

我通过Python子进程调用FFmpeg向Nginx搭建的RTMP服务器推流时,本地推流正常,但远程推流偶尔会触发以下错误导致程序崩溃:

av_interleaved_write_frame(): Broken pipe
Error writing trailer of rtmp://.../live: Broken pipe

已确认服务器网络连接正常,当前Nginx RTMP配置如下:

rtmp {
    server {
        listen 1935;
        chunk_size 4096;

        application live {
            live on;
            record off;
        }
    }
}

FFmpeg推流的Python代码如下:

command = ['ffmpeg',
           '-y',
           '-f', 'rawvideo',
           '-vcodec', 'rawvideo',
           '-pix_fmt', 'bgr24',
           '-s', "{}x{}".format(width, height),
           '-re',
           '-r', str(fps),
           '-i', 'pipe:',
           '-c:v', 'libx264',
           '-pix_fmt', 'yuv420p',
           '-preset', 'medium',
           '-vsync','vfr',
           '-f', 'flv',
           '-flvflags', 'no_duration_filesize',
           rtmp_url]

p = subprocess.Popen(command, stdin=subprocess.PIPE)

怀疑问题和RTMP服务器配置有关,寻求排查思路和解决办法。


可能的解决方向

  1. 优化Nginx RTMP超时配置
    默认Nginx RTMP可能会在连接空闲时主动断开,添加超时参数避免误断:
rtmp {
    server {
        listen 1935;
        chunk_size 4096;
        # 新增超时配置,防止空闲连接被强制断开
        ping 30s;
        ping_timeout 2m;
        drop_idle_publisher 5m;

        application live {
            live on;
            record off;
        }
    }
}
  1. FFmpeg侧增加错误处理与重连机制
    Broken pipe通常是连接中断导致,在Python代码中监听子进程状态,捕获异常后自动重启推流:
import subprocess
import time

def start_ffmpeg_push(width, height, fps, rtmp_url):
    command = ['ffmpeg',
               '-y',
               '-f', 'rawvideo',
               '-vcodec', 'rawvideo',
               '-pix_fmt', 'bgr24',
               '-s', "{}x{}".format(width, height),
               '-re',
               '-r', str(fps),
               '-i', 'pipe:',
               '-c:v', 'libx264',
               '-pix_fmt', 'yuv420p',
               '-preset', 'medium',
               '-vsync','vfr',
               '-f', 'flv',
               '-flvflags', 'no_duration_filesize',
               rtmp_url]
    return subprocess.Popen(command, stdin=subprocess.PIPE)

# 主循环:自动检测并重启异常推流进程
p = start_ffmpeg_push(width, height, fps, rtmp_url)
while True:
    if p.poll() is not None:
        print("推流进程异常,重启中...")
        p = start_ffmpeg_push(width, height, fps, rtmp_url)
    time.sleep(1)
    # 此处继续向p.stdin写入视频帧数据
  1. 调整FFmpeg推流参数
  • 增加-max_delay参数,提升网络抖动容忍度:-max_delay 5000000(单位微秒,对应5秒)
  • 添加-flush_packets 1确保数据包及时发送:
    command = ['ffmpeg',
               # ... 原有参数
               '-max_delay', '5000000',
               '-flush_packets', '1',
               rtmp_url]
    
  1. 排查服务器网络稳定性
    尽管已确认连接正常,但间歇性丢包可能导致RTMP会话中断,可通过ping和traceroute工具持续监测服务器网络质量,定位是否存在偶发丢包节点。

内容的提问来源于stack exchange,提问作者Loc Bui Nhien

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 15:17:22