1.問題背景
在最近的項目中,涉及到海康接入的視頻播放的問題,海康這邊獲取到的視頻流是rtsp格式,web端目前沒有直接可以播放的組件,於是最開始是后端處理了視頻流,返回hls格式的m3u8地址,這樣用videojs插件就可以播放了,但是問題就是處理了的m3u8地址播放效果非常差,第一次加載時間較長,且播放過程中很卡,尤其是項目的界面做的是視頻監控牆,不止一個視頻,導致沒辦法看了。想着最好的方式還是直接播放rtsp地址,不經過轉碼。於是問題回到了如何播放rtsp.
2.方案的篩選
播放rtsp格式的視頻流,網上有很多方式,除了上述的轉m3u8,還有轉rtmp的,或者使用WebRTC、streamedian、h5stream等,其中webRTC我不太了解,看了一下文檔,也比較復雜,就放棄了。然后是streamedian、h5stream這兩個,前者是需要收費,另一個我看了文檔,沒有可以動態設置rtsp地址的地方,只有在配置文件里寫好,這樣不符合項目的要求,也放棄了,就在糾結到底該怎么辦的時候,同事大佬提出了一個建議,看看人家bilibili也有直播,人家是怎么做的呢,於是順手搜了一下B站直播原理,看到了一篇博文是說bilibili開發的flv.js,講述了里面的用法,我看了看,確實算是一個比較可行的方法了,於是開干起來。
3.實際運用
首先了解這個方案的大致流程:1.需要一個node服務器處理rtsp流,轉為flv流,2.前端安裝flv.js顯示flv視頻流。其中第一步搭建的服務器實際上是搭建了一個websokect服務器,前端通過flv里提供的方法,通過websokect連接到node服務器,這樣flv流就源源不斷的送到了前端,雖然這里也對rtsp進行了處理,但是效果卻出奇的好,比m3u8格式的效果好太多,基本上3、4s就加載出來了,如果同時加載的視頻很多,那么差不多也在5-8s內加載出來了,最多的一次12個視頻,最后一個加載出來用了12s左右。總得來說比之前m3u8單個都要加載10s左右,視頻多了甚至加載不出來好太多了。
好了,介紹的話太多了,還是回到如何搭建吧。node搭建的服務器需要配合ffmpeg。所以首先安裝ffmpeg,這個我在Windows上測試的,直接下載了一個壓縮包,解壓就好,然后是搭建node服務器,將以下package.json直接復制到文件里,然后npm install就可以得到一個服務器環境(前提是已經安裝了node哦)。
1 { 2 "name": "ffmpeg-server", 3 "version": "1.0.0", 4 "description": "", 5 "main": "index.js", 6 "scripts": { 7 "test": "echo \"Error: no test specified\" && exit 1" 8 }, 9 "author": "", 10 "license": "ISC", 11 "devDependencies": { 12 "express": "^4.17.1", 13 "express-ws": "^4.0.0", 14 "ffmpeg": "0.0.4", 15 "fluent-ffmpeg": "^2.1.2", 16 "http": "0.0.0", 17 "websocket-stream": "^5.5.0" 18 } 19 }
接下來是index.js
1 var express = require("express"); 2 var expressWebSocket = require("express-ws"); 3 var ffmpeg = require("fluent-ffmpeg"); 4 ffmpeg.setFfmpegPath("G:/ffmpeg/ffmpeg/ffmpeg-4.3.1-win64-static/bin/ffmpeg"); 5 var webSocketStream = require("websocket-stream/stream"); 6 var WebSocket = require("websocket-stream"); 7 var http = require("http"); 8 function localServer() { 9 let app = express(); 10 app.use(express.static(__dirname)); 11 expressWebSocket(app, null, { 12 perMessageDeflate: true 13 }); 14 app.ws("/rtsp/:id/", rtspRequestHandle) 15 app.listen(8888); 16 console.log("express listened") 17 } 18 function rtspRequestHandle(ws, req) { 19 console.log("rtsp request handle"); 20 const stream = webSocketStream(ws, { 21 binary: true, 22 browserBufferTimeout: 1000000 23 }, { 24 browserBufferTimeout: 1000000 25 }); 26 let url = req.query.url; 27 // console.log("rtsp url:", url); 28 // console.log("rtsp params:", req.params); 29 try { 30 ffmpeg(url) 31 .addInputOption("-rtsp_transport", "tcp", "-buffer_size", "102400") // 這里可以添加一些 RTSP 優化的參數 32 .on("start", function () { 33 console.log(url, "Stream started."); 34 }) 35 .on("codecData", function () { 36 console.log(url, "Stream codecData.") 37 // 攝像機在線處理 38 }) 39 .on("error", function (err) { 40 console.log(url, "An error occured: ", err.message); 41 }) 42 .on("end", function () { 43 console.log(url, "Stream end!"); 44 // 攝像機斷線的處理 45 }) 46 .outputFormat("flv").videoCodec("copy").noAudio().pipe(stream); 47 } catch (error) { 48 console.log(error); 49 } 50 } 51 localServer();
文件目錄如下:

然后在backendNode這個文件下執行: node index.js就完成了服務器的搭建。
接下來是前端文件的寫法:
前端也要先安裝flv.js npm install flv.js -S -D
然后就是建一個文件顯示視頻:<template>
<div class="video-box" v-loading="loading">
<video class="demo-video" ref="player" muted @dblclick="fullScreen"></video> </div> </template> <script> import flvjs from 'flv.js' export default { props: { rtsp: { type: String, default: '' }, id: { type: [String, Number], default: '' } }, data () { return { // id: '1', player: null, loading: true } }, watch: { rtsp: { handler: function (val) { if (val) { if (this.player) { this.player.unload() this.player.destroy() this.player = null this.loading = true } this.$nextTick(() => { this.playVideo() }) } }, immediate: true } }, methods: { fullScreen () { if (this.$refs.player.requestFullScreen) { this.$refs.player.requestFullScreen() } else if (this.$refs.player.mozRequestFullScreen) { this.$refs.player.mozRequestFullScreen() } else if (this.$refs.player.webkitRequestFullScreen) { this.$refs.player.webkitRequestFullScreen() } }, playVideo () { const time1 = new Date().getTime() if (flvjs.isSupported()) { let video = this.$refs.player if (video) { this.player = flvjs.createPlayer({ type: 'flv', isLive: true, url: `ws://localhost:8888/rtsp/${this.id}/?url=${this.rtsp}`
}) this.player.attachMediaElement(video) try { this.player.load() this.player.play().then(() => { console.log(new Date().getTime() - time1) this.loading = false }) } catch (error) { console.log(error) } } } } }, beforeDestroy () { if (this.player) { this.player.unload() this.player.destroy() this.player = null } } } </script> <style lang="scss"> .video-box { width: 100%; height: 100%; video { width: 100%; height: 100%; object-fit: fill; } //播放按鈕 video::-webkit-media-controls-play-button { display: none; } video::-webkit-media-controls-current-time-display { display: none; } video::-webkit-media-controls-timeline { display: none; } } </style>
因為我是寫成的一個組件,所以我的rtsp地址是傳進來的。
這樣就可以播放rtsp了,效果真的不錯。
4,其他問題
出了上述的流程,還有其他的問題,比如這個是在本地搭建的,不存在代理的問題,如果要發布到線上環境,則node服務器肯定也是要搭建到線上的服務器的(線上搭建和之前的方式差不多,就是看服務器是Linux還是Windows了,兩者區別在於ffmpeg的安裝,其他index.js是一樣的),就會涉及到代理websokect的問題。因為之前沒有代理過,所以也有些坑。
1.首先是本地代理
用vue+axios,通常代理http的都是直接在配置文件里寫的,代理websokect的需要在此基礎上加上ws:true字段,如下:
'/streamWs/**':{ // target: 'ws:xxx', secure: false, changeOrigin: false, pathRewrite: { '^/streamWs': '' }, ws: true //開啟ws, 如果是http代理此處可以不用設置 }
這個地方都不難,主要還是在調用代理的地方,需要這樣寫:
this.player = flvjs.createPlayer({ type: 'flv', isLive: true, // url: `ws://localhost:8888/rtsp/${this.id}/?url=${this.rtsp}`
// 代理ws需要寫上ws://${location.host},然后再是代理前綴/streamWs
url: `ws://${location.host}/streamWs/rtsp/${this.id}/?url=${this.rtsp}` })
通過這樣設置,就可以成功代理了。
2.然后是線上的代理
線上我用的是nginx代理,重點在於兩個地方:
第一個地方是http下面加的東西:
map $http_upgrade $connection_upgrade { default upgrade; '' close; }
第二個是在前端頁面的端口下server下加的代理
location /streamWs/ {
# http地址是node服務器的地址 proxy_pass http:xxx; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #重點是下面這三條,寫上了才是代理ws proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; }
好了,經過這一系列的配置,就可以在線上環境看到了。
------------------------------------------------------------------分割線,我又來了,還是視頻的問題,這次優化了,提出了新的方案----------------------------------------------------------------------------------------------------------------------
原因在於,用戶方一直抱怨視頻不能播放h265格式的視頻,然后又說延時高,rtsp都被嫌棄延時高了,真的是沒辦法了,一直拖着沒去解決,正好公司有個后端大佬有空,就一起解決這個問題。前端要改的地方不多,就是將url從ws變為了http://xxxxx.flv格式的,其他的處理都在后端了,包括搭建了一個流服務器,將h265格式的視頻轉碼為h264(再也不用麻煩甲方去改視頻流格式了),然后推送給前端,使用的還是flv.js。值得一提的是,將rtsp換成了http-flv之后,加載視頻的速度簡直飛起了,基本上秒開了。之前我打印過時間戳,差不多網速好的時候,播放rtsp的視頻,也要花費1000ms以上,這個直接就是250ms左右,看着真的是賞心悅目呀!