10.2 Advanced Peer-to-peer Example with Warm-up
When two peers decide they are going to set up a connection to each other and want to have the ICE, DTLS, and media connections “warmed up” such that they are ready to send and receive media immediately, they both go through these steps.
const signaling = new SignalingChannel(); // handles JSON.stringify/parse
const constraints = {audio: true, video: true};
const configuration = {iceServers: [{urls: 'stun:stun.example.org'}]};
let pc;
let audio;
let video;
let started = false;
// Call warmup() before media is ready, to warm-up ICE, DTLS, and media.
async function warmup(isAnswerer) {
pc = new RTCPeerConnection(configuration);
if (!isAnswerer) {
audio = pc.addTransceiver('audio');
video = pc.addTransceiver('video');
}
// send any ice candidates to the other peer
pc.onicecandidate = ({candidate}) => signaling.send({candidate});
// let the "negotiationneeded" event trigger offer generation
pc.onnegotiationneeded = async () => {
try {
await pc.setLocalDescription();
// send the offer to the other peer
signaling.send({description: pc.localDescription});
} catch (err) {
console.error(err);
}
};
pc.ontrack = async ({track, transceiver}) => {
try {
// once media for the remote track arrives, show it in the video element
event.track.onunmute = () => {
// don't set srcObject again if it is already set.
if (!remoteView.srcObject) {
remoteView.srcObject = new MediaStream();
}
remoteView.srcObject.addTrack(track);
}
if (isAnswerer) {
if (track.kind == 'audio') {
audio = transceiver;
} else if (track.kind == 'video') {
video = transceiver;
}
if (started) await addCameraMicWarmedUp();
}
} catch (err) {
console.error(err);
}
};
try {
// get a local stream, show it in a self-view and add it to be sent
selfView.srcObject = await navigator.mediaDevices.getUserMedia(constraints);
if (started) await addCameraMicWarmedUp();
} catch (err) {
console.error(err);
}
}
// call start() after warmup() to begin transmitting media from both ends
function start() {
signaling.send({start: true});
signaling.onmessage({data: {start: true}});
}
// add camera and microphone to already warmed-up connection
async function addCameraMicWarmedUp() {
const stream = selfView.srcObject;
if (audio && video && stream) {
await Promise.all([
audio.sender.replaceTrack(stream.getAudioTracks()[0]),
video.sender.replaceTrack(stream.getVideoTracks()[0]),
]);
}
}
signaling.onmessage = async ({data: {start, description, candidate}}) => {
if (!pc) warmup(true);
try {
if (start) {
started = true;
await addCameraMicWarmedUp();
} else if (description) {
await pc.setRemoteDescription(description);
// if we got an offer, we need to reply with an answer
if (description.type == 'offer') {
await pc.setLocalDescription();
signaling.send({description: pc.localDescription});
}
} else {
await pc.addIceCandidate(candidate);
}
} catch (err) {
console.error(err);
}
};