Real time communication with WebRTC

1. Introduction

WebRTC is an open source project to enable realtime communication of audio, video and data in Web and native apps.

WebRTC has several JavaScript APIs — click the links to see demos.

Where can I use WebRTC?

In Firefox, Opera and in Chrome on desktop and Android. WebRTC is also available for native apps on iOS and Android.

What is signaling?

WebRTC uses RTCPeerConnection to communicate streaming data between browsers, but also needs a mechanism to coordinate communication and to send control messages, a process known as signaling. Signaling methods and protocols are not specified by WebRTC. In this codelab you will use Socket.IO for messaging, but there are many alternatives.

What are STUN and TURN?

WebRTC is designed to work peer-to-peer, so users can connect by the most direct route possible. However, WebRTC is built to cope with real-world networking: client applications need to traverse NAT gateways and firewalls, and peer to peer networking needs fallbacks in case direct connection fails. As part of this process, the WebRTC APIs use STUN servers to get the IP address of your computer, and TURN servers to function as relay servers in case peer-to-peer communication fails. (WebRTC in the real world explains in more detail.)

Is WebRTC secure?

Encryption is mandatory for all WebRTC components, and its JavaScript APIs can only be used from secure origins (HTTPS or localhost). Signaling mechanisms aren't defined by WebRTC standards, so it's up to you make sure to use secure protocols.

2. Overview

Build an app to get video and take snapshots with your webcam and share them peer-to-peer via WebRTC. Along the way you'll learn how to use the core WebRTC APIs and set up a messaging server using Node.js.

What you'll learn

  • Get video from your webcam
  • Stream video with RTCPeerConnection
  • Stream data with RTCDataChannel
  • Set up a signaling service to exchange messages
  • Combine peer connection and signaling
  • Take a photo and share it via a data channel

What you'll need

  • Chrome 47 or above
  • Web Server for Chrome, or use your own web server of choice.
  • The sample code
  • A text editor
  • Basic knowledge of HTML, CSS and JavaScript

3. Get the sample code

Download the code

If you're familiar with git, you can download the code for this codelab from GitHub by cloning it:

git clone https://github.com/googlecodelabs/webrtc-web

Alternatively, click the following button to download a .zip file of the code:

Open the downloaded zip file. This will unpack a project folder (adaptive-web-media) that contains one folder for each step of this codelab, along with all of the resources you will need.

You'll be doing all your coding work in the directory named work.

The step-nn folders contain a finished version for each step of this codelab. They are there for reference.

Install and verify web server

While you're free to use your own web server, this codelab is designed to work well with the Chrome Web Server. If you don't have that app installed yet, you can install it from the Chrome Web Store.

6ddeb4aee53c0f0e.png

After installing the Web Server for Chrome app, click on the Chrome Apps shortcut from the bookmarks bar, a New Tab page, or from the App Launcher:

1d2b4aa977ab7e24.png

Click on the Web Server icon:

27fce4494f641883.png

Next, you'll see this dialog, which allows you to configure your local web server:

Screen Shot 2016-02-18 at 11.48.14 AM.png

Click the CHOOSE FOLDER button, and select the work folder you just created. This will enable you to view your work in progress in Chrome via the URL highlighted in the Web Server dialog in the Web Server URL(s) section.

Under Options, check the box next to Automatically show index.html as shown below:

Screen Shot 2016-02-18 at 11.56.30 AM.png

Then stop and restart the server by sliding the toggle labeled Web Server: STARTED to the left and then back to the right.

Screen Shot 2016-02-18 at 12.22.18 PM.png

Now visit your work site in your web browser by clicking on the highlighted Web Server URL. You should see a page that looks like this, which corresponds to work/index.html:

18a705cb6ccc5181.png

Obviously, this app is not yet doing anything interesting — so far, it's just a minimal skeleton we're using to make sure your web server is working properly. You'll add functionality and layout features in subsequent steps.

4. Stream video from your webcam

What you'll learn

