So on the offerer I have this code. It has a function which sends the SDP to the database.
const videoConstraints = {
'video': true,
'audio': false
}
var localStream = new MediaStream();
try {
navigator.mediaDevices.getUserMedia(videoConstraints).then((stream) => {
localStream = stream;
video = document.getElementById("video");
video.srcObject = stream;
})
} catch (error) {
console.log(error);
}
const turnConfig = {
iceServers: [
//servers
]
}
const createOfferer = () => {
var peer = new RTCPeerConnection(turnConfig);
localStream.getTracks().forEach(track => {
peer.addTrack(track, localStream);
});
peer.createOffer()
.then((offer) => {
fetch(window.location.href, {
method: "POST",
body: JSON.stringify(offer),
headers: {
"Content-Type": "application/json"
}
});
})
}
From there, the SDP is taken by the answerer, and then createAnswerer is called:
const setOnTrack = (peer, remoteVideo) => {
var remoteStream = new MediaStream();
remoteVideo.srcObject = remoteStream;
peer.addEventListener('track', async (e) => {
remoteStream.addTrack(e.track, remoteStream);
})
}
const createAnswererForSeat = (offer) => {
var peer = new RTCPeerConnection(turnConfig);
var remoteVideo = createVideoForSeat(); //this function only creates the video element
setOnTrack(peer, remoteVideo);
peer.setRemoteDescription(offer)
.then(() => {
return peer.createAnswer();
})
.then((answer) => {
peer.setLocalDescription(answer);
});
}
For some reason, on Chrome there is no camera on answerer's side, and on Firefox I receive a WebRTC error.
Why is it not working? I am new to WebRTC, so if I'm missing something obvious sorry :)
Thanks.
In offerer you need to set local description after you create offer:
peer.createOffer()
.then((offer) => {
peer.setLocalDescription(offer) // <--- here
fetch(window.location.href, {
method: "POST",
body: JSON.stringify(offer),
headers: {
"Content-Type": "application/json"
}
});
})
In answerer you need to send the answer back to offerer and set it as a remote description there. Should be something like:
const onAnswer = async (answer) => {
await peer.setRemoteDescription(answer)
}
Also, RTCPeerConnection should be stored somewhere outside callbacks, otherwise it will be garbage collected after the function exits.