WebRTC丢包监控

利用RTCPeerConnection对象的getStats方法拿到WebRTC两端之间的接收发出数据统计报告进行分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

// 上次接收成功的包
let lastPacketsReceived = 0
// 上次接收丢失的包
let lastPacketsLost = 0
// 上次共发出的包(包括成功和失败的)
let lastPacketsSent = 0
// 远端接收丢失的包
let lastRemotePacketsLost = 0

async function getRTCStats() {
try {
// 拿到RTCPeerConnection对象
const pc = cur_call.rtc.peer.peer
// 这次与上次比较之后的数据
let packetsSent = 0
let packetsReceived = 0
let packetsLost = 0
pc.getStats(null).then(stats => {
stats.forEach(report => {
// 接收数据情况
if (report.type === 'inbound-rtp') {
packetsReceived =
report.packetsReceived - lastPacketsReceived
lastPacketsReceived = report.packetsReceived
lastPacketsLost = report.packetsLost
}
// 传出数据情况
if (report.type === 'outbound-rtp') {
packetsSent = report.packetsSent - lastPacketsSent
lastPacketsSent = report.packetsSent
}
// 远端接收情况
if (report.type === 'remote-inbound-rtp') {
//上行丢包,
packetsLost = report.packetsLost - lastRemotePacketsLost
lastRemotePacketsLost = report.packetsLost
}
})
// (共发送的 - 接收成功的 )/ 共发送的 = 接收丢包率
const fractionLost = (packetsSent - packetsReceived) / packetsSent
// 远端接收丢的 / 本地共发送的
const outboundLost = packetsLost / packetsSent
if (fractionLost > 0.3 || outboundLost > 0.3) {
// 丢包
}
})
} catch (e) {
console.log(e)
}
}

setInterval(() => {
getRTCStats()
},5 * 1000)

参考文章1
参考文章2
参考文章3