WebRTC transceiver stats count
by jib1
HTML
<div id="div"></div><br>
<video id="video1" height="120" width="160" autoplay muted></video>
<video id="video2" height="120" width="160" autoplay></video>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
CSS
body { white-space: pre; font-family: monospace; }
JavaScript
const console = { log: msg => div.innerHTML += msg + "<br>" };
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
const pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();
(async (n = 10) => {
console.log(`Creating ${n} transceivers`);
for (let i = 0; i < 10; i++) pc1.addTransceiver("video");
video2.srcObject = (await new Promise(r => pc2.ontrack = r)).streams[0];
const connected = pc => pc.iceConnectionState == "connected";
await Promise.all([pc1, pc2].map(
pc => new Promise(r => pc.oniceconnectionstatechange = () => connected(pc) && r())
));
console.log("wait 5 seconds for rtcp packets...");
await wait(5000);
const statsPair = await Promise.all([pc1, pc2].map(pc => pc.getStats()));
for (const stats of statsPair) {
let transports = 0, codecs = 0;
for (const stat of stats.values()) {
if (stat.type == "transport") transports++;
if (stat.type == "codec") codecs++;
// console.log(JSON.stringify(stat, null, 2));
}
console.log(`${transports} "transport" stats`)
console.log(`${codecs} "codec" stats`)
}
})();
pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate);
pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate);
pc1.onnegotiationneeded = async () => {
try {
await pc1.setLocalDescription();
await pc2.setRemoteDescription(pc1.localDescription);
await pc2.setLocalDescription();
await pc1.setRemoteDescription(pc2.localDescription);
} catch (e) {
console.log(e);
}
}