In this step you'll find out how to:

  • Get a video stream from your webcam.
  • Manipulate stream playback.
  • Use CSS and SVG to manipulate video.

A complete version of this step is in the step-01 folder.

A dash of HTML...

Add a video element and a script element to index.html in your work directory:

<!DOCTYPE html>
<html>

<head>

  <title>Realtime communication with WebRTC</title>

  <link rel="stylesheet" href="css/main.css" />

</head>

<body>

  <h1>Realtime communication with WebRTC</h1>

  <video autoplay playsinline></video>

  <script src="js/main.js"></script>

</body>

</html>

...and a pinch of JavaScript

Add the following to main.js in your js folder:

'use strict';

// On this codelab, you will be streaming only video (video: true).
const mediaStreamConstraints = {
  video: true,
};

// Video element where stream will be placed.
const localVideo = document.querySelector('video');

// Local stream that will be reproduced on the video.
let localStream;

// Handles success by adding the MediaStream to the video element.
function gotLocalMediaStream(mediaStream) {
  localStream = mediaStream;
  localVideo.srcObject = mediaStream;
}

// Handles error by logging a message to the console with the error message.
function handleLocalMediaStreamError(error) {
  console.log('navigator.getUserMedia error: ', error);
}

// Initializes media stream.
navigator.mediaDevices.getUserMedia(mediaStreamConstraints)
  .then(gotLocalMediaStream).catch(handleLocalMediaStreamError);

Try it out

Open index.html in your browser and you should see something like this (featuring the view from your webcam, of course!):

9297048e43ed0f3d.png

How it works

Following the getUserMedia() call, the browser requests permission from the user to access their camera (if this is the first time camera access has been requested for the current origin). If successful, a MediaStream is returned, which can be used by a media element via the srcObject attribute:

navigator.mediaDevices.getUserMedia(mediaStreamConstraints)
  .then(gotLocalMediaStream).catch(handleLocalMediaStreamError);


}
function gotLocalMediaStream(mediaStream) {
  localVideo.srcObject = mediaStream;
}

The constraints argument allows you to specify what media to get. In this example, video only, since audio is disabled by default:

const mediaStreamConstraints = {
  video: true,
};

You can use constraints for additional requirements such as video resolution:

const hdConstraints = {
  video: {
    width: {
      min: 1280
    },
    height: {
      min: 720
    }
  }
}

The MediaTrackConstraints specification lists all potential constraint types, though not all options are supported by all browsers. If the resolution requested isn't supported by the currently selected camera, getUserMedia() will be rejected with an OverconstrainedError and the user will not be prompted to give permission to access their camera.

If getUserMedia() is successful, the video stream from the webcam is set as the source of the video element:

function gotLocalMediaStream(mediaStream) {
  localVideo.srcObject = mediaStream;
}

