+ const remoteStream = new MediaStream();
+ peerConnection.ontrack = (event) => {
+ remoteStream.addTrack(event.track);
+ const remoteAudioElement = new Audio();
+ remoteAudioElement.srcObject = remoteStream;
+ remoteAudioElement.play();
+ };
+
+ peerConnection.onnegotiationneeded = async () => {
+ console.debug("Creating RTC offer to ", peerId);
+ const offer = await peerConnection.createOffer();
+ await peerConnection.setLocalDescription(offer);
+
+ onOffer({ peerId, offer });
+ };
+
+ console.info(`There are now ${countPeers()} participants`);
+}
+
+export function removePeer({ peerId }) {
+ delete internals.peers[peerId];
+ console.info(`There are now ${countPeers()} participants`);
+}
+
+export async function answerPeerOffer({ peerId, offer }) {
+ const peerConnection = internals.peers[peerId];
+
+ const remoteDescription = new RTCSessionDescription(offer);
+ await peerConnection.setRemoteDescription(remoteDescription);
+
+ const answer = await peerConnection.createAnswer();
+ await peerConnection.setLocalDescription(answer);
+
+ return { peerId, answer };
+}
+
+export async function processPeerAnswer({ peerId, answer }) {
+ const peerConnection = internals.peers[peerId];
+ const remoteDescription = new RTCSessionDescription(answer);
+ await peerConnection.setRemoteDescription(remoteDescription);
+}
+
+export async function addIceCandidate({ peerId, candidate }) {
+ const peerConnection = internals.peers[peerId];
+ const iceCandidate = new RTCIceCandidate(candidate);
+ await peerConnection.addIceCandidate(iceCandidate);
+}
+
+export function countPeers() {
+ return Object.keys(internals.peers).length;
+}
+
+export function resetPeers() {
+ internals.peers = {};
+ document
+ .querySelectorAll(".junction-call-audio")
+ .forEach((audioElement) => audioElement.remove());
+}