+ internals.socket.on("addPeer", function ({ peerId }) {
+ /**
+ * Eventually the whole rtc connection logic should be moved to Peers.
+ * Now it only plays tadas.
+ */
+ Peers.add(peerId, tada);
+
+ const peerConnection = new RTCPeerConnection(
+ { iceServers: internals.kIceServers },
+ { optional: [{ DtlsSrtpKeyAgreement: true }] },
+ );
+
+ internals.peers[peerId] = peerConnection;
+ mediaStream.getTracks().forEach((track) => {
+ peerConnection.addTrack(track, mediaStream);
+ });
+
+ peerConnection.onicecandidate = (event) => {
+ if (event.candidate) {
+ internals.socket.emit("relayICECandidate", {
+ peerId: peerId,
+ candidate: event.candidate,
+ });
+ }
+ };
+
+ const remoteStream = new MediaStream();
+ peerConnection.ontrack = (event) => {
+ remoteStream.addTrack(event.track);
+ const remoteAudioElement = new Audio();
+ remoteAudioElement.srcObject = remoteStream;
+ remoteAudioElement.play();
+ };
+
+ peerConnection.onnegotiationneeded = async () => {
+ console.log("Creating RTC offer to ", peerId);
+ const offer = await peerConnection.createOffer();
+ await peerConnection.setLocalDescription(offer);
+
+ // Emit the offer to the peer
+ internals.socket.emit("relayOffer", { offer, peerId });
+ };