公司以前项目播放监控视频使用的是浏览器安装插件的方式,只能ie浏览器使用,谷歌和其他高级浏览器已经不支持,客户使用不方便,于是有了这个rstp流转h5播放器可以使用流的技术探索。
解决方案:node + ffmpeg + websocket + flv.js
0.在node服务中建立websocket
1.通过fluent-ffmpeg转码,将RTSP 流转为flv格式
2.前端通过flv.js连接websocket,并对获取的flv格式视频数据进行渲染播放
node服务相关依赖
0.ws
1.websocket-stream
2.fluent-ffmpeg
3.@ffmpeg-installer/ffmpeg
前端相关
0.flv.js (bilibili开源播放器库)
### *注意事项*
0.node转流服务部署服务器需要安装ffmpeg软件用来将rstp转为flv流
1.demo只是基本实现功能,运用到生产环境时,可进一步完善代码细节,增加代码健壮性
2.如果需要同时打开多个监控或直播画面,前端多实例化几个flvjs,挂载到video元素上即可
// node服务相关代码
import { WebSocketServer } from "ws";
import websocketStream from "websocket-stream/stream.js";
import ffmpeg from "fluent-ffmpeg";
import {path as ffmpegPath} from '@ffmpeg-installer/ffmpeg'
ffmpeg.setFfmpegPath(ffmpegPath);
//建立ws服务
const ws = new WebSocketServer({port: 8888, perMessageDeflate: false})
// 监听连接
ws.on("connection", handleConnection)
// 连接回调
function handleConnection (ws, req) {
console.log("connection.....")
// 获取前端请求的流地址(前端websocket连接时后面带上流地址)
const url = req.url.slice(1)
// 传入连接的ws客户端 实例化一个流
const stream = websocketStream(ws, { binary: true})
// 通过ffmpeg命令 对实时流进行格式转换 输出flv格式
const ffmpegCommand = ffmpeg(url)
.addInputOption("-analyzeduration", '100000', '-max_delay', '1000000')
.on("start", function () { console.log("Stream started.")})
.on("codecData", () => { console.log("Stream codeData.")})
.on("error", err => {
console.log("An error occured", err.message)
stream.end()
})
.on("end",() =>{
console.log("Stream end.")
stream.end()
})
.outputFormat("flv")
.videoCodec("copy")
.noAudio()
stream.on("close", () => {
ffmpegCommand.kill("SIGKILL")
})
try {
// 执行命令 传输到实例流中返回给客户端
ffmpegCommand.pipe(stream)
} catch (error) {
console.log(error)
}
}