This repository has been archived by the owner on Jul 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
call.js
204 lines (171 loc) · 5.88 KB
/
call.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
'use strict';
const callButton = document.getElementById('callButton');
const hangupButton = document.getElementById('hangupButton');
const videobox = document.getElementById('videobox');
const msgbox = document.getElementById('messagesouter')
hangupButton.disabled = true;
callButton.addEventListener('click', call);
hangupButton.addEventListener('click', hangup);
var initiator = false;
var usedICEs = []
let startTime;
const localVideo = document.getElementById('localVideo');
const remoteVideo = document.getElementById('remoteVideo');
localVideo.addEventListener('loadedmetadata', function() {
console.log(`Local video videoWidth: ${this.videoWidth}px, videoHeight: ${this.videoHeight}px`);
});
remoteVideo.addEventListener('loadedmetadata', function() {
console.log(`Remote video videoWidth: ${this.videoWidth}px, videoHeight: ${this.videoHeight}px`);
});
remoteVideo.addEventListener('resize', () => {
console.log(`Remote video size changed to ${remoteVideo.videoWidth}x${remoteVideo.videoHeight}`);
// We'll use the first onsize callback as an indication that video has started
// playing out.
if (startTime) {
const elapsedTime = window.performance.now() - startTime;
console.log('Setup time: ' + elapsedTime.toFixed(3) + 'ms');
startTime = null;
}
});
let localStream;
let pc;
const offerOptions = {
offerToReceiveAudio: 1,
offerToReceiveVideo: 1
};
const configuration = {iceServers: [{urls: ['stun:stun1.l.google.com:19302', 'stun:stun2.l.google.com:19305']}]};
//basically getUserMedia call
async function grabMedia() {
try {
const stream = await navigator.mediaDevices.getUserMedia({audio: true, video: true});
localVideo.srcObject = stream;
localStream = stream;
callButton.disabled = false;
} catch (e) {
alert(`getUserMedia() error: ${e.name}`);
}
}
//create PC and add local tracks
async function initPC() {
callButton.disabled = true;
hangupButton.disabled = false;
//get local media
await grabMedia()
console.log('Starting call');
startTime = window.performance.now();
const videoTracks = localStream.getVideoTracks();
const audioTracks = localStream.getAudioTracks();
if (videoTracks.length > 0) {
console.log(`Using video device: ${videoTracks[0].label}`);
}
if (audioTracks.length > 0) {
console.log(`Using audio device: ${audioTracks[0].label}`);
}
//create pc
pc = new RTCPeerConnection(configuration);
pc.addEventListener('icecandidate', e => onIceCandidate(pc, e));
//add local stram tracks to pc
localStream.getTracks().forEach(track => pc.addTrack(track, localStream));
// reorder frontend
videobox.style.display = "inline-block";
msgbox.className="container-fluid height20"
pc.addEventListener('track', gotRemoteStream);
pc.onconnectionstatechange = function(event) {
console.log("Connection state: ", pc.connectionState)
if (pc.connectionState == "closed" || pc.connectionState == "failed" || pc.connectionState == "disconnected")
{
hangup();
}
}
}
// initiate a call
async function call() {
initiator=true;
await initPC();
try {
const offer = await pc.createOffer(offerOptions);
await onCreateOfferSuccess(offer);
} catch (e) {
console.log(`Failed to create session description: ${error.toString()}`);
}
}
//local sdp created, send it over
async function onCreateOfferSuccess(desc) {
try {
await pc.setLocalDescription(desc);
sendSignal(desc)
} catch (e) {
console.log('failed to set the session description to \n', desc.sdp)
}
}
// when generating a new ice candidate
async function onIceCandidate(pc, event) {
try {
sendSignal(event.candidate)
} catch (e) {
console.log(`failed to send ICE candidate:\n${event.candidate ? event.candidate.candidate : '(null)'}`);
}
}
async function onOfferRecieved(signalingMsgs) {
//only do this once per call
if(typeof pc == "undefined" || pc == null){
await initPC();
}
var i;
for(i=0;i<signalingMsgs.length;i++){
if (signalingMsgs[i].includes("offer") && pc.remoteDescription == null ){
await sendAnswer(JSON.parse(signalingMsgs[i]));
} else if (signalingMsgs[i].includes("candidate") && !usedICEs.includes(signalingMsgs[i]) && pc.remoteDescription !== null) {
usedICEs.push(signalingMsgs[i])
await pc.addIceCandidate(JSON.parse(signalingMsgs[i]))
}
}
}
// Set remote offer and send answer
async function sendAnswer(desc) {
try {
await pc.setRemoteDescription(new RTCSessionDescription(desc));
var answer = await pc.createAnswer();
await pc.setLocalDescription(answer);
sendSignal(answer)
} catch (e) {
console.log('failed to set the remote description to \n', desc.sdp)
}
}
// when stream is recieved display it
function gotRemoteStream(e) {
if (remoteVideo.srcObject !== e.streams[0]) {
remoteVideo.srcObject = e.streams[0];
console.log('received remote stream', e.streams);
}
}
// if peer sent an answer
async function onAnswerRecived(signalingMsgs) {
var i;
for(i=0;i<signalingMsgs.length;i++){
if (signalingMsgs[i].includes("answer") && pc.remoteDescription == null){
await pc.setRemoteDescription(new RTCSessionDescription(JSON.parse(signalingMsgs[i])))
} else if (signalingMsgs[i].includes("candidate") && !usedICEs.includes(signalingMsgs[i]) && pc.remoteDescription !== null) {
usedICEs.push(signalingMsgs[i])
await pc.addIceCandidate(JSON.parse(signalingMsgs[i]))
}
}
}
// for ending calls
function hangup() {
console.log('Ending call');
pc.close();
pc = null;
initiator=false;
hangupButton.disabled = true;
callButton.disabled = false;
videobox.style.display = "none";
msgbox.className="container-fluid height100"
}