# python-rtsp-webrtc-server **Repository Path**: lxc1118/python-rtsp-webrtc-server ## Basic Information - **Project Name**: python-rtsp-webrtc-server - **Description**: 一个基于FFmpe + C++ python的RTSP到WebRTC转换服务器,支持实时流媒体传输,适用于视频监控、在线教育等场景。 - **Primary Language**: Python - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-03-09 - **Last Updated**: 2026-03-12 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # RTSP 视频流 WebRTC 视频融合服务插件 基于 FFMPEG C++ RTSP 拼接器和 Python WebRTC 服务器的实时视频流解决方案,支持多路 RTSP 流的硬件解码、智能帧缓存、视频拼接和 WebRTC 推流。 ## 🚀 核心特性 ### 最新更新 - ✅ **独立线程获取图像** - C++ 拼接器在独立线程中运行,不阻塞 Python 主线程 - ✅ **共享图像源架构** - 所有 VideoTrack 复用同一个图像源,减少资源消耗 - ✅ **独立 VideoTrack** - 每个客户端连接使用独立的 VideoTrack 实例 - ✅ **智能帧缓存** - 10 秒超时机制,消除黑白闪烁,使用最后一帧缓存 - ✅ **性能监控** - 实时 FPS、帧延迟、缓冲区状态监控 ## 项目结构 ``` /home/cat/gitee/python-rtsp-webrtc-server/ ├── README.md # 本说明文档 ├── CMakeLists.txt # CMake 构建配置 ├── build.sh # 构建脚本 ├── src/ │ ├── rtsp_stitcher.cpp # C++ RTSP 拼接器核心 │ └── rtsp_stitcher.h # 头文件 ├── webrtc_display_server.py # Python WebRTC 显示服务器(主程序) ├── rtsp_stitcher.so # 编译后的 Python 模块 ├── build/ # 构建输出目录 │ ├── rtsp_stitcher.cpython-39-aarch64-linux-gnu.so │ └── test_stitcher # C++ 测试程序 └── start_optimized_server.sh # 启动脚本 ``` ## 快速开始 ### 1. 构建 C++ 模块 ```bash cd /home/cat/gitee/python-rtsp-webrtc-server ./build.sh Release OFF # OFF 表示不使用 RGA 硬件加速 # 或 ./build.sh Release ON # ON 表示启用 RGA 硬件加速 ``` ### 2. 启动 WebRTC 服务器 ```bash # 使用优化后的启动脚本 ./start_optimized_server.sh # 或直接运行 python3 webrtc_display_server.py ``` ### 3. 访问视频流 - **WebRTC 播放**: `http://localhost:8081` - **统计信息**: `http://localhost:8081/stats` ## 架构设计 ### 系统架构 ``` ┌─────────────────────────────────────────────────────────┐ │ WebRTC 客户端 │ └───────────────────┬─────────────────────────────────────┘ │ WebRTC (RTCDataChannel) ┌───────────────────▼─────────────────────────────────────┐ │ Python WebRTC 服务器 │ │ ┌─────────────────────────────────────────────────┐ │ │ │ WebRTCServer │ │ │ │ - 为每个客户端创建独立 VideoTrack │ │ │ │ - 管理客户端连接 │ │ │ └─────────────────┬───────────────────────────────┘ │ │ │ │ │ ┌─────────────────▼───────────────────────────────┐ │ │ │ SharedImageSource (单例) │ │ │ │ - 独立线程获取 C++ 图像 │ │ │ │ - 共享图像缓冲区 │ │ │ │ - 线程安全访问 │ │ │ └─────────────────┬───────────────────────────────┘ │ └────────────────────│────────────────────────────────────┘ │ Python C API ┌────────────────────▼────────────────────────────────────┐ │ C++ RTSP 拼接器 │ │ ┌─────────────────────────────────────────────────┐ │ │ │ RTSPStitcher │ │ │ │ - 4 路 RTSP 流独立接收线程 │ │ │ │ - 智能帧缓存(10 秒超时) │ │ │ │ - 帧同步与拼接 │ │ │ │ - H.264 硬件编码 │ │ │ └─────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────┘ ``` ### 数据流 ``` RTSP 流 1 ──┐ RTSP 流 2 ──┼──> [帧缓存] ──> [同步] ──> [拼接] ──> [编码] ──> YUV 数据 RTSP 流 3 ──┤ │ RTSP 流 4 ──┘ │ ▼ [Python SharedImageSource] │ ▼ [VideoTrack #1] ──> 客户端 1 [VideoTrack #2] ──> 客户端 2 [VideoTrack #3] ──> 客户端 3 ``` ## 核心组件 ### 1. C++ RTSP 拼接器 (`rtsp_stitcher`) #### 主要特性 - **独立接收线程**: 每个 RTSP 流使用独立线程接收 - **智能帧缓存**: - 最后一帧缓存机制 - 10 秒超时切换黑屏 - 消除黑白闪烁 - **帧同步**: 多路视频流时间戳同步 - **硬件加速**: 支持 Rockchip MPP 编解码和 RGA 缩放 #### 配置参数 ```python config = rtsp_stitcher.StitcherConfig() config.output_width = 1920 # 输出分辨率:1920x1080 config.output_height = 1080 config.output_fps = 25 # 输出帧率 config.output_bitrate = 4000000 # 比特率:4Mbps config.codec = "libx264" # 编码器 config.enable_hardware_accel = False # 硬件加速 ``` #### 流配置 ```python stream = rtsp_stitcher.StreamConfig() stream.name = "left" stream.rtsp_url = "rtsp://192.168.8.101:554/live/left" stream.target_width = 480 stream.target_height = 1080 stream.dst_x = 0 stream.dst_y = 0 config.add_stream(stream) ``` ### 2. Python WebRTC 服务器 #### SharedImageSource(共享图像源) - **单例模式**: 全局唯一实例 - **独立线程**: 后台线程持续获取图像 - **线程安全**: 使用锁保护共享数据 - **性能监控**: 实时 FPS、帧计数统计 ```python # 创建共享图像源(单例) image_source = SharedImageSource(stitcher) # 启动图像获取线程 image_source.start() # 获取统计信息 stats = image_source.get_stats() print(f"FPS: {stats['avg_fps']:.1f}, 总帧数:{stats['total_frames']}") ``` #### WebRTCServer - **独立 VideoTrack**: 每个客户端一个实例 - **连接管理**: 自动清理断开的连接 - **统计接口**: `/stats` 端点提供详细统计 ```python # 创建服务器 server = WebRTCServer(image_source) # 启动服务器 await server.start(host='0.0.0.0', port=8081) ``` #### RTSPVideoTrack - **每连接独立**: 每个客户端独立的 VideoTrack - **共享数据源**: 从 SharedImageSource 获取图像 - **性能监控**: 每帧处理时间统计 ## 视频流布局 ``` ┌─────────────────────────────────────────────────────────┐ │ 1920×1080 输出 │ ├──────────────┬──────────────────────┬───────────────┤ │ │ │ │ │ │ 中上 (960×540) │ │ │ │ │ │ │ 左 (480×1080) ├──────────────────────┤ 右 (480×1080) │ │ │ │ │ │ │ 中下 (960×540) │ │ │ │ │ │ ├──────────────┴──────────────────────┴───────────────┤ │ 480px 960px 480px │ └─────────────────────────────────────────────────────┘ ``` ## API 参考 ### RTSPStitcher (C++) ```python # 创建拼接器 stitcher = rtsp_stitcher.RTSPStitcher(config) # 初始化 if not stitcher.initialize(): raise Exception("初始化失败") # 启动 stitcher.start() # 获取 YUV 帧 yuv_data = stitcher.get_frame_as_yuv() # 停止 stitcher.stop() # 查询信息 width = stitcher.get_output_width() height = stitcher.get_output_height() ``` ### SharedImageSource ```python # 创建(单例) image_source = SharedImageSource(stitcher) # 启动线程 image_source.start() # 获取最新帧 frame = image_source.get_latest_frame() # 获取统计 stats = image_source.get_stats() # 返回:{ # 'running': True, # 'total_frames': 1234, # 'avg_fps': 20.5, # 'resolution': '1920x1080', # 'thread_alive': True # } # 停止 image_source.stop() ``` ### WebRTCServer ```python # 创建服务器 server = WebRTCServer(image_source) # 启动 await server.start(host='0.0.0.0', port=8081) # 停止 await server.stop() # 统计接口 # GET http://localhost:8081/stats # 返回:{ # 'clients': 2, # 'video_tracks': 2, # 'running': True, # 'total_frames': 5000, # 'avg_fps': 22.3, # 'image_source_stats': {...} # } ``` ## 性能监控 ### 日志输出 ``` [图像源] 实时 FPS=22.3, 平均 FPS=20.6, 总帧数=2130, YUV 耗时=1.0ms [VideoTrack #0] Frame #2250: FPS=82.9, 获取=0.8ms, 转换=8.2ms [RTSP Sync] Stream 0 using CACHED frame (age=1500ms) [RTSP Sync] Stream 1 using BLACK frame (TIMEOUT >10s) [Stitcher] FPS: 7 ``` ### 关键指标 1. **图像源 FPS**: 应接近 25 FPS(配置值) 2. **YUV 耗时**: 应 < 40ms(1 帧时间@25fps) 3. **VideoTrack FPS**: 应接近图像源 FPS 4. **Stitcher FPS**: C++ 端实际输出帧率 ### 故障诊断 #### 问题:FPS 过低(< 10) **可能原因**: 1. RTSP 流本身帧率低 2. 网络带宽不足 3. CPU 解码性能瓶颈 **解决方法**: - 检查 RTSP 流原始 FPS - 降低输出分辨率 - 启用硬件解码 #### 问题:黑白闪烁 **已解决**: 使用智能帧缓存机制 - < 10 秒无信号:使用最后一帧 - > 10 秒无信号:显示黑屏 #### 问题:客户端连接失败 **检查项**: 1. 服务器是否启动:`http://localhost:8081/stats` 2. 端口是否开放:`netstat -tlnp | grep 8081` 3. 防火墙设置 ## 依赖项 ### 系统依赖 - FFmpeg (libavcodec, libavformat, libavutil, libswscale) - Rockchip MPP (可选,硬件编解码) - Rockchip RGA (可选,硬件缩放) ### Python 依赖 - Python 3.9+ - aiortc - aiohttp - av (PyAV) - numpy - opencv-python (可选) ## 高级配置 ### 调整帧率 ```python # C++ 端 config.output_fps = 30 # 提高到 30fps # Python 端 self.fps = 30 # SharedImageSource.fps ``` ### 调整超时时间 ```cpp // C++ 代码 static constexpr int64_t BLACK_SCREEN_TIMEOUT_US = 10000000; // 10 秒 // 修改为 5 秒 static constexpr int64_t BLACK_SCREEN_TIMEOUT_US = 5000000; ``` ### 多客户端支持 系统天然支持多客户端: - 每个客户端独立 VideoTrack - 共享同一个图像源 - 不增加 C++ 端负载 ## 开发指南 ### 添加新的 RTSP 流 ```python streams = [ {"name": "new_stream", "url": "rtsp://...", "w": 640, "h": 480, "x": 0, "y": 0}, ] ``` ### 自定义布局 修改 `create_rtsp_stitcher()` 中的流配置: - `dst_x`, `dst_y`: 控制位置 - `target_width`, `target_height`: 控制大小 ### 集成到现有系统 ```python from webrtc_display_server import SharedImageSource, WebRTCServer # 创建图像源 image_source = SharedImageSource(your_stitcher) image_source.start() # 创建服务器 server = WebRTCServer(image_source) await server.start(port=8081) ``` ## 参考资料 - [FFmpeg 文档](https://ffmpeg.org/documentation.html) - [Rockchip MPP](https://github.com/rockchip-linux/rk_mpp) - [aiortc](https://aiortc.readthedocs.io/) - [WebRTC 规范](https://webrtc.org/) ## 许可证 MIT License ## 更新日志 ### v2.0 (最新) - ✅ 添加独立线程获取 C++ 图像 - ✅ 实现共享图像源架构 - ✅ 每个客户端独立 VideoTrack - ✅ 智能帧缓存(10 秒超时) - ✅ 消除黑白闪烁 - ✅ 增强性能监控 - ✅ 优化退出机制 ### v1.0 - 初始版本 - 基础 RTSP 拼接功能 - WebRTC 推流支持