Files
Testing/html5-chat/nodeMulti/serverms.js
sean 0e8a8b3028
Some checks are pending
deploy-testing / deploy (push) Waiting to run
Initial testing snapshot
2026-11-17 16:15:01 -05:00

304 lines
12 KiB
JavaScript

'use strict';
// These are the https socket.io server parameters.
var config = require('./config');
// This port is needed because Apache serves HTTPS on port 443.
var PORT = 8443;
// The peerName of the publisher in a given room.
var PUBLISHER_PEER = 'publisher';
// Whether to print verbose MediaSoup debugging logs.
var DEBUG = false;
// The log* properties only work if process.env.DEBUG is set appropriately.
var SERVER_OPTIONS = {
//logLevel: 'warn',
//logTags: ['info', 'ice', 'rtp', 'rtcp', 'srtp'],
};
if (DEBUG) {
process.env.DEBUG = 'mediasoup:*';
SERVER_OPTIONS.logLevel = 'debug';
SERVER_OPTIONS.logTags = ['info', 'ice', 'dtls', 'rtp', 'srtp', 'rtcp', 'rbe', 'rtx'];
}
// Use h264, which is the only video codec shared between Safari 11 and Edge.
// Firefox and Chrome have no issues with any codec.
// Maybe someday we can use VP8, once Edge is gone and Safari supports it.
var MEDIA_CODECS = [
{
kind : "audio",
name : "opus",
clockRate : 48000,
channels : 2,
parameters :
{
useinbandfec : 1
}
},
{
kind : "video",
name : "vp8",
clockRate : 90000,
parameters :
{
"packetization-mode" : 1,
"profile-level-id" : "42e01f",
"level-asymmetry-allowed" : 1
}
},
];
// The modules we need.
var https = require('https');
var fs = require('fs');
var mediasoup = require('mediasoup');
// Create a MediaSoup server (and all its workers).
var ms = mediasoup.Server(SERVER_OPTIONS);
console.log(config);
//process.exit();
// Create an HTTPS server with the letsencrypt certificates.
var server = https.createServer({
key: fs.readFileSync(config.key2),
cert: fs.readFileSync(config.cert2
),
}, function onRequest(req, res) {
res.writeHead(404);
res.end('not found');
});
console.log('MediaSoupServer start...');
// Have HTTPS listen on the specified port.
server.listen(PORT, function onListen() {
//console.log('listening on', PORT);
});
// Mapping of streamids to MediaSoup rooms.
// Note that we have only one publisher per room. We put them in
// separate rooms to take advantage of distributing the load
// among mediasoup-workers (each room needs to run entirely on one
// worker).
//
// This is the only global collection. The rest are scoped to
// the individual socket.io connection.
var rooms = {};
// We listen for socket.io only.
var io = require('socket.io').listen(server);
io.sockets.on('connection', function newConn(socket) {
// New connection from a web browser running client/index.html.
var id = socket.id;
// Generate a unique address for logging this connection's details.
var addr = id + ':' + '*' + ':';
// A "session" is an identifier that is scoped to the current connections
// which the cilent can use to publish/subscribe to different streamids
// without requiring separate socket.io connections.
// Map of sessions to the streamid they are publishing/subscribing to.
var streams = {};
// Map of sessions to `true` if they are a publisher.
var canPublish = {};
// Map of sessions to the MediaSoup peer they correspond to.
var peers = {};
// Let them know we got a connection.
//console.log(addr, 'connected');
// Helper function to send an object to the client.
function send(addr, obj) {
//console.log(addr, 'send', obj);
socket.emit('ms', obj);
}
// Helper function to release all resources used by a given session.
function closeSession(addr, session) {
// Remove any existing publisher f lag.
delete canPublish[session];
if (peers[session]) {
// If they have a peer, close it.
peers[session].close();
}
delete peers[session];
// Remove the stream mapping for the session.
var streamid = streams[session];
delete streams[session]
// If there is a room, clean up if it is no longer used.
var room = rooms[streamid];
if (room && room.peers.length === 0) {
//console.log(addr, 'close empty streamid', streamid);
room.close();
delete rooms[streamid];
}
}
// Clean up all of this connection's sessions on disconnect.
socket.on('disconnect', function disco(reason) {
//console.log(addr, 'disconnected:', reason);
for (var session in streams) {
closeSession(addr, session);
}
});
// Handle MediaSoup-related messages from the client.
socket.on('ms', function recv(obj) {
// Check which session this message is for.
var session = obj.meta.session;
// Shadow the addr variable with the current session's information.
var addr = id + ':' + session + ':';
//console.log(addr, 'recv', obj);
// Dispatch on the object's type.
switch (obj.type) {
case 'MS_STOP': {
// Terminate a session.
//console.log(addr, 'stopping session: streamid', streams[session]);
closeSession(addr, session);
break;
}
case 'MS_START': {
// Initiate a new session.
// FIXME: Should not allow overwriting an existing sesssion.
var streamid = streams[session] = obj.payload.streamid;
//console.log(addr, 'starting session: streamid', streamid);
// FIXME: Authenticate here.
if (obj.payload.kind === 'publish') {
// They're a publisher.
canPublish[session] = true;
}
// Create a new room for the streamid if there isn't one.
if (!rooms[streamid]) {
//console.log(addr, 'new streamid', streamid);
rooms[streamid] = ms.Room(MEDIA_CODECS);
}
// Tell them we're ready for MediaSoup messages.
send(addr, {type: 'MS_RESPONSE', payload: obj.payload, meta: obj.meta});
break;
}
case 'MS_SEND': {
// This is a message sent directly by the MediaSoup client.
var target;
// Look up the particular details of this session.
var isPublisher = canPublish[session];
var streamid = streams[session];
var room = rooms[streamid];
var peer = peers[session];
// Check to see the target: either the current room, or this peer.
switch (obj.payload.target) {
case 'room':
target = room;
break;
case 'peer':
target = peer;
break;
}
if (obj.meta.notification) {
// It was a notification.
if (!target) {
//console.log(addr, 'unknown notification target', obj.payload.target);
// FIXME: Maybe send a special MS_ERROR to the client side, where it can
// be handled and logged, too.
// For now we just drop it on the floor.
break;
}
target.receiveNotification(obj.payload);
break;
}
if (!target) {
// Send an error response (mirroring the object meta) to say that it
// was not a valid target.
//console.log(addr, 'unknown request target', obj.payload.target);
send(addr, {type: 'MS_ERROR', payload: 'unknown request target', meta: obj.meta});
break;
}
if (obj.payload.method === 'join') {
// Special meaning of the 'join' method: restrict publshing to just
// one session globally.
if (isPublisher) {
// Publisher has a reserved name.
obj.payload.peerName = PUBLISHER_PEER;
}
else if (obj.payload.peerName === PUBLISHER_PEER) {
// A subscriber attempted to be the publisher.
// Just prefix their peerName so it doesn't replace
// the real publisher.
obj.payload.peerName = 'pseudo' + PUBLISHER_PEER;
}
// Kick out the old peer. This is the only really sane thing
// we can do, or else we would have competing pubsub for
// the same name.
var oldPeer = room.getPeerByName(obj.payload.peerName);
if (oldPeer) {
// Let MediaSoup generate the right messages.
oldPeer.close();
}
}
// Tell the request to the room/peer target.
target.receiveRequest(obj.payload)
.then(function onResponse(response) {
// If the target was successful, process the response.
if (obj.payload.method === 'join') {
// Detected a join request, so get the new peer object.
var peerName = obj.payload.peerName;
peer = peers[session] = room.getPeerByName(peerName);
// Install our notification handler.
peer.on('notify', function onNotify(notification) {
if (notification.method === 'newPeer' || notification.method === 'peerClosed') {
if (!isPublisher && notification.name !== PUBLISHER_PEER) {
// Skip the notification to hide all peers but the publisher
// from non-publishers.
return;
}
}
// Send the notification to the client.
send(addr, {type: 'MS_NOTIFY', payload: notification, meta: session});
});
// Log that we joined.
//console.log(addr, 'new peer', JSON.stringify(peerName), 'joined streamid', streamid);
if (!isPublisher) {
// Filter out all peers but the publisher to hide them
// from non-publishers.
response = Object.assign({}, response,
{peers: response.peers.filter(function(peer) {
// Reveal the publisher, if any.
return peer.name === PUBLISHER_PEER;
})});
}
}
// Send the response to the client with the same metadata (message id and session).
send(addr, {type: 'MS_RESPONSE', payload: response, meta: obj.meta});
})
.catch(function onError(err) {
// Error processing the request, so send an error to the client's error callback.
send(addr, {type: 'MS_ERROR', payload: err, meta: obj.meta});
});
break;
}
default:
// Didn't find valid MS_* protocol type.
throw Error('Unrecognized object type ' + obj.type);
}
});
});