10.3 Simulcast Example

A client wants to send multiple RTP encodings (simulcast) to a server.

Example 11

  1. const signaling = new SignalingChannel(); // handles JSON.stringify/parse
  2. const constraints = {audio: true, video: true};
  3. const configuration = {'iceServers': [{'urls': 'stun:stun.example.org'}]};
  4. let pc;
  5. // call start() to initiate
  6. async function start() {
  7. pc = new RTCPeerConnection(configuration);
  8. // let the "negotiationneeded" event trigger offer generation
  9. pc.onnegotiationneeded = async () => {
  10. try {
  11. await pc.setLocalDescription();
  12. // send the offer to the other peer
  13. signaling.send({description: pc.localDescription});
  14. } catch (err) {
  15. console.error(err);
  16. }
  17. };
  18. try {
  19. // get a local stream, show it in a self-view and add it to be sent
  20. const stream = await navigator.mediaDevices.getUserMedia(constraints);
  21. selfView.srcObject = stream;
  22. pc.addTransceiver(stream.getAudioTracks()[0], {direction: 'sendonly'});
  23. pc.addTransceiver(stream.getVideoTracks()[0], {
  24. direction: 'sendonly',
  25. sendEncodings: [
  26. {rid: 'q', scaleResolutionDownBy: 4.0}
  27. {rid: 'h', scaleResolutionDownBy: 2.0},
  28. {rid: 'f'},
  29. ]
  30. });
  31. } catch (err) {
  32. console.error(err);
  33. }
  34. }
  35. signaling.onmessage = async ({data: {description, candidate}}) => {
  36. try {
  37. if (description) {
  38. await pc.setRemoteDescription(description);
  39. // if we got an offer, we need to reply with an answer
  40. if (description.type == 'offer') {
  41. await pc.setLocalDescription();
  42. signaling.send({description: pc.localDescription});
  43. }
  44. } else if (candidate) {
  45. await pc.addIceCandidate(candidate);
  46. }
  47. } catch (err) {
  48. console.error(err);
  49. }
  50. };