Connection theoretically stable now

This commit is contained in:
Arya Vohra 2020-06-05 22:17:49 +08:00
parent f4f9d053b5
commit 437856bb92
2 changed files with 31 additions and 75 deletions

View File

@ -37,10 +37,10 @@ var VideoChat = {
socket: io(), socket: io(),
remoteVideoWrapper: document.getElementById("wrapper"), remoteVideoWrapper: document.getElementById("wrapper"),
localVideo: document.getElementById("local-video"), localVideo: document.getElementById("local-video"),
peerColors: new Map(),
peerConnections: new Map(), peerConnections: new Map(),
recognition: undefined, recognition: undefined,
borderColor: undefined, borderColor: "hsl(120,100%,70%)",
peerColors: new Map(),
// Call to getUserMedia (provided by adapter.js for cross browser compatibility) // Call to getUserMedia (provided by adapter.js for cross browser compatibility)
// asking for access to both the video and audio streams. If the request is // asking for access to both the video and audio streams. If the request is
@ -97,18 +97,21 @@ var VideoChat = {
Snackbar.close(); Snackbar.close();
}, },
}); });
// VideoChat.borderColor = uuidToColor(VideoChat.socket.id);
VideoChat.localVideo.srcObject = stream; VideoChat.localVideo.srcObject = stream;
VideoChat.localVideo.style.border = `3px solid ${VideoChat.borderColor}`;
// Now we're ready to join the chat room. // Now we're ready to join the chat room.
VideoChat.socket.emit("join", roomHash); VideoChat.socket.emit("join", roomHash);
VideoChat.borderColor = uuidToColor(VideoChat.socket.id);
VideoChat.localVideo.style.border = `3px solid ${VideoChat.borderColor}`;
// Add listeners to the websocket // Add listeners to the websocket
VideoChat.socket.on("leave", VideoChat.onLeave); VideoChat.socket.on("leave", VideoChat.onLeave);
VideoChat.socket.on("full", chatRoomFull); VideoChat.socket.on("full", chatRoomFull);
VideoChat.socket.on("offer", VideoChat.onOffer); VideoChat.socket.on("offer", VideoChat.onOffer);
VideoChat.socket.on("initiateCall", VideoChat.call); VideoChat.socket.on("willInitiateCall", VideoChat.call);
// Set up listeners on the socket
VideoChat.socket.on("candidate", VideoChat.onCandidate); VideoChat.socket.on("candidate", VideoChat.onCandidate);
VideoChat.socket.on("answer", VideoChat.onAnswer); VideoChat.socket.on("answer", VideoChat.onAnswer);
VideoChat.socket.on("requestToggleCaptions", () => toggleSendCaptions()); VideoChat.socket.on("requestToggleCaptions", () => toggleSendCaptions());
@ -117,7 +120,6 @@ var VideoChat = {
); );
}, },
// Initiate a call with newly joined peer
call: function (uuid, room) { call: function (uuid, room) {
logIt(`call >>> Initiating call with ${uuid}...`); logIt(`call >>> Initiating call with ${uuid}...`);
VideoChat.socket.on( VideoChat.socket.on(
@ -129,7 +131,6 @@ var VideoChat = {
VideoChat.socket.emit("token", roomHash, uuid); VideoChat.socket.emit("token", roomHash, uuid);
}, },
// Handle a peer leaving the room
onLeave: function(uuid) { onLeave: function(uuid) {
logIt("disconnected - UUID " + uuid); logIt("disconnected - UUID " + uuid);
// Remove video element // Remove video element
@ -373,12 +374,6 @@ var VideoChat = {
VideoChat.connected.set(uuid, true); VideoChat.connected.set(uuid, true);
// Hide caption status text // Hide caption status text
captionText.fadeOut(); captionText.fadeOut();
// Downscale send resolution and bitrate if num in room > 4
// if (VideoChat.peerConnections.size > 3) {
// VideoChat.peerConnections.forEach(function (value, key, map) {
// downscaleStream(value);
// });
// }
// Reposition local video after a second, as there is often a delay // Reposition local video after a second, as there is often a delay
// between adding a stream and the height of the video div changing // between adding a stream and the height of the video div changing
setTimeout(() => rePositionLocalVideo(), 500); setTimeout(() => rePositionLocalVideo(), 500);
@ -517,32 +512,6 @@ function sendToAllDataChannels(message) {
// } // }
// End Fullscreen // End Fullscreen
// Downscale single stream
// async function downscaleStream(pc, applying = false) {
// height = 240;
// rate = 800000;
// if (applying) return;
// try {
// applying = true;
// do {
// h = height;
// const sender = pc.getSenders().find(function (s) {
// return s.track.kind === "video";
// });
// const ratio = sender.track.getSettings().height / height;
// const params = sender.getParameters();
// if (!params.encodings) params.encodings = [{}]; // Firefox workaround!
// params.encodings[0].scaleResolutionDownBy = Math.max(ratio, 1);
// params.encodings[0].maxBitrate = rate;
// await sender.setParameters(params);
// } while (h != height);
// } catch (e) {
// logIt(e);
// } finally {
// applying = false;
// }
// }
// Mute microphone // Mute microphone
function muteMicrophone() { function muteMicrophone() {
var audioTrack = null; var audioTrack = null;
@ -874,33 +843,29 @@ function uuidToColor(uuid) {
// Using uuid to generate random. unique pastel color // Using uuid to generate random. unique pastel color
var hash = 0; var hash = 0;
for (var i = 0; i < uuid.length; i++) { for (var i = 0; i < uuid.length; i++) {
hash = uuid.charCodeAt(i) + ((hash << 5) - hash); hash = uuid.charCodeAt(i) + ((hash << 5) - hash);
hash = hash & hash; hash = hash & hash;
} }
var hue = Math.abs(hash % 360); var hue = Math.abs(hash % 360);
// Ensure color is not similar to other colors // Ensure color is not similar to other colors
var availColors = Array.from({ length: 9 }, (x, i) => i * 40); var availColors = Array.from({length: 18}, (x,i) => i*20);
VideoChat.peerColors.forEach(function (value, key, map) { VideoChat.peerColors.forEach(function(value, key, map) {availColors[Math.floor(value/20)] = null});
availColors[Math.floor(value / 40)] = null; if (availColors[Math.floor(hue/20)] == null) {
});
if (availColors[Math.floor(hue / 40)] == null) {
for (var i = 0; i < availColors.length; i++) { for (var i = 0; i < availColors.length; i++) {
if (availColors[i] != null) { if (availColors[i] != null) {
hue = (hue % 40) + availColors[i]; hue = (hue % 20) + availColors[i];
availColors[i] = null; availColors[i] = null;
break; break;
} }
} }
} }
return `hsl(${hue},100%,60%)`; return `hsl(${hue},100%,70%)`;
} }
// Sets the border color of uuid's stream // Sets the border color of uuid's stream
function setStreamColor(uuid) { function setStreamColor(uuid) {
const color = uuidToColor(uuid); const color = uuidToColor(uuid);
document.querySelectorAll( document.querySelectorAll(`[uuid="${uuid}"]`)[0].style.border = `3px solid ${color}`;
`[uuid="${uuid}"]`
)[0].style.border = `3px solid ${color}`;
VideoChat.peerColors[uuid] = color; VideoChat.peerColors[uuid] = color;
} }
@ -935,27 +900,18 @@ function togglePictureInPicture() {
logIt("Error exiting pip."); logIt("Error exiting pip.");
logIt(error); logIt(error);
}); });
} else if (VideoChat.remoteVideoWrapper.lastChild.webkitPresentationMode === "inline") {
VideoChat.remoteVideoWrapper.lastChild.webkitSetPresentationMode("picture-in-picture");
} else if ( } else if (
VideoChat.remoteVideoWrapper.lastChild.webkitPresentationMode === "inline" VideoChat.remoteVideoWrapper.lastChild.webkitPresentationMode === "picture-in-picture"
) { ) {
VideoChat.remoteVideoWrapper.lastChild.webkitSetPresentationMode( VideoChat.remoteVideoWrapper.lastChild.webkitSetPresentationMode("inline");
"picture-in-picture"
);
} else if (
VideoChat.remoteVideoWrapper.lastChild.webkitPresentationMode ===
"picture-in-picture"
) {
VideoChat.remoteVideoWrapper.lastChild.webkitSetPresentationMode(
"inline"
);
} else { } else {
VideoChat.remoteVideoWrapper.lastChild VideoChat.remoteVideoWrapper.lastChild.requestPictureInPicture().catch((error) => {
.requestPictureInPicture() alert(
.catch((error) => { "You must be connected to another person to enter picture in picture."
alert( );
"You must be connected to another person to enter picture in picture." });
);
});
} }
} else { } else {
alert( alert(
@ -978,6 +934,7 @@ window.onbeforeunload = function () {
return null; return null;
}; };
function startUp() { function startUp() {
// Try and detect in-app browsers and redirect // Try and detect in-app browsers and redirect
var ua = navigator.userAgent || navigator.vendor || window.opera; var ua = navigator.userAgent || navigator.vendor || window.opera;

View File

@ -8,7 +8,6 @@ var twillioAccountSID =
var twilio = require("twilio")(twillioAccountSID, twillioAuthToken); var twilio = require("twilio")(twillioAccountSID, twillioAuthToken);
var express = require("express"); var express = require("express");
var app = express(); var app = express();
const fs = require('fs');
var http = require("http").createServer(app); var http = require("http").createServer(app);
var io = require("socket.io")(http); var io = require("socket.io")(http);
var path = require("path"); var path = require("path");
@ -81,9 +80,9 @@ io.on("connection", function (socket) {
socket.join(room); socket.join(room);
} else if (numClients < 5) { } else if (numClients < 5) {
socket.join(room); socket.join(room);
logIt("Broadcasting request to connect with new peer...", room); // When the client is not the first to join the room, all clients are ready.
// Emits message to ask peers in room to connect with joining peer logIt("Broadcasting ready message", room);
socket.broadcast.to(room).emit("initiateCall", socket.id, room); socket.broadcast.to(room).emit("willInitiateCall", socket.id, room);
} else { } else {
logIt( logIt(
"room already full with " + numClients + " people in the room.", "room already full with " + numClients + " people in the room.",
@ -138,7 +137,7 @@ io.on("connection", function (socket) {
}); });
// Listen for Heroku port, otherwise just use 3000 // Listen for Heroku port, otherwise just use 3000
var port = process.env.PORT || 443; var port = process.env.PORT || 3000;
http.listen(port, function () { http.listen(port, function () {
console.log("http://localhost:" + port); console.log("http://localhost:" + port);
}); });