Peer to Peer Communications in a Browser: Part 1 - Basics

I have a lot experience with WebRTC and successfully done a few project using this technology. Basically it’s not a problem to share sound, video (webcam or screensharing) but you will encounter a number of problems with different API implementations in different browsers and even different versions of one browser.

Firstly I should provide you a bit basic information and explain few architecture points. Bellow you can see a simple schema of WebRTC implementation:

 

p2p

Now I will try to simplify these logic to 5 steps explained how to setup direct connection between two remote users. Pay attention to this flow:

  1. User logged into your web application (Also you can create a sharing between anonymous users, of course).
  2. Prepare an unique tokens for every user that should be connected to conversation.
  3. Initialize websocket connection between every user and server
  4. Broadcast pull of addresses between users. Send unique addresses for each user.
  5. Enable interaction with GetUserMedia API (I will explain it later).
  6. Initialize WebRTC application on each client.
  7. Initialize connection over UDP protocol.
    It’s simple and sounds great, but unfortunatelly browsers doesn’t support this API… Officially doesn’t support. In 16-17 versions of chrome it was possible to initialize getUserMedia API without any additional overhead. Now half of these API features is disabled by default from security point of view. You will not able to share a screen without additional browser setup in any contemporary browser. Also, you will able to share video from webcam and sound without any environment preparations.

GetUserMedia API

navigator.mediaDevices.getUserMedia(constraints).then(function(mediaStream) { ... })

You can find detailed specification on Official MDN and I won’t repeat documentation. Also I want to say few words about this technology.

This API based on ES6 promises and returns an mediaStream object. And you can easily extend it now, because stable ES6 promises is already implemented in firefox and chrome.

Api provides possibility to set media parameters like:

  • Fixed video resolution
  • Minimal video resolution
  • Recommended video resolution
  • Framerate
  • Select video device
    It sounds like joke, but you can’t change any sounds settings using GetUserMedia API. And audio device too.

In the next part of these cycle of posts I will explain how to share video between users on example.