Bonus points

  • The localStream object passed to getUserMedia() is in global scope, so you can inspect it from the browser console: open the console, type stream and press Return. (To view the console in Chrome, press Ctrl-Shift-J, or Command-Option-J if you're on a Mac.)
  • What does localStream.getVideoTracks() return?
  • Try calling localStream.getVideoTracks()[0].stop().
  • Look at the constraints object: what happens when you change it to {audio: true, video: true}?
  • What size is the video element? How can you get the video's natural size from JavaScript, as opposed to display size? Use the Chrome Dev Tools to check.
  • Try adding CSS filters to the video element. For example:
video {
  filter: blur(4px) invert(1) opacity(0.5);
}
  • Try adding SVG filters. For example:
video {
   filter: hue-rotate(180deg) saturate(200%);
 }

What you learned

In this step you learned how to:

  • Get video from your webcam.
  • Set media constraints.
  • Mess with the video element.

A complete version of this step is in the step-01 folder.

Tips

  • Don't forget the autoplay attribute on the video element. Without that, you'll only see a single frame!
  • There are lots more options for getUserMedia() constraints. Take a look at the demo at webrtc.github.io/samples/src/content/peerconnection/constraints. As you'll see, there are lots of interesting WebRTC samples on that site.

Best practice

  • Make sure your video element doesn't overflow its container. We've added width and max-width to set a preferred size and a maximum size for the video. The browser will calculate the height automatically:
video {
  max-width: 100%;
  width: 320px;
}

Next up

You've got video, but how do you stream it? Find out in the next step!

5. Stream video with RTCPeerConnection

What you'll learn

In this step you'll find out how to:

  • Abstract away browser differences with the WebRTC shim, adapter.js.
  • Use the RTCPeerConnection API to stream video.
  • Control media capture and streaming.

A complete version of this step is in the step-2 folder.

What is RTCPeerConnection?

RTCPeerConnection is an API for making WebRTC calls to stream video and audio, and exchange data.

This example sets up a connection between two RTCPeerConnection objects (known as peers) on the same page.

Not much practical use, but good for understanding how RTCPeerConnection works.

Add video elements and control buttons

In index.html replace the single video element with two video elements and three buttons:

<video id="localVideo" autoplay playsinline></video>
<video id="remoteVideo" autoplay playsinline></video>


<div>
  <button id="startButton">Start</button>
  <button id="callButton">Call</button>
  <button id="hangupButton">Hang Up</button>
</div>

One video element will display the stream from getUserMedia()and the other will show the same video streamed via RTCPeerconnection. (In a real world application, one video element would display the local stream and the other the remote stream.)

Add the adapter.js shim

Add a link to the current version of adapter.js above the link to main.js:

<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>

Index.html should now look like this:

<!DOCTYPE html>
<html>

<head>
  <title>Realtime communication with WebRTC</title>
  <link rel="stylesheet" href="css/main.css" />
</head>

<body>
  <h1>Realtime communication with WebRTC</h1>

  <video id="localVideo" autoplay playsinline></video>
  <video id="remoteVideo" autoplay playsinline></video>

  <div>
    <button id="startButton">Start</button>
    <button id="callButton">Call</button>
    <button id="hangupButton">Hang Up</button>
  </div>

  <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
  <script src="js/main.js"></script>
</body>
</html>

Install the RTCPeerConnection code

Replace main.js with the version in the step-02 folder.

Make the call

Open index.html, click the Start button to get video from your webcam, and click Call to make the peer connection. You should see the same video (from your webcam) in both video elements. View the browser console to see WebRTC logging.

How it works

This step does a lot...

WebRTC uses the RTCPeerConnection API to set up a connection to stream video between WebRTC clients, known as peers.

In this example, the two RTCPeerConnection objects are on the same page: pc1 and pc2. Not much practical use, but good for demonstrating how the APIs work.

Setting up a call between WebRTC peers involves three tasks:

  • Create a RTCPeerConnection for each end of the call and, at each end, add the local stream from getUserMedia().
  • Get and share network information: potential connection endpoints are known as ICE candidates.
  • Get and share local and remote descriptions: metadata about local media in SDP format.

Imagine that Alice and Bob want to use RTCPeerConnection to set up a video chat.

First up, Alice and Bob exchange network information. The expression ‘finding candidates' refers to the process of finding network interfaces and ports using the ICE framework.

  1. Alice creates an RTCPeerConnection object with an onicecandidate (addEventListener('icecandidate')) handler. This corresponds to the following code from main.js:
let localPeerConnection;
localPeerConnection = new RTCPeerConnection(servers);
localPeerConnection.addEventListener('icecandidate', handleConnection);
localPeerConnection.addEventListener(
    'iceconnectionstatechange', handleConnectionChange);
  1. Alice calls getUserMedia() and adds the stream passed to that:
navigator.mediaDevices.getUserMedia(mediaStreamConstraints).
  then(gotLocalMediaStream).
  catch(handleLocalMediaStreamError);
function gotLocalMediaStream(mediaStream) {
  localVideo.srcObject = mediaStream;
  localStream = mediaStream;
  trace('Received local stream.');
  callButton.disabled = false;  // Enable call button.
}
localPeerConnection.addStream(localStream);
trace('Added local stream to localPeerConnection.');
  1. The onicecandidate handler from step 1. is called when network candidates become available.
  2. Alice sends serialized candidate data to Bob. In a real application, this process (known as signaling) takes place via a messaging service – you'll learn how to do that in a later step. Of course, in this step, the two RTCPeerConnection objects are on the same page and can communicate directly with no need for external messaging.
  3. When Bob gets a candidate message from Alice, he calls addIceCandidate(), to add the candidate to the remote peer description:
function handleConnection(event) {
  const peerConnection = event.target;
  const iceCandidate = event.candidate;

  if (iceCandidate) {
    const newIceCandidate = new RTCIceCandidate(iceCandidate);
    const otherPeer = getOtherPeer(peerConnection);

    otherPeer.addIceCandidate(newIceCandidate)
      .then(() => {
        handleConnectionSuccess(peerConnection);
      }).catch((error) => {
        handleConnectionFailure(peerConnection, error);
      });

    trace(`${getPeerName(peerConnection)} ICE candidate:\n` +
          `${event.candidate.candidate}.`);
  }
}

WebRTC peers also need to find out and exchange local and remote audio and video media information, such as resolution and codec capabilities. Signaling to exchange media configuration information proceeds by exchanging blobs of metadata, known as an offer and an answer, using the Session Description Protocol format, known as SDP:

  1. Alice runs the RTCPeerConnection createOffer() method. The promise returned provides an RTCSessionDescription: Alice's local session description:
trace('localPeerConnection createOffer start.');
localPeerConnection.createOffer(offerOptions)
  .then(createdOffer).catch(setSessionDescriptionError);
  1. If successful, Alice sets the local description using setLocalDescription() and then sends this session description to Bob via their signaling channel.
  2. Bob sets the description Alice sent him as the remote description using setRemoteDescription().
  3. Bob runs the RTCPeerConnection createAnswer() method, passing it the remote description he got from Alice, so a local session can be generated that is compatible with hers. The createAnswer() promise passes on an RTCSessionDescription: Bob sets that as the local description and sends it to Alice.
  4. When Alice gets Bob's session description, she sets that as the remote description with setRemoteDescription().
// Logs offer creation and sets peer connection session descriptions.
function createdOffer(description) {
  trace(`Offer from localPeerConnection:\n${description.sdp}`);

  trace('localPeerConnection setLocalDescription start.');
  localPeerConnection.setLocalDescription(description)
    .then(() => {
      setLocalDescriptionSuccess(localPeerConnection);
    }).catch(setSessionDescriptionError);

  trace('remotePeerConnection setRemoteDescription start.');
  remotePeerConnection.setRemoteDescription(description)
    .then(() => {
      setRemoteDescriptionSuccess(remotePeerConnection);
    }).catch(setSessionDescriptionError);

  trace('remotePeerConnection createAnswer start.');
  remotePeerConnection.createAnswer()
    .then(createdAnswer)
    .catch(setSessionDescriptionError);
}

// Logs answer to offer creation and sets peer connection session descriptions.
function createdAnswer(description) {
  trace(`Answer from remotePeerConnection:\n${description.sdp}.`);

  trace('remotePeerConnection setLocalDescription start.');
  remotePeerConnection.setLocalDescription(description)
    .then(() => {
      setLocalDescriptionSuccess(remotePeerConnection);
    }).catch(setSessionDescriptionError);

  trace('localPeerConnection setRemoteDescription start.');
  localPeerConnection.setRemoteDescription(description)
    .then(() => {
      setRemoteDescriptionSuccess(localPeerConnection);
    }).catch(setSessionDescriptionError);
}
  1. Ping!

Bonus points

  1. Take a look at chrome://webrtc-internals. This provides WebRTC stats and debugging data. (A full list of Chrome URLs is at chrome://about.)
  2. Style the page with CSS:
  • Put the videos side by side.
  • Make the buttons the same width, with bigger text.
  • Make sure the layout works on mobile.