Coder Social home page Coder Social logo

Comments (4)

JaviLopezG avatar JaviLopezG commented on July 28, 2024

You can see the branch 'solution', is not related to what you see on webrtc.org but it's something. You can assume that:

localName = 'callerCandidates';
remoteName = 'calleeCandidates';

from firebasertc.

pksof avatar pksof commented on July 28, 2024

thank you for your help sir @JaviLopezG one more question I successfully create the peer connection but it works only when the caller and the callee are using same router connection but when they are in different network it's not working why ?

from firebasertc.

pksof avatar pksof commented on July 28, 2024

here is my app.js file

mdc.ripple.MDCRipple.attachTo(document.querySelector('.mdc-button'));

const configuration = {
iceServers: [
{
urls: [
'stun:stun1.l.google.com:19302',
'stun:stun2.l.google.com:19302',
],
},
],
iceCandidatePoolSize: 10,
};

let peerConnection = null;
let localStream = null;
let remoteStream = null;
let roomDialog = null;
let roomId = null;

function init() {
document.querySelector('#cameraBtn').addEventListener('click', openUserMedia);
document.querySelector('#hangupBtn').addEventListener('click', hangUp);
document.querySelector('#createBtn').addEventListener('click', createRoom);
document.querySelector('#joinBtn').addEventListener('click', joinRoom);
roomDialog = new mdc.dialog.MDCDialog(document.querySelector('#room-dialog'));
}

async function createRoom() {
document.querySelector('#createBtn').disabled = true;
document.querySelector('#joinBtn').disabled = true;
const db = firebase.firestore();
const roomRef = await db.collection('rooms').doc();

console.log('Create PeerConnection with configuration: ', configuration);
peerConnection = new RTCPeerConnection(configuration);

registerPeerConnectionListeners();

localStream.getTracks().forEach(track => {
peerConnection.addTrack(track, localStream);
});

// Code for collecting ICE candidates below
const callerCandidatesCollection = roomRef.collection('callerCandidates');

peerConnection.addEventListener('icecandidate', event => {
if (!event.candidate) {
console.log('Got final candidate!');
return;
}
console.log('Got candidate: ', event.candidate);
callerCandidatesCollection.add(event.candidate.toJSON());
});
// Code for collecting ICE candidates above

// Code for creating a room below
const offer = await peerConnection.createOffer();
await peerConnection.setLocalDescription(offer);
console.log('Created offer:', offer);

const roomWithOffer = {
'offer': {
type: offer.type,
sdp: offer.sdp,
},
};
await roomRef.set(roomWithOffer);
roomId = roomRef.id;
console.log(New room created with SDP offer. Room ID: ${roomRef.id});
document.querySelector(
'#currentRoom').innerText = Current room is ${roomRef.id} - You are the caller!;
// Code for creating a room above

peerConnection.addEventListener('track', event => {
console.log('Got remote track:', event.streams[0]);
event.streams[0].getTracks().forEach(track => {
console.log('Add a track to the remoteStream:', track);
remoteStream.addTrack(track);
});
});

// Listening for remote session description below
roomRef.onSnapshot(async snapshot => {
const data = snapshot.data();
if (!peerConnection.currentRemoteDescription && data && data.answer) {
console.log('Got remote description: ', data.answer);
const rtcSessionDescription = new RTCSessionDescription(data.answer);
await peerConnection.setRemoteDescription(rtcSessionDescription);
}
});
// Listening for remote session description above

// Listen for remote ICE candidates below
roomRef.collection('calleeCandidates').onSnapshot(snapshot => {
snapshot.docChanges().forEach(async change => {
if (change.type === 'added') {
let data = change.doc.data();
console.log(Got new remote ICE candidate: ${JSON.stringify(data)});
await peerConnection.addIceCandidate(new RTCIceCandidate(data));
}
});
});
// Listen for remote ICE candidates above
}

function joinRoom() {
document.querySelector('#createBtn').disabled = true;
document.querySelector('#joinBtn').disabled = true;

document.querySelector('#confirmJoinBtn').
addEventListener('click', async () => {
roomId = document.querySelector('#room-id').value;
console.log('Join room: ', roomId);
document.querySelector(
'#currentRoom').innerText = Current room is ${roomId} - You are the callee!;
await joinRoomById(roomId);
}, { once: true });
roomDialog.open();
}

