Peer-to-Peer Video Chat with PeerJS
I was speaking with a potential customer about their project which has a video component to it. Their need was to build out a system for peer-to-peer video, record it, and distribute the video. It’s a pretty tall order that got me thinking about how difficult that would be to build out.
It turns out to be very difficult in a real life scenario so naturally I had to try it out. This is how the network diagram looked once I got it working.
WebRTC is a fascinating technology that will give us access to the mic and camera through the browser. Under the hood it’s also going to give us some really nice video and audio codecs. The browser can use network hole punching to achieve peer-to-peer in the browser.
After reading through a lot of the information about WebRTC and the associated libraries I came to understand that it is quite the undertaking. No wonder the customer could not easily accomplish the goal of integrating their video feature that way.
I used the web server to connect up the peers and save their username.
We’re going to need different rooms for people to talk in.
It worked! Finally, we get in the room and activate our video.
In the demo I had the peers in a room all try to maintain connections to all other peers. That is not the most efficient way to connect the peers because they will each have to send their video to all the other peers rather than to some intermediate server. However, when you’re just messing around it’s great!
If you’re looking for more sophisticated architectures you can look for:
- webrtc sfu
- webrtc mcu
If you get the time it’s pretty neat to learn about and experiment with.
Reference and interesting libraries#
- WebRTC API the raw API documented at Mozilla
- simpleWebRTC The excellent team &yet built a sweet library
- PeerJS Client and server library implementations
- SIP.js A great lbirary for WebRTC
- WebRTC adapter A shim, adapter, for browsers that are behind