many fixes, core override, UNREAL 5.3
This commit is contained in:
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"FileVersion": 3,
|
||||
"EngineAssociation": "5.1",
|
||||
"EngineAssociation": "5.3",
|
||||
"Category": "",
|
||||
"Description": "",
|
||||
"Plugins": [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"FileVersion": 3,
|
||||
"EngineAssociation": "5.1",
|
||||
"EngineAssociation": "5.3",
|
||||
"Category": "",
|
||||
"Description": "",
|
||||
"Plugins": [
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"HttpPort": 90,
|
||||
"UseHTTPS": false,
|
||||
"MatchmakerPort": 9999,
|
||||
"LogToFile": true
|
||||
}
|
||||
@@ -1,295 +0,0 @@
|
||||
// Copyright Epic Games, Inc. All Rights Reserved.
|
||||
var enableRedirectionLinks = true;
|
||||
var enableRESTAPI = true;
|
||||
|
||||
const defaultConfig = {
|
||||
// The port clients connect to the matchmaking service over HTTP
|
||||
HttpPort: 80,
|
||||
UseHTTPS: false,
|
||||
// The matchmaking port the signaling service connects to the matchmaker
|
||||
MatchmakerPort: 9999,
|
||||
|
||||
// Log to file
|
||||
LogToFile: true
|
||||
};
|
||||
|
||||
// Similar to the Signaling Server (SS) code, load in a config.json file for the MM parameters
|
||||
const argv = require('yargs').argv;
|
||||
|
||||
var configFile = (typeof argv.configFile != 'undefined') ? argv.configFile.toString() : 'config.json';
|
||||
console.log(`configFile ${configFile}`);
|
||||
const config = require('./modules/config.js').init(configFile, defaultConfig);
|
||||
console.log("Config: " + JSON.stringify(config, null, '\t'));
|
||||
|
||||
const express = require('express');
|
||||
var cors = require('cors');
|
||||
const app = express();
|
||||
const http = require('http').Server(app);
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const logging = require('./modules/logging.js');
|
||||
logging.RegisterConsoleLogger();
|
||||
|
||||
if (config.LogToFile) {
|
||||
logging.RegisterFileLogger('./logs');
|
||||
}
|
||||
|
||||
// A list of all the Cirrus server which are connected to the Matchmaker.
|
||||
var cirrusServers = new Map();
|
||||
|
||||
//
|
||||
// Parse command line.
|
||||
//
|
||||
|
||||
if (typeof argv.HttpPort != 'undefined') {
|
||||
config.HttpPort = argv.HttpPort;
|
||||
}
|
||||
if (typeof argv.MatchmakerPort != 'undefined') {
|
||||
config.MatchmakerPort = argv.MatchmakerPort;
|
||||
}
|
||||
|
||||
http.listen(config.HttpPort, () => {
|
||||
console.log('HTTP listening on *:' + config.HttpPort);
|
||||
});
|
||||
|
||||
|
||||
if (config.UseHTTPS) {
|
||||
//HTTPS certificate details
|
||||
const options = {
|
||||
key: fs.readFileSync(path.join(__dirname, './certificates/client-key.pem')),
|
||||
cert: fs.readFileSync(path.join(__dirname, './certificates/client-cert.pem'))
|
||||
};
|
||||
|
||||
var https = require('https').Server(options, app);
|
||||
|
||||
//Setup http -> https redirect
|
||||
console.log('Redirecting http->https');
|
||||
app.use(function (req, res, next) {
|
||||
if (!req.secure) {
|
||||
if (req.get('Host')) {
|
||||
var hostAddressParts = req.get('Host').split(':');
|
||||
var hostAddress = hostAddressParts[0];
|
||||
if (httpsPort != 443) {
|
||||
hostAddress = `${hostAddress}:${httpsPort}`;
|
||||
}
|
||||
return res.redirect(['https://', hostAddress, req.originalUrl].join(''));
|
||||
} else {
|
||||
console.error(`unable to get host name from header. Requestor ${req.ip}, url path: '${req.originalUrl}', available headers ${JSON.stringify(req.headers)}`);
|
||||
return res.status(400).send('Bad Request');
|
||||
}
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
https.listen(443, function () {
|
||||
console.log('Https listening on 443');
|
||||
});
|
||||
}
|
||||
|
||||
// No servers are available so send some simple JavaScript to the client to make
|
||||
// it retry after a short period of time.
|
||||
function sendRetryResponse(res) {
|
||||
res.send(`All ${cirrusServers.size} Cirrus servers are in use. Retrying in <span id="countdown">3</span> seconds.
|
||||
<script>
|
||||
var countdown = document.getElementById("countdown").textContent;
|
||||
setInterval(function() {
|
||||
countdown--;
|
||||
if (countdown == 0) {
|
||||
window.location.reload(1);
|
||||
} else {
|
||||
document.getElementById("countdown").textContent = countdown;
|
||||
}
|
||||
}, 1000);
|
||||
</script>`);
|
||||
}
|
||||
|
||||
// Get a Cirrus server if there is one available which has no clients connected.
|
||||
function getAvailableCirrusServer() {
|
||||
for (cirrusServer of cirrusServers.values()) {
|
||||
if (cirrusServer.numConnectedClients === 0 && cirrusServer.ready === true) {
|
||||
|
||||
// Check if we had at least 10 seconds since the last redirect, avoiding the
|
||||
// chance of redirecting 2+ users to the same SS before they click Play.
|
||||
// In other words, give the user 10 seconds to click play button the claim the server.
|
||||
if( cirrusServer.hasOwnProperty('lastRedirect')) {
|
||||
if( ((Date.now() - cirrusServer.lastRedirect) / 1000) < 10 )
|
||||
continue;
|
||||
}
|
||||
cirrusServer.lastRedirect = Date.now();
|
||||
|
||||
return cirrusServer;
|
||||
}
|
||||
}
|
||||
|
||||
console.log('WARNING: No empty Cirrus servers are available');
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if(enableRESTAPI) {
|
||||
// Handle REST signalling server only request.
|
||||
app.options('/signallingserver', cors())
|
||||
app.get('/signallingserver', cors(), (req, res) => {
|
||||
cirrusServer = getAvailableCirrusServer();
|
||||
if (cirrusServer != undefined) {
|
||||
res.json({ signallingServer: `${cirrusServer.address}:${cirrusServer.port}`});
|
||||
console.log(`Returning ${cirrusServer.address}:${cirrusServer.port}`);
|
||||
} else {
|
||||
res.json({ signallingServer: '', error: 'No signalling servers available'});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if(enableRedirectionLinks) {
|
||||
// Handle standard URL.
|
||||
app.get('/', (req, res) => {
|
||||
cirrusServer = getAvailableCirrusServer();
|
||||
if (cirrusServer != undefined) {
|
||||
res.redirect(`http://${cirrusServer.address}:${cirrusServer.port}/`);
|
||||
//console.log(req);
|
||||
console.log(`Redirect to ${cirrusServer.address}:${cirrusServer.port}`);
|
||||
} else {
|
||||
sendRetryResponse(res);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle URL with custom HTML.
|
||||
app.get('/custom_html/:htmlFilename', (req, res) => {
|
||||
cirrusServer = getAvailableCirrusServer();
|
||||
if (cirrusServer != undefined) {
|
||||
res.redirect(`http://${cirrusServer.address}:${cirrusServer.port}/custom_html/${req.params.htmlFilename}`);
|
||||
console.log(`Redirect to ${cirrusServer.address}:${cirrusServer.port}`);
|
||||
} else {
|
||||
sendRetryResponse(res);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
//
|
||||
// Connection to Cirrus.
|
||||
//
|
||||
|
||||
const net = require('net');
|
||||
|
||||
function disconnect(connection) {
|
||||
console.log(`Ending connection to remote address ${connection.remoteAddress}`);
|
||||
connection.end();
|
||||
}
|
||||
|
||||
const matchmaker = net.createServer((connection) => {
|
||||
connection.on('data', (data) => {
|
||||
try {
|
||||
message = JSON.parse(data);
|
||||
|
||||
if(message)
|
||||
console.log(`Message TYPE: ${message.type}`);
|
||||
} catch(e) {
|
||||
console.log(`ERROR (${e.toString()}): Failed to parse Cirrus information from data: ${data.toString()}`);
|
||||
disconnect(connection);
|
||||
return;
|
||||
}
|
||||
if (message.type === 'connect') {
|
||||
// A Cirrus server connects to this Matchmaker server.
|
||||
cirrusServer = {
|
||||
address: message.address,
|
||||
port: message.port,
|
||||
numConnectedClients: 0,
|
||||
lastPingReceived: Date.now()
|
||||
};
|
||||
cirrusServer.ready = message.ready === true;
|
||||
|
||||
// Handles disconnects between MM and SS to not add dupes with numConnectedClients = 0 and redirect users to same SS
|
||||
// Check if player is connected and doing a reconnect. message.playerConnected is a new variable sent from the SS to
|
||||
// help track whether or not a player is already connected when a 'connect' message is sent (i.e., reconnect).
|
||||
if(message.playerConnected == true) {
|
||||
cirrusServer.numConnectedClients = 1;
|
||||
}
|
||||
|
||||
// Find if we already have a ciruss server address connected to (possibly a reconnect happening)
|
||||
let server = [...cirrusServers.entries()].find(([key, val]) => val.address === cirrusServer.address && val.port === cirrusServer.port);
|
||||
|
||||
// if a duplicate server with the same address isn't found -- add it to the map as an available server to send users to.
|
||||
if (!server || server.size <= 0) {
|
||||
console.log(`Adding connection for ${cirrusServer.address.split(".")[0]} with playerConnected: ${message.playerConnected}`)
|
||||
cirrusServers.set(connection, cirrusServer);
|
||||
} else {
|
||||
console.log(`RECONNECT: cirrus server address ${cirrusServer.address.split(".")[0]} already found--replacing. playerConnected: ${message.playerConnected}`)
|
||||
var foundServer = cirrusServers.get(server[0]);
|
||||
|
||||
// Make sure to retain the numConnectedClients from the last one before the reconnect to MM
|
||||
if (foundServer) {
|
||||
cirrusServers.set(connection, cirrusServer);
|
||||
console.log(`Replacing server with original with numConn: ${cirrusServer.numConnectedClients}`);
|
||||
cirrusServers.delete(server[0]);
|
||||
} else {
|
||||
cirrusServers.set(connection, cirrusServer);
|
||||
console.log("Connection not found in Map() -- adding a new one");
|
||||
}
|
||||
}
|
||||
} else if (message.type === 'streamerConnected') {
|
||||
// The stream connects to a Cirrus server and so is ready to be used
|
||||
cirrusServer = cirrusServers.get(connection);
|
||||
if(cirrusServer) {
|
||||
cirrusServer.ready = true;
|
||||
console.log(`Cirrus server ${cirrusServer.address}:${cirrusServer.port} ready for use`);
|
||||
} else {
|
||||
disconnect(connection);
|
||||
}
|
||||
} else if (message.type === 'streamerDisconnected') {
|
||||
// The stream connects to a Cirrus server and so is ready to be used
|
||||
cirrusServer = cirrusServers.get(connection);
|
||||
if(cirrusServer) {
|
||||
cirrusServer.ready = false;
|
||||
console.log(`Cirrus server ${cirrusServer.address}:${cirrusServer.port} no longer ready for use`);
|
||||
} else {
|
||||
disconnect(connection);
|
||||
}
|
||||
} else if (message.type === 'clientConnected') {
|
||||
// A client connects to a Cirrus server.
|
||||
cirrusServer = cirrusServers.get(connection);
|
||||
if(cirrusServer) {
|
||||
cirrusServer.numConnectedClients++;
|
||||
console.log(`Client connected to Cirrus server ${cirrusServer.address}:${cirrusServer.port}`);
|
||||
} else {
|
||||
disconnect(connection);
|
||||
}
|
||||
} else if (message.type === 'clientDisconnected') {
|
||||
// A client disconnects from a Cirrus server.
|
||||
cirrusServer = cirrusServers.get(connection);
|
||||
if(cirrusServer) {
|
||||
cirrusServer.numConnectedClients--;
|
||||
console.log(`Client disconnected from Cirrus server ${cirrusServer.address}:${cirrusServer.port}`);
|
||||
if(cirrusServer.numConnectedClients === 0) {
|
||||
// this make this server immediately available for a new client
|
||||
cirrusServer.lastRedirect = 0;
|
||||
}
|
||||
} else {
|
||||
disconnect(connection);
|
||||
}
|
||||
} else if (message.type === 'ping') {
|
||||
cirrusServer = cirrusServers.get(connection);
|
||||
if(cirrusServer) {
|
||||
cirrusServer.lastPingReceived = Date.now();
|
||||
} else {
|
||||
disconnect(connection);
|
||||
}
|
||||
} else {
|
||||
console.log('ERROR: Unknown data: ' + JSON.stringify(message));
|
||||
disconnect(connection);
|
||||
}
|
||||
});
|
||||
|
||||
// A Cirrus server disconnects from this Matchmaker server.
|
||||
connection.on('error', () => {
|
||||
cirrusServer = cirrusServers.get(connection);
|
||||
if(cirrusServer) {
|
||||
cirrusServers.delete(connection);
|
||||
console.log(`Cirrus server ${cirrusServer.address}:${cirrusServer.port} disconnected from Matchmaker`);
|
||||
} else {
|
||||
console.log(`Disconnected machine that wasn't a registered cirrus server, remote address: ${connection.remoteAddress}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
matchmaker.listen(config.MatchmakerPort, () => {
|
||||
console.log('Matchmaker listening on *:' + config.MatchmakerPort);
|
||||
});
|
||||
@@ -1,49 +0,0 @@
|
||||
// Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
//-- Provides configuration information from file and combines it with default values and command line arguments --//
|
||||
//-- Hierachy of values: Default Values < Config File < Command Line arguments --//
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const argv = require('yargs').argv;
|
||||
|
||||
function initConfig(configFile, defaultConfig){
|
||||
defaultConfig = defaultConfig || {};
|
||||
|
||||
// Using object spread syntax: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals
|
||||
let config = {...defaultConfig};
|
||||
try{
|
||||
let configData = fs.readFileSync(configFile, 'UTF8');
|
||||
fileConfig = JSON.parse(configData);
|
||||
config = {...config, ...fileConfig}
|
||||
// Update config file with any additional defaults (does not override existing values if default has changed)
|
||||
fs.writeFileSync(configFile, JSON.stringify(config, null, '\t'), 'UTF8');
|
||||
} catch(err) {
|
||||
if (err.code === 'ENOENT') {
|
||||
console.log("No config file found, writing defaults to log file " + configFile);
|
||||
fs.writeFileSync(configFile, JSON.stringify(config, null, '\t'), 'UTF8');
|
||||
} else if (err instanceof SyntaxError) {
|
||||
console.log(`ERROR: Invalid JSON in ${configFile}, ignoring file config, ${err}`)
|
||||
} else {
|
||||
console.log(`ERROR: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
try{
|
||||
//Make a copy of the command line args and remove the unneccessary ones
|
||||
//The _ value is an array of any elements without a key
|
||||
let commandLineConfig = {...argv}
|
||||
delete commandLineConfig._;
|
||||
delete commandLineConfig.help;
|
||||
delete commandLineConfig.version;
|
||||
delete commandLineConfig['$0'];
|
||||
config = {...config, ...commandLineConfig}
|
||||
} catch(err) {
|
||||
console.log(`ERROR: ${err}`);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
init: initConfig
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
// Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
const fs = require('fs');
|
||||
const { Console } = require('console');
|
||||
|
||||
var loggers=[];
|
||||
var logFunctions=[];
|
||||
var logColorFunctions=[];
|
||||
|
||||
console.log = function(msg, ...args) {
|
||||
logFunctions.forEach((logFunction) => {
|
||||
logFunction(msg, ...args);
|
||||
});
|
||||
}
|
||||
|
||||
console.logColor = function(color, msg, ...args) {
|
||||
logColorFunctions.forEach((logColorFunction) => {
|
||||
logColorFunction(color, msg, ...args);
|
||||
});
|
||||
}
|
||||
|
||||
const AllAttributesOff = '\x1b[0m';
|
||||
const BoldOn = '\x1b[1m';
|
||||
const Black = '\x1b[30m';
|
||||
const Red = '\x1b[31m';
|
||||
const Green = '\x1b[32m';
|
||||
const Yellow = '\x1b[33m';
|
||||
const Blue = '\x1b[34m';
|
||||
const Magenta = '\x1b[35m';
|
||||
const Cyan = '\x1b[36m';
|
||||
const White = '\x1b[37m';
|
||||
|
||||
/**
|
||||
* Pad the start of the given number with zeros so it takes up the number of digits.
|
||||
* e.g. zeroPad(5, 3) = '005' and zeroPad(23, 2) = '23'.
|
||||
*/
|
||||
function zeroPad(number, digits) {
|
||||
let string = number.toString();
|
||||
while (string.length < digits) {
|
||||
string = '0' + string;
|
||||
}
|
||||
return string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a string of the form 'YEAR.MONTH.DATE.HOURS.MINUTES.SECONDS'.
|
||||
*/
|
||||
function dateTimeToString() {
|
||||
let date = new Date();
|
||||
return `${date.getFullYear()}.${zeroPad(date.getMonth(), 2)}.${zeroPad(date.getDate(), 2)}.${zeroPad(date.getHours(), 2)}.${zeroPad(date.getMinutes(), 2)}.${zeroPad(date.getSeconds(), 2)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a string of the form 'HOURS.MINUTES.SECONDS.MILLISECONDS'.
|
||||
*/
|
||||
function timeToString() {
|
||||
let date = new Date();
|
||||
return `${zeroPad(date.getHours(), 2)}:${zeroPad(date.getMinutes(), 2)}:${zeroPad(date.getSeconds(), 2)}.${zeroPad(date.getMilliseconds(), 3)}`;
|
||||
}
|
||||
|
||||
function RegisterFileLogger(path) {
|
||||
if(path == null)
|
||||
path = './';
|
||||
|
||||
if (!fs.existsSync(path))
|
||||
fs.mkdirSync(path);
|
||||
|
||||
var output = fs.createWriteStream(`./logs/${dateTimeToString()}.log`);
|
||||
var fileLogger = new Console(output);
|
||||
logFunctions.push(function(msg, ...args) {
|
||||
fileLogger.log(`${timeToString()} ${msg}`, ...args);
|
||||
});
|
||||
|
||||
logColorFunctions.push(function(color, msg, ...args) {
|
||||
fileLogger.log(`${timeToString()} ${msg}`, ...args);
|
||||
});
|
||||
loggers.push(fileLogger);
|
||||
}
|
||||
|
||||
function RegisterConsoleLogger() {
|
||||
var consoleLogger = new Console(process.stdout, process.stderr)
|
||||
logFunctions.push(function(msg, ...args) {
|
||||
consoleLogger.log(`${timeToString()} ${msg}`, ...args);
|
||||
});
|
||||
|
||||
logColorFunctions.push(function(color, msg, ...args) {
|
||||
consoleLogger.log(`${BoldOn}${color}${timeToString()} ${msg}${AllAttributesOff}`, ...args);
|
||||
});
|
||||
loggers.push(consoleLogger);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
//Functions
|
||||
RegisterFileLogger,
|
||||
RegisterConsoleLogger,
|
||||
|
||||
//Variables
|
||||
AllAttributesOff,
|
||||
BoldOn,
|
||||
Black,
|
||||
Red,
|
||||
Green,
|
||||
Yellow,
|
||||
Blue,
|
||||
Magenta,
|
||||
Cyan,
|
||||
White
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"name": "cirrus-matchmaker",
|
||||
"version": "0.0.1",
|
||||
"description": "Cirrus servers connect to the Matchmaker which redirects a browser to the next available Cirrus server",
|
||||
"dependencies": {
|
||||
"cors": "^2.8.5",
|
||||
"express": "^4.18.2",
|
||||
"socket.io": "4.6.0",
|
||||
"yargs": "17.3.1"
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
function log_msg() { #message
|
||||
if [ ! -z $VERBOSE ]; then
|
||||
echo $1
|
||||
fi
|
||||
}
|
||||
|
||||
function print_usage() {
|
||||
echo "
|
||||
Usage:
|
||||
${0} [--help] [--publicip <IP Address>] [--turn <turn server>] [--stun <stun server>] [cirrus options...]
|
||||
Where:
|
||||
--help will print this message and stop this script.
|
||||
--debug will run all scripts with --inspect
|
||||
--nosudo will run all scripts without \`sudo\` command useful for when run in containers.
|
||||
--verbose will enable additional logging
|
||||
--package-manager <package manager name> specify an alternative package manager to apt-get
|
||||
"
|
||||
exit 1
|
||||
}
|
||||
|
||||
function use_args() {
|
||||
while(($#)) ; do
|
||||
case "$1" in
|
||||
--debug ) IS_DEBUG=1; shift;;
|
||||
--nosudo ) NO_SUDO=1; shift;;
|
||||
--verbose ) VERBOSE=1; shift;;
|
||||
--help ) print_usage;;
|
||||
* ) echo "Unknown command"; shift;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
function call_setup_sh() {
|
||||
bash "setup.sh"
|
||||
}
|
||||
|
||||
function start_process() {
|
||||
if [ ! -z $NO_SUDO ]; then
|
||||
log_msg "running with sudo removed"
|
||||
eval $(echo "$@" | sed 's/sudo//g')
|
||||
else
|
||||
eval $@
|
||||
fi
|
||||
}
|
||||
|
||||
function get_version() {
|
||||
local version=$1
|
||||
|
||||
if command -v $version; then
|
||||
version=$($@)
|
||||
fi
|
||||
|
||||
echo $version | sed -E 's/[^0-9.]//g'
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
BASH_LOCATION=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
||||
|
||||
pushd "${BASH_LOCATION}" > /dev/null
|
||||
|
||||
source common_utils.sh
|
||||
|
||||
use_args "$@"
|
||||
call_setup_sh
|
||||
|
||||
process="${BASH_LOCATION}/node/bin/node matchmaker.js"
|
||||
|
||||
pushd ../.. > /dev/null
|
||||
|
||||
echo ""
|
||||
echo "Starting Matchmaker use ctrl-c to exit"
|
||||
echo "-----------------------------------------"
|
||||
echo ""
|
||||
|
||||
start_process $process
|
||||
|
||||
popd > /dev/null # ../..
|
||||
|
||||
popd > /dev/null # BASH_SOURCE
|
||||
@@ -1,114 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
BASH_LOCATION=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
||||
|
||||
pushd "${BASH_LOCATION}" > /dev/null
|
||||
|
||||
source common_utils.sh
|
||||
|
||||
use_args $@
|
||||
# Azure specific fix to allow installing NodeJS from NodeSource
|
||||
if test -f "/etc/apt/sources.list.d/azure-cli.list"; then
|
||||
sudo touch /etc/apt/sources.list.d/nodesource.list
|
||||
sudo touch /usr/share/keyrings/nodesource.gpg
|
||||
sudo chmod 644 /etc/apt/sources.list.d/nodesource.list
|
||||
sudo chmod 644 /usr/share/keyrings/nodesource.gpg
|
||||
sudo chmod 644 /etc/apt/sources.list.d/azure-cli.list
|
||||
fi
|
||||
|
||||
function check_version() { #current_version #min_version
|
||||
#check if same string
|
||||
if [ -z "$2" ] || [ "$1" = "$2" ]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
local i current minimum
|
||||
|
||||
IFS="." read -r -a current <<< $1
|
||||
IFS="." read -r -a minimum <<< $2
|
||||
|
||||
# fill empty fields in current with zeros
|
||||
for ((i=${#current[@]}; i<${#minimum[@]}; i++))
|
||||
do
|
||||
current[i]=0
|
||||
done
|
||||
|
||||
for ((i=0; i<${#current[@]}; i++))
|
||||
do
|
||||
if [[ -z ${minimum[i]} ]]; then
|
||||
# fill empty fields in minimum with zeros
|
||||
minimum[i]=0
|
||||
fi
|
||||
|
||||
if ((10#${current[i]} > 10#${minimum[i]})); then
|
||||
return 1
|
||||
fi
|
||||
|
||||
if ((10#${current[i]} < 10#${minimum[i]})); then
|
||||
return 2
|
||||
fi
|
||||
done
|
||||
|
||||
# if got this far string is the same once we added missing 0
|
||||
return 0
|
||||
}
|
||||
|
||||
function check_and_install() { #dep_name #get_version_string #version_min #install_command
|
||||
local is_installed=0
|
||||
|
||||
log_msg "Checking for required $1 install"
|
||||
|
||||
local current=$(echo $2 | sed -E 's/[^0-9.]//g')
|
||||
local minimum=$(echo $3 | sed -E 's/[^0-9.]//g')
|
||||
|
||||
if [ $# -ne 4 ]; then
|
||||
log_msg "check_and_install expects 4 args (dep_name get_version_string version_min install_command) got $#"
|
||||
return -1
|
||||
fi
|
||||
|
||||
if [ ! -z $current ]; then
|
||||
log_msg "Current version: $current checking >= $minimum"
|
||||
check_version "$current" "$minimum"
|
||||
if [ "$?" -lt 2 ]; then
|
||||
log_msg "$1 is installed."
|
||||
return 0
|
||||
else
|
||||
log_msg "Required install of $1 not found installing"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ $is_installed -ne 1 ]; then
|
||||
echo "$1 installation not found installing..."
|
||||
|
||||
start_process $4
|
||||
|
||||
if [ $? -ge 1 ]; then
|
||||
echo "Installation of $1 failed try running `export VERBOSE=1` then run this script again for more details"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
fi
|
||||
}
|
||||
|
||||
echo "Checking Matchmaker dependencies..."
|
||||
|
||||
# navigate to Matchmaker root
|
||||
pushd ../.. > /dev/null
|
||||
|
||||
node_version=""
|
||||
if [[ -f "${BASH_LOCATION}/node/bin/node" ]]; then
|
||||
node_version=$("${BASH_LOCATION}/node/bin/node" --version)
|
||||
fi
|
||||
check_and_install "node" "$node_version" "v16.4.2" "curl https://nodejs.org/dist/v16.14.2/node-v16.14.2-linux-x64.tar.gz --output node.tar.xz
|
||||
&& tar -xf node.tar.xz
|
||||
&& rm node.tar.xz
|
||||
&& mv node-v*-linux-x64 \"${BASH_LOCATION}/node\""
|
||||
|
||||
PATH="${BASH_LOCATION}/node/bin:$PATH"
|
||||
"${BASH_LOCATION}/node/lib/node_modules/npm/bin/npm-cli.js" install
|
||||
|
||||
popd > /dev/null # Matchmaker
|
||||
|
||||
popd > /dev/null # BASH_SOURCE
|
||||
|
||||
echo "All Matchmaker dependencies up to date."
|
||||
@@ -1,25 +0,0 @@
|
||||
@Rem Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
@echo off
|
||||
|
||||
@Rem Set script directory as working directory.
|
||||
pushd "%~dp0"
|
||||
|
||||
title Matchmaker
|
||||
|
||||
@Rem Run setup to ensure we have node and matchmaker installed.
|
||||
call setup.bat
|
||||
|
||||
@Rem Move to matchmaker.js directory.
|
||||
pushd ..\..
|
||||
|
||||
@Rem Run node server and pass any argument along.
|
||||
platform_scripts\cmd\node\node.exe matchmaker %*
|
||||
|
||||
@Rem Pop matchmaker.js directory.
|
||||
popd
|
||||
|
||||
@Rem Pop script directory.
|
||||
popd
|
||||
|
||||
pause
|
||||
@@ -1,17 +0,0 @@
|
||||
@Rem Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
@echo off
|
||||
|
||||
@Rem Set script location as working directory for commands.
|
||||
pushd "%~dp0"
|
||||
|
||||
@Rem Ensure we have NodeJs available for calling.
|
||||
call setup_node.bat
|
||||
|
||||
@Rem Move to matchmaker.js directory and install its package.json
|
||||
pushd %~dp0\..\..\
|
||||
call platform_scripts\cmd\node\npm install --no-save
|
||||
popd
|
||||
|
||||
@Rem Pop working directory
|
||||
popd
|
||||
@@ -1,35 +0,0 @@
|
||||
@Rem Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
@echo off
|
||||
|
||||
@Rem Set script location as working directory for commands.
|
||||
pushd "%~dp0"
|
||||
|
||||
@Rem Name and version of node that we are downloading
|
||||
SET NodeVersion=v16.4.2
|
||||
SET NodeName=node-%NodeVersion%-win-x64
|
||||
|
||||
@Rem Look for a node directory next to this script
|
||||
if exist node\ (
|
||||
echo Node directory found...skipping install.
|
||||
) else (
|
||||
echo Node directory not found...beginning NodeJS download for Windows.
|
||||
|
||||
@Rem Download nodejs and follow redirects.
|
||||
curl -L -o ./node.zip "https://nodejs.org/dist/%NodeVersion%/%NodeName%.zip"
|
||||
|
||||
@Rem Unarchive the .zip
|
||||
tar -xf node.zip
|
||||
|
||||
@Rem Rename the extracted, versioned, directory that contains the NodeJS binaries to simply "node".
|
||||
ren "%NodeName%\" "node"
|
||||
|
||||
@Rem Delete the downloaded node.zip
|
||||
del node.zip
|
||||
)
|
||||
|
||||
@Rem Print node version
|
||||
echo Node version: & node\node.exe -v
|
||||
|
||||
@Rem Pop working directory
|
||||
popd
|
||||
@@ -1 +0,0 @@
|
||||
node_modules
|
||||
@@ -1,108 +0,0 @@
|
||||
// Parse passed arguments
|
||||
let passedPublicIP = null;
|
||||
for(let arg of process.argv){
|
||||
if(arg && arg.startsWith("--PublicIP=")){
|
||||
let splitArr = arg.split("=");
|
||||
if(splitArr.length == 2){
|
||||
passedPublicIP = splitArr[1];
|
||||
console.log("--PublicIP=" + passedPublicIP);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const config = {
|
||||
signallingURL: "ws://localhost:8889",
|
||||
|
||||
mediasoup: {
|
||||
worker: {
|
||||
rtcMinPort: 40000,
|
||||
rtcMaxPort: 49999,
|
||||
logLevel: "debug",
|
||||
logTags: [
|
||||
"info",
|
||||
"ice",
|
||||
"dtls",
|
||||
"rtp",
|
||||
"srtp",
|
||||
"rtcp",
|
||||
"sctp"
|
||||
// 'rtx',
|
||||
// 'bwe',
|
||||
// 'score',
|
||||
// 'simulcast',
|
||||
// 'svc'
|
||||
],
|
||||
},
|
||||
router: {
|
||||
mediaCodecs: [
|
||||
{
|
||||
kind: "audio",
|
||||
mimeType: "audio/opus",
|
||||
clockRate: 48000,
|
||||
channels: 2,
|
||||
},
|
||||
{
|
||||
kind: 'video',
|
||||
mimeType: 'video/VP8',
|
||||
clockRate: 90000,
|
||||
parameters: {
|
||||
"packetization-mode": 1,
|
||||
"profile-level-id": "42e01f",
|
||||
"level-asymmetry-allowed": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
kind: "video",
|
||||
mimeType: "video/h264",
|
||||
clockRate: 90000,
|
||||
parameters: {
|
||||
"packetization-mode": 1,
|
||||
"profile-level-id": "42e01f",
|
||||
"level-asymmetry-allowed": 1
|
||||
},
|
||||
},
|
||||
|
||||
],
|
||||
},
|
||||
|
||||
// here you must specify ip addresses to listen on
|
||||
// some browsers have issues with connecting to ICE on
|
||||
// localhost so you might have to specify a proper
|
||||
// private or public ip here.
|
||||
webRtcTransport: {
|
||||
listenIps: passedPublicIP != null ? [{ ip: "0.0.0.0", announcedIp: passedPublicIP}] : getLocalListenIps(),
|
||||
// 100 megabits
|
||||
initialAvailableOutgoingBitrate: 100_000_000,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
function getLocalListenIps() {
|
||||
const listenIps = []
|
||||
if (typeof window === 'undefined') {
|
||||
const os = require('os')
|
||||
const networkInterfaces = os.networkInterfaces()
|
||||
const ips = []
|
||||
if (networkInterfaces) {
|
||||
for (const [key, addresses] of Object.entries(networkInterfaces)) {
|
||||
addresses.forEach(address => {
|
||||
if (address.family === 'IPv4') {
|
||||
listenIps.push({ ip: address.address, announcedIp: null })
|
||||
}
|
||||
/* ignore link-local and other special ipv6 addresses.
|
||||
* https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml
|
||||
*/
|
||||
else if (address.family === 'IPv6' && address.address[0] !== 'f') {
|
||||
listenIps.push({ ip: address.address, announcedIp: null })
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
if (listenIps.length === 0) {
|
||||
listenIps.push({ ip: '127.0.0.1', announcedIp: null })
|
||||
}
|
||||
return listenIps
|
||||
}
|
||||
|
||||
module.exports = config;
|
||||
@@ -1,15 +0,0 @@
|
||||
ISC License
|
||||
|
||||
Copyright © 2020, Iñaki Baz Castillo <ibc@aliax.net>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
@@ -1,182 +0,0 @@
|
||||
# mediasoup-sdp-bridge v3
|
||||
|
||||
[![][npm-shield-mediasoup-sdp-bridge]][npm-mediasoup-sdp-bridge]
|
||||
[![][travis-ci-shield-mediasoup-sdp-bridge]][travis-ci-mediasoup-sdp-bridge]
|
||||
|
||||
Node.js library to allow integration of SDP based clients with [mediasoup][mediasoup-website].
|
||||
|
||||
|
||||
## Website and Documentation
|
||||
|
||||
* [mediasoup.org][mediasoup-website]
|
||||
|
||||
|
||||
## Support Forum
|
||||
|
||||
* [mediasoup.discourse.group][mediasoup-discourse]
|
||||
|
||||
|
||||
## Use-Case Design Proposal
|
||||
|
||||
This section contains a use-case that can serve as usage example to guide design of the internal implementation.
|
||||
|
||||
Within the Node.js server app running mediasoup:
|
||||
|
||||
|
||||
### mediasoup receiving media from a remote SDP endpoint
|
||||
|
||||
```typescript
|
||||
import * as SdpBridge from "mediasoup-sdp-bridge";
|
||||
import Signaling from "./my-signaling"; // Our own signaling stuff.
|
||||
|
||||
const transport: Transport = ... // A mediasoup WebRtcTransport or PlainTransport.
|
||||
|
||||
// Create an SdpEndpoint to handle SDP negotiation with the remote endpoint.
|
||||
const sdpEndpoint = await SdpBridge.createSdpEndpoint({
|
||||
transport: transport,
|
||||
});
|
||||
|
||||
// Upon receipt of an SDP Offer from the remote endpoint, apply it.
|
||||
Signaling.on("sdp-offer", async (sdpOffer: string) => {
|
||||
// For each media section in the SDP Offer, SdpEndpoint creates a new Producer
|
||||
// on top of the Transport that was provided.
|
||||
const producers: Producer[] = await sdpEndpoint.processOffer(sdpOffer);
|
||||
|
||||
// Generate an SDP Answer and reply to the remote endpoint with it.
|
||||
const sdpAnswer: string = sdpEndpoint.createAnswer();
|
||||
|
||||
await Signaling.sendAnswer(sdpAnswer);
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
### mediasoup sending media to a remote SDP endpoint
|
||||
|
||||
```typescript
|
||||
import * as SdpBridge from "mediasoup-sdp-bridge";
|
||||
import Signaling from "./my-signaling"; // Our own signaling stuff.
|
||||
|
||||
const transport: Transport = ... // A mediasoup WebRtcTransport or PlainTransport.
|
||||
|
||||
// Create an SdpEndpoint to send media to the remote endpoint.
|
||||
const sdpEndpoint = await createSdpEndpoint({
|
||||
transport: transport,
|
||||
});
|
||||
|
||||
// Listen for the "negotiationneeded" event, to send an SDP Offer to the remote
|
||||
// endpoint. This event is emitted when transport.consume() is called, or when
|
||||
// a Producer being consumed is closed or paused/resumed.
|
||||
sdpEndpoint.on("negotiationneeded", () => {
|
||||
// For each Consumer present in the Transport that was provided,
|
||||
// SdpEndpoint creates a new media section in the SDP Offer.
|
||||
const sdpOffer: string = sdpEndpoint.createOffer();
|
||||
|
||||
// Send the SDP Offer to the remote endpoint.
|
||||
await Signaling.sendOffer(sdpOffer);
|
||||
});
|
||||
|
||||
// Upon receipt of an SDP Answer from the remote endpoint, apply it.
|
||||
Signaling.on("sdp-answer", async (sdpAnswer: string) => {
|
||||
await sdpEndpoint.processAnswer(sdpAnswer);
|
||||
});
|
||||
|
||||
// Generate remote endpoint's RTP capabilities based on a remote SDP or based
|
||||
// on handmade capabilities.
|
||||
const endpointRtpCapabilities = SdpBridge.generateRtpCapabilities(
|
||||
router.rtpCapabilities,
|
||||
remoteSdp
|
||||
);
|
||||
// or:
|
||||
const endpointRtpCapabilities = SdpBridge.generateRtpCapabilities(
|
||||
router.rtpCapabilities,
|
||||
handmadeRtpCapabilities
|
||||
);
|
||||
|
||||
// If there were mediasoup Producers already created in the Router, or if a new
|
||||
// one is created, and we want to consume them in the remote endpoint, tell the
|
||||
// Transport to consume them. transport.consume() method will trigger the
|
||||
// "negotiationneeded" event, handled above.
|
||||
//
|
||||
// NOTE: By calling consume() method in parallel (without waiting for the
|
||||
// previous one to complete) we ensure that the "negotiationneeded" event will
|
||||
// just be emitted once upon completion of all consume() calls, so a single
|
||||
// SDP Offer/Answer roundtrip will be needed.
|
||||
transport
|
||||
.consume({
|
||||
producerId: producer1.id,
|
||||
rtpCapabilities: endpointRtpCapabilities,
|
||||
})
|
||||
.catch((error) => console.error("transport.consume() failed:", error));
|
||||
|
||||
transport
|
||||
.consume({
|
||||
producerId: producer2.id,
|
||||
rtpCapabilities: endpointRtpCapabilities,
|
||||
})
|
||||
.catch((error) => console.error("transport.consume() failed:", error));
|
||||
```
|
||||
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
### Design limitations
|
||||
|
||||
The initial Use-Case Design Proposal lacks an important detail: it uses an `endpointRtpCapabilities` object, which represents the WebRTC and RTP capabilities of the remote endpoint that will receive media from mediasoup. This *RtpCapabilities* object is assumed to be written either by hand, or obtained from a previous SDP message that somehow might have been obtained from the remote endpoint. It is only *after* having these *RtpCapabilities*, that the SDP Offer/Answer process starts.
|
||||
|
||||
All this, however, goes backwards with the normal flow of the SDP Offer/Answer model. **The remote capabilities should be obtained from the SDP Offer/Answer exchange itself**, not as an unspecified out-of-band mechanism. In theory, how the mediasoup application learns about remote capabilities should come from one of these sources:
|
||||
|
||||
1. An SDP Offer (with *recvonly* or *sendrecv* direction) from a remote endpoint that wants to receive media.
|
||||
|
||||
2. An SDP Answer (with *recvonly* or *sendrecv* direction) from a remote endpoint, in response to an SDP Offer (with *sendonly* or *sendrecv* direction) that the application had previously sent.
|
||||
|
||||
However, in practice both of these options conflict with the current design proposal:
|
||||
|
||||
* (1) is not being considered for now. mediasoup is designed around the assumption that the participant sending media should always be the one starting the connection; thus, the endpoint that will send media is also the one sending the SDP Offer.
|
||||
|
||||
* (2) is the ideal but *it's not possible* with the current design, because the remote capabilities must be already known by the time `sdpEndpoint.createOffer()` is called.
|
||||
|
||||
(Note: Additionally, the *sendrecv* direction is also not considered for now. Both the local application or the remote endpoints are be assumed to be either *sendonly* or *recvonly*.)
|
||||
|
||||
|
||||
### Current implementation
|
||||
|
||||
The implementation found in this repo is enough to cover basic usage, but is not complete by any means. Also, it tries to work around the limitations described above, using alternatives that are far from ideal.
|
||||
|
||||
Some notes:
|
||||
|
||||
* Receiving media is the part that works best. It suffices to call `SdpEndpoint.processOffer()`, and this will return one Producer for each media section found in the SDP Offer.
|
||||
|
||||
* Sending media, on the other hand, suffers from the limitation described in (2) above. To work around this, the class `BrowserRtpCapabilities` contains predefined capabilities objects for some of the most common web browsers. These can be used by the application to provide `transport.consume()` with something to work with.
|
||||
|
||||
The obvious drawback to this solution is that the objects in `BrowserRtpCapabilities` must be kept up to date from time to time, in order to accurately represent the actual capabilities of web browsers. To help with this task, there is a handy tool that can be found in the [tools/browser-rtpcapabilities](./tools/browser-rtpcapabilities/) subdirectory.
|
||||
|
||||
* SDP renegotiation is not implemented. The local endpoint cannot make an SDP Re-Offer when the state of the Producers or Consumers changes.
|
||||
|
||||
* There are minor improvements to be done in the implementation.
|
||||
|
||||
- Right now the SdpEndpoint class exports an `SdpEndpoint.addConsumer()` method, which the application uses to provide all Consumers that are created from the corresponding Transport. However, chances are that this is unnecessary: the Transport class already provides an observer event `Transport.observer.on("newconsumer")`, which could be used by the SdpEndpoint to be notified of all new Consumers in its Transport, saving the application the need to provide them explicitly with `addConsumer()`.
|
||||
|
||||
- Some unexpected errors are not handled gracefully, and instead a "BUG" error is logged before the application is forced to exit. These should probably be replaced by a `throw new Error(...)`.
|
||||
|
||||
- Some debug messages are simply commented out to avoid causing too much noise. A proper logging library should be used to allow setting different levels and hiding the less interesting ones.
|
||||
|
||||
- The code hasn't been linted. The default linter rules were left as per the initial commit, but haven't been used yet. For now, the code has just been formatted with the default rules from *Prettier.js*.
|
||||
|
||||
|
||||
## Contributors
|
||||
|
||||
* Iñaki Baz Castillo [[website](https://inakibaz.me)|[github](https://github.com/ibc/)]
|
||||
* Juan Navarro [[github](https://github.com/j1elo)]
|
||||
|
||||
|
||||
## License
|
||||
|
||||
[ISC](./LICENSE)
|
||||
|
||||
|
||||
[mediasoup-website]: https://mediasoup.org
|
||||
[mediasoup-discourse]: https://mediasoup.discourse.group
|
||||
[npm-shield-mediasoup-sdp-bridge]: https://img.shields.io/npm/v/mediasoup-sdp-bridge.svg
|
||||
[npm-mediasoup-sdp-bridge]: https://npmjs.org/package/mediasoup-sdp-bridge
|
||||
[travis-ci-shield-mediasoup-sdp-bridge]: https://travis-ci.com/versatica/mediasoup-sdp-bridge.svg?branch=master
|
||||
[travis-ci-mediasoup-sdp-bridge]: https://travis-ci.com/versatica/mediasoup-sdp-bridge
|
||||
-1182
File diff suppressed because it is too large
Load Diff
@@ -1,89 +0,0 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.sdpToSendRtpParameters = exports.sdpToRecvRtpCapabilities = void 0;
|
||||
const MsRtpUtils = __importStar(require("mediasoup-client/lib/handlers/sdp/unifiedPlanUtils"));
|
||||
const MsSdpUtils = __importStar(require("mediasoup-client/lib/handlers/sdp/commonUtils"));
|
||||
const MsOrtc = __importStar(require("mediasoup-client/lib/ortc"));
|
||||
require("util").inspect.defaultOptions.depth = null;
|
||||
function sdpToRecvRtpCapabilities(sdpObject, localCaps) {
|
||||
const caps = MsSdpUtils.extractRtpCapabilities({
|
||||
sdpObject,
|
||||
});
|
||||
try {
|
||||
MsOrtc.validateRtpCapabilities(caps);
|
||||
}
|
||||
catch (err) {
|
||||
console.error("FIXME BUG:", err);
|
||||
process.exit(1);
|
||||
}
|
||||
const extendedCaps = MsOrtc.getExtendedRtpCapabilities(caps, localCaps);
|
||||
const recvCaps = MsOrtc.getRecvRtpCapabilities(extendedCaps);
|
||||
{
|
||||
}
|
||||
return recvCaps;
|
||||
}
|
||||
exports.sdpToRecvRtpCapabilities = sdpToRecvRtpCapabilities;
|
||||
function sdpToSendRtpParameters(sdpObject, sdpMediaObj, localCaps, kind) {
|
||||
var _a;
|
||||
const caps = MsSdpUtils.extractRtpCapabilities({
|
||||
sdpObject,
|
||||
});
|
||||
try {
|
||||
MsOrtc.validateRtpCapabilities(caps);
|
||||
}
|
||||
catch (err) {
|
||||
console.error("FIXME BUG:", err);
|
||||
process.exit(1);
|
||||
}
|
||||
const extendedCaps = MsOrtc.getExtendedRtpCapabilities(caps, localCaps);
|
||||
const sendParams = MsOrtc.getSendingRemoteRtpParameters(kind, extendedCaps);
|
||||
// const sdpMediaObj = (sdpObject.media || []).find((m) => m.type === kind) ||
|
||||
// {};
|
||||
if ("mid" in sdpMediaObj) {
|
||||
sendParams.mid = String(sdpMediaObj.mid);
|
||||
}
|
||||
else {
|
||||
sendParams.mid = kind === "audio" ? "0" : "1";
|
||||
}
|
||||
if ("rids" in sdpMediaObj) {
|
||||
for (const mediaRid of sdpMediaObj.rids) {
|
||||
(_a = sendParams.encodings) === null || _a === void 0 ? void 0 : _a.push({ rid: mediaRid.id });
|
||||
}
|
||||
}
|
||||
else {
|
||||
// sendParams.encodings = MsRtpUtils.getRtpEncodings({
|
||||
// sdpObject,
|
||||
// kind,
|
||||
// });
|
||||
sendParams.encodings = MsRtpUtils.getRtpEncodings({ offerMediaObject: sdpMediaObj });
|
||||
}
|
||||
sendParams.rtcp = {
|
||||
cname: MsSdpUtils.getCname({ offerMediaObject: sdpMediaObj }),
|
||||
reducedSize: "rtcpRsize" in sdpMediaObj && sdpMediaObj.rtcpRsize,
|
||||
mux: "rtcpMux" in sdpMediaObj && sdpMediaObj.rtcpMux,
|
||||
};
|
||||
{
|
||||
}
|
||||
return sendParams;
|
||||
}
|
||||
exports.sdpToSendRtpParameters = sdpToSendRtpParameters;
|
||||
//# sourceMappingURL=SdpUtils.js.map
|
||||
@@ -1,198 +0,0 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.generateRtpCapabilities2 = exports.generateRtpCapabilities1 = exports.generateRtpCapabilities0 = exports.createSdpEndpoint = exports.SdpEndpoint = void 0;
|
||||
const MsSdpUtils = __importStar(require("mediasoup-client/lib/handlers/sdp/commonUtils"));
|
||||
const RemoteSdp_1 = require("mediasoup-client/lib/handlers/sdp/RemoteSdp");
|
||||
const SdpTransform = __importStar(require("sdp-transform"));
|
||||
const uuid_1 = require("uuid");
|
||||
const BrowserRtpCapabilities = __importStar(require("./BrowserRtpCapabilities"));
|
||||
const SdpUtils = __importStar(require("./SdpUtils"));
|
||||
const MediaSection_1 = require("mediasoup-client/lib/handlers/sdp/MediaSection");
|
||||
require("util").inspect.defaultOptions.depth = null;
|
||||
class SdpEndpoint {
|
||||
constructor(webRtcTransport, localCaps) {
|
||||
this.producers = [];
|
||||
this.producerMedias = [];
|
||||
this.consumers = [];
|
||||
this.webRtcTransport = webRtcTransport;
|
||||
this.transport = webRtcTransport;
|
||||
this.localCaps = localCaps;
|
||||
this.sctpMedia = null;
|
||||
this.consumeData = false;
|
||||
}
|
||||
async processOffer(sdpOffer) {
|
||||
if (this.remoteSdp) {
|
||||
console.error("[SdpEndpoint.processOffer] ERROR: A remote description was already set");
|
||||
return [];
|
||||
}
|
||||
this.remoteSdp = sdpOffer;
|
||||
const remoteSdpObj = SdpTransform.parse(sdpOffer);
|
||||
await this.webRtcTransport.connect({
|
||||
dtlsParameters: MsSdpUtils.extractDtlsParameters({
|
||||
sdpObject: remoteSdpObj,
|
||||
}),
|
||||
});
|
||||
for (const media of remoteSdpObj.media) {
|
||||
if (media.type == "application") {
|
||||
this.sctpMedia = media;
|
||||
console.log("[SdpEndpoint.processOffer] SCTP association received");
|
||||
}
|
||||
else {
|
||||
if (!("rtp" in media)) {
|
||||
continue;
|
||||
}
|
||||
if (!("direction" in media)) {
|
||||
continue;
|
||||
}
|
||||
if (media.direction !== "sendonly") {
|
||||
continue;
|
||||
}
|
||||
const sendParams = SdpUtils.sdpToSendRtpParameters(remoteSdpObj, media, this.localCaps, media.type);
|
||||
let producer;
|
||||
try {
|
||||
producer = await this.transport.produce({
|
||||
kind: media.type,
|
||||
rtpParameters: sendParams,
|
||||
paused: false,
|
||||
});
|
||||
}
|
||||
catch (err) {
|
||||
console.error("FIXME BUG:", err);
|
||||
process.exit(1);
|
||||
}
|
||||
this.producers.push(producer);
|
||||
this.producerMedias.push(media);
|
||||
console.log("[SdpEndpoint.processOffer] mediasoup Producer created, kind: %s, type: %s, paused: %s", producer.kind, producer.type, producer.paused);
|
||||
}
|
||||
}
|
||||
return this.producers;
|
||||
}
|
||||
createAnswer() {
|
||||
if (this.localSdp) {
|
||||
console.error("[SdpEndpoint.createAnswer] ERROR: A local description was already set");
|
||||
return "";
|
||||
}
|
||||
const sdpBuilder = new RemoteSdp_1.RemoteSdp({
|
||||
iceParameters: this.webRtcTransport.iceParameters,
|
||||
iceCandidates: this.webRtcTransport.iceCandidates,
|
||||
dtlsParameters: this.webRtcTransport.dtlsParameters,
|
||||
sctpParameters: this.webRtcTransport.sctpParameters,
|
||||
planB: false,
|
||||
});
|
||||
console.log("[SdpEndpoint.createAnswer] Make 'recvonly' SDP Answer");
|
||||
for (let i = 0; i < this.producers.length; i++) {
|
||||
const sdpMediaObj = this.producerMedias[i];
|
||||
const recvParams = this.producers[i].rtpParameters;
|
||||
sdpBuilder.send({
|
||||
offerMediaObject: sdpMediaObj,
|
||||
reuseMid: undefined,
|
||||
offerRtpParameters: recvParams,
|
||||
answerRtpParameters: recvParams,
|
||||
codecOptions: undefined,
|
||||
extmapAllowMixed: false,
|
||||
});
|
||||
}
|
||||
if (this.sctpMedia != null) {
|
||||
sdpBuilder.sendSctpAssociation({offerMediaObject: this.sctpMedia});
|
||||
}
|
||||
this.localSdp = sdpBuilder.getSdp();
|
||||
return this.localSdp;
|
||||
}
|
||||
addConsumer(consumer) {
|
||||
this.consumers.push(consumer);
|
||||
}
|
||||
addConsumeData() {
|
||||
this.consumeData = true;
|
||||
}
|
||||
createOffer() {
|
||||
var _a;
|
||||
if (this.localSdp) {
|
||||
console.error("[SdpEndpoint.createOffer] ERROR: A local description was already set");
|
||||
return "";
|
||||
}
|
||||
const sdpBuilder = new RemoteSdp_1.RemoteSdp({
|
||||
iceParameters: this.webRtcTransport.iceParameters,
|
||||
iceCandidates: this.webRtcTransport.iceCandidates,
|
||||
dtlsParameters: this.webRtcTransport.dtlsParameters,
|
||||
sctpParameters: this.webRtcTransport.sctpParameters,
|
||||
planB: false,
|
||||
});
|
||||
const sendMsid = uuid_1.v4().substr(0, 8);
|
||||
console.log("[SdpEndpoint.createOffer] Make 'sendonly' SDP Offer");
|
||||
for (let i = 0; i < this.consumers.length; i++) {
|
||||
const mid = (_a = this.consumers[i].rtpParameters.mid) !== null && _a !== void 0 ? _a : "nomid";
|
||||
const kind = this.consumers[i].kind;
|
||||
const sendParams = this.consumers[i].rtpParameters;
|
||||
sdpBuilder.receive({
|
||||
mid,
|
||||
kind,
|
||||
offerRtpParameters: sendParams,
|
||||
streamId: sendMsid,
|
||||
trackId: `${sendMsid}-${kind}`,
|
||||
});
|
||||
}
|
||||
if (this.consumeData) {
|
||||
sdpBuilder.receiveSctpAssociation();
|
||||
}
|
||||
this.localSdp = sdpBuilder.getSdp();
|
||||
return this.localSdp;
|
||||
}
|
||||
async processAnswer(sdpAnswer) {
|
||||
if (this.remoteSdp) {
|
||||
console.error("[SdpEndpoint.processAnswer] ERROR: A remote description was already set");
|
||||
return;
|
||||
}
|
||||
this.remoteSdp = sdpAnswer;
|
||||
const remoteSdpObj = SdpTransform.parse(sdpAnswer);
|
||||
await this.webRtcTransport.connect({
|
||||
dtlsParameters: MsSdpUtils.extractDtlsParameters({
|
||||
sdpObject: remoteSdpObj,
|
||||
}),
|
||||
});
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.SdpEndpoint = SdpEndpoint;
|
||||
function createSdpEndpoint(webRtcTransport, localCaps) {
|
||||
return new SdpEndpoint(webRtcTransport, localCaps);
|
||||
}
|
||||
exports.createSdpEndpoint = createSdpEndpoint;
|
||||
function generateRtpCapabilities0() {
|
||||
return BrowserRtpCapabilities.chrome;
|
||||
}
|
||||
exports.generateRtpCapabilities0 = generateRtpCapabilities0;
|
||||
function generateRtpCapabilities1(localCaps, remoteSdp) {
|
||||
console.error("[SdpEndpoint.generateRtpCapabilities1] BUG: Not implemented");
|
||||
process.exit(1);
|
||||
let caps;
|
||||
return caps;
|
||||
}
|
||||
exports.generateRtpCapabilities1 = generateRtpCapabilities1;
|
||||
function generateRtpCapabilities2(localCaps, remoteCaps) {
|
||||
console.error("[SdpEndpoint.generateRtpCapabilities2] BUG: Not implemented");
|
||||
process.exit(1);
|
||||
let caps;
|
||||
return caps;
|
||||
}
|
||||
exports.generateRtpCapabilities2 = generateRtpCapabilities2;
|
||||
//# sourceMappingURL=index.js.map
|
||||
@@ -1,27 +0,0 @@
|
||||
{
|
||||
"name": "mediasoup-sdp-bridge",
|
||||
"version": "3.6.5",
|
||||
"description": "Node.js library to allow integration of SDP based clients with mediasoup",
|
||||
"contributors": [
|
||||
"Iñaki Baz Castillo <ibc@aliax.net> (https://inakibaz.me)",
|
||||
"Juan Navarro <juan.navarro@gmx.es> (https://github.com/j1elo)"
|
||||
],
|
||||
"homepage": "https://mediasoup.org",
|
||||
"license": "ISC",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/versatica/mediasoup-sdp-bridge.git"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/mediasoup"
|
||||
},
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/index.d.ts",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"dependencies": {
|
||||
"mediasoup-client": "^3.6.41"
|
||||
}
|
||||
}
|
||||
-383
@@ -1,383 +0,0 @@
|
||||
{
|
||||
"name": "pixelstreaming-sfu",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "pixelstreaming-sfu",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"mediasoup_prebuilt": "^3.8.4",
|
||||
"mediasoup-sdp-bridge": "file:mediasoup-sdp-bridge",
|
||||
"run-script-os": "^1.1.6",
|
||||
"ws": "^7.1.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/debug": {
|
||||
"version": "4.1.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.7.tgz",
|
||||
"integrity": "sha512-9AonUzyTjXXhEOa0DnqpzZi6VHlqKMswga9EXjpXnnqxwLtdvPPtlO8evrI5D9S6asFRCQ6v+wpiUKbw+vKqyg==",
|
||||
"dependencies": {
|
||||
"@types/ms": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/events": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/events/-/events-3.0.0.tgz",
|
||||
"integrity": "sha512-EaObqwIvayI5a8dCzhFrjKzVwKLxjoG9T6Ppd5CEo07LRKfQ8Yokw54r5+Wq7FaBQ+yXRvQAYPrHwya1/UFt9g=="
|
||||
},
|
||||
"node_modules/@types/ms": {
|
||||
"version": "0.7.31",
|
||||
"resolved": "https://registry.npmjs.org/@types/ms/-/ms-0.7.31.tgz",
|
||||
"integrity": "sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA=="
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "16.11.10",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-16.11.10.tgz",
|
||||
"integrity": "sha512-3aRnHa1KlOEEhJ6+CvyHKK5vE9BcLGjtUpwvqYLRvYNQKMfabu3BwfJaA/SLW8dxe28LsNDjtHwePTuzn3gmOA=="
|
||||
},
|
||||
"node_modules/awaitqueue": {
|
||||
"version": "2.3.3",
|
||||
"resolved": "https://registry.npmjs.org/awaitqueue/-/awaitqueue-2.3.3.tgz",
|
||||
"integrity": "sha512-RbzQg6VtPUtyErm55iuQLTrBJ2uihy5BKBOEkyBwv67xm5Fn2o/j+Bz+a5BmfSoe2oZ5dcz9Z3fExS8pL+LLhw==",
|
||||
"engines": {
|
||||
"node": ">=8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/bowser": {
|
||||
"version": "2.11.0",
|
||||
"resolved": "https://registry.npmjs.org/bowser/-/bowser-2.11.0.tgz",
|
||||
"integrity": "sha512-AlcaJBi/pqqJBIQ8U9Mcpc9i8Aqxn88Skv5d+xBX006BY5u8N3mGLHa5Lgppa7L/HfwgwLgZ6NYs+Ag6uUmJRA=="
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "4.3.2",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz",
|
||||
"integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==",
|
||||
"dependencies": {
|
||||
"ms": "2.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"supports-color": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/event-target-shim": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
|
||||
"integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/events": {
|
||||
"version": "3.3.0",
|
||||
"resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
|
||||
"integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
|
||||
"engines": {
|
||||
"node": ">=0.8.x"
|
||||
}
|
||||
},
|
||||
"node_modules/fake-mediastreamtrack": {
|
||||
"version": "1.1.6",
|
||||
"resolved": "https://registry.npmjs.org/fake-mediastreamtrack/-/fake-mediastreamtrack-1.1.6.tgz",
|
||||
"integrity": "sha512-lcoO5oPsW57istAsnjvQxNjBEahi18OdUhWfmEewwfPfzNZnji5OXuodQM+VnUPi/1HnQRJ6gBUjbt1TNXrkjQ==",
|
||||
"dependencies": {
|
||||
"event-target-shim": "^5.0.1",
|
||||
"uuid": "^8.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/h264-profile-level-id": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/h264-profile-level-id/-/h264-profile-level-id-1.0.1.tgz",
|
||||
"integrity": "sha512-D3Rln/jKNjKDW5ZTJTK3niSoOGE+pFqPvRHHVgQN3G7umcn/zWGPUo8Q8VpDj16x3hKz++zVviRNRmXu5cpN+Q==",
|
||||
"dependencies": {
|
||||
"debug": "^4.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/mediasoup_prebuilt": {
|
||||
"version": "3.8.4",
|
||||
"resolved": "https://registry.npmjs.org/mediasoup_prebuilt/-/mediasoup_prebuilt-3.8.4.tgz",
|
||||
"integrity": "sha512-IdPcuT3YTJXNFYAY4JuIy8sZ88qagKPg2dR8d4USR5csTvC+qOq9wAIywO+u2lxLjePHJH+Y8UBM3kKfyU6Uug==",
|
||||
"dependencies": {
|
||||
"@types/node": "^16.9.1",
|
||||
"awaitqueue": "^2.3.3",
|
||||
"debug": "^4.3.2",
|
||||
"h264-profile-level-id": "^1.0.1",
|
||||
"netstring": "^0.3.0",
|
||||
"random-number": "^0.0.9",
|
||||
"supports-color": "^9.0.2",
|
||||
"uuid": "^8.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/mediasoup-client": {
|
||||
"version": "3.6.46",
|
||||
"resolved": "https://registry.npmjs.org/mediasoup-client/-/mediasoup-client-3.6.46.tgz",
|
||||
"integrity": "sha512-Dv8RxCa1cjSPrKWGf1mnypU5TiQCnrOIy4JpZwwjRQzEtCukCfV1zQabij6BigrtkI+l22ui3fl67Mmm4I0XCA==",
|
||||
"dependencies": {
|
||||
"@types/debug": "^4.1.7",
|
||||
"@types/events": "^3.0.0",
|
||||
"awaitqueue": "^2.3.3",
|
||||
"bowser": "^2.11.0",
|
||||
"debug": "^4.3.2",
|
||||
"events": "^3.3.0",
|
||||
"fake-mediastreamtrack": "^1.1.6",
|
||||
"h264-profile-level-id": "^1.0.1",
|
||||
"sdp-transform": "^2.14.1",
|
||||
"supports-color": "^9.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/mediasoup"
|
||||
}
|
||||
},
|
||||
"node_modules/mediasoup-sdp-bridge": {
|
||||
"version": "3.6.5",
|
||||
"resolved": "file:mediasoup-sdp-bridge",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"mediasoup-client": "^3.6.41"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/mediasoup"
|
||||
}
|
||||
},
|
||||
"node_modules/ms": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
|
||||
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
|
||||
},
|
||||
"node_modules/netstring": {
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://registry.npmjs.org/netstring/-/netstring-0.3.0.tgz",
|
||||
"integrity": "sha1-ho3FsgxY0/cwVTHUk2jqqr0ZtxI=",
|
||||
"engines": {
|
||||
"node": ">=0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/random-number": {
|
||||
"version": "0.0.9",
|
||||
"resolved": "https://registry.npmjs.org/random-number/-/random-number-0.0.9.tgz",
|
||||
"integrity": "sha512-ipG3kRCREi/YQpi2A5QGcvDz1KemohovWmH6qGfboVyyGdR2t/7zQz0vFxrfxpbHQgPPdtVlUDaks3aikD1Ljw=="
|
||||
},
|
||||
"node_modules/run-script-os": {
|
||||
"version": "1.1.6",
|
||||
"resolved": "https://registry.npmjs.org/run-script-os/-/run-script-os-1.1.6.tgz",
|
||||
"integrity": "sha512-ql6P2LzhBTTDfzKts+Qo4H94VUKpxKDFz6QxxwaUZN0mwvi7L3lpOI7BqPCq7lgDh3XLl0dpeXwfcVIitlrYrw==",
|
||||
"bin": {
|
||||
"run-os": "index.js",
|
||||
"run-script-os": "index.js"
|
||||
}
|
||||
},
|
||||
"node_modules/sdp-transform": {
|
||||
"version": "2.14.1",
|
||||
"resolved": "https://registry.npmjs.org/sdp-transform/-/sdp-transform-2.14.1.tgz",
|
||||
"integrity": "sha512-RjZyX3nVwJyCuTo5tGPx+PZWkDMCg7oOLpSlhjDdZfwUoNqG1mM8nyj31IGHyaPWXhjbP7cdK3qZ2bmkJ1GzRw==",
|
||||
"bin": {
|
||||
"sdp-verify": "checker.js"
|
||||
}
|
||||
},
|
||||
"node_modules/supports-color": {
|
||||
"version": "9.1.0",
|
||||
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-9.1.0.tgz",
|
||||
"integrity": "sha512-lOCGOTmBSN54zKAoPWhHkjoqVQ0MqgzPE5iirtoSixhr0ZieR/6l7WZ32V53cvy9+1qghFnIk7k52p991lKd6g==",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/chalk/supports-color?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/uuid": {
|
||||
"version": "8.3.2",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
|
||||
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
|
||||
"bin": {
|
||||
"uuid": "dist/bin/uuid"
|
||||
}
|
||||
},
|
||||
"node_modules/ws": {
|
||||
"version": "7.5.6",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-7.5.6.tgz",
|
||||
"integrity": "sha512-6GLgCqo2cy2A2rjCNFlxQS6ZljG/coZfZXclldI8FB/1G3CCI36Zd8xy2HrFVACi8tfk5XrgLQEk+P0Tnz9UcA==",
|
||||
"engines": {
|
||||
"node": ">=8.3.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"bufferutil": "^4.0.1",
|
||||
"utf-8-validate": "^5.0.2"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"bufferutil": {
|
||||
"optional": true
|
||||
},
|
||||
"utf-8-validate": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@types/debug": {
|
||||
"version": "4.1.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.7.tgz",
|
||||
"integrity": "sha512-9AonUzyTjXXhEOa0DnqpzZi6VHlqKMswga9EXjpXnnqxwLtdvPPtlO8evrI5D9S6asFRCQ6v+wpiUKbw+vKqyg==",
|
||||
"requires": {
|
||||
"@types/ms": "*"
|
||||
}
|
||||
},
|
||||
"@types/events": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/events/-/events-3.0.0.tgz",
|
||||
"integrity": "sha512-EaObqwIvayI5a8dCzhFrjKzVwKLxjoG9T6Ppd5CEo07LRKfQ8Yokw54r5+Wq7FaBQ+yXRvQAYPrHwya1/UFt9g=="
|
||||
},
|
||||
"@types/ms": {
|
||||
"version": "0.7.31",
|
||||
"resolved": "https://registry.npmjs.org/@types/ms/-/ms-0.7.31.tgz",
|
||||
"integrity": "sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA=="
|
||||
},
|
||||
"@types/node": {
|
||||
"version": "16.11.10",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-16.11.10.tgz",
|
||||
"integrity": "sha512-3aRnHa1KlOEEhJ6+CvyHKK5vE9BcLGjtUpwvqYLRvYNQKMfabu3BwfJaA/SLW8dxe28LsNDjtHwePTuzn3gmOA=="
|
||||
},
|
||||
"awaitqueue": {
|
||||
"version": "2.3.3",
|
||||
"resolved": "https://registry.npmjs.org/awaitqueue/-/awaitqueue-2.3.3.tgz",
|
||||
"integrity": "sha512-RbzQg6VtPUtyErm55iuQLTrBJ2uihy5BKBOEkyBwv67xm5Fn2o/j+Bz+a5BmfSoe2oZ5dcz9Z3fExS8pL+LLhw=="
|
||||
},
|
||||
"bowser": {
|
||||
"version": "2.11.0",
|
||||
"resolved": "https://registry.npmjs.org/bowser/-/bowser-2.11.0.tgz",
|
||||
"integrity": "sha512-AlcaJBi/pqqJBIQ8U9Mcpc9i8Aqxn88Skv5d+xBX006BY5u8N3mGLHa5Lgppa7L/HfwgwLgZ6NYs+Ag6uUmJRA=="
|
||||
},
|
||||
"debug": {
|
||||
"version": "4.3.2",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz",
|
||||
"integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==",
|
||||
"requires": {
|
||||
"ms": "2.1.2"
|
||||
}
|
||||
},
|
||||
"event-target-shim": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
|
||||
"integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="
|
||||
},
|
||||
"events": {
|
||||
"version": "3.3.0",
|
||||
"resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
|
||||
"integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q=="
|
||||
},
|
||||
"fake-mediastreamtrack": {
|
||||
"version": "1.1.6",
|
||||
"resolved": "https://registry.npmjs.org/fake-mediastreamtrack/-/fake-mediastreamtrack-1.1.6.tgz",
|
||||
"integrity": "sha512-lcoO5oPsW57istAsnjvQxNjBEahi18OdUhWfmEewwfPfzNZnji5OXuodQM+VnUPi/1HnQRJ6gBUjbt1TNXrkjQ==",
|
||||
"requires": {
|
||||
"event-target-shim": "^5.0.1",
|
||||
"uuid": "^8.1.0"
|
||||
}
|
||||
},
|
||||
"h264-profile-level-id": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/h264-profile-level-id/-/h264-profile-level-id-1.0.1.tgz",
|
||||
"integrity": "sha512-D3Rln/jKNjKDW5ZTJTK3niSoOGE+pFqPvRHHVgQN3G7umcn/zWGPUo8Q8VpDj16x3hKz++zVviRNRmXu5cpN+Q==",
|
||||
"requires": {
|
||||
"debug": "^4.1.1"
|
||||
}
|
||||
},
|
||||
"mediasoup_prebuilt": {
|
||||
"version": "3.8.4",
|
||||
"resolved": "https://registry.npmjs.org/mediasoup_prebuilt/-/mediasoup_prebuilt-3.8.4.tgz",
|
||||
"integrity": "sha512-IdPcuT3YTJXNFYAY4JuIy8sZ88qagKPg2dR8d4USR5csTvC+qOq9wAIywO+u2lxLjePHJH+Y8UBM3kKfyU6Uug==",
|
||||
"requires": {
|
||||
"@types/node": "^16.9.1",
|
||||
"awaitqueue": "^2.3.3",
|
||||
"debug": "^4.3.2",
|
||||
"h264-profile-level-id": "^1.0.1",
|
||||
"netstring": "^0.3.0",
|
||||
"random-number": "^0.0.9",
|
||||
"supports-color": "^9.0.2",
|
||||
"uuid": "^8.3.2"
|
||||
}
|
||||
},
|
||||
"mediasoup-client": {
|
||||
"version": "3.6.46",
|
||||
"resolved": "https://registry.npmjs.org/mediasoup-client/-/mediasoup-client-3.6.46.tgz",
|
||||
"integrity": "sha512-Dv8RxCa1cjSPrKWGf1mnypU5TiQCnrOIy4JpZwwjRQzEtCukCfV1zQabij6BigrtkI+l22ui3fl67Mmm4I0XCA==",
|
||||
"requires": {
|
||||
"@types/debug": "^4.1.7",
|
||||
"@types/events": "^3.0.0",
|
||||
"awaitqueue": "^2.3.3",
|
||||
"bowser": "^2.11.0",
|
||||
"debug": "^4.3.2",
|
||||
"events": "^3.3.0",
|
||||
"fake-mediastreamtrack": "^1.1.6",
|
||||
"h264-profile-level-id": "^1.0.1",
|
||||
"sdp-transform": "^2.14.1",
|
||||
"supports-color": "^9.1.0"
|
||||
}
|
||||
},
|
||||
"mediasoup-sdp-bridge": {
|
||||
"version": "3.6.5",
|
||||
"requires": {
|
||||
"mediasoup-client": "^3.6.41"
|
||||
}
|
||||
},
|
||||
"ms": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
|
||||
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
|
||||
},
|
||||
"netstring": {
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://registry.npmjs.org/netstring/-/netstring-0.3.0.tgz",
|
||||
"integrity": "sha1-ho3FsgxY0/cwVTHUk2jqqr0ZtxI="
|
||||
},
|
||||
"random-number": {
|
||||
"version": "0.0.9",
|
||||
"resolved": "https://registry.npmjs.org/random-number/-/random-number-0.0.9.tgz",
|
||||
"integrity": "sha512-ipG3kRCREi/YQpi2A5QGcvDz1KemohovWmH6qGfboVyyGdR2t/7zQz0vFxrfxpbHQgPPdtVlUDaks3aikD1Ljw=="
|
||||
},
|
||||
"run-script-os": {
|
||||
"version": "1.1.6",
|
||||
"resolved": "https://registry.npmjs.org/run-script-os/-/run-script-os-1.1.6.tgz",
|
||||
"integrity": "sha512-ql6P2LzhBTTDfzKts+Qo4H94VUKpxKDFz6QxxwaUZN0mwvi7L3lpOI7BqPCq7lgDh3XLl0dpeXwfcVIitlrYrw=="
|
||||
},
|
||||
"sdp-transform": {
|
||||
"version": "2.14.1",
|
||||
"resolved": "https://registry.npmjs.org/sdp-transform/-/sdp-transform-2.14.1.tgz",
|
||||
"integrity": "sha512-RjZyX3nVwJyCuTo5tGPx+PZWkDMCg7oOLpSlhjDdZfwUoNqG1mM8nyj31IGHyaPWXhjbP7cdK3qZ2bmkJ1GzRw=="
|
||||
},
|
||||
"supports-color": {
|
||||
"version": "9.1.0",
|
||||
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-9.1.0.tgz",
|
||||
"integrity": "sha512-lOCGOTmBSN54zKAoPWhHkjoqVQ0MqgzPE5iirtoSixhr0ZieR/6l7WZ32V53cvy9+1qghFnIk7k52p991lKd6g=="
|
||||
},
|
||||
"uuid": {
|
||||
"version": "8.3.2",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
|
||||
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="
|
||||
},
|
||||
"ws": {
|
||||
"version": "7.5.6",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-7.5.6.tgz",
|
||||
"integrity": "sha512-6GLgCqo2cy2A2rjCNFlxQS6ZljG/coZfZXclldI8FB/1G3CCI36Zd8xy2HrFVACi8tfk5XrgLQEk+P0Tnz9UcA==",
|
||||
"requires": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
{
|
||||
"name": "pixelstreaming-sfu",
|
||||
"version": "1.0.0",
|
||||
"description": "Reference implementation for a PixelStreaming SFU",
|
||||
"scripts": {
|
||||
"start-local": "run-script-os --",
|
||||
"start-local:windows": ".\\platform_scripts\\cmd\\run.bat",
|
||||
"start-local:default": "./platform_scripts/bash/run_local.sh",
|
||||
"start-cloud": "run-script-os --",
|
||||
"start-cloud:windows": ".\\platform_scripts\\cmd\\run_cloud.bat",
|
||||
"start-cloud:default": "./platform_scripts/bash/run_cloud.sh",
|
||||
"start": "run-script-os",
|
||||
"start:windows": "platform_scripts\\cmd\\node\\node.exe sfu_server.js",
|
||||
"start:default": "if [ `id -u` -eq 0 ]\nthen\n export process=\"./platform_scripts/bash/node/bin/node sfu_server.js\"\nelse\n export process=\"sudo ./platform_scripts/bash/node/bin/node sfu_server.js\"\nfi\n$process "
|
||||
|
||||
},
|
||||
"dependencies": {
|
||||
"mediasoup-sdp-bridge": "file:mediasoup-sdp-bridge",
|
||||
"ws": "^7.1.2",
|
||||
"mediasoup_prebuilt": "^3.8.4",
|
||||
"run-script-os": "^1.1.6"
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
FROM node:latest
|
||||
|
||||
# Make sure Mediasoup requirements are met
|
||||
RUN apt -y update
|
||||
RUN apt -y install python3-pip
|
||||
|
||||
# Copy the Selective Forwarding Unit (SFU) to the Docker build context
|
||||
COPY . /opt/SFU
|
||||
|
||||
# Install the dependencies for the mediasoup server
|
||||
WORKDIR /opt/SFU
|
||||
RUN npm update
|
||||
RUN npm install .
|
||||
|
||||
# Expose TCP port 80 for player WebSocket connections and web server HTTP access
|
||||
EXPOSE 40000-49999
|
||||
|
||||
# Expose TCP port 8888 for streamer WebSocket connections
|
||||
EXPOSE 8889
|
||||
|
||||
# Set the signalling server as the container's entrypoint
|
||||
ENTRYPOINT ["/usr/local/bin/node", "/opt/SFU/sfu_server.js"]
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
function log_msg() { #message
|
||||
if [ ! -z $VERBOSE ]; then
|
||||
echo $1
|
||||
fi
|
||||
}
|
||||
|
||||
function print_usage() {
|
||||
echo "
|
||||
Usage:
|
||||
${0} [--help] [--publicip <IP Address>] [sfu options...]
|
||||
Where:
|
||||
--help will print this message and stop this script.
|
||||
--debug will run all scripts with --inspect
|
||||
--nosudo will run all scripts without \`sudo\` command useful for when run in containers.
|
||||
--verbose will enable additional logging
|
||||
--package-manager <package manager name> specify an alternative package manager to apt-get
|
||||
--publicip is used to define public ip address (using default port) for turn server, syntax: --publicip ; it is used for
|
||||
default value: Retrieved from 'curl https://api.ipify.org' or if unsuccessful then set to 127.0.0.1. It is the IP address of the SFU
|
||||
Other options: stored and passed to the SFU. All parameters printed once the script values are set.
|
||||
"
|
||||
exit 1
|
||||
}
|
||||
|
||||
function print_parameters() {
|
||||
echo ""
|
||||
echo "${0} is running with the following parameters:"
|
||||
echo "--------------------------------------"
|
||||
echo "Public IP address : ${publicip}"
|
||||
echo "SFU command line arguments: ${sfucmd}"
|
||||
echo ""
|
||||
}
|
||||
|
||||
function set_start_default_values() {
|
||||
# publicip and sfucmd are always needed
|
||||
publicip=$(curl -s https://api.ipify.org)
|
||||
if [[ -z $publicip ]]; then
|
||||
publicip="127.0.0.1"
|
||||
fi
|
||||
|
||||
sfucmd=""
|
||||
}
|
||||
|
||||
function use_args() {
|
||||
while(($#)) ; do
|
||||
case "$1" in
|
||||
--debug ) IS_DEBUG=1; shift;;
|
||||
--nosudo ) NO_SUDO=1; shift;;
|
||||
--verbose ) VERBOSE=1; shift;;
|
||||
--publicip ) publicip="$2"; shift 2;;
|
||||
--help ) print_usage;;
|
||||
* ) echo "Unknown command, adding to SFU command line: $1"; sfucmd+=" $1"; shift;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
function call_setup_sh() {
|
||||
bash "setup.sh"
|
||||
}
|
||||
|
||||
function start_process() {
|
||||
if [ ! -z $NO_SUDO ]; then
|
||||
log_msg "running with sudo removed"
|
||||
eval $(echo "$@" | sed 's/sudo//g')
|
||||
else
|
||||
eval $@
|
||||
fi
|
||||
}
|
||||
|
||||
function get_version() {
|
||||
local version=$1
|
||||
|
||||
if command -v $version; then
|
||||
version=$($@)
|
||||
fi
|
||||
|
||||
echo $version | sed -E 's/[^0-9.]//g'
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
# Build docker image for the Selective Forwarding Unit (SFU)
|
||||
|
||||
# When run from SFU/platform_scripts/bash, this uses the SFU directory
|
||||
# as the build context so the SFU files can be successfully copied into the container image
|
||||
docker build -t 'mediasoup_sfu:latest' -f ./Dockerfile ../..
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
# Start docker container by name using host networking
|
||||
docker run --name sfu_latest --network host --rm mediasoup_sfu
|
||||
|
||||
# Interactive start example
|
||||
#docker run --name sfu_latest --network host --rm -it --entrypoint /bin/bash mediasoup_sfu
|
||||
@@ -1,12 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
# Stop the docker container
|
||||
PSID=$(docker ps -a -q --filter="name=sfu_latest")
|
||||
if [ -z "$PSID" ]; then
|
||||
echo "Docker SFU is not running, no stopping will be done"
|
||||
exit 1;
|
||||
fi
|
||||
echo "Stopping Mediasoup SFU server ..."
|
||||
docker stop sfu_latest
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
BASH_LOCATION=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
||||
|
||||
pushd "${BASH_LOCATION}" > /dev/null
|
||||
|
||||
source common_utils.sh
|
||||
|
||||
set_start_default_values # No server specific defaults
|
||||
use_args "$@"
|
||||
call_setup_sh
|
||||
print_parameters
|
||||
|
||||
process="${BASH_LOCATION}/node/lib/node_modules/npm/bin/npm-cli.js run start:default --"
|
||||
arguments="--PublicIP=${publicip}"
|
||||
|
||||
# Add arguments passed to script to arguments for executable
|
||||
arguments+=" ${sfucmd}"
|
||||
|
||||
pushd ../.. > /dev/null
|
||||
|
||||
echo "Running: $process $arguments"
|
||||
PATH="${BASH_LOCATION}/node/bin:$PATH"
|
||||
start_process $process $arguments
|
||||
popd
|
||||
|
||||
popd
|
||||
@@ -1,27 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
BASH_LOCATION=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
||||
|
||||
pushd "${BASH_LOCATION}" > /dev/null
|
||||
|
||||
source common_utils.sh
|
||||
|
||||
set_start_default_values # No server specific defaults
|
||||
use_args "$@"
|
||||
call_setup_sh
|
||||
|
||||
process="${BASH_LOCATION}/node/lib/node_modules/npm/bin/npm-cli.js run start:default --"
|
||||
|
||||
pushd ../.. > /dev/null
|
||||
|
||||
echo ""
|
||||
echo "Starting (S)elective (F)orwarding (U)nit use ctrl-c to exit"
|
||||
echo "-----------------------------------------"
|
||||
echo ""
|
||||
|
||||
PATH="${BASH_LOCATION}/node/bin:$PATH"
|
||||
start_process $process
|
||||
|
||||
popd > /dev/null # ../..
|
||||
|
||||
popd > /dev/null # BASH_SOURCE
|
||||
@@ -1,114 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
BASH_LOCATION=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
||||
|
||||
pushd "${BASH_LOCATION}" > /dev/null
|
||||
|
||||
source common_utils.sh
|
||||
|
||||
use_args $@
|
||||
# Azure specific fix to allow installing NodeJS from NodeSource
|
||||
if test -f "/etc/apt/sources.list.d/azure-cli.list"; then
|
||||
sudo touch /etc/apt/sources.list.d/nodesource.list
|
||||
sudo touch /usr/share/keyrings/nodesource.gpg
|
||||
sudo chmod 644 /etc/apt/sources.list.d/nodesource.list
|
||||
sudo chmod 644 /usr/share/keyrings/nodesource.gpg
|
||||
sudo chmod 644 /etc/apt/sources.list.d/azure-cli.list
|
||||
fi
|
||||
|
||||
function check_version() { #current_version #min_version
|
||||
#check if same string
|
||||
if [ -z "$2" ] || [ "$1" = "$2" ]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
local i current minimum
|
||||
|
||||
IFS="." read -r -a current <<< $1
|
||||
IFS="." read -r -a minimum <<< $2
|
||||
|
||||
# fill empty fields in current with zeros
|
||||
for ((i=${#current[@]}; i<${#minimum[@]}; i++))
|
||||
do
|
||||
current[i]=0
|
||||
done
|
||||
|
||||
for ((i=0; i<${#current[@]}; i++))
|
||||
do
|
||||
if [[ -z ${minimum[i]} ]]; then
|
||||
# fill empty fields in minimum with zeros
|
||||
minimum[i]=0
|
||||
fi
|
||||
|
||||
if ((10#${current[i]} > 10#${minimum[i]})); then
|
||||
return 1
|
||||
fi
|
||||
|
||||
if ((10#${current[i]} < 10#${minimum[i]})); then
|
||||
return 2
|
||||
fi
|
||||
done
|
||||
|
||||
# if got this far string is the same once we added missing 0
|
||||
return 0
|
||||
}
|
||||
|
||||
function check_and_install() { #dep_name #get_version_string #version_min #install_command
|
||||
local is_installed=0
|
||||
|
||||
log_msg "Checking for required $1 install"
|
||||
|
||||
local current=$(echo $2 | sed -E 's/[^0-9.]//g')
|
||||
local minimum=$(echo $3 | sed -E 's/[^0-9.]//g')
|
||||
|
||||
if [ $# -ne 4 ]; then
|
||||
log_msg "check_and_install expects 4 args (dep_name get_version_string version_min install_command) got $#"
|
||||
return -1
|
||||
fi
|
||||
|
||||
if [ ! -z $current ]; then
|
||||
log_msg "Current version: $current checking >= $minimum"
|
||||
check_version "$current" "$minimum"
|
||||
if [ "$?" -lt 2 ]; then
|
||||
log_msg "$1 is installed."
|
||||
return 0
|
||||
else
|
||||
log_msg "Required install of $1 not found installing"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ $is_installed -ne 1 ]; then
|
||||
echo "$1 installation not found installing..."
|
||||
|
||||
start_process $4
|
||||
|
||||
if [ $? -ge 1 ]; then
|
||||
echo "Installation of $1 failed try running `export VERBOSE=1` then run this script again for more details"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
fi
|
||||
}
|
||||
|
||||
echo "Checking Pixel Streaming SFU dependencies."
|
||||
|
||||
# navigate to SFU root
|
||||
pushd ../.. > /dev/null
|
||||
|
||||
node_version=""
|
||||
if [[ -f "${BASH_LOCATION}/node/bin/node" ]]; then
|
||||
node_version=$("${BASH_LOCATION}/node/bin/node" --version)
|
||||
fi
|
||||
check_and_install "node" "$node_version" "v16.4.2" "curl https://nodejs.org/dist/v16.14.2/node-v16.14.2-linux-x64.tar.gz --output node.tar.xz
|
||||
&& tar -xf node.tar.xz
|
||||
&& rm node.tar.xz
|
||||
&& mv node-v*-linux-x64 \"${BASH_LOCATION}/node\""
|
||||
|
||||
PATH="${BASH_LOCATION}/node/bin:$PATH"
|
||||
"${BASH_LOCATION}/node/lib/node_modules/npm/bin/npm-cli.js" install
|
||||
|
||||
popd > /dev/null # SFU
|
||||
|
||||
popd > /dev/null # BASH_SOURCE
|
||||
|
||||
echo "All Pixel Streaming SFU dependencies up to date."
|
||||
@@ -1,19 +0,0 @@
|
||||
@Rem Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
@echo off
|
||||
|
||||
@Rem Set script directory as working directory.
|
||||
pushd "%~dp0"
|
||||
|
||||
title SFU
|
||||
|
||||
@Rem Get our public IP if we are running this SFU on the cloud we will need this.
|
||||
FOR /F "tokens=*" %%g IN ('curl -L -S -s https://api.ipify.org') do (SET PUBLICIP=%%g)
|
||||
|
||||
@Rem Call out run.bat and pass in the Public IP we grabbed earlier.
|
||||
call run_local.bat --PublicIP=%PUBLICIP%
|
||||
|
||||
@Rem Pop script directory.
|
||||
popd
|
||||
|
||||
pause
|
||||
@@ -1,25 +0,0 @@
|
||||
@Rem Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
@echo off
|
||||
|
||||
@Rem Set script directory as working directory.
|
||||
pushd "%~dp0"
|
||||
|
||||
title SFU
|
||||
|
||||
@Rem Run setup to ensure we have node and mediasoup installed.
|
||||
call setup.bat
|
||||
|
||||
@Rem Move to sfu_server.js directory.
|
||||
pushd ..\..
|
||||
|
||||
@Rem Run node server and pass any argument along.
|
||||
platform_scripts\cmd\node\node.exe sfu_server %*
|
||||
|
||||
@Rem Pop sfu_server directory.
|
||||
popd
|
||||
|
||||
@Rem Pop script directory.
|
||||
popd
|
||||
|
||||
pause
|
||||
@@ -1,17 +0,0 @@
|
||||
@Rem Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
@echo off
|
||||
|
||||
@Rem Set script location as working directory for commands.
|
||||
pushd "%~dp0"
|
||||
|
||||
@Rem Ensure we have NodeJs available for calling.
|
||||
call setup_node.bat
|
||||
|
||||
@Rem Move to sfu_server.js directory and install its package.json
|
||||
pushd %~dp0\..\..\
|
||||
call platform_scripts\cmd\node\npm install --no-save
|
||||
popd
|
||||
|
||||
@Rem Pop working directory
|
||||
popd
|
||||
@@ -1,35 +0,0 @@
|
||||
@Rem Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
@echo off
|
||||
|
||||
@Rem Set script location as working directory for commands.
|
||||
pushd "%~dp0"
|
||||
|
||||
@Rem Name and version of node that we are downloading
|
||||
SET NodeVersion=v16.4.2
|
||||
SET NodeName=node-%NodeVersion%-win-x64
|
||||
|
||||
@Rem Look for a node directory next to this script
|
||||
if exist node\ (
|
||||
echo Node directory found...skipping install.
|
||||
) else (
|
||||
echo Node directory not found...beginning NodeJS download for Windows.
|
||||
|
||||
@Rem Download nodejs and follow redirects.
|
||||
curl -L -o ./node.zip "https://nodejs.org/dist/%NodeVersion%/%NodeName%.zip"
|
||||
|
||||
@Rem Unarchive the .zip
|
||||
tar -xf node.zip
|
||||
|
||||
@Rem Rename the extracted, versioned, directory that contains the NodeJS binaries to simply "node".
|
||||
ren "%NodeName%\" "node"
|
||||
|
||||
@Rem Delete the downloaded node.zip
|
||||
del node.zip
|
||||
)
|
||||
|
||||
@Rem Print node version
|
||||
echo Node version: & node\node.exe -v
|
||||
|
||||
@Rem Pop working directory
|
||||
popd
|
||||
@@ -1,321 +0,0 @@
|
||||
const config = require('./config');
|
||||
const WebSocket = require('ws');
|
||||
const mediasoup = require('mediasoup_prebuilt');
|
||||
const mediasoupSdp = require('mediasoup-sdp-bridge');
|
||||
|
||||
let signalServer = null;
|
||||
let mediasoupRouter;
|
||||
let streamer = null;
|
||||
let peers = new Map();
|
||||
|
||||
function connectSignalling(server) {
|
||||
console.log("Connecting to Signalling Server at %s", server);
|
||||
signalServer = new WebSocket(server);
|
||||
signalServer.addEventListener("open", _ => { console.log(`Connected to signalling server`); });
|
||||
signalServer.addEventListener("error", result => { console.log(`Error: ${result.message}`); });
|
||||
signalServer.addEventListener("message", result => onSignallingMessage(result.data));
|
||||
signalServer.addEventListener("close", result => {
|
||||
console.log(`Disconnected from signalling server: ${result.code} ${result.reason}`);
|
||||
console.log("Attempting reconnect to signalling server...");
|
||||
setTimeout(()=> {
|
||||
connectSignalling(server);
|
||||
}, 2000);
|
||||
});
|
||||
}
|
||||
|
||||
async function onStreamerOffer(sdp) {
|
||||
console.log("Got offer from streamer");
|
||||
|
||||
if (streamer != null) {
|
||||
signalServer.close(1013 /* Try again later */, 'Producer is already connected');
|
||||
return;
|
||||
}
|
||||
|
||||
const transport = await createWebRtcTransport("Streamer");
|
||||
const sdpEndpoint = mediasoupSdp.createSdpEndpoint(transport, mediasoupRouter.rtpCapabilities);
|
||||
const producers = await sdpEndpoint.processOffer(sdp);
|
||||
const sdpAnswer = sdpEndpoint.createAnswer();
|
||||
const answer = { type: "answer", sdp: sdpAnswer };
|
||||
|
||||
console.log("Sending answer to streamer.");
|
||||
signalServer.send(JSON.stringify(answer));
|
||||
streamer = { transport: transport, producers: producers };
|
||||
}
|
||||
|
||||
function getNextStreamerSCTPId() {
|
||||
if(!streamer){
|
||||
throw new TypeError('Cannot generate an SCTP stream id - streamer was null.');
|
||||
}
|
||||
if (!streamer.transport || !streamer.transport.sctpParameters || typeof streamer.transport.sctpParameters.MIS !== 'number') {
|
||||
throw new TypeError('Streamer was not setup with the following require properties: streamer.transport.sctpParameters.MIS');
|
||||
}
|
||||
const numStreams = streamer.transport.sctpParameters.MIS;
|
||||
if (!streamer.dataStreamIds){
|
||||
streamer.dataStreamIds = Buffer.alloc(numStreams, 0);
|
||||
}
|
||||
if (!streamer.nextDataStreamId) {
|
||||
streamer.nextDataStreamId = 0;
|
||||
}
|
||||
|
||||
let sctpStreamId;
|
||||
for (let idx = streamer.nextDataStreamId; idx < streamer.dataStreamIds.length; ++idx) {
|
||||
sctpStreamId = idx % streamer.dataStreamIds.length;
|
||||
if (!streamer.dataStreamIds[sctpStreamId]) {
|
||||
streamer.nextDataStreamId = sctpStreamId + 1;
|
||||
return sctpStreamId;
|
||||
}
|
||||
}
|
||||
console.error("No available SCTP ids, they are all allocated.");
|
||||
return -1;
|
||||
}
|
||||
|
||||
function onStreamerDisconnected() {
|
||||
console.log("Streamer disconnected");
|
||||
disconnectAllPeers();
|
||||
|
||||
if (streamer != null) {
|
||||
for (const mediaProducer of streamer.producers) {
|
||||
mediaProducer.close();
|
||||
}
|
||||
streamer.transport.close();
|
||||
streamer = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function onPeerConnected(peerId) {
|
||||
console.log("Player %s joined", peerId);
|
||||
|
||||
if (streamer == null) {
|
||||
console.log("No streamer connected, ignoring player.");
|
||||
return;
|
||||
}
|
||||
|
||||
const transport = await createWebRtcTransport("Peer " + peerId);
|
||||
const sdpEndpoint = mediasoupSdp.createSdpEndpoint( transport, mediasoupRouter.rtpCapabilities );
|
||||
sdpEndpoint.addConsumeData(); // adds the sctp 'application' section to the offer
|
||||
|
||||
// media consumers
|
||||
let consumers = [];
|
||||
try {
|
||||
for (const mediaProducer of streamer.producers) {
|
||||
const consumer = await transport.consume({ producerId: mediaProducer.id, rtpCapabilities: mediasoupRouter.rtpCapabilities });
|
||||
consumer.observer.on("layerschange", function() { console.log("layer changed!", consumer.currentLayers); });
|
||||
sdpEndpoint.addConsumer(consumer);
|
||||
consumers.push(consumer);
|
||||
}
|
||||
} catch(err) {
|
||||
console.error("transport.consume() failed:", err);
|
||||
return;
|
||||
}
|
||||
|
||||
const offerSignal = {
|
||||
type: "offer",
|
||||
playerId: peerId,
|
||||
sdp: sdpEndpoint.createOffer(),
|
||||
sfu: true // indicate we're offering from sfu
|
||||
};
|
||||
|
||||
// send offer to peer
|
||||
signalServer.send(JSON.stringify(offerSignal));
|
||||
|
||||
const newPeer = {
|
||||
id: peerId,
|
||||
transport: transport,
|
||||
sdpEndpoint: sdpEndpoint,
|
||||
consumers: consumers
|
||||
};
|
||||
|
||||
// add the new peer
|
||||
peers.set(peerId, newPeer);
|
||||
}
|
||||
|
||||
async function setupPeerDataChannels(peerId) {
|
||||
const peer = peers.get(peerId);
|
||||
if (!peer) {
|
||||
console.error(`Could not send browser any datachannels for peer=${peerId} because peer was not found.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const nextStreamerSCTPStreamId = getNextStreamerSCTPId();
|
||||
const nextPeerSCTPStreamId = getNextStreamerSCTPId();
|
||||
|
||||
console.log(`Attempting streamer SCTP id=${nextStreamerSCTPStreamId}`);
|
||||
|
||||
// streamer data producer (produces data for the peer)
|
||||
peer.streamerDataProducer = await streamer.transport.produceData({label: 'send-datachannel', sctpStreamParameters: {streamId: nextStreamerSCTPStreamId, ordered: true}});
|
||||
|
||||
console.log(`Attempting peer SCTP id=${nextPeerSCTPStreamId}`);
|
||||
|
||||
// peer data producer (produces data for the streamer)
|
||||
peer.peerDataProducer = await peer.transport.produceData({label: 'send-datachannel', sctpStreamParameters: {streamId: nextPeerSCTPStreamId, ordered: true}});
|
||||
|
||||
// peer data consumer (consumes streamer data)
|
||||
peer.peerDataConsumer = await peer.transport.consumeData({ dataProducerId: peer.streamerDataProducer.id });
|
||||
|
||||
// streamer data consumer (consumes peer data)
|
||||
peer.streamerDataConsumer = await streamer.transport.consumeData({ dataProducerId: peer.peerDataProducer.id });
|
||||
|
||||
const peerSignal = {
|
||||
type: 'peerDataChannels',
|
||||
playerId: peerId,
|
||||
sendStreamId: peer.peerDataProducer.sctpStreamParameters.streamId,
|
||||
recvStreamId: peer.peerDataConsumer.sctpStreamParameters.streamId
|
||||
};
|
||||
|
||||
// Send browser a message with a send/recv data channel SCTP stream id
|
||||
signalServer.send(JSON.stringify(peerSignal));
|
||||
|
||||
}
|
||||
|
||||
async function setupStreamerDataChannelsForPeer(peerId) {
|
||||
|
||||
const peer = peers.get(peerId);
|
||||
if (!peer) {
|
||||
console.error(`Could not send streamer any datachannels for peer=${peerId} because peer was not found.`);
|
||||
return;
|
||||
}
|
||||
|
||||
if(!peer.streamerDataProducer || !peer.streamerDataConsumer){
|
||||
console.error(`There was no streamer data producer/consumer setup for peer=${peerId}. Did you make sure to send "dataChannelRequest" first?`);
|
||||
return;
|
||||
}
|
||||
|
||||
const streamerSignal = {
|
||||
type: "streamerDataChannels",
|
||||
playerId: peerId,
|
||||
sendStreamId: peer.streamerDataProducer.sctpStreamParameters.streamId,
|
||||
recvStreamId: peer.streamerDataConsumer.sctpStreamParameters.streamId
|
||||
};
|
||||
|
||||
// send streamer a message with a send/recv data channel SCTP stream id
|
||||
signalServer.send(JSON.stringify(streamerSignal));
|
||||
}
|
||||
|
||||
async function onPeerAnswer(peerId, sdp) {
|
||||
console.log("Got answer from player %s", peerId);
|
||||
|
||||
const consumer = peers.get(peerId);
|
||||
if (!consumer){
|
||||
console.error(`Unable to find player ${peerId}`);
|
||||
}
|
||||
else{
|
||||
consumer.sdpEndpoint.processAnswer(sdp);
|
||||
}
|
||||
}
|
||||
|
||||
function onPeerDisconnected(peerId) {
|
||||
console.log("Player %s disconnected", peerId);
|
||||
const peer = peers.get(peerId);
|
||||
if (peer != null) {
|
||||
for (consumer of peer.consumers) {
|
||||
consumer.close();
|
||||
}
|
||||
if (peer.peerDataConsumer) {
|
||||
peer.peerDataConsumer.close();
|
||||
peer.peerDataProducer.close();
|
||||
}
|
||||
if(peer.streamerDataConsumer){
|
||||
// Set the streamer sctp id we generated back to zero indicating it can be reused.
|
||||
if(streamer && streamer.dataStreamIds){
|
||||
const allocatedStreamId = peer.streamerDataProducer.sctpStreamParameters.streamId;
|
||||
const allocatedPeerStreamId = peer.peerDataProducer.sctpStreamParameters.streamId;
|
||||
streamer.dataStreamIds[allocatedStreamId] = 0;
|
||||
streamer.dataStreamIds[allocatedPeerStreamId] = 0;
|
||||
}
|
||||
peer.streamerDataConsumer.close();
|
||||
peer.streamerDataProducer.close();
|
||||
}
|
||||
peer.transport.close();
|
||||
}
|
||||
peers.delete(peerId);
|
||||
}
|
||||
|
||||
function disconnectAllPeers() {
|
||||
console.log("Disconnected all players");
|
||||
for (const [peerId, peer] of peers) {
|
||||
onPeerDisconnected(peerId);
|
||||
}
|
||||
}
|
||||
|
||||
async function onSignallingMessage(message) {
|
||||
//console.log(`Got MSG: ${message}`);
|
||||
const msg = JSON.parse(message);
|
||||
|
||||
if (msg.type == 'offer') {
|
||||
onStreamerOffer(msg.sdp);
|
||||
}
|
||||
else if (msg.type == 'answer') {
|
||||
onPeerAnswer(msg.playerId, msg.sdp);
|
||||
}
|
||||
else if (msg.type == 'playerConnected') {
|
||||
onPeerConnected(msg.playerId);
|
||||
}
|
||||
else if (msg.type == 'playerDisconnected') {
|
||||
onPeerDisconnected(msg.playerId);
|
||||
}
|
||||
else if (msg.type == 'streamerDisconnected') {
|
||||
onStreamerDisconnected();
|
||||
}
|
||||
else if (msg.type == 'dataChannelRequest') {
|
||||
setupPeerDataChannels(msg.playerId);
|
||||
}
|
||||
else if (msg.type == 'peerDataChannelsReady') {
|
||||
setupStreamerDataChannelsForPeer(msg.playerId);
|
||||
}
|
||||
// todo a new message type for force layer switch (for debugging)
|
||||
// see: https://mediasoup.org/documentation/v3/mediasoup/api/#consumer-setPreferredLayers
|
||||
// preferredLayers for debugging to select a particular simulcast layer, looks like { spatialLayer: 2, temporalLayer: 0 }
|
||||
}
|
||||
|
||||
async function startMediasoup() {
|
||||
let worker = await mediasoup.createWorker({
|
||||
logLevel: config.mediasoup.worker.logLevel,
|
||||
logTags: config.mediasoup.worker.logTags,
|
||||
rtcMinPort: config.mediasoup.worker.rtcMinPort,
|
||||
rtcMaxPort: config.mediasoup.worker.rtcMaxPort,
|
||||
});
|
||||
|
||||
worker.on('died', () => {
|
||||
console.error('mediasoup worker died (this should never happen)');
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
const mediaCodecs = config.mediasoup.router.mediaCodecs;
|
||||
const mediasoupRouter = await worker.createRouter({ mediaCodecs });
|
||||
|
||||
return mediasoupRouter;
|
||||
}
|
||||
|
||||
async function createWebRtcTransport(identifier) {
|
||||
const {
|
||||
listenIps,
|
||||
initialAvailableOutgoingBitrate
|
||||
} = config.mediasoup.webRtcTransport;
|
||||
|
||||
const transport = await mediasoupRouter.createWebRtcTransport({
|
||||
listenIps: listenIps,
|
||||
enableUdp: true,
|
||||
enableTcp: false,
|
||||
preferUdp: true,
|
||||
enableSctp: true, // datachannels
|
||||
initialAvailableOutgoingBitrate: initialAvailableOutgoingBitrate
|
||||
});
|
||||
|
||||
transport.on("icestatechange", (iceState) => { console.log("%s ICE state changed to %s", identifier, iceState); });
|
||||
transport.on("iceselectedtuplechange", (iceTuple) => { console.log("%s ICE selected tuple %s", identifier, JSON.stringify(iceTuple)); });
|
||||
transport.on("sctpstatechange", (sctpState) => { console.log("%s SCTP state changed to %s", identifier, sctpState); });
|
||||
|
||||
return transport;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('Starting Mediasoup...');
|
||||
console.log("Config = ");
|
||||
console.log(config);
|
||||
|
||||
mediasoupRouter = await startMediasoup();
|
||||
|
||||
connectSignalling(config.signallingURL);
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -1,4 +0,0 @@
|
||||
logs/*.log
|
||||
node_modules
|
||||
platform_scripts
|
||||
tps
|
||||
@@ -1,25 +0,0 @@
|
||||
# Use the current Long Term Support (LTS) version of Node.js
|
||||
FROM node:lts
|
||||
|
||||
# Copy the signalling server source code from the build context
|
||||
COPY . /opt/SignallingWebServer
|
||||
|
||||
# Install the dependencies for the signalling server
|
||||
WORKDIR /opt/SignallingWebServer
|
||||
RUN npm install .
|
||||
|
||||
# Expose TCP ports 80 and 443 for player WebSocket connections and web server HTTP(S) access
|
||||
EXPOSE 80
|
||||
EXPOSE 443
|
||||
|
||||
# Expose TCP port 8888 for streamer WebSocket connections
|
||||
EXPOSE 8888
|
||||
|
||||
# Expose TCP port 8889 for connections from the SFU
|
||||
EXPOSE 8889
|
||||
|
||||
# Expose TCP port 9999 for connections from the Matchmaker
|
||||
EXPOSE 9999
|
||||
|
||||
# Set the signalling server as the container's entrypoint
|
||||
ENTRYPOINT ["/usr/local/bin/node", "/opt/SignallingWebServer/cirrus.js"]
|
||||
@@ -1,37 +0,0 @@
|
||||
<!-- Copyright Epic Games, Inc. All Rights Reserved. -->
|
||||
<!DOCTYPE html>
|
||||
<html style="width: 100%; height: 100%">
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
|
||||
<link href="https://fonts.googleapis.com/css2?family=Michroma&family=Montserrat:wght@600&display=swap" rel="stylesheet">
|
||||
|
||||
<!-- Required - the Login style sheet -->
|
||||
<link rel="stylesheet" type="text/css" href="css/login.css">
|
||||
|
||||
<!-- Optional: set some favicons -->
|
||||
<link id="favPng" rel="icon" type="image/png" href="images/favicon.png">
|
||||
|
||||
<!-- Optional: set a title for your page -->
|
||||
<title>Pixel Streaming Login</title>
|
||||
<script defer src="login.js"></script></head>
|
||||
|
||||
<body style="width: 100vw; height: 100vh; min-height: -webkit-fill-available; font-family: 'Montserrat'; margin: 0px">
|
||||
<form action="/login" method="post">
|
||||
<div class="entry">
|
||||
<input type="text" id="username" name="username" placeholder="Username"
|
||||
autocomplete="username">
|
||||
</div>
|
||||
<div class="entry">
|
||||
<input type="password" id="password" name="password" placeholder="Password"
|
||||
autocomplete="current-password">
|
||||
</div>
|
||||
<div class="entry button">
|
||||
<button type="submit">LOGIN</button>
|
||||
</div>
|
||||
</form>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -1,42 +0,0 @@
|
||||
<!-- Copyright Epic Games, Inc. All Rights Reserved. -->
|
||||
<!DOCTYPE HTML>
|
||||
<html style="width: 100%; height: 100%">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
|
||||
<link href="https://fonts.googleapis.com/css2?family=Michroma&family=Montserrat:wght@600&display=swap" rel="stylesheet">
|
||||
|
||||
<!-- Required - the stress tester style sheet -->
|
||||
<link rel="stylesheet" type="text/css" href="css/stresstest.css">
|
||||
|
||||
<!-- Optional: set some favicons -->
|
||||
<link id="favPng" rel="icon" type="image/png" href="images/favicon.png">
|
||||
|
||||
<!-- Optional: set a title for your page -->
|
||||
<title>Pixel Streaming Stress Tester</title>
|
||||
<script defer src="stresstest.js"></script></head>
|
||||
|
||||
<body style="width: 100vw; height: 100vh; min-height: -webkit-fill-available; font-family: 'Montserrat'; margin: 0px">
|
||||
<div id="control">
|
||||
<button id="playPause">Pause</button>
|
||||
<div>Total streams: <span id="nStreamsLabel">0</span></div>
|
||||
<div>
|
||||
<span>Max peers: </span>
|
||||
<span id="nPeerLabel">5</span>
|
||||
<input type="range" min="1" max="8" value="5" class="slider" id="nPeersSlider">
|
||||
</div>
|
||||
<div>
|
||||
<span>Peer creation interval (seconds): </span>
|
||||
<input type="number" id="creationIntervalInput" min="0" max="100" step="1" value="1">
|
||||
</div>
|
||||
<div>
|
||||
<span>Peer deletion interval (seconds): </span>
|
||||
<input type="number" id="deletionIntervalInput" min="0" max="100" step="1" value="2">
|
||||
</div>
|
||||
</div>
|
||||
<div id="streamsContainer"></div>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -1,932 +0,0 @@
|
||||
// Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
//-- Server side logic. Serves pixel streaming WebRTC-based page, proxies data back to Streamer --//
|
||||
|
||||
var express = require('express');
|
||||
var app = express();
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const querystring = require('querystring');
|
||||
const bodyParser = require('body-parser');
|
||||
const logging = require('./modules/logging.js');
|
||||
logging.RegisterConsoleLogger();
|
||||
|
||||
// Command line argument --configFile needs to be checked before loading the config, all other command line arguments are dealt with through the config object
|
||||
|
||||
const defaultConfig = {
|
||||
UseFrontend: false,
|
||||
UseMatchmaker: false,
|
||||
UseHTTPS: false,
|
||||
UseAuthentication: false,
|
||||
LogToFile: true,
|
||||
LogVerbose: true,
|
||||
HomepageFile: 'player.html',
|
||||
AdditionalRoutes: new Map(),
|
||||
EnableWebserver: true,
|
||||
MatchmakerAddress: "",
|
||||
MatchmakerPort: 9999,
|
||||
PublicIp: "localhost",
|
||||
HttpPort: 80,
|
||||
HttpsPort: 443,
|
||||
StreamerPort: 8888,
|
||||
SFUPort: 8889,
|
||||
MaxPlayerCount: -1
|
||||
};
|
||||
|
||||
const argv = require('yargs').argv;
|
||||
var configFile = (typeof argv.configFile != 'undefined') ? argv.configFile.toString() : path.join(__dirname, 'config.json');
|
||||
console.log(`configFile ${configFile}`);
|
||||
const config = require('./modules/config.js').init(configFile, defaultConfig);
|
||||
|
||||
if (config.LogToFile) {
|
||||
logging.RegisterFileLogger('./logs/');
|
||||
}
|
||||
|
||||
console.log("Config: " + JSON.stringify(config, null, '\t'));
|
||||
|
||||
var http = require('http').Server(app);
|
||||
|
||||
if (config.UseHTTPS) {
|
||||
//HTTPS certificate details
|
||||
const options = {
|
||||
key: fs.readFileSync(path.join(__dirname, './certificates/client-key.pem')),
|
||||
cert: fs.readFileSync(path.join(__dirname, './certificates/client-cert.pem'))
|
||||
};
|
||||
|
||||
var https = require('https').Server(options, app);
|
||||
}
|
||||
|
||||
//If not using authetication then just move on to the next function/middleware
|
||||
var isAuthenticated = redirectUrl => function (req, res, next) { return next(); }
|
||||
|
||||
if (config.UseAuthentication && config.UseHTTPS) {
|
||||
var passport = require('passport');
|
||||
require('./modules/authentication').init(app);
|
||||
// Replace the isAuthenticated with the one setup on passport module
|
||||
isAuthenticated = passport.authenticationMiddleware ? passport.authenticationMiddleware : isAuthenticated
|
||||
} else if (config.UseAuthentication && !config.UseHTTPS) {
|
||||
console.error('Trying to use authentication without using HTTPS, this is not allowed and so authentication will NOT be turned on, please turn on HTTPS to turn on authentication');
|
||||
}
|
||||
|
||||
const helmet = require('helmet');
|
||||
var hsts = require('hsts');
|
||||
var net = require('net');
|
||||
|
||||
var FRONTEND_WEBSERVER = 'https://localhost';
|
||||
if (config.UseFrontend) {
|
||||
var httpPort = 3000;
|
||||
var httpsPort = 8000;
|
||||
|
||||
//Required for self signed certs otherwise just get an error back when sending request to frontend see https://stackoverflow.com/a/35633993
|
||||
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"
|
||||
|
||||
const httpsClient = require('./modules/httpsClient.js');
|
||||
var webRequest = new httpsClient();
|
||||
} else {
|
||||
var httpPort = config.HttpPort;
|
||||
var httpsPort = config.HttpsPort;
|
||||
}
|
||||
|
||||
var streamerPort = config.StreamerPort; // port to listen to Streamer connections
|
||||
var sfuPort = config.SFUPort;
|
||||
|
||||
var matchmakerAddress = '127.0.0.1';
|
||||
var matchmakerPort = 9999;
|
||||
var matchmakerRetryInterval = 5;
|
||||
var matchmakerKeepAliveInterval = 30;
|
||||
var maxPlayerCount = -1;
|
||||
|
||||
var gameSessionId;
|
||||
var userSessionId;
|
||||
var serverPublicIp;
|
||||
|
||||
// `clientConfig` is send to Streamer and Players
|
||||
// Example of STUN server setting
|
||||
// let clientConfig = {peerConnectionOptions: { 'iceServers': [{'urls': ['stun:34.250.222.95:19302']}] }};
|
||||
var clientConfig = { type: 'config', peerConnectionOptions: {} };
|
||||
|
||||
// Parse public server address from command line
|
||||
// --publicIp <public address>
|
||||
try {
|
||||
if (typeof config.PublicIp != 'undefined') {
|
||||
serverPublicIp = config.PublicIp.toString();
|
||||
}
|
||||
|
||||
if (typeof config.HttpPort != 'undefined') {
|
||||
httpPort = config.HttpPort;
|
||||
}
|
||||
|
||||
if (typeof config.HttpsPort != 'undefined') {
|
||||
httpsPort = config.HttpsPort;
|
||||
}
|
||||
|
||||
if (typeof config.StreamerPort != 'undefined') {
|
||||
streamerPort = config.StreamerPort;
|
||||
}
|
||||
|
||||
if (typeof config.SFUPort != 'undefined') {
|
||||
sfuPort = config.SFUPort;
|
||||
}
|
||||
|
||||
if (typeof config.FrontendUrl != 'undefined') {
|
||||
FRONTEND_WEBSERVER = config.FrontendUrl;
|
||||
}
|
||||
|
||||
if (typeof config.peerConnectionOptions != 'undefined') {
|
||||
clientConfig.peerConnectionOptions = JSON.parse(config.peerConnectionOptions);
|
||||
console.log(`peerConnectionOptions = ${JSON.stringify(clientConfig.peerConnectionOptions)}`);
|
||||
} else {
|
||||
console.log("No peerConnectionConfig")
|
||||
}
|
||||
|
||||
if (typeof config.MatchmakerAddress != 'undefined') {
|
||||
matchmakerAddress = config.MatchmakerAddress;
|
||||
}
|
||||
|
||||
if (typeof config.MatchmakerPort != 'undefined') {
|
||||
matchmakerPort = config.MatchmakerPort;
|
||||
}
|
||||
|
||||
if (typeof config.MatchmakerRetryInterval != 'undefined') {
|
||||
matchmakerRetryInterval = config.MatchmakerRetryInterval;
|
||||
}
|
||||
|
||||
if (typeof config.MaxPlayerCount != 'undefined') {
|
||||
maxPlayerCount = config.MaxPlayerCount;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
if (config.UseHTTPS) {
|
||||
app.use(helmet());
|
||||
|
||||
app.use(hsts({
|
||||
maxAge: 15552000 // 180 days in seconds
|
||||
}));
|
||||
|
||||
//Setup http -> https redirect
|
||||
console.log('Redirecting http->https');
|
||||
app.use(function (req, res, next) {
|
||||
if (!req.secure) {
|
||||
if (req.get('Host')) {
|
||||
var hostAddressParts = req.get('Host').split(':');
|
||||
var hostAddress = hostAddressParts[0];
|
||||
if (httpsPort != 443) {
|
||||
hostAddress = `${hostAddress}:${httpsPort}`;
|
||||
}
|
||||
return res.redirect(['https://', hostAddress, req.originalUrl].join(''));
|
||||
} else {
|
||||
console.error(`unable to get host name from header. Requestor ${req.ip}, url path: '${req.originalUrl}', available headers ${JSON.stringify(req.headers)}`);
|
||||
return res.status(400).send('Bad Request');
|
||||
}
|
||||
}
|
||||
next();
|
||||
});
|
||||
}
|
||||
|
||||
sendGameSessionData();
|
||||
|
||||
//Setup the login page if we are using authentication
|
||||
if(config.UseAuthentication){
|
||||
if(config.EnableWebserver) {
|
||||
app.get('/login', function(req, res){
|
||||
res.sendFile(path.join(__dirname, '/Public', '/login.html'));
|
||||
});
|
||||
}
|
||||
|
||||
// create application/x-www-form-urlencoded parser
|
||||
var urlencodedParser = bodyParser.urlencoded({ extended: false })
|
||||
|
||||
//login page form data is posted here
|
||||
app.post('/login',
|
||||
urlencodedParser,
|
||||
passport.authenticate('local', { failureRedirect: '/login' }),
|
||||
function(req, res){
|
||||
//On success try to redirect to the page that they originally tired to get to, default to '/' if no redirect was found
|
||||
var redirectTo = req.session.redirectTo ? req.session.redirectTo : '/';
|
||||
delete req.session.redirectTo;
|
||||
console.log(`Redirecting to: '${redirectTo}'`);
|
||||
res.redirect(redirectTo);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
if(config.EnableWebserver) {
|
||||
//Setup folders
|
||||
app.use(express.static(path.join(__dirname, '/Public')))
|
||||
app.use('/images', express.static(path.join(__dirname, './images')))
|
||||
app.use('/scripts', [isAuthenticated('/login'),express.static(path.join(__dirname, '/scripts'))]);
|
||||
app.use('/', [isAuthenticated('/login'), express.static(path.join(__dirname, '/custom_html'))])
|
||||
}
|
||||
|
||||
try {
|
||||
for (var property in config.AdditionalRoutes) {
|
||||
if (config.AdditionalRoutes.hasOwnProperty(property)) {
|
||||
console.log(`Adding additional routes "${property}" -> "${config.AdditionalRoutes[property]}"`)
|
||||
app.use(property, [isAuthenticated('/login'), express.static(path.join(__dirname, config.AdditionalRoutes[property]))]);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`reading config.AdditionalRoutes: ${err}`)
|
||||
}
|
||||
|
||||
if(config.EnableWebserver) {
|
||||
|
||||
// Request has been sent to site root, send the homepage file
|
||||
app.get('/', isAuthenticated('/login'), function (req, res) {
|
||||
homepageFile = (typeof config.HomepageFile != 'undefined' && config.HomepageFile != '') ? config.HomepageFile.toString() : defaultConfig.HomepageFile;
|
||||
|
||||
let pathsToTry = [ path.join(__dirname, homepageFile), path.join(__dirname, '/Public', homepageFile), path.join(__dirname, '/custom_html', homepageFile), homepageFile ];
|
||||
|
||||
// Try a few paths, see if any resolve to a homepage file the user has set
|
||||
for(let pathToTry of pathsToTry){
|
||||
if(fs.existsSync(pathToTry)){
|
||||
// Send the file for browser to display it
|
||||
res.sendFile(pathToTry);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Catch file doesn't exist, and send back 404 if not
|
||||
console.error('Unable to locate file ' + homepageFile)
|
||||
res.status(404).send('Unable to locate file ' + homepageFile);
|
||||
return;
|
||||
});
|
||||
}
|
||||
|
||||
//Setup http and https servers
|
||||
http.listen(httpPort, function () {
|
||||
console.logColor(logging.Green, 'Http listening on *: ' + httpPort);
|
||||
});
|
||||
|
||||
if (config.UseHTTPS) {
|
||||
https.listen(httpsPort, function () {
|
||||
console.logColor(logging.Green, 'Https listening on *: ' + httpsPort);
|
||||
});
|
||||
}
|
||||
|
||||
console.logColor(logging.Cyan, `Running Cirrus - The Pixel Streaming reference implementation signalling server for Unreal Engine 5.1.`);
|
||||
|
||||
let nextPlayerId = 100; // reserve some player ids
|
||||
const SFUPlayerId = "1"; // sfu is a special kind of player
|
||||
|
||||
let streamer = null; // WebSocket connected to Streamer
|
||||
let sfu = null; // WebSocket connected to SFU
|
||||
let players = new Map(); // playerId <-> player, where player is either a web-browser or a native webrtc player
|
||||
|
||||
function sfuIsConnected() {
|
||||
return sfu && sfu.readyState == 1;
|
||||
}
|
||||
|
||||
function logIncoming(sourceName, msgType, msg) {
|
||||
if (config.LogVerbose)
|
||||
console.logColor(logging.Blue, "\x1b[37m-> %s\x1b[34m: %s", sourceName, msg);
|
||||
else
|
||||
console.logColor(logging.Blue, "\x1b[37m-> %s\x1b[34m: %s", sourceName, msgType);
|
||||
}
|
||||
|
||||
function logOutgoing(destName, msgType, msg) {
|
||||
if (config.LogVerbose)
|
||||
console.logColor(logging.Green, "\x1b[37m<- %s\x1b[32m: %s", destName, msg);
|
||||
else
|
||||
console.logColor(logging.Green, "\x1b[37m<- %s\x1b[32m: %s", destName, msgType);
|
||||
}
|
||||
|
||||
// normal peer to peer signalling goes to streamer. SFU streaming signalling goes to the sfu
|
||||
function sendMessageToController(msg, skipSFU, skipStreamer = false) {
|
||||
const rawMsg = JSON.stringify(msg);
|
||||
if (sfu && sfu.readyState == 1 && !skipSFU) {
|
||||
logOutgoing("SFU", msg.type, rawMsg);
|
||||
sfu.send(rawMsg);
|
||||
}
|
||||
if (streamer && streamer.readyState == 1 && !skipStreamer) {
|
||||
logOutgoing("Streamer", msg.type, rawMsg);
|
||||
streamer.send(rawMsg);
|
||||
}
|
||||
|
||||
if (!sfu && !streamer) {
|
||||
console.error("sendMessageToController: No streamer or SFU connected!\nMSG: %s", rawMsg);
|
||||
}
|
||||
}
|
||||
|
||||
function sendMessageToPlayer(playerId, msg) {
|
||||
let player = players.get(playerId);
|
||||
if (!player) {
|
||||
console.log(`dropped message ${msg.type} as the player ${playerId} is not found`);
|
||||
return;
|
||||
}
|
||||
const playerName = playerId == SFUPlayerId ? "SFU" : `player ${playerId}`;
|
||||
const rawMsg = JSON.stringify(msg);
|
||||
logOutgoing(playerName, msg.type, rawMsg);
|
||||
player.ws.send(rawMsg);
|
||||
}
|
||||
|
||||
let WebSocket = require('ws');
|
||||
|
||||
console.logColor(logging.Green, `WebSocket listening for Streamer connections on :${streamerPort}`)
|
||||
let streamerServer = new WebSocket.Server({ port: streamerPort, backlog: 1 });
|
||||
streamerServer.on('connection', function (ws, req) {
|
||||
|
||||
// Check if we have an already existing connection to a streamer, if so, deny a new streamer connecting.
|
||||
if(streamer != null){
|
||||
/* We send a 1008 because that a "policy violation", which similar enough to what is happening here. */
|
||||
ws.close(1008, 'Cirrus supports only 1 streamer being connected, already one connected, so dropping this new connection.');
|
||||
console.logColor(logging.Yellow, `Dropping new streamer connection, we already have a connected streamer`);
|
||||
return;
|
||||
}
|
||||
|
||||
console.logColor(logging.Green, `Streamer connected: ${req.connection.remoteAddress}`);
|
||||
sendStreamerConnectedToMatchmaker();
|
||||
|
||||
ws.on('message', (msgRaw) => {
|
||||
|
||||
var msg;
|
||||
try {
|
||||
msg = JSON.parse(msgRaw);
|
||||
} catch(err) {
|
||||
console.error(`cannot parse Streamer message: ${msgRaw}\nError: ${err}`);
|
||||
streamer.close(1008, 'Cannot parse');
|
||||
return;
|
||||
}
|
||||
|
||||
logIncoming("Streamer", msg.type, msgRaw);
|
||||
|
||||
try {
|
||||
// just send pings back to sender
|
||||
if (msg.type == 'ping') {
|
||||
const rawMsg = JSON.stringify({ type: "pong", time: msg.time});
|
||||
logOutgoing("Streamer", msg.type, rawMsg);
|
||||
ws.send(rawMsg);
|
||||
return;
|
||||
}
|
||||
|
||||
// Convert incoming playerId to a string if it is an integer, if needed. (We support receiving it as an int or string).
|
||||
let playerId = msg.playerId;
|
||||
if (playerId && typeof playerId === 'number')
|
||||
{
|
||||
playerId = playerId.toString();
|
||||
}
|
||||
delete msg.playerId; // no need to send it to the player
|
||||
|
||||
if (msg.type == 'offer') {
|
||||
sendMessageToPlayer(playerId, msg);
|
||||
} else if (msg.type == 'answer') {
|
||||
sendMessageToPlayer(playerId, msg);
|
||||
} else if (msg.type == 'iceCandidate') {
|
||||
sendMessageToPlayer(playerId, msg);
|
||||
} else if (msg.type == 'disconnectPlayer') {
|
||||
let player = players.get(playerId);
|
||||
if (player) {
|
||||
player.ws.close(1011 /* internal error */, msg.reason);
|
||||
}
|
||||
} else {
|
||||
console.error(`unsupported Streamer message type: ${msg.type}`);
|
||||
streamer.close(1008, 'Unsupported message type');
|
||||
}
|
||||
} catch(err) {
|
||||
console.error(`ERROR: ws.on message error: ${err.message}`);
|
||||
}
|
||||
});
|
||||
|
||||
function onStreamerDisconnected() {
|
||||
sendStreamerDisconnectedToMatchmaker();
|
||||
disconnectAllPlayers();
|
||||
if (sfuIsConnected()) {
|
||||
const msg = { type: "streamerDisconnected" };
|
||||
sfu.send(JSON.stringify(msg));
|
||||
}
|
||||
streamer = null;
|
||||
}
|
||||
|
||||
ws.on('close', function(code, reason) {
|
||||
console.error(`streamer disconnected: ${code} - ${reason}`);
|
||||
onStreamerDisconnected();
|
||||
});
|
||||
|
||||
ws.on('error', function(error) {
|
||||
console.error(`streamer connection error: ${error}`);
|
||||
onStreamerDisconnected();
|
||||
try {
|
||||
ws.close(1006 /* abnormal closure */, error);
|
||||
} catch(err) {
|
||||
console.error(`ERROR: ws.on error: ${err.message}`);
|
||||
}
|
||||
});
|
||||
|
||||
streamer = ws;
|
||||
|
||||
streamer.send(JSON.stringify(clientConfig));
|
||||
|
||||
if (sfuIsConnected()) {
|
||||
const msg = { type: "playerConnected", playerId: SFUPlayerId, dataChannel: true, sfu: true };
|
||||
streamer.send(JSON.stringify(msg));
|
||||
}
|
||||
});
|
||||
|
||||
console.logColor(logging.Green, `WebSocket listening for SFU connections on :${sfuPort}`);
|
||||
let sfuServer = new WebSocket.Server({ port: sfuPort});
|
||||
sfuServer.on('connection', function (ws, req) {
|
||||
// reject if we already have an sfu
|
||||
if (sfuIsConnected()) {
|
||||
ws.close(1013, 'Already have SFU');
|
||||
return;
|
||||
}
|
||||
|
||||
players.set(SFUPlayerId, { ws: ws, id: SFUPlayerId });
|
||||
|
||||
ws.on('message', (msgRaw) => {
|
||||
var msg;
|
||||
try {
|
||||
msg = JSON.parse(msgRaw);
|
||||
} catch (err) {
|
||||
console.error(`cannot parse SFU message: ${msgRaw}\nError: ${err}`);
|
||||
ws.close(1008, 'Cannot parse');
|
||||
return;
|
||||
}
|
||||
|
||||
logIncoming("SFU", msg.type, msgRaw);
|
||||
|
||||
if (msg.type == 'offer') {
|
||||
// offers from the sfu are for players
|
||||
const playerId = msg.playerId;
|
||||
delete msg.playerId;
|
||||
sendMessageToPlayer(playerId, msg);
|
||||
}
|
||||
else if (msg.type == 'answer') {
|
||||
// answers from the sfu are for the streamer
|
||||
msg.playerId = SFUPlayerId;
|
||||
const rawMsg = JSON.stringify(msg);
|
||||
logOutgoing("Streamer", msg.type, rawMsg);
|
||||
streamer.send(rawMsg);
|
||||
}
|
||||
else if (msg.type == 'streamerDataChannels') {
|
||||
// sfu is asking streamer to open a data channel for a connected peer
|
||||
msg.sfuId = SFUPlayerId;
|
||||
const rawMsg = JSON.stringify(msg);
|
||||
logOutgoing("Streamer", msg.type, rawMsg);
|
||||
streamer.send(rawMsg);
|
||||
}
|
||||
else if (msg.type == 'peerDataChannels') {
|
||||
// sfu is telling a peer what stream id to use for a data channel
|
||||
const playerId = msg.playerId;
|
||||
delete msg.playerId;
|
||||
sendMessageToPlayer(playerId, msg);
|
||||
// remember the player has a data channel
|
||||
const player = players.get(playerId);
|
||||
player.datachannel = true;
|
||||
}
|
||||
});
|
||||
|
||||
ws.on('close', function(code, reason) {
|
||||
console.error(`SFU disconnected: ${code} - ${reason}`);
|
||||
sfu = null;
|
||||
disconnectSFUPlayer();
|
||||
});
|
||||
|
||||
ws.on('error', function(error) {
|
||||
console.error(`SFU connection error: ${error}`);
|
||||
sfu = null;
|
||||
disconnectSFUPlayer();
|
||||
try {
|
||||
ws.close(1006 /* abnormal closure */, error);
|
||||
} catch(err) {
|
||||
console.error(`ERROR: ws.on error: ${err.message}`);
|
||||
}
|
||||
});
|
||||
|
||||
sfu = ws;
|
||||
console.logColor(logging.Green, `SFU (${req.connection.remoteAddress}) connected `);
|
||||
|
||||
if (streamer && streamer.readyState == 1) {
|
||||
const msg = { type: "playerConnected", playerId: SFUPlayerId, dataChannel: true, sfu: true };
|
||||
streamer.send(JSON.stringify(msg));
|
||||
}
|
||||
});
|
||||
|
||||
let playerCount = 0;
|
||||
|
||||
console.logColor(logging.Green, `WebSocket listening for Players connections on :${httpPort}`);
|
||||
let playerServer = new WebSocket.Server({ server: config.UseHTTPS ? https : http});
|
||||
playerServer.on('connection', function (ws, req) {
|
||||
// Reject connection if streamer is not connected
|
||||
if (!streamer || streamer.readyState != 1 /* OPEN */) {
|
||||
ws.close(1013 /* Try again later */, 'Streamer is not connected');
|
||||
return;
|
||||
}
|
||||
|
||||
var url = require('url');
|
||||
const parsedUrl = url.parse(req.url);
|
||||
const urlParams = new URLSearchParams(parsedUrl.search);
|
||||
const preferSFU = urlParams.has('preferSFU') && urlParams.get('preferSFU') !== 'false';
|
||||
const skipSFU = !preferSFU;
|
||||
const skipStreamer = preferSFU && sfu;
|
||||
|
||||
if(preferSFU && !sfu) {
|
||||
ws.send(JSON.stringify({ type: "warning", warning: "Even though ?preferSFU was specified, there is currently no SFU connected." }));
|
||||
}
|
||||
|
||||
if(playerCount + 1 > maxPlayerCount && maxPlayerCount !== -1)
|
||||
{
|
||||
console.logColor(logging.Red, `new connection would exceed number of allowed concurrent connections. Max: ${maxPlayerCount}, Current ${playerCount}`);
|
||||
ws.close(1013, `too many connections. max: ${maxPlayerCount}, current: ${playerCount}`);
|
||||
return;
|
||||
}
|
||||
|
||||
++playerCount;
|
||||
let playerId = (++nextPlayerId).toString();
|
||||
console.logColor(logging.Green, `player ${playerId} (${req.connection.remoteAddress}) connected`);
|
||||
players.set(playerId, { ws: ws, id: playerId });
|
||||
|
||||
function sendPlayersCount() {
|
||||
let playerCountMsg = JSON.stringify({ type: 'playerCount', count: players.size });
|
||||
for (let p of players.values()) {
|
||||
p.ws.send(playerCountMsg);
|
||||
}
|
||||
}
|
||||
|
||||
ws.on('message', (msgRaw) =>{
|
||||
|
||||
var msg;
|
||||
try {
|
||||
msg = JSON.parse(msgRaw);
|
||||
} catch (err) {
|
||||
console.error(`cannot parse player ${playerId} message: ${msgRaw}\nError: ${err}`);
|
||||
ws.close(1008, 'Cannot parse');
|
||||
return;
|
||||
}
|
||||
|
||||
if(!msg || !msg.type)
|
||||
{
|
||||
console.error(`Cannot parse message ${msgRaw}`);
|
||||
return;
|
||||
}
|
||||
|
||||
logIncoming(`player ${playerId}`, msg.type, msgRaw);
|
||||
|
||||
if (msg.type == 'offer') {
|
||||
msg.playerId = playerId;
|
||||
sendMessageToController(msg, skipSFU);
|
||||
} else if (msg.type == 'answer') {
|
||||
msg.playerId = playerId;
|
||||
sendMessageToController(msg, skipSFU, skipStreamer);
|
||||
} else if (msg.type == 'iceCandidate') {
|
||||
msg.playerId = playerId;
|
||||
sendMessageToController(msg, skipSFU, skipStreamer);
|
||||
} else if (msg.type == 'stats') {
|
||||
console.log(`player ${playerId}: stats\n${msg.data}`);
|
||||
} else if (msg.type == "dataChannelRequest") {
|
||||
msg.playerId = playerId;
|
||||
sendMessageToController(msg, skipSFU, true);
|
||||
} else if (msg.type == "peerDataChannelsReady") {
|
||||
msg.playerId = playerId;
|
||||
sendMessageToController(msg, skipSFU, true);
|
||||
}
|
||||
else {
|
||||
console.error(`player ${playerId}: unsupported message type: ${msg.type}`);
|
||||
ws.close(1008, 'Unsupported message type');
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
function onPlayerDisconnected() {
|
||||
try {
|
||||
--playerCount;
|
||||
const player = players.get(playerId);
|
||||
if (player.datachannel) {
|
||||
// have to notify the streamer that the datachannel can be closed
|
||||
sendMessageToController({ type: 'playerDisconnected', playerId: playerId }, true, false);
|
||||
}
|
||||
players.delete(playerId);
|
||||
sendMessageToController({ type: 'playerDisconnected', playerId: playerId }, skipSFU);
|
||||
sendPlayerDisconnectedToFrontend();
|
||||
sendPlayerDisconnectedToMatchmaker();
|
||||
sendPlayersCount();
|
||||
} catch(err) {
|
||||
console.logColor(logging.Red, `ERROR:: onPlayerDisconnected error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
ws.on('close', function(code, reason) {
|
||||
console.logColor(logging.Yellow, `player ${playerId} connection closed: ${code} - ${reason}`);
|
||||
onPlayerDisconnected();
|
||||
});
|
||||
|
||||
ws.on('error', function(error) {
|
||||
console.error(`player ${playerId} connection error: ${error}`);
|
||||
ws.close(1006 /* abnormal closure */, error);
|
||||
onPlayerDisconnected();
|
||||
|
||||
console.logColor(logging.Red, `Trying to reconnect...`);
|
||||
reconnect();
|
||||
});
|
||||
|
||||
sendPlayerConnectedToFrontend();
|
||||
sendPlayerConnectedToMatchmaker();
|
||||
|
||||
ws.send(JSON.stringify(clientConfig));
|
||||
|
||||
sendMessageToController({ type: "playerConnected", playerId: playerId, dataChannel: true, sfu: false }, skipSFU, skipStreamer);
|
||||
sendPlayersCount();
|
||||
});
|
||||
|
||||
function disconnectAllPlayers(code, reason) {
|
||||
console.log("killing all players");
|
||||
let clone = new Map(players);
|
||||
for (let player of clone.values()) {
|
||||
if (player.id != SFUPlayerId) { // dont dc the sfu
|
||||
player.ws.close(code, reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function disconnectSFUPlayer() {
|
||||
console.log("disconnecting SFU from streamer");
|
||||
if(players.has(SFUPlayerId)) {
|
||||
players.get(SFUPlayerId).ws.close(4000, "SFU Disconnected");
|
||||
players.delete(SFUPlayerId);
|
||||
}
|
||||
sendMessageToController({ type: 'playerDisconnected', playerId: SFUPlayerId }, true, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function that handles the connection to the matchmaker.
|
||||
*/
|
||||
|
||||
if (config.UseMatchmaker) {
|
||||
var matchmaker = new net.Socket();
|
||||
|
||||
matchmaker.on('connect', function() {
|
||||
console.log(`Cirrus connected to Matchmaker ${matchmakerAddress}:${matchmakerPort}`);
|
||||
|
||||
// message.playerConnected is a new variable sent from the SS to help track whether or not a player
|
||||
// is already connected when a 'connect' message is sent (i.e., reconnect). This happens when the MM
|
||||
// and the SS get disconnected unexpectedly (was happening often at scale for some reason).
|
||||
var playerConnected = false;
|
||||
|
||||
// Set the playerConnected flag to tell the MM if there is already a player active (i.e., don't send a new one here)
|
||||
if( players && players.size > 0) {
|
||||
playerConnected = true;
|
||||
}
|
||||
|
||||
// Add the new playerConnected flag to the message body to the MM
|
||||
message = {
|
||||
type: 'connect',
|
||||
address: typeof serverPublicIp === 'undefined' ? '127.0.0.1' : serverPublicIp,
|
||||
port: httpPort,
|
||||
ready: streamer && streamer.readyState === 1,
|
||||
playerConnected: playerConnected
|
||||
};
|
||||
|
||||
matchmaker.write(JSON.stringify(message));
|
||||
});
|
||||
|
||||
matchmaker.on('error', (err) => {
|
||||
console.log(`Matchmaker connection error ${JSON.stringify(err)}`);
|
||||
});
|
||||
|
||||
matchmaker.on('end', () => {
|
||||
console.log('Matchmaker connection ended');
|
||||
});
|
||||
|
||||
matchmaker.on('close', (hadError) => {
|
||||
console.logColor(logging.Blue, 'Setting Keep Alive to true');
|
||||
matchmaker.setKeepAlive(true, 60000); // Keeps it alive for 60 seconds
|
||||
|
||||
console.log(`Matchmaker connection closed (hadError=${hadError})`);
|
||||
|
||||
reconnect();
|
||||
});
|
||||
|
||||
// Attempt to connect to the Matchmaker
|
||||
function connect() {
|
||||
matchmaker.connect(matchmakerPort, matchmakerAddress);
|
||||
}
|
||||
|
||||
// Try to reconnect to the Matchmaker after a given period of time
|
||||
function reconnect() {
|
||||
console.log(`Try reconnect to Matchmaker in ${matchmakerRetryInterval} seconds`)
|
||||
setTimeout(function() {
|
||||
connect();
|
||||
}, matchmakerRetryInterval * 1000);
|
||||
}
|
||||
|
||||
function registerMMKeepAlive() {
|
||||
setInterval(function() {
|
||||
message = {
|
||||
type: 'ping'
|
||||
};
|
||||
matchmaker.write(JSON.stringify(message));
|
||||
}, matchmakerKeepAliveInterval * 1000);
|
||||
}
|
||||
|
||||
connect();
|
||||
registerMMKeepAlive();
|
||||
}
|
||||
|
||||
//Keep trying to send gameSessionId in case the server isn't ready yet
|
||||
function sendGameSessionData() {
|
||||
//If we are not using the frontend web server don't try and make requests to it
|
||||
if (!config.UseFrontend)
|
||||
return;
|
||||
webRequest.get(`${FRONTEND_WEBSERVER}/server/requestSessionId`,
|
||||
function (response, body) {
|
||||
if (response.statusCode === 200) {
|
||||
gameSessionId = body;
|
||||
console.log('SessionId: ' + gameSessionId);
|
||||
}
|
||||
else {
|
||||
console.error('Status code: ' + response.statusCode);
|
||||
console.error(body);
|
||||
}
|
||||
},
|
||||
function (err) {
|
||||
//Repeatedly try in cases where the connection timed out or never connected
|
||||
if (err.code === "ECONNRESET") {
|
||||
//timeout
|
||||
sendGameSessionData();
|
||||
} else if (err.code === 'ECONNREFUSED') {
|
||||
console.error('Frontend server not running, unable to setup game session');
|
||||
} else {
|
||||
console.error(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function sendUserSessionData(serverPort) {
|
||||
//If we are not using the frontend web server don't try and make requests to it
|
||||
if (!config.UseFrontend)
|
||||
return;
|
||||
webRequest.get(`${FRONTEND_WEBSERVER}/server/requestUserSessionId?gameSessionId=${gameSessionId}&serverPort=${serverPort}&appName=${querystring.escape(clientConfig.AppName)}&appDescription=${querystring.escape(clientConfig.AppDescription)}${(typeof serverPublicIp === 'undefined' ? '' : '&serverHost=' + serverPublicIp)}`,
|
||||
function (response, body) {
|
||||
if (response.statusCode === 410) {
|
||||
sendUserSessionData(serverPort);
|
||||
} else if (response.statusCode === 200) {
|
||||
userSessionId = body;
|
||||
console.log('UserSessionId: ' + userSessionId);
|
||||
} else {
|
||||
console.error('Status code: ' + response.statusCode);
|
||||
console.error(body);
|
||||
}
|
||||
},
|
||||
function (err) {
|
||||
//Repeatedly try in cases where the connection timed out or never connected
|
||||
if (err.code === "ECONNRESET") {
|
||||
//timeout
|
||||
sendUserSessionData(serverPort);
|
||||
} else if (err.code === 'ECONNREFUSED') {
|
||||
console.error('Frontend server not running, unable to setup user session');
|
||||
} else {
|
||||
console.error(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function sendServerDisconnect() {
|
||||
//If we are not using the frontend web server don't try and make requests to it
|
||||
if (!config.UseFrontend)
|
||||
return;
|
||||
try {
|
||||
webRequest.get(`${FRONTEND_WEBSERVER}/server/serverDisconnected?gameSessionId=${gameSessionId}&appName=${querystring.escape(clientConfig.AppName)}`,
|
||||
function (response, body) {
|
||||
if (response.statusCode === 200) {
|
||||
console.log('serverDisconnected acknowledged by Frontend');
|
||||
} else {
|
||||
console.error('Status code: ' + response.statusCode);
|
||||
console.error(body);
|
||||
}
|
||||
},
|
||||
function (err) {
|
||||
//Repeatedly try in cases where the connection timed out or never connected
|
||||
if (err.code === "ECONNRESET") {
|
||||
//timeout
|
||||
sendServerDisconnect();
|
||||
} else if (err.code === 'ECONNREFUSED') {
|
||||
console.error('Frontend server not running, unable to setup user session');
|
||||
} else {
|
||||
console.error(err);
|
||||
}
|
||||
});
|
||||
} catch(err) {
|
||||
console.logColor(logging.Red, `ERROR::: sendServerDisconnect error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function sendPlayerConnectedToFrontend() {
|
||||
//If we are not using the frontend web server don't try and make requests to it
|
||||
if (!config.UseFrontend)
|
||||
return;
|
||||
try {
|
||||
webRequest.get(`${FRONTEND_WEBSERVER}/server/clientConnected?gameSessionId=${gameSessionId}&appName=${querystring.escape(clientConfig.AppName)}`,
|
||||
function (response, body) {
|
||||
if (response.statusCode === 200) {
|
||||
console.log('clientConnected acknowledged by Frontend');
|
||||
} else {
|
||||
console.error('Status code: ' + response.statusCode);
|
||||
console.error(body);
|
||||
}
|
||||
},
|
||||
function (err) {
|
||||
//Repeatedly try in cases where the connection timed out or never connected
|
||||
if (err.code === "ECONNRESET") {
|
||||
//timeout
|
||||
sendPlayerConnectedToFrontend();
|
||||
} else if (err.code === 'ECONNREFUSED') {
|
||||
console.error('Frontend server not running, unable to setup game session');
|
||||
} else {
|
||||
console.error(err);
|
||||
}
|
||||
});
|
||||
} catch(err) {
|
||||
console.logColor(logging.Red, `ERROR::: sendPlayerConnectedToFrontend error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function sendPlayerDisconnectedToFrontend() {
|
||||
//If we are not using the frontend web server don't try and make requests to it
|
||||
if (!config.UseFrontend)
|
||||
return;
|
||||
try {
|
||||
webRequest.get(`${FRONTEND_WEBSERVER}/server/clientDisconnected?gameSessionId=${gameSessionId}&appName=${querystring.escape(clientConfig.AppName)}`,
|
||||
function (response, body) {
|
||||
if (response.statusCode === 200) {
|
||||
console.log('clientDisconnected acknowledged by Frontend');
|
||||
}
|
||||
else {
|
||||
console.error('Status code: ' + response.statusCode);
|
||||
console.error(body);
|
||||
}
|
||||
},
|
||||
function (err) {
|
||||
//Repeatedly try in cases where the connection timed out or never connected
|
||||
if (err.code === "ECONNRESET") {
|
||||
//timeout
|
||||
sendPlayerDisconnectedToFrontend();
|
||||
} else if (err.code === 'ECONNREFUSED') {
|
||||
console.error('Frontend server not running, unable to setup game session');
|
||||
} else {
|
||||
console.error(err);
|
||||
}
|
||||
});
|
||||
} catch(err) {
|
||||
console.logColor(logging.Red, `ERROR::: sendPlayerDisconnectedToFrontend error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function sendStreamerConnectedToMatchmaker() {
|
||||
if (!config.UseMatchmaker)
|
||||
return;
|
||||
try {
|
||||
message = {
|
||||
type: 'streamerConnected'
|
||||
};
|
||||
matchmaker.write(JSON.stringify(message));
|
||||
} catch (err) {
|
||||
console.logColor(logging.Red, `ERROR sending streamerConnected: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function sendStreamerDisconnectedToMatchmaker() {
|
||||
if (!config.UseMatchmaker)
|
||||
return;
|
||||
try {
|
||||
message = {
|
||||
type: 'streamerDisconnected'
|
||||
};
|
||||
matchmaker.write(JSON.stringify(message));
|
||||
} catch (err) {
|
||||
console.logColor(logging.Red, `ERROR sending streamerDisconnected: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// The Matchmaker will not re-direct clients to this Cirrus server if any client
|
||||
// is connected.
|
||||
function sendPlayerConnectedToMatchmaker() {
|
||||
if (!config.UseMatchmaker)
|
||||
return;
|
||||
try {
|
||||
message = {
|
||||
type: 'clientConnected'
|
||||
};
|
||||
matchmaker.write(JSON.stringify(message));
|
||||
} catch (err) {
|
||||
console.logColor(logging.Red, `ERROR sending clientConnected: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// The Matchmaker is interested when nobody is connected to a Cirrus server
|
||||
// because then it can re-direct clients to this re-cycled Cirrus server.
|
||||
function sendPlayerDisconnectedToMatchmaker() {
|
||||
if (!config.UseMatchmaker)
|
||||
return;
|
||||
try {
|
||||
message = {
|
||||
type: 'clientDisconnected'
|
||||
};
|
||||
matchmaker.write(JSON.stringify(message));
|
||||
} catch (err) {
|
||||
console.logColor(logging.Red, `ERROR sending clientDisconnected: ${err.message}`);
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"UseFrontend": false,
|
||||
"UseMatchmaker": false,
|
||||
"UseHTTPS": false,
|
||||
"UseAuthentication": false,
|
||||
"LogToFile": true,
|
||||
"LogVerbose": true,
|
||||
"HomepageFile": "player.html",
|
||||
"AdditionalRoutes": {},
|
||||
"EnableWebserver": true,
|
||||
"MatchmakerAddress": "",
|
||||
"MatchmakerPort": 9999,
|
||||
"PublicIp": "localhost",
|
||||
"HttpPort": 80,
|
||||
"HttpsPort": 443,
|
||||
"StreamerPort": 8888,
|
||||
"SFUPort": 8889,
|
||||
"MaxPlayerCount": -1
|
||||
}
|
||||
-2
@@ -1,2 +0,0 @@
|
||||
// Copyright Epic Games, Inc. All Rights Reserved.
|
||||
exports.users = require('./users');
|
||||
-80
@@ -1,80 +0,0 @@
|
||||
// Copyright Epic Games, Inc. All Rights Reserved.
|
||||
//
|
||||
// Usage: npm run store_password -- --username <USERNAME> --password <PASSWORD>
|
||||
// or from ./modules/authentication/db dir: node store_password.js --username <USERNAME> --password <PASSWORD>
|
||||
//
|
||||
// --usersFile is an optional parameter that can be used to specify a different location for the users database file
|
||||
// use this if running the command from a different working dir. The default location is './users.json'
|
||||
// e.g. If running from the SignallingWebServer dir use: --usersFile ./modules/authentication/db/users.json
|
||||
|
||||
const argv = require('yargs').argv;
|
||||
const fs = require('fs');
|
||||
const bcrypt = require('bcryptjs');
|
||||
|
||||
var username, password;
|
||||
var usersFile = './users.json'
|
||||
|
||||
const STORE_PLAINTEXT_PASSWORD = false;
|
||||
|
||||
try {
|
||||
if(typeof argv.username != 'undefined'){
|
||||
username = argv.username.toString();
|
||||
}
|
||||
|
||||
if(typeof argv.password != 'undefined'){
|
||||
password = argv.password;
|
||||
}
|
||||
|
||||
if(typeof argv.usersFile != 'undefined'){
|
||||
usersFile = argv.usersFile;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
if(username && password){
|
||||
let existingAccounts = [];
|
||||
if (fs.existsSync(usersFile)) {
|
||||
console.log(`File '${usersFile}' exists, reading file`)
|
||||
var content = fs.readFileSync(usersFile, 'utf8');
|
||||
try{
|
||||
existingAccounts = JSON.parse(content);
|
||||
}
|
||||
catch(e){
|
||||
console.error(`Existing file '${usersFile}', has invalid JSON: ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
var existingUser = existingAccounts.find( u => u.username == username)
|
||||
if(existingUser){
|
||||
console.log(`User '${username}', already exists, updating password`)
|
||||
existingUser.passwordHash = generatePasswordHash(password)
|
||||
if(STORE_PLAINTEXT_PASSWORD)
|
||||
existingUser.password = password;
|
||||
else if (existingUser.password)
|
||||
delete existingUser.password;
|
||||
|
||||
} else {
|
||||
console.log(`Adding new user '${username}'`)
|
||||
let newUser = {
|
||||
id: existingAccounts.length + 1,
|
||||
username: username,
|
||||
passwordHash: generatePasswordHash(password)
|
||||
}
|
||||
if(STORE_PLAINTEXT_PASSWORD)
|
||||
newUser.password = password;
|
||||
|
||||
existingAccounts.push(newUser);
|
||||
}
|
||||
|
||||
console.log(`Writing updated users to '${usersFile}'`);
|
||||
var newContent = JSON.stringify(existingAccounts);
|
||||
fs.writeFileSync(usersFile, newContent);
|
||||
} else {
|
||||
console.log(`Please pass in both username (${username}) and password (${password}) please`);
|
||||
}
|
||||
|
||||
function generatePasswordHash(pass){
|
||||
return bcrypt.hashSync(pass, 12)
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
// Copyright Epic Games, Inc. All Rights Reserved.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
// Read in users from file
|
||||
let records = [];
|
||||
let usersFile = path.join(__dirname, './users.json');
|
||||
if (fs.existsSync(usersFile)) {
|
||||
console.log(`Reading users from '${usersFile}'`)
|
||||
var content = fs.readFileSync(usersFile, 'utf8');
|
||||
try {
|
||||
records = JSON.parse(content);
|
||||
} catch(e) {
|
||||
console.log(`ERROR: Failed to parse users from file '${usersFile}'`)
|
||||
}
|
||||
}
|
||||
|
||||
exports.findById = function(id, cb) {
|
||||
var idx = id - 1;
|
||||
if (records[idx]) {
|
||||
cb(null, records[idx]);
|
||||
} else {
|
||||
cb(new Error('User ' + id + ' does not exist'));
|
||||
}
|
||||
}
|
||||
|
||||
exports.findByUsername = function(username, cb) {
|
||||
for (var i = 0, len = records.length; i < len; i++) {
|
||||
var record = records[i];
|
||||
if (record.username === username) {
|
||||
return cb(null, record);
|
||||
}
|
||||
}
|
||||
return cb(null, null);
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
// Copyright Epic Games, Inc. All Rights Reserved.
|
||||
module.exports = {
|
||||
init: require('./init')
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
// Copyright Epic Games, Inc. All Rights Reserved.
|
||||
// Adapted from
|
||||
// * https://blog.risingstack.com/node-hero-node-js-authentication-passport-js/
|
||||
// * https://github.com/RisingStack/nodehero-authentication/tree/master/app
|
||||
// * https://github.com/passport/express-4.x-local-example
|
||||
|
||||
|
||||
const passport = require('passport');
|
||||
const session = require('express-session');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const LocalStrategy = require('passport-local').Strategy;
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
var db = require('./db');
|
||||
|
||||
function initPassport (app) {
|
||||
|
||||
// Generate session secret if it doesn't already exist and save it to file for use next time
|
||||
let config = {};
|
||||
let configPath = path.join(__dirname, './config.json');
|
||||
if (fs.existsSync(configPath)) {
|
||||
let content = fs.readFileSync(configPath, 'utf8');
|
||||
try {
|
||||
config = JSON.parse(content);
|
||||
} catch (e) {
|
||||
console.log(`Error with config file '${configPath}': ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
if(!config.sessionSecret){
|
||||
config.sessionSecret = bcrypt.genSaltSync(12);
|
||||
let content = JSON.stringify(config);
|
||||
fs.writeFileSync(configPath, content);
|
||||
}
|
||||
|
||||
// Setup session id settings
|
||||
app.use(session({
|
||||
secret: config.sessionSecret,
|
||||
resave: false,
|
||||
saveUninitialized: false,
|
||||
cookie: {
|
||||
secure: true,
|
||||
maxAge: 24 * 60 * 60 * 1000 /* 1 day */
|
||||
//maxAge: 5 * 1000 /* 5 seconds */
|
||||
}
|
||||
}));
|
||||
|
||||
app.use(passport.initialize());
|
||||
app.use(passport.session());
|
||||
|
||||
passport.serializeUser(function(user, cb) {
|
||||
cb(null, user.id);
|
||||
});
|
||||
|
||||
passport.deserializeUser(function(id, cb) {
|
||||
db.users.findById(id, function (err, user) {
|
||||
if (err) { return cb(err); }
|
||||
cb(null, user);
|
||||
});
|
||||
});
|
||||
|
||||
console.log('Setting up auth');
|
||||
passport.use(new LocalStrategy(
|
||||
(username, password, callback) => {
|
||||
db.users.findByUsername(username, (err, user) => {
|
||||
if (err) {
|
||||
console.log(`Unable to login '${username}', error ${err}`);
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
// User not found
|
||||
if (!user) {
|
||||
console.log(`User '${username}' not found`);
|
||||
return callback(null, false);
|
||||
}
|
||||
|
||||
// Always use hashed passwords and fixed time comparison
|
||||
bcrypt.compare(password, user.passwordHash, (err, isValid) => {
|
||||
if (err) {
|
||||
console.log(`Error comparing password for user '${username}': ${err}`);
|
||||
return callback(err);
|
||||
}
|
||||
if (!isValid) {
|
||||
console.log(`Password incorrect for user '${username}'`)
|
||||
return callback(null, false);
|
||||
}
|
||||
|
||||
console.log(`User '${username}' logged in`);
|
||||
return callback(null, user);
|
||||
});
|
||||
})
|
||||
}
|
||||
));
|
||||
|
||||
passport.authenticationMiddleware = function authenticationMiddleware (redirectUrl) {
|
||||
return function (req, res, next) {
|
||||
if (req.isAuthenticated()) {
|
||||
return next();
|
||||
}
|
||||
|
||||
// Set redirectTo property so that user can be redirected back there after logging in
|
||||
//console.log(`Original request path '${req.originalUrl}'`);
|
||||
req.session.redirectTo = req.originalUrl;
|
||||
res.redirect(redirectUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = initPassport;
|
||||
@@ -1,56 +0,0 @@
|
||||
// Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
//-- Provides configuration information from file and combines it with default values and command line arguments --//
|
||||
//-- Hierachy of values: Default Values < Config File < Command Line arguments --//
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const argv = require('yargs').argv;
|
||||
|
||||
function initConfig(configFile, defaultConfig){
|
||||
defaultConfig = defaultConfig || {};
|
||||
|
||||
// Using object spread syntax: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals
|
||||
let config = {...defaultConfig};
|
||||
try {
|
||||
let configData = fs.readFileSync(configFile, 'UTF8');
|
||||
fileConfig = JSON.parse(configData);
|
||||
config = {...config, ...fileConfig}
|
||||
|
||||
try {
|
||||
accessSync('configFile', constants.W_OK);
|
||||
// Update config file with any additional defaults (does not override existing values if default has changed)
|
||||
fs.writeFileSync(configFile, JSON.stringify(config, null, '\t'), 'UTF8');
|
||||
} catch (err) {
|
||||
console.log("Config file is readonly, skipping writing config...");
|
||||
}
|
||||
|
||||
} catch(err) {
|
||||
if (err.code === 'ENOENT') {
|
||||
console.log("No config file found, writing defaults to log file " + configFile);
|
||||
fs.writeFileSync(configFile, JSON.stringify(config, null, '\t'), 'UTF8');
|
||||
} else if (err instanceof SyntaxError) {
|
||||
console.log(`ERROR: Invalid JSON in ${configFile}, ignoring file config, ${err}`)
|
||||
} else {
|
||||
console.log(`ERROR: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
//Make a copy of the command line args and remove the unneccessary ones
|
||||
//The _ value is an array of any elements without a key
|
||||
let commandLineConfig = {...argv}
|
||||
delete commandLineConfig._;
|
||||
delete commandLineConfig.help;
|
||||
delete commandLineConfig.version;
|
||||
delete commandLineConfig['$0'];
|
||||
config = {...config, ...commandLineConfig}
|
||||
} catch(err) {
|
||||
console.log(`ERROR: ${err}`);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
init: initConfig
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
// Copyright Epic Games, Inc. All Rights Reserved.
|
||||
var querystring = require('querystring')
|
||||
const https = require('https');
|
||||
const assert = require('assert');
|
||||
|
||||
function cleanUrl(aUrl){
|
||||
let url = aUrl;
|
||||
if(url.startsWith("https://"))
|
||||
url = url.substring("https://".length);
|
||||
|
||||
return url
|
||||
}
|
||||
|
||||
function createOptions(requestType, url){
|
||||
let index = url.indexOf('/');
|
||||
|
||||
let urlParts = url.split('/', 2)
|
||||
|
||||
return {
|
||||
hostname: (index === -1) ? url.substring(0) : url.substring(0, index),
|
||||
port: 443,
|
||||
path: (index === -1) ? '' : url.substring(index),
|
||||
method: requestType,
|
||||
timeout: 30000,
|
||||
};
|
||||
}
|
||||
|
||||
function makeHttpsCall(options, aCallback, aError){
|
||||
//console.log(JSON.stringify(options));
|
||||
const req = https.request(options, function(response){
|
||||
let data = '';
|
||||
|
||||
//console.log('statusCode:', response.statusCode);
|
||||
//console.log('headers:', response.headers);
|
||||
|
||||
// A chunk of data has been received.
|
||||
response.on('data', (chunk) => {
|
||||
data += chunk;
|
||||
});
|
||||
|
||||
// The whole response has been received. Print out the result.
|
||||
response.on('end', () => {
|
||||
if(typeof aCallback != "undefined")
|
||||
aCallback(response, data);
|
||||
});
|
||||
});
|
||||
|
||||
req.on('timeout', function () {
|
||||
console.log("Request timed out. " + (options.timeout / 1000) + " seconds expired");
|
||||
|
||||
// Source: https://github.com/nodejs/node/blob/master/test/parallel/test-http-client-timeout-option.js#L27
|
||||
req.destroy();
|
||||
});
|
||||
|
||||
req.on("error", (err) => {
|
||||
if(typeof aError != "undefined") {
|
||||
aError(err);
|
||||
} else {
|
||||
console.log("Error: " + err.message);
|
||||
}
|
||||
});
|
||||
|
||||
return req;
|
||||
}
|
||||
|
||||
module.exports = class HttpClient {
|
||||
get(aUrl, aCallback, aError) {
|
||||
let url = cleanUrl(aUrl);
|
||||
|
||||
let options = createOptions('GET', url);
|
||||
|
||||
const req = makeHttpsCall(options, aCallback, aError);
|
||||
|
||||
req.end();
|
||||
}
|
||||
|
||||
post(aUrl, body, aCallback, aError) {
|
||||
let url = cleanUrl(aUrl);
|
||||
|
||||
let options = createOptions('POST', url);
|
||||
|
||||
let postBody = querystring.stringify(body);
|
||||
|
||||
//Add extra options for POST request type
|
||||
options.headers = {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Content-Length': postBody.length
|
||||
};
|
||||
|
||||
const req = makeHttpsCall(options, aCallback, aError);
|
||||
|
||||
req.write(postBody);
|
||||
req.end();
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
// Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
const fs = require('fs');
|
||||
const { Console } = require('console');
|
||||
|
||||
var loggers=[];
|
||||
var logFunctions=[];
|
||||
var logColorFunctions=[];
|
||||
|
||||
console.log = function(msg, ...args) {
|
||||
logFunctions.forEach((logFunction) => {
|
||||
logFunction(msg, ...args);
|
||||
});
|
||||
}
|
||||
|
||||
console.logColor = function(color, msg, ...args) {
|
||||
logColorFunctions.forEach((logColorFunction) => {
|
||||
logColorFunction(color, msg, ...args);
|
||||
});
|
||||
}
|
||||
|
||||
const AllAttributesOff = '\x1b[0m';
|
||||
const BoldOn = '\x1b[1m';
|
||||
const Black = '\x1b[30m';
|
||||
const Red = '\x1b[31m';
|
||||
const Green = '\x1b[32m';
|
||||
const Yellow = '\x1b[33m';
|
||||
const Blue = '\x1b[34m';
|
||||
const Magenta = '\x1b[35m';
|
||||
const Cyan = '\x1b[36m';
|
||||
const White = '\x1b[37m';
|
||||
|
||||
/**
|
||||
* Pad the start of the given number with zeros so it takes up the number of digits.
|
||||
* e.g. zeroPad(5, 3) = '005' and zeroPad(23, 2) = '23'.
|
||||
*/
|
||||
function zeroPad(number, digits) {
|
||||
let string = number.toString();
|
||||
while (string.length < digits) {
|
||||
string = '0' + string;
|
||||
}
|
||||
return string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a string of the form 'YEAR.MONTH.DATE.HOURS.MINUTES.SECONDS'.
|
||||
*/
|
||||
function dateTimeToString() {
|
||||
let date = new Date();
|
||||
return `${date.getFullYear()}.${zeroPad(date.getMonth(), 2)}.${zeroPad(date.getDate(), 2)}.${zeroPad(date.getHours(), 2)}.${zeroPad(date.getMinutes(), 2)}.${zeroPad(date.getSeconds(), 2)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a string of the form 'HOURS.MINUTES.SECONDS.MILLISECONDS'.
|
||||
*/
|
||||
function timeToString() {
|
||||
let date = new Date();
|
||||
return `${zeroPad(date.getHours(), 2)}:${zeroPad(date.getMinutes(), 2)}:${zeroPad(date.getSeconds(), 2)}.${zeroPad(date.getMilliseconds(), 3)}`;
|
||||
}
|
||||
|
||||
function RegisterFileLogger(path) {
|
||||
if(path == null)
|
||||
path = './logs/';
|
||||
|
||||
if (!fs.existsSync(path))
|
||||
fs.mkdirSync(path);
|
||||
|
||||
var output = fs.createWriteStream(`${path}${dateTimeToString()}.log`);
|
||||
var fileLogger = new Console(output);
|
||||
logFunctions.push(function(msg, ...args) {
|
||||
fileLogger.log(`${timeToString()} ${msg}`, ...args);
|
||||
});
|
||||
|
||||
logColorFunctions.push(function(color, msg, ...args) {
|
||||
fileLogger.log(`${timeToString()} ${msg}`, ...args);
|
||||
});
|
||||
loggers.push(fileLogger);
|
||||
}
|
||||
|
||||
function RegisterConsoleLogger() {
|
||||
var consoleLogger = new Console(process.stdout, process.stderr)
|
||||
logFunctions.push(function(msg, ...args) {
|
||||
consoleLogger.log(`${timeToString()} ${msg}`, ...args);
|
||||
});
|
||||
|
||||
logColorFunctions.push(function(color, msg, ...args) {
|
||||
consoleLogger.log(`${BoldOn}${color}${timeToString()} ${msg}${AllAttributesOff}`, ...args);
|
||||
});
|
||||
loggers.push(consoleLogger);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
//Functions
|
||||
RegisterFileLogger,
|
||||
RegisterConsoleLogger,
|
||||
|
||||
//Variables
|
||||
AllAttributesOff,
|
||||
BoldOn,
|
||||
Black,
|
||||
Red,
|
||||
Green,
|
||||
Yellow,
|
||||
Blue,
|
||||
Magenta,
|
||||
Cyan,
|
||||
White
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,34 +0,0 @@
|
||||
{
|
||||
"name": "cirrus-webserver",
|
||||
"version": "0.0.1",
|
||||
"description": "cirrus web server",
|
||||
"scripts": {
|
||||
"store_password": "run-script-os",
|
||||
"store_password:default": "./platform_scripts/bash/node/bin/node ./modules/authentication/db/store_password.js --usersFile=./modules/authentication/db/users.json",
|
||||
"store_password:windows": "platform_scripts\\cmd\\node\\node.exe ./modules/authentication/db/store_password.js --usersFile=./modules/authentication/db/users.json",
|
||||
"start-local": "run-script-os --",
|
||||
"start-local:default": "./platform_scripts/bash/Start_Local.sh",
|
||||
"start-local:windows": ".\\platform_scripts\\cmd\\Start_Local.bat",
|
||||
"start-signalling-server": "run-script-os --",
|
||||
"start-signalling-server:default": "./platform_scripts/bash/Start_SignallingServer.sh",
|
||||
"start-signalling-server:windows": ".\\platform_scripts\\cmd\\Start_SignallingServer.bat",
|
||||
"start-with-turn-signalling-server": "run-script-os --",
|
||||
"start-with-turn-signalling-server:default": "./platform_scripts/bash/Start_WithTurn_SignallingServer.sh",
|
||||
"start-wiht-turn-signalling-server:windows": ".\\platform_scripts\\cmd\\Start_WithTurn_SignallingServer.bat",
|
||||
"start": "run-script-os",
|
||||
"start:default": "if [ `id -u` -eq 0 ] || [ ! -z $NO_SUDO ]\nthen\n export process=\"./platform_scripts/bash/node/bin/node cirrus.js\"\nelse\n export process=\"sudo ./platform_scripts/bash/node/bin/node cirrus.js\"\nfi\n$process ",
|
||||
"start:windows": "platform_scripts\\cmd\\node\\node.exe cirrus.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"bcryptjs": "^2.4.3",
|
||||
"express": "^4.18.2",
|
||||
"express-session": "^1.15.6",
|
||||
"helmet": "^3.21.3",
|
||||
"passport": "^0.6.0",
|
||||
"passport-local": "^1.0.0",
|
||||
"run-script-os": "^1.1.6",
|
||||
"ws": "^7.1.2",
|
||||
"y18n": "^5.0.5",
|
||||
"yargs": "^15.3.0"
|
||||
}
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
FROM node:latest
|
||||
|
||||
# Copy the signalling server source code to the Docker build context
|
||||
COPY . /opt/SignallingWebServer
|
||||
|
||||
# Install the dependencies for the signalling server
|
||||
WORKDIR /opt/SignallingWebServer
|
||||
RUN npm install .
|
||||
|
||||
# Expose TCP port 80 for player WebSocket connections and web server HTTP access
|
||||
EXPOSE 80
|
||||
|
||||
# Expose TCP port 8888 for streamer WebSocket connections
|
||||
EXPOSE 8888
|
||||
EXPOSE 8888/udp
|
||||
|
||||
# Expose port for SFU connections
|
||||
EXPOSE 8889
|
||||
|
||||
# Google stun
|
||||
EXPOSE 19302
|
||||
|
||||
# Matchmaker
|
||||
EXPOSE 9999
|
||||
|
||||
# Turn coturn
|
||||
EXPOSE 3478
|
||||
EXPOSE 3479
|
||||
|
||||
# Set the signalling server as the container's entrypoint
|
||||
ENTRYPOINT ["/usr/local/bin/node", "/opt/SignallingWebServer/cirrus.js"]
|
||||
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
How to use files in this directory:
|
||||
- Make sure that all of your dependencies are installed. Use ./setup.sh what will install whatever is missing as long as you are on a supported operating system. Please note that setup.sh is called from every script designed to run
|
||||
|
||||
- Run a local instance of the Cirrus server by using the ./run_local.sh script
|
||||
|
||||
- Use the following scripts to run locally or in your cloud instance:
|
||||
- Start_SignallingServer.sh - Start only the Signalling (STUN) server
|
||||
- Start_TURNServer.sh - Start only the TURN server
|
||||
- Start_WithTURN_SignallingServer.sh - Start a TURN server and the Cirrus server together
|
||||
|
||||
- Please note that scripts intended to run need to be executable: $ chmod +x *.sh will do that job.
|
||||
- The local/cloud Start_*.sh shell scripts can be invoked with the --help command line option to see how those can be configured. The following options can be supplied: --publicip, --turn, --stun. Please read the --help
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
BASH_LOCATION=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
||||
|
||||
pushd "${BASH_LOCATION}" > /dev/null
|
||||
|
||||
source common_utils.sh
|
||||
|
||||
set_start_default_values "n" "y" # Set STUN server defaults only
|
||||
use_args "$@"
|
||||
call_setup_sh
|
||||
print_parameters
|
||||
|
||||
peerconnectionoptions='{\"iceServers\":[{\"urls\":[\"stun:${stunserver}\"]}]}'
|
||||
|
||||
process="${BASH_LOCATION}/node/lib/node_modules/npm/bin/npm-cli.js run start:default --"
|
||||
arguments=""
|
||||
|
||||
if [ ! -z $IS_DEBUG ]; then
|
||||
arguments+=" --inspect"
|
||||
fi
|
||||
|
||||
arguments+=" --peerConnectionOptions=\"${peerconnectionoptions}\" --PublicIp=${publicip}"
|
||||
# Add arguments passed to script to arguments for executable
|
||||
arguments+=" ${cirruscmd}"
|
||||
|
||||
pushd ../..
|
||||
echo "Running: $process $arguments"
|
||||
PATH="${BASH_LOCATION}/node/bin:$PATH"
|
||||
start_process $process $arguments
|
||||
popd
|
||||
|
||||
popd
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
BASH_LOCATION=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
||||
|
||||
pushd "${BASH_LOCATION}" > /dev/null
|
||||
|
||||
source turn_user_pwd.sh
|
||||
source common_utils.sh
|
||||
|
||||
set_start_default_values "y" "n" # TURN server defaults only
|
||||
use_args "$@"
|
||||
call_setup_sh
|
||||
print_parameters
|
||||
|
||||
localip=$(hostname -I | awk '{print $1}')
|
||||
echo "Private IP: $localip"
|
||||
|
||||
turnport="${turnserver##*:}"
|
||||
if [ -z "${turnport}" ]; then
|
||||
turnport=3478
|
||||
fi
|
||||
echo "TURN port: ${turnport}"
|
||||
echo ""
|
||||
|
||||
|
||||
# Hmm, plain text
|
||||
realm="PixelStreaming"
|
||||
process="turnserver"
|
||||
arguments="-p ${turnport} -r $realm -X $publicip -E $localip -L $localip --no-cli --no-tls --no-dtls --pidfile /var/run/turnserver.pid -f -a -v -n -u ${turnusername}:${turnpassword}"
|
||||
|
||||
# Add arguments passed to script to arguments for executable
|
||||
arguments+=" ${cirruscmd}"
|
||||
|
||||
pushd ../.. >/dev/null
|
||||
echo "Running: $process $arguments"
|
||||
# pause
|
||||
start_process $process $arguments &
|
||||
popd >/dev/null # ../..
|
||||
|
||||
popd >/dev/null # BASH_SOURCE
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
BASH_LOCATION=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
||||
|
||||
pushd "${BASH_LOCATION}" > /dev/null
|
||||
|
||||
source common_utils.sh
|
||||
|
||||
set_start_default_values "y" "y" # Set both TURN and STUN server defaults
|
||||
use_args "$@"
|
||||
call_setup_sh
|
||||
print_parameters
|
||||
|
||||
bash Start_TURNServer.sh --turn "${turnserver}"
|
||||
|
||||
peerconnectionoptions='{\"iceServers\":[{\"urls\":[\"stun:$stunserver\",\"turn:$turnserver\"],\"username\":\"PixelStreamingUser\",\"credential\":\"AnotherTURNintheroad\"}]}'
|
||||
|
||||
process="${BASH_LOCATION}/node/lib/node_modules/npm/bin/npm-cli.js run start:default --"
|
||||
arguments=""
|
||||
|
||||
if [ ! -z $IS_DEBUG ]; then
|
||||
arguments+=" --inspect"
|
||||
fi
|
||||
|
||||
arguments+=" --peerConnectionOptions=\"$peerconnectionoptions\" --PublicIp=$publicip"
|
||||
# Add arguments passed to script to arguments for executable
|
||||
arguments+=" ${cirruscmd}"
|
||||
|
||||
pushd ../..
|
||||
echo "Running: $process $arguments"
|
||||
PATH="${BASH_LOCATION}/node/bin:$PATH"
|
||||
start_process $process $arguments
|
||||
popd
|
||||
|
||||
popd
|
||||
-98
@@ -1,98 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
function log_msg() { #message
|
||||
if [ ! -z $VERBOSE ]; then
|
||||
echo $1
|
||||
fi
|
||||
}
|
||||
|
||||
function print_usage() {
|
||||
echo "
|
||||
Usage:
|
||||
${0} [--help] [--publicip <IP Address>] [--turn <turn server>] [--stun <stun server>] [cirrus options...]
|
||||
Where:
|
||||
--help will print this message and stop this script.
|
||||
--debug will run all scripts with --inspect
|
||||
--nosudo will run all scripts without \`sudo\` command useful for when run in containers.
|
||||
--verbose will enable additional logging
|
||||
--package-manager <package manager name> specify an alternative package manager to apt-get
|
||||
--publicip is used to define public ip address (using default port) for turn server, syntax: --publicip ; it is used for
|
||||
default value: Retrieved from 'curl https://api.ipify.org' or if unsuccessful then set to 127.0.0.1. It is the IP address of the Cirrus server and the default IP address of the TURN server
|
||||
--turn defines what TURN server to be used, syntax: --turn 127.0.0.1:19303
|
||||
default value: as above, IP address downloaded from https://api.ipify.org; in case if download failure it is set to 127.0.0.1
|
||||
--stun defined what STUN server to be used, syntax: --stun stun.l.google.com:19302
|
||||
default value as above
|
||||
--build will force a rebuild of the typescript frontend even if it already exists
|
||||
Other options: stored and passed to the Cirrus server. All parameters printed once the script values are set.
|
||||
Command line options might be omitted to run with defaults and it is a good practice to omit specific ones when just starting the TURN or the STUN server alone, not the whole set of scripts.
|
||||
"
|
||||
exit 1
|
||||
}
|
||||
|
||||
function print_parameters() {
|
||||
echo ""
|
||||
echo "${0} is running with the following parameters:"
|
||||
echo "--------------------------------------"
|
||||
if [[ -n "${stunserver}" ]]; then echo "STUN server : ${stunserver}" ; fi
|
||||
if [[ -n "${turnserver}" ]]; then echo "TURN server : ${turnserver}" ; fi
|
||||
echo "Public IP address : ${publicip}"
|
||||
echo "Cirrus server command line arguments: ${cirruscmd}"
|
||||
echo ""
|
||||
}
|
||||
|
||||
function set_start_default_values() {
|
||||
# publicip and cirruscmd are always needed
|
||||
publicip=$(curl -s https://api.ipify.org)
|
||||
if [[ -z $publicip ]]; then
|
||||
publicip="127.0.0.1"
|
||||
fi
|
||||
cirruscmd=""
|
||||
|
||||
if [ "$1" = "y" ]; then
|
||||
turnserver="${publicip}:19303"
|
||||
fi
|
||||
|
||||
if [ "$2" = "y" ]; then
|
||||
stunserver="stun.l.google.com:19302"
|
||||
fi
|
||||
}
|
||||
|
||||
function use_args() {
|
||||
while(($#)) ; do
|
||||
case "$1" in
|
||||
--debug ) IS_DEBUG=1; shift;;
|
||||
--nosudo ) NO_SUDO=1; shift;;
|
||||
--verbose ) VERBOSE=1; shift;;
|
||||
--build ) FORCE_BUILD=1; shift;;
|
||||
--stun ) stunserver="$2"; shift 2;;
|
||||
--turn ) turnserver="$2"; shift 2;;
|
||||
--publicip ) publicip="$2"; turnserver="${publicip}:19303"; shift 2;;
|
||||
--help ) print_usage;;
|
||||
* ) echo "Unknown command, adding to cirrus command line: $1"; cirruscmd+=" $1"; shift;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
function call_setup_sh() {
|
||||
bash "setup.sh"
|
||||
}
|
||||
|
||||
function start_process() {
|
||||
if [ ! -z $NO_SUDO ]; then
|
||||
log_msg "running with sudo removed"
|
||||
eval $(echo "$@" | sed 's/sudo//g')
|
||||
else
|
||||
eval $@
|
||||
fi
|
||||
}
|
||||
|
||||
function get_version() {
|
||||
local version=$1
|
||||
|
||||
if command -v $version; then
|
||||
version=$($@)
|
||||
fi
|
||||
|
||||
echo $version | sed -E 's/[^0-9.]//g'
|
||||
}
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
# When run from SignallingWebServer/platform_scripts/bash, this uses the SignallingWebServer directory
|
||||
# as the build context so the Cirrus files can be successfully copied into the container image
|
||||
docker build --network=host -t 'cirrus-webserver:latest' -f ./Dockerfile ../..
|
||||
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
# Start docker container by name using host networking
|
||||
docker run --name cirrus_latest --network host --rm cirrus-webserver
|
||||
|
||||
# Interactive start example
|
||||
#docker run --name cirrus_latest --network host --rm -it --entrypoint /bin/bash cirrus-webserver
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
# Suppress printing of directory stack
|
||||
pushd () {
|
||||
command pushd "$@" > /dev/null
|
||||
}
|
||||
popd () {
|
||||
command popd "$@" > /dev/null
|
||||
}
|
||||
|
||||
# Stop both stun and turn
|
||||
pushd "$(dirname ${BASH_SOURCE[0]})"
|
||||
./docker-start-cirrus.sh --with-turn &
|
||||
popd
|
||||
-31
@@ -1,31 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
source turn_user_pwd.sh
|
||||
|
||||
USETURN="false"
|
||||
|
||||
for arg do
|
||||
shift
|
||||
[ "${arg}" = "--with-turn" ] && USETURN="true" && continue
|
||||
set -- "$@" "${arg}"
|
||||
done
|
||||
|
||||
# Get stun server data for passing to the container
|
||||
source common_utils.sh
|
||||
if [ "${USETURN}" = "true" ]; then
|
||||
set_start_default_values "y" "y" # Both TURN and STUN server defaults
|
||||
else
|
||||
set_start_default_values "n" "y" # Only STUN server defaults
|
||||
fi
|
||||
use_args "$@"
|
||||
|
||||
# Start docker container by name using host networking
|
||||
if [ "${USETURN}" = "true" ]; then
|
||||
peerConnectionOptions="{\""iceServers\"":[{\""urls\"":[\""stun:"${stunserver}"\"",\""turn":"${turnserver}\""],\""username\"":\""${turnusername}\"",\""credential\"":\""${turnpassword}\""}]}"
|
||||
else
|
||||
peerConnectionOptions="{\""iceServers\"":[{\""urls\"":[\""stun:"${stunserver}"\""]}]}"
|
||||
fi
|
||||
|
||||
docker run --name cirrus_latest --network host --rm --entrypoint /usr/local/bin/node cirrus-webserver /opt/SignallingWebServer/cirrus.js --peerConnectionOptions="${peerConnectionOptions}" --publicIp="${publicip}"
|
||||
|
||||
-42
@@ -1,42 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
# Get stun server data for passing to the container
|
||||
source common_utils.sh
|
||||
set_start_default_values "n" "y" # Only STUN server defaults
|
||||
use_args "$@"
|
||||
|
||||
localip=$(hostname -I | awk '{print $1}')
|
||||
echo "Private IP: $localip"
|
||||
|
||||
turnport="${turnserver##*:}"
|
||||
if [ -z "${turnport}" ]; then
|
||||
turnport=3478
|
||||
fi
|
||||
echo "TURN port: ${turnport}"
|
||||
echo ""
|
||||
|
||||
turnusername="PixelStreamingUser"
|
||||
turnpassword="AnotherTURNintheroad"
|
||||
realm="PixelStreaming"
|
||||
process="turnserver"
|
||||
arguments="-p ${turnport} -r $realm -X $publicip -E $localip -L $localip --no-cli --no-tls --no-dtls --pidfile /var/run/turnserver.pid -f -a -v -n -u ${turnusername}:${turnpassword}"
|
||||
|
||||
# Add arguments passed to script to arguments for executable
|
||||
arguments+=" ${cirruscmd}"
|
||||
|
||||
# Start docker container by name using host networking
|
||||
echo "Running: ${process} ${arguments}"
|
||||
|
||||
# Get the docker image
|
||||
docker pull coturn/coturn
|
||||
|
||||
# Start the TURN server
|
||||
#docker run --name coturn_latest --network host -it --entrypoint /bin/bash coturn/coturn
|
||||
#docker run --name coturn_latest --network host --rm -a stdin -a stdout -a stderr --entrypoint "sudo mkdir -p /var/run" coturn/coturn ""
|
||||
#docker run --name coturn_latest --network host --rm -a stdin -a stdout -a stderr --entrypoint "/bin/ls" coturn/coturn "/var/"
|
||||
|
||||
docker run --name coturn_latest --network host --rm -a stdin -a stdout -a stderr --entrypoint "${process}" coturn/coturn "${arguments}"
|
||||
|
||||
#docker run --name coturn_latest --network host --rm -a stdin -a stdout -a stderr --entrypoint "/bin/bash" coturn/coturn "ls -latr /var/run/"
|
||||
#docker run --name coturn_latest --network host --rm -a stdin -a stdout -a stderr --entrypoint "sudo chown ubuntu:ubuntu /var/run/turnserver.pid | sudo chmod +x /var/run/turnserver.pid | ${process}" coturn/coturn "${arguments}"
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
# Suppress printing of directory stack
|
||||
pushd () {
|
||||
command pushd "$@" > /dev/null
|
||||
}
|
||||
popd () {
|
||||
command popd "$@" > /dev/null
|
||||
}
|
||||
|
||||
# Stop both stun and turn
|
||||
pushd "$(dirname ${BASH_SOURCE[0]})"
|
||||
./docker-stop-cirrus.sh
|
||||
./docker-stop-turn.sh
|
||||
popd
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
# Stop the docker container
|
||||
PSID=$(docker ps -a -q --filter="name=cirrus_latest")
|
||||
if [ -z "$PSID" ]; then
|
||||
echo "Docker stun is not running, no stopping will be done"
|
||||
exit 1;
|
||||
fi
|
||||
echo "Stopping stun server ..."
|
||||
docker stop cirrus_latest
|
||||
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
# Stop the docker container
|
||||
PSID=$(docker ps -a -q --filter="name=coturn_latest")
|
||||
if [ -z "$PSID" ]; then
|
||||
echo "Docker turn is not running, no stopping will be done"
|
||||
exit 1;
|
||||
fi
|
||||
echo "Stopping turn server..."
|
||||
docker stop coturn_latest
|
||||
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
BASH_LOCATION=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
||||
|
||||
pushd "${BASH_LOCATION}" > /dev/null
|
||||
|
||||
source common_utils.sh
|
||||
|
||||
set_start_default_values "n" "n" # No server specific defaults
|
||||
use_args "$@"
|
||||
call_setup_sh
|
||||
print_parameters
|
||||
|
||||
process="${BASH_LOCATION}/node/lib/node_modules/npm/bin/npm-cli.js run start:default --"
|
||||
arguments=""
|
||||
|
||||
if [ ! -z $IS_DEBUG ]; then
|
||||
arguments+=" --inspect"
|
||||
fi
|
||||
|
||||
arguments+=" --publicIp=${publicip}"
|
||||
arguments+=" ${cirruscmd}"
|
||||
|
||||
pushd ../.. > /dev/null
|
||||
|
||||
echo ""
|
||||
echo "Starting Cirrus server use ctrl-c to exit"
|
||||
echo "-----------------------------------------"
|
||||
echo ""
|
||||
|
||||
PATH="${BASH_LOCATION}/node/bin:$PATH"
|
||||
start_process $process $arguments
|
||||
|
||||
popd > /dev/null # ../..
|
||||
|
||||
popd > /dev/null # BASH_SOURCE
|
||||
@@ -1,158 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
BASH_LOCATION=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
||||
|
||||
pushd "${BASH_LOCATION}" > /dev/null
|
||||
|
||||
source common_utils.sh
|
||||
|
||||
use_args $@
|
||||
# Azure specific fix to allow installing NodeJS from NodeSource
|
||||
if test -f "/etc/apt/sources.list.d/azure-cli.list"; then
|
||||
sudo touch /etc/apt/sources.list.d/nodesource.list
|
||||
sudo touch /usr/share/keyrings/nodesource.gpg
|
||||
sudo chmod 644 /etc/apt/sources.list.d/nodesource.list
|
||||
sudo chmod 644 /usr/share/keyrings/nodesource.gpg
|
||||
sudo chmod 644 /etc/apt/sources.list.d/azure-cli.list
|
||||
fi
|
||||
|
||||
function check_version() { #current_version #min_version
|
||||
#check if same string
|
||||
if [ -z "$2" ] || [ "$1" = "$2" ]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
local i current minimum
|
||||
|
||||
IFS="." read -r -a current <<< $1
|
||||
IFS="." read -r -a minimum <<< $2
|
||||
|
||||
# fill empty fields in current with zeros
|
||||
for ((i=${#current[@]}; i<${#minimum[@]}; i++))
|
||||
do
|
||||
current[i]=0
|
||||
done
|
||||
|
||||
for ((i=0; i<${#current[@]}; i++))
|
||||
do
|
||||
if [[ -z ${minimum[i]} ]]; then
|
||||
# fill empty fields in minimum with zeros
|
||||
minimum[i]=0
|
||||
fi
|
||||
|
||||
if ((10#${current[i]} > 10#${minimum[i]})); then
|
||||
return 1
|
||||
fi
|
||||
|
||||
if ((10#${current[i]} < 10#${minimum[i]})); then
|
||||
return 2
|
||||
fi
|
||||
done
|
||||
|
||||
# if got this far string is the same once we added missing 0
|
||||
return 0
|
||||
}
|
||||
|
||||
function check_and_install() { #dep_name #get_version_string #version_min #install_command
|
||||
local is_installed=0
|
||||
|
||||
log_msg "Checking for required $1 install"
|
||||
|
||||
local current=$(echo $2 | sed -E 's/[^0-9.]//g')
|
||||
local minimum=$(echo $3 | sed -E 's/[^0-9.]//g')
|
||||
|
||||
if [ $# -ne 4 ]; then
|
||||
log_msg "check_and_install expects 4 args (dep_name get_version_string version_min install_command) got $#"
|
||||
return -1
|
||||
fi
|
||||
|
||||
if [ ! -z $current ]; then
|
||||
log_msg "Current version: $current checking >= $minimum"
|
||||
check_version "$current" "$minimum"
|
||||
if [ "$?" -lt 2 ]; then
|
||||
log_msg "$1 is installed."
|
||||
return 0
|
||||
else
|
||||
log_msg "Required install of $1 not found installing"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ $is_installed -ne 1 ]; then
|
||||
echo "$1 installation not found installing..."
|
||||
|
||||
start_process $4
|
||||
|
||||
if [ $? -ge 1 ]; then
|
||||
echo "Installation of $1 failed try running `export VERBOSE=1` then run this script again for more details"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
function setup_frontend() {
|
||||
# navigate to root
|
||||
pushd ${BASH_LOCATION}/../../.. > /dev/null
|
||||
export PATH="../../SignallingWebServer/platform_scripts/bash/node/bin:$PATH"
|
||||
# If player.html doesn't exist, or --build passed as arg, rebuild the frontend
|
||||
if [ ! -f SignallingWebServer/Public/player.html ] || [ ! -z "$FORCE_BUILD" ] ; then
|
||||
echo "Building Typescript Frontend."
|
||||
# Using our bundled NodeJS, build the web frontend files
|
||||
pushd ${BASH_LOCATION}/../../../Frontend/library > /dev/null
|
||||
../../SignallingWebServer/platform_scripts/bash/node/bin/npm install
|
||||
../../SignallingWebServer/platform_scripts/bash/node/bin/npx webpack
|
||||
popd
|
||||
|
||||
pushd ${BASH_LOCATION}/../../../Frontend/implementations/EpicGames > /dev/null
|
||||
../../../SignallingWebServer/platform_scripts/bash/node/bin/npm install
|
||||
../../../SignallingWebServer/platform_scripts/bash/node/bin/npm link ../../library
|
||||
../../../SignallingWebServer/platform_scripts/bash/node/bin/npx webpack
|
||||
popd
|
||||
else
|
||||
echo 'Skipping building Frontend because files already exist. Please run with "--build" to force a rebuild'
|
||||
fi
|
||||
|
||||
popd > /dev/null # root
|
||||
}
|
||||
|
||||
|
||||
echo "Checking Pixel Streaming Server dependencies."
|
||||
|
||||
# navigate to SignallingWebServer root
|
||||
pushd ${BASH_LOCATION}/../.. > /dev/null
|
||||
|
||||
node_version=""
|
||||
if [[ -f "${BASH_LOCATION}/node/bin/node" ]]; then
|
||||
node_version=$("${BASH_LOCATION}/node/bin/node" --version)
|
||||
fi
|
||||
check_and_install "node" "$node_version" "v16.4.2" "curl https://nodejs.org/dist/v16.14.2/node-v16.14.2-linux-x64.tar.gz --output node.tar.xz
|
||||
&& tar -xf node.tar.xz
|
||||
&& rm node.tar.xz
|
||||
&& mv node-v*-linux-x64 \"${BASH_LOCATION}/node\""
|
||||
|
||||
PATH="${BASH_LOCATION}/node/bin:$PATH"
|
||||
"${BASH_LOCATION}/node/lib/node_modules/npm/bin/npm-cli.js" install
|
||||
|
||||
popd > /dev/null # SignallingWebServer
|
||||
|
||||
# Trigger Frontend Build if needed or requested
|
||||
# This has to be done after check_and_install "node"
|
||||
setup_frontend
|
||||
|
||||
popd > /dev/null # BASH_SOURCE
|
||||
|
||||
#command #dep_name #get_version_string #version_min #install command
|
||||
coturn_version=$(if command -v turnserver &> /dev/null; then echo 1; else echo 0; fi)
|
||||
if [ $coturn_version -eq 0 ]; then
|
||||
if ! command -v apt-get &> /dev/null; then
|
||||
echo "Setup for the scripts is designed for use with distros that use the apt-get package manager" \
|
||||
"if you are seeing this message you will have to update \"${BASH_LOCATION}/setup.sh\" with\n" \
|
||||
"a package manger and the equivalent packages for your distribution. Please follow the\n" \
|
||||
"instructions found at https://pkgs.org/search/?q=coturn to install Coturn for your specific distribution"
|
||||
exit 1
|
||||
else
|
||||
if [ `id -u` -eq 0 ]; then
|
||||
check_and_install "coturn" "$coturn_version" "1" "apt-get install -y coturn"
|
||||
else
|
||||
check_and_install "coturn" "$coturn_version" "1" "sudo apt-get install -y coturn"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
# Plain text TURN setup
|
||||
turnusername="PixelStreamingUser"
|
||||
turnpassword="AnotherTURNintheroad"
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
How to use files in this directory:
|
||||
- Files with .ps1 extension can be run with PowerShell[.exe] in Windows. Powershell needs to be started as Administrator to run setup.ps1 so it can run installation / installation check steps
|
||||
- Make sure that all of your dependencies are installed. Use .\setup.ps1 what will install whatever is missing as long as you are on a supported operating system
|
||||
|
||||
- Run a local instance of the Cirrus server by using the .\run_local.ps1 script
|
||||
|
||||
- Use the following scripts to run locally or in your cloud instance:
|
||||
- Start_SignallingServer.ps1 - Start only the Signalling (STUN) server
|
||||
- Start_TURNServer.ps1 - Start only the TURN server
|
||||
- Start_WithTURN_SignallingServer.ps1 - Start a TURN server and the Cirrus server together
|
||||
- The Start_Common.ps1 file contains shared functions for other Start_*.ps1 scripts and it is not supposed to run alone
|
||||
|
||||
- The local/cloud Start_*.ps1 powershell scripts can be invoked with the --help command line option to see how those can be configured. The following options can be supplied: --publicip, --turn, --stun. Please read the --help
|
||||
-89
@@ -1,89 +0,0 @@
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
# Parse $args into a string
|
||||
$params = $args[0]
|
||||
if ( $args.Count -gt 1 ) {
|
||||
$params = $args[1..$($args.Count - 1)]
|
||||
# Do setup as a common task, it is smart and will not reinstall if not required.
|
||||
Start-Process -FilePath "$PSScriptRoot\setup.bat" -Wait -NoNewWindow -ArgumentList $params
|
||||
}
|
||||
else {
|
||||
Start-Process -FilePath "$PSScriptRoot\setup.bat" -Wait -NoNewWindow
|
||||
}
|
||||
echo $params
|
||||
|
||||
$global:ScriptName = $MyInvocation.MyCommand.Name
|
||||
$global:PublicIP = $null
|
||||
$global:StunServer = $null
|
||||
$global:TurnServer = $null
|
||||
$global:CirrusCmd = $null
|
||||
$global:BuildFrontend = $null
|
||||
|
||||
function print_usage {
|
||||
echo "
|
||||
Usage (in MS Windows Power Shell):
|
||||
$global:ScriptName [--help] [--publicip <IP Address>] [--turn <turn server>] [--stun <stun server>] [cirrus options...]
|
||||
Where:
|
||||
--help will print this message and stop this script.
|
||||
--publicip is used to define public ip address (using default port) for turn server, syntax: --publicip ; it is used for
|
||||
default value: Retrieved from 'curl https://api.ipify.org' or if unsuccessful then set to 127.0.0.1. It is the IP address of the Cirrus server and the default IP address of the TURN server
|
||||
--turn defines what TURN server to be used, syntax: --turn 127.0.0.1:19303
|
||||
default value: as above, IP address downloaded from https://api.ipify.org; in case if download failure it is set to 127.0.0.1
|
||||
--stun defined what STUN server to be used, syntax: --stun stun.l.google.com:19302
|
||||
default value as above
|
||||
Other options: stored and passed to the Cirrus server. All parameters printed once the script values are set.
|
||||
Command line options might be omitted to run with defaults and it is a good practice to omit specific ones when just starting the TURN or the STUN server alone, not the whole set of scripts.
|
||||
"
|
||||
exit 1
|
||||
}
|
||||
|
||||
function print_parameters {
|
||||
echo ""
|
||||
echo "$scriptname is running with the following parameters:"
|
||||
echo "--------------------------------------"
|
||||
if ($global:StunServer -ne $null) { echo "STUN server : $global:StunServer" }
|
||||
if ($global:TurnServer -ne $null) { echo "TURN server : $global:TurnServer" }
|
||||
echo "Public IP address : $global:PublicIP"
|
||||
echo "Cirrus server command line arguments: $global:CirrusCmd"
|
||||
echo ""
|
||||
}
|
||||
|
||||
function set_start_default_values($SetTurnServerVar, $SetStunServerVar) {
|
||||
# publicip and cirruscmd are always needed
|
||||
$global:PublicIP = Invoke-WebRequest -Uri "https://api.ipify.org" -UseBasicParsing
|
||||
if ($global:PublicIP -eq $null -Or $global:PublicIP.length -eq 0) {
|
||||
$global:PublicIP = "127.0.0.1"
|
||||
} else {
|
||||
$global:PublicIP = ($global:PublicIP).Content
|
||||
}
|
||||
$global:cirruscmd = ""
|
||||
|
||||
if ($SetTurnServerVar -eq "y") {
|
||||
$global:TurnServer = $global:PublicIP + ":19303"
|
||||
}
|
||||
if ($SetStunServerVar -eq "y") {
|
||||
$global:StunServer = "stun.l.google.com:19302"
|
||||
}
|
||||
}
|
||||
|
||||
function use_args($arg) {
|
||||
$CmdArgs = $arg -split (" ")
|
||||
while($CmdArgs.count -gt 0) {
|
||||
$Cmd, $CmdArgs = $CmdArgs
|
||||
if ($Cmd -eq "--stun") {
|
||||
$global:StunServer, $CmdArgs = $CmdArgs
|
||||
} elseif ($Cmd -eq "--turn") {
|
||||
$global:TurnServer, $CmdArgs = $CmdArgs
|
||||
} elseif ($Cmd -eq "--publicip") {
|
||||
$global:PublicIP, $CmdArgs = $CmdArgs
|
||||
$global:TurnServer = $global:publicip + ":19303"
|
||||
} elseif ($Cmd -eq "--build") {
|
||||
$global:BuildFrontend, $CmdArgs = $CmdArgs
|
||||
} elseif ($Cmd -eq "--help") {
|
||||
print_usage
|
||||
} else {
|
||||
echo "Unknown command, adding to cirrus command line: $Cmd"
|
||||
$global:CirrusCmd += " $Cmd"
|
||||
}
|
||||
}
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
. "$PSScriptRoot\Start_Common.ps1" $args
|
||||
|
||||
set_start_default_values "n" "y" # Set both TURN and STUN server defaults
|
||||
use_args($args)
|
||||
print_parameters
|
||||
|
||||
$peerConnectionOptions = "{ \""iceServers\"": [{\""urls\"": [\""stun:" + $global:StunServer + "\""]}] }"
|
||||
|
||||
$ProcessExe = "platform_scripts\cmd\node\node.exe"
|
||||
$Arguments = @("cirrus", "--peerConnectionOptions=""$peerConnectionOptions""", "--PublicIp=$global:PublicIp")
|
||||
# Add arguments passed to script to Arguments for executable
|
||||
$Arguments += $global:CirrusCmd
|
||||
|
||||
Push-Location $PSScriptRoot\..\..\
|
||||
Write-Output "Running: $ProcessExe $Arguments"
|
||||
Start-Process -FilePath $ProcessExe -ArgumentList "$Arguments" -Wait -NoNewWindow
|
||||
Pop-Location
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
. "$PSScriptRoot\Start_Common.ps1" $args
|
||||
|
||||
set_start_default_values "y" "n" # Set both TURN and STUN server defaults
|
||||
use_args($args)
|
||||
print_parameters
|
||||
#$LocalIp = Invoke-WebRequest -Uri "http://169.254.169.254/latest/meta-data/local-ipv4"
|
||||
$LocalIP = (Test-Connection -ComputerName (hostname) -Count 1 | Select IPV4Address).IPV4Address.IPAddressToString
|
||||
|
||||
Write-Output "Private IP: $LocalIp"
|
||||
|
||||
$TurnPort="19303"
|
||||
$Pos = $global:TurnServer.LastIndexOf(":")
|
||||
if ($Pos -ne -1) {
|
||||
$TurnPort = $global:TurnServer.Substring($Pos+ 1)
|
||||
}
|
||||
echo "TURN port: ${turnport}"
|
||||
echo ""
|
||||
|
||||
Push-Location $PSScriptRoot
|
||||
|
||||
$TurnUsername = "PixelStreamingUser"
|
||||
$TurnPassword = "AnotherTURNintheroad"
|
||||
$Realm = "PixelStreaming"
|
||||
$ProcessExe = ".\turnserver.exe"
|
||||
$Arguments = "-p $TurnPort -r $Realm -X $PublicIP -E $LocalIP -L $LocalIP --no-cli --no-tls --no-dtls --pidfile `"C:\coturn.pid`" -f -a -v -n -u $TurnUsername`:$TurnPassword"
|
||||
|
||||
# Add arguments passed to script to Arguments for executable
|
||||
$Arguments += $args
|
||||
|
||||
Push-Location $PSScriptRoot\coturn\
|
||||
Write-Output "Running: $ProcessExe $Arguments"
|
||||
# pause
|
||||
Start-Process -FilePath $ProcessExe -ArgumentList $Arguments -NoNewWindow
|
||||
Pop-Location
|
||||
|
||||
Pop-Location
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
# Copyright Epic Games, Inc. All Rights Reserved.
|
||||
|
||||
. "$PSScriptRoot\Start_Common.ps1" $args
|
||||
|
||||
set_start_default_values "y" "y" # Set both TURN and STUN server defaults
|
||||
use_args($args)
|
||||
print_parameters
|
||||
|
||||
Push-Location $PSScriptRoot
|
||||
|
||||
Start-Process -FilePath "PowerShell" -ArgumentList ".\Start_TURNServer.ps1" -WorkingDirectory "$PSScriptRoot"
|
||||
|
||||
$peerConnectionOptions = "{ \""iceServers\"": [{\""urls\"": [\""stun:" + $global:StunServer + "\"",\""turn:" + $global:TurnServer + "\""], \""username\"": \""PixelStreamingUser\"", \""credential\"": \""AnotherTURNintheroad\""}] }"
|
||||
|
||||
$ProcessExe = "platform_scripts\cmd\node\node.exe"
|
||||
$Arguments = @("cirrus", "--peerConnectionOptions=""$peerConnectionOptions""", "--PublicIp=$global:PublicIp")
|
||||
# Add arguments passed to script to Arguments for executable
|
||||
$Arguments += $args
|
||||
|
||||
Push-Location $PSScriptRoot\..\..\
|
||||
Write-Output "Running: $ProcessExe $Arguments"
|
||||
Start-Process -FilePath $ProcessExe -ArgumentList $Arguments -Wait -NoNewWindow
|
||||
Pop-Location
|
||||
|
||||
Pop-Location
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user