forked from EpicGames/PixelStreamingInfrastructure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sfu_server.js
370 lines (307 loc) · 11.6 KB
/
sfu_server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
const config = require('./config');
const WebSocket = require('ws');
const mediasoup = require('mediasoup_prebuilt');
const mediasoupSdp = require('mediasoup-sdp-bridge');
const minimist = require('minimist');
if (!config.retrySubscribeDelaySecs) {
config.retrySubscribeDelaySecs = 10;
}
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 => {
onStreamerDisconnected();
console.log(`Disconnected from signalling server: ${result.code} ${result.reason}`);
console.log("Attempting reconnect to signalling server...");
setTimeout(()=> {
connectSignalling(server);
}, 2000);
});
}
async function onStreamerList(msg) {
let success = false;
// subscribe to either the configured streamer, or if not configured, just grab the first id
if (msg.ids.length > 0) {
if (!!config.subscribeStreamerId && config.subscribeStreamerId.length != 0) {
if (msg.ids.includes(config.subscribeStreamerId)) {
signalServer.send(JSON.stringify({type: 'subscribe', streamerId: config.subscribeStreamerId}));
success = true;
}
} else {
signalServer.send(JSON.stringify({type: 'subscribe', streamerId: msg.ids[0]}));
success = true;
}
}
if (!success) {
// did not subscribe to anything
setTimeout(function() {
signalServer.send(JSON.stringify({type: 'listStreamers'}));
}, config.retrySubscribeDelaySecs * 1000);
}
}
async function onIdentify(msg) {
signalServer.send(JSON.stringify({type: 'endpointId', id: config.SFUId}));
signalServer.send(JSON.stringify({type: 'listStreamers'}));
}
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() {
return streamer.transport._getNextSctpStreamId();
}
function onStreamerDisconnected() {
console.log("Streamer disconnected");
disconnectAllPeers();
if (streamer != null) {
for (const mediaProducer of streamer.producers) {
mediaProducer.close();
}
streamer.transport.close();
streamer = null;
signalServer.send(JSON.stringify({type: 'stopStreaming'}));
setTimeout(function() {
signalServer.send(JSON.stringify({type: 'listStreamers'}));
}, config.retrySubscribeDelaySecs * 1000);
}
}
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 });
streamer.transport._sctpStreamIds[nextStreamerSCTPStreamId] = 1;
streamer.transport._sctpStreamIds[nextPeerSCTPStreamId] = 1;
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.transport && streamer.transport._sctpStreamIds){
const allocatedStreamId = peer.streamerDataProducer.sctpStreamParameters.streamId;
const allocatedPeerStreamId = peer.peerDataProducer.sctpStreamParameters.streamId;
streamer.transport._sctpStreamIds[allocatedStreamId] = 0;
streamer.transport._sctpStreamIds[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);
}
}
function onLayerPreference(msg) {
const peer = peers.get(`${msg.playerId}`);
if (peer != null) {
for (consumer of peer.consumers) {
consumer.setPreferredLayers({ spatialLayer: msg.spatialLayer, temporalLayer: msg.temporalLayer });
}
}
}
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);
}
else if (msg.type == 'layerPreference') {
onLayerPreference(msg);
}
else if (msg.type == 'streamerList') {
onStreamerList(msg);
}
else if (msg.type == 'identify') {
onIdentify(msg);
}
}
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 onICEStateChange(identifier, iceState) {
console.log("%s ICE state changed to %s", identifier, iceState);
if (identifier == 'Streamer' && iceState == 'completed') {
signalServer.send(JSON.stringify({type: 'startStreaming'}));
}
}
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) => onICEStateChange(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() {
var argv = minimist(process.argv.slice(2));
if ('signallingURL' in argv) {
config.signallingURL = argv['signallingURL'];
}
console.log('Starting Mediasoup...');
console.log("Config = ");
console.log(config);
mediasoupRouter = await startMediasoup();
connectSignalling(config.signallingURL);
}
main();