forked from vasanthv/hello
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebrtc.js
executable file
·346 lines (298 loc) · 11 KB
/
webrtc.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/* globals App, io */
"use strict";
const ICE_SERVERS = [
{ urls: "stun:stun.l.google.com:19302" },
{ urls: "turn:openrelay.metered.ca:443", username: "openrelayproject", credential: "openrelayproject" },
];
const APP_URL = (() => {
const protocol = "http" + (location.hostname == "localhost" ? "" : "s") + "://";
return protocol + location.hostname + (location.hostname == "localhost" ? location.port : "");
})();
const USE_AUDIO = true;
const USE_VIDEO = true;
// You can continue using this signalling server or spin up your own.
// Source to code for thiscan be found at https://github.com/vasanthv/talk/blob/master/signalling-server/index.js
const SIGNALLING_SERVER = "https://talk-zxrf.onrender.com";
let signalingSocket = null; /* our socket.io connection to our webserver */
let localMediaStream = null; /* our own microphone / webcam */
let peers = {}; /* keep track of our peer connections, indexed by peer_id (aka socket.io id) */
let channel = {}; /* keep track of the peers Info in the channel, indexed by peer_id (aka socket.io id) */
let peerMediaElements = {}; /* keep track of our <video>/<audio> tags, indexed by peer_id */
let dataChannels = {};
window.initiateCall = () => {
App.userAgent = navigator.userAgent;
App.isMobileDevice = !!/Android|webOS|iPhone|iPad|iPod|BB10|BlackBerry|IEMobile|Opera Mini|Mobile|mobile/i.test(
App.userAgent.toUpperCase() || ""
);
App.isTablet =
/(ipad|tablet|(android(?!.*mobile))|(windows(?!.*phone)(.*touch))|kindle|playbook|silk|(puffin(?!.*(IP|AP|WP))))/.test(
App.userAgent.toLowerCase()
);
App.isIpad = /macintosh/.test(App.userAgent.toLowerCase()) && "ontouchend" in document;
App.isDesktop = !App.isMobileDevice && !App.isTablet && !App.isIpad;
App.roomLink = `${APP_URL}/?room=${App.roomId}`;
signalingSocket = io(SIGNALLING_SERVER);
signalingSocket.on("connect", function () {
App.peerId = signalingSocket.id;
console.log("peerId: " + App.peerId);
const userData = {
peerName: App.name,
videoEnabled: App.videoEnabled,
audioEnabled: App.audioEnabled,
userAgent: App.userAgent,
isMobileDevice: App.isMobileDevice,
isTablet: App.isTablet,
isIpad: App.isIpad,
isDesktop: App.isDesktop,
};
if (localMediaStream) joinChatChannel(App.roomId, userData);
else
setupLocalMedia(function () {
joinChatChannel(App.roomId, userData);
});
});
signalingSocket.on("disconnect", function () {
for (let peer_id in peerMediaElements) {
document.getElementById("videos").removeChild(peerMediaElements[peer_id].parentNode);
resizeVideos();
}
for (let peer_id in peers) {
peers[peer_id].close();
}
peers = {};
peerMediaElements = {};
});
function joinChatChannel(channel, userData) {
signalingSocket.emit("join", { channel: channel, userData: userData });
}
signalingSocket.on("addPeer", function (config) {
//console.log("addPeer", config);
const peer_id = config.peer_id;
if (peer_id in peers) return;
channel = config.channel;
//console.log('[Join] - connected peers in the channel', JSON.stringify(channel, null, 2));
const peerConnection = new RTCPeerConnection({ iceServers: ICE_SERVERS });
peers[peer_id] = peerConnection;
peerConnection.onicecandidate = function (event) {
if (event.candidate) {
signalingSocket.emit("relayICECandidate", {
peer_id: peer_id,
ice_candidate: {
sdpMLineIndex: event.candidate.sdpMLineIndex,
candidate: event.candidate.candidate,
},
});
}
};
peerConnection.onaddstream = function (event) {
if (!channel[peer_id]["userData"]["userAgent"]) return;
const remoteMedia = getVideoElement(peer_id);
peerMediaElements[peer_id] = remoteMedia;
attachMediaStream(remoteMedia, event.stream);
resizeVideos();
for (let peerId in channel) {
const videoPeerName = document.getElementById(peerId + "_videoPeerName");
const peerName = channel[peerId]["userData"]["peerName"];
if (videoPeerName && peerName) {
videoPeerName.innerHTML = peerName;
}
const videoAvatarImg = document.getElementById(peerId + "_videoEnabled");
const videoEnabled = channel[peerId]["userData"]["videoEnabled"];
if (videoAvatarImg && !videoEnabled) {
videoAvatarImg.style.visibility = "visible";
}
const audioEnabledEl = document.getElementById(peerId + "_audioEnabled");
const audioEnabled = channel[peerId]["userData"]["audioEnabled"];
if (audioEnabledEl) {
audioEnabledEl.className = "audioEnabled icon-mic" + (audioEnabled ? "" : "-off");
}
}
};
peerConnection.ondatachannel = function (event) {
console.log("Datachannel event" + peer_id, event);
event.channel.onmessage = (msg) => {
let dataMessage = {};
try {
dataMessage = JSON.parse(msg.data);
App.handleIncomingDataChannelMessage(dataMessage);
} catch (err) {
console.log(err);
}
};
};
/* Add our local stream */
peerConnection.addStream(localMediaStream);
dataChannels[peer_id] = peerConnection.createDataChannel("talk__data_channel");
if (config.should_create_offer) {
peerConnection.onnegotiationneeded = () => {
peerConnection
.createOffer()
.then((localDescription) => {
peerConnection
.setLocalDescription(localDescription)
.then(() => {
signalingSocket.emit("relaySessionDescription", {
peer_id: peer_id,
session_description: localDescription,
});
})
.catch(() => {
alert("Offer setLocalDescription failed!");
});
})
.catch((error) => {
console.log("Error sending offer: ", error);
});
};
}
});
signalingSocket.on("sessionDescription", function (config) {
const peer_id = config.peer_id;
const peer = peers[peer_id];
const remoteDescription = config.session_description;
const desc = new RTCSessionDescription(remoteDescription);
peer.setRemoteDescription(
desc,
() => {
if (remoteDescription.type == "offer") {
peer.createAnswer(
(localDescription) => {
peer.setLocalDescription(
localDescription,
() => {
signalingSocket.emit("relaySessionDescription", {
peer_id: peer_id,
session_description: localDescription,
});
},
() => alert("Answer setLocalDescription failed!")
);
},
(error) => console.log("Error creating answer: ", error)
);
}
},
(error) => console.log("setRemoteDescription error: ", error)
);
});
signalingSocket.on("iceCandidate", function (config) {
const peer = peers[config.peer_id];
const iceCandidate = config.ice_candidate;
peer.addIceCandidate(new RTCIceCandidate(iceCandidate)).catch((error) => {
console.log("Error addIceCandidate", error);
});
});
signalingSocket.on("removePeer", function (config) {
const peer_id = config.peer_id;
if (peer_id in peerMediaElements) {
document.getElementById("videos").removeChild(peerMediaElements[peer_id].parentNode);
resizeVideos();
}
if (peer_id in peers) {
peers[peer_id].close();
}
delete dataChannels[peer_id];
delete peers[peer_id];
delete peerMediaElements[config.peer_id];
delete channel[config.peer_id];
//console.log('removePeer', JSON.stringify(channel, null, 2));
});
};
const attachMediaStream = (element, stream) => (element.srcObject = stream);
function setupLocalMedia(callback, errorback) {
if (localMediaStream != null) {
if (callback) callback();
return;
}
navigator.mediaDevices
.getUserMedia({ audio: USE_AUDIO, video: USE_VIDEO })
.then((stream) => {
localMediaStream = stream;
const localMedia = getVideoElement(App.peerId, true);
attachMediaStream(localMedia, stream);
resizeVideos();
if (callback) callback();
navigator.mediaDevices.enumerateDevices().then((devices) => {
App.videoDevices = devices.filter((device) => device.kind === "videoinput" && device.deviceId !== "default");
App.audioDevices = devices.filter((device) => device.kind === "audioinput" && device.deviceId !== "default");
});
})
.catch(() => {
/* user denied access to a/v */
alert("This site will not work without camera/microphone access.");
if (errorback) errorback();
});
}
const getVideoElement = (peerId, isLocal) => {
const videoWrap = document.createElement("div");
videoWrap.className = "video";
const media = document.createElement("video");
media.setAttribute("playsinline", true);
media.autoplay = true;
media.controls = false;
if (isLocal) {
media.setAttribute("id", "selfVideo");
media.className = "mirror";
media.muted = true;
media.volume = 0;
} else {
media.mediaGroup = "remotevideo";
}
const audioEnabled = document.createElement("i");
audioEnabled.setAttribute("id", peerId + "_audioEnabled");
audioEnabled.className = "audioEnabled icon-mic";
const peerNameEle = document.createElement("div");
peerNameEle.setAttribute("id", peerId + "_videoPeerName");
peerNameEle.className = "videoPeerName";
if (isLocal) {
peerNameEle.innerHTML = `${App.name ?? ""} (you)`;
} else {
peerNameEle.innerHTML = "Unnamed";
}
const fullScreenBtn = document.createElement("button");
fullScreenBtn.className = "icon-maximize";
fullScreenBtn.addEventListener("click", () => {
if (videoWrap.requestFullscreen) {
videoWrap.requestFullscreen();
} else if (videoWrap.webkitRequestFullscreen) {
videoWrap.webkitRequestFullscreen();
}
});
const videoAvatarImgSize = App.isMobileDevice ? "100px" : "200px";
const videoAvatarImg = document.createElement("img");
videoAvatarImg.setAttribute("id", peerId + "_videoEnabled");
videoAvatarImg.setAttribute("src", "videoOff.png");
videoAvatarImg.setAttribute("width", videoAvatarImgSize);
videoAvatarImg.setAttribute("height", videoAvatarImgSize);
videoAvatarImg.className = "videoAvatarImg";
videoWrap.setAttribute("id", peerId);
videoWrap.appendChild(media);
videoWrap.appendChild(audioEnabled);
videoWrap.appendChild(peerNameEle);
videoWrap.appendChild(fullScreenBtn);
videoWrap.appendChild(videoAvatarImg);
document.getElementById("videos").appendChild(videoWrap);
return media;
};
const resizeVideos = () => {
const numToString = ["", "one", "two", "three", "four", "five", "six"];
const videos = document.querySelectorAll("#videos .video");
document.querySelectorAll("#videos .video").forEach((v) => {
v.className = "video " + numToString[videos.length];
});
};
const calcViewPortUnit = () => {
let vh = document.getElementById("blanket").offsetHeight * 0.01;
document.documentElement.style.setProperty("--vh", `${vh}px`);
};
window.addEventListener("resize", calcViewPortUnit);
window.addEventListener("load", calcViewPortUnit);
document.addEventListener("click", () => {
if (!App.showChat && !App.showSettings) {
App.hideToolbar = !App.hideToolbar;
}
if (App.showSettings && App.showChat) {
App.showChat = !App.showChat;
App.showSettings = !App.showSettings;
}
});