async function joinRoomById(roomId) {
const db = firebase.firestore();
const roomRef = db.collection('rooms').doc(${roomId});
const roomSnapshot = await roomRef.get();
console.log('Got room:', roomSnapshot.exists);

if (roomSnapshot.exists) {
console.log('Create PeerConnection with configuration: ', configuration);
peerConnection = new RTCPeerConnection(configuration);
registerPeerConnectionListeners();
localStream.getTracks().forEach(track => {
peerConnection.addTrack(track, localStream);
});

// Code for collecting ICE candidates below
const calleeCandidatesCollection = roomRef.collection('calleeCandidates');
peerConnection.addEventListener('icecandidate', event => {
  if (!event.candidate) {
    console.log('Got final candidate!');
    return;
  }
  console.log('Got candidate: ', event.candidate);
  calleeCandidatesCollection.add(event.candidate.toJSON());
});
// Code for collecting ICE candidates above

peerConnection.addEventListener('track', event => {
  console.log('Got remote track:', event.streams[0]);
  event.streams[0].getTracks().forEach(track => {
    console.log('Add a track to the remoteStream:', track);
    remoteStream.addTrack(track);
  });
});

// Code for creating SDP answer below
const offer = roomSnapshot.data().offer;
console.log('Got offer:', offer);
await peerConnection.setRemoteDescription(new RTCSessionDescription(offer));
const answer = await peerConnection.createAnswer();
console.log('Created answer:', answer);
await peerConnection.setLocalDescription(answer);

const roomWithAnswer = {
  answer: {
    type: answer.type,
    sdp: answer.sdp,
  },
};
await roomRef.update(roomWithAnswer);
// Code for creating SDP answer above

// Listening for remote ICE candidates below
roomRef.collection('callerCandidates').onSnapshot(snapshot => {
  snapshot.docChanges().forEach(async change => {
    if (change.type === 'added') {
      let data = change.doc.data();
      console.log(`Got new remote ICE candidate: ${JSON.stringify(data)}`);
      await peerConnection.addIceCandidate(new RTCIceCandidate(data));
    }
  });
});
// Listening for remote ICE candidates above

}
}

async function openUserMedia(e) {
const stream = await navigator.mediaDevices.getUserMedia(
{ video: true, audio: true });
document.querySelector('#localVideo').srcObject = stream;
localStream = stream;
remoteStream = new MediaStream();
document.querySelector('#remoteVideo').srcObject = remoteStream;

console.log('Stream:', document.querySelector('#localVideo').srcObject);
document.querySelector('#cameraBtn').disabled = true;
document.querySelector('#joinBtn').disabled = false;
document.querySelector('#createBtn').disabled = false;
document.querySelector('#hangupBtn').disabled = false;
}

async function hangUp(e) {
const tracks = document.querySelector('#localVideo').srcObject.getTracks();
tracks.forEach(track => {
track.stop();
});

if (remoteStream) {
remoteStream.getTracks().forEach(track => track.stop());
}

if (peerConnection) {
peerConnection.close();
}

document.querySelector('#localVideo').srcObject = null;
document.querySelector('#remoteVideo').srcObject = null;
document.querySelector('#cameraBtn').disabled = false;
document.querySelector('#joinBtn').disabled = true;
document.querySelector('#createBtn').disabled = true;
document.querySelector('#hangupBtn').disabled = true;
document.querySelector('#currentRoom').innerText = '';

// Delete room on hangup
if (roomId) {
const db = firebase.firestore();
const roomRef = db.collection('rooms').doc(roomId);
const calleeCandidates = await roomRef.collection('calleeCandidates').get();
calleeCandidates.forEach(async candidate => {
await candidate.ref.delete();
});
const callerCandidates = await roomRef.collection('callerCandidates').get();
callerCandidates.forEach(async candidate => {
await candidate.ref.delete();
});
await roomRef.delete();
}

document.location.reload(true);
}

function registerPeerConnectionListeners() {
peerConnection.addEventListener('icegatheringstatechange', () => {
console.log(
ICE gathering state changed: ${peerConnection.iceGatheringState});
});

peerConnection.addEventListener('connectionstatechange', () => {
console.log(Connection state change: ${peerConnection.connectionState});
});

peerConnection.addEventListener('signalingstatechange', () => {
console.log(Signaling state change: ${peerConnection.signalingState});
});

peerConnection.addEventListener('iceconnectionstatechange ', () => {
console.log(
ICE connection state change: ${peerConnection.iceConnectionState});
});
}

init();

from firebasertc.

JaviLopezG avatar JaviLopezG commented on July 28, 2024

Actually, I don't know. I am a total newbie on WebRTC and I am trying to figure out how to implement it.

I tested a code similar to yours and it worked for me. It could be that one of your devices is under firewall protection or something like that and you need to use a TURN server instead of a stun one. There are some public servers that you can use to test it.

from firebasertc.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.