forked from AidanNelson/YORB2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
1087 lines (927 loc) · 34.2 KB
/
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* YORB 2020
*
* This server uses code from a THREE.js Multiplayer boilerplate made by Or Fleisher:
* https://github.com/juniorxsound/THREE.Multiplayer
* And a WEBRTC chat app made by Mikołaj Wargowski:
* https://github.com/Miczeq22/simple-chat-app
*
* Aidan Nelson, April 2020
*
*/
// Set environment variables
// Set Debug level before we require 'debug' or 'mediasoup'!
const config = require("./config");
require("dotenv").config();
// if we are in production environment, copy over config from .env file:
if (process.env.NODE_ENV == "production") {
config.sslCrt = process.env.PRODUCTION_CERT;
config.sslKey = process.env.PRODUCTION_KEY;
config.httpIp = process.env.PRODUCTION_IP;
config.httpPort = process.env.PRODUCTION_PORT;
config.mediasoup.webRtcTransport.listenIps = [
{ ip: "127.0.0.1", announcedIp: null },
{ ip: process.env.PRODUCTION_IP, announcedIp: null },
];
}
console.log("Environment Variables:");
console.log("~~~~~~~~~~~~~~~~~~~~~~~~~");
console.log(process.env);
console.log("~~~~~~~~~~~~~~~~~~~~~~~~~");
// IMPORTS
const debugModule = require("debug");
const mediasoup = require("mediasoup");
const fs = require("fs");
const https = require("https");
// HTTP Server setup:
// https://stackoverflow.com/questions/27393705/how-to-resolve-a-socket-io-404-not-found-error
var express = require('express'),
http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
app.use(express.static(__dirname + "/public"));
server.listen(process.env.PRODUCTION_PORT);
console.log('Server listening on http://localhost:' + process.env.PRODUCTION_PORT);
const log = debugModule("demo-app");
const warn = debugModule("demo-app:WARN");
const err = debugModule("demo-app:ERROR");
// one mediasoup worker and router
//
// let worker, router, audioLevelObserver;
let workers = [];
let routers = [];
// let audioLevelObservers = [];
let roomStates = [];
//
// and one "room" ...
//
// const roomState = {
// // external
// peers: {},
// activeSpeaker: { producerId: null, volume: null, peerId: null },
// // internal
// transports: {},
// producers: [],
// consumers: []
// }
// this will store which worker/router/room a peer is in
let peerLocations = {};
//
// for each peer that connects, we keep a table of peers and what
// tracks are being sent and received. we also need to know the last
// time we saw the peer, so that we can disconnect clients that have
// network issues.
//
// for this simple demo, each client polls the server at 1hz, and we
// just send this roomState.peers data structure as our answer to each
// poll request.
//
// [peerId] : {
// joinTs: <ms timestamp>
// lastSeenTs: <ms timestamp>
// media: {
// [mediaTag] : {
// paused: <bool>
// encodings: []
// }
// },
// stats: {
// producers: {
// [producerId]: {
// ...(selected producer stats)
// }
// consumers: {
// [consumerId]: { ...(selected consumer stats) }
// }
// }
// consumerLayers: {
// [consumerId]:
// currentLayer,
// clientSelectedLayer,
// }
// }
// }
// }
//
// we also send information about the active speaker, as tracked by
// our audioLevelObserver.
//
// internally, we keep lists of transports, producers, and
// consumers. whenever we create a transport, producer, or consumer,
// we save the remote peerId in the object's `appData`. for producers
// and consumers we also keep track of the client-side "media tag", to
// correlate tracks.
//
/**
* https://stackoverflow.com/questions/1527803/generating-random-whole-numbers-in-javascript-in-a-specific-range
* Returns a random integer between min (inclusive) and max (inclusive).
* The value is no lower than min (or the next integer greater than min
* if min isn't an integer) and no greater than max (or the next integer
* lower than max if max isn't an integer).
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
let clients = {};
let testProjects = [
{
project_id: "8558",
project_name: "You Are Not the Only Particle in Universe",
elevator_pitch:
"A multi-media performance using home lamps as performing instruments. You Are Not the Only Particle in Universe is an experiment of transforming home lamps to new interfaces of performing music and light as interactive props in performance.",
description:
"I have a background in stage lighting design. In most stage performances, designers hide the light instrument above the stage or on the side behind curtains where audience could not see the light source itself. When I designed lighting for dance, I always thought I am also creating choreography but with medium of light. With this experience, I started to wonder what if I put light on stage, so that they are no longer complimentary roles in performance, but instead an actor, an expressive performing instrument on stage. &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;\r\n&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;\r\nYou Are Not the Only Particle in Universe is a continued research from a past performance project, In a Box, which I first created a performance that included a custom made instrument with home lamps and home lamp switches. My thesis project further develops this instrument with more interactive functions and allows the performer to create more versatile music and movement.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;\r\n&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;\r\nLight 2.0 is a multimedia performance that combines light, music, and movement, when light and music are not complementary roles and movement and performers are also not leading roles. Together, all these elements become performing instruments on stage.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;\r\n&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;\r\nThe performer can bow, tap, or spin the lamps to create various combinations of music, light, and movement. When bowing the lamp with a bow or tap near the sensors, it looks like bowing a cello and plucking. The performer can also spin the lamp shade to activate different parts of music composition.&lt;br /&gt;",
zoom_link: "https://nyu.zoom.us/j/2673933378",
},
];
let projects = [];
// projects = testProjects;
//
// main() -- our execution entry point
//
const os = require("os");
const numCPUs = os.cpus().length;
async function main() {
// start mediasoup
log("starting mediasoup");
for (let i = 0; i < numCPUs; i++) {
log("Starting Mediasoup worker in CPU #", i);
let worker, router, roomState;
({ worker, router, roomState } = await startMediasoup());
workers[i] = worker;
routers[i] = router;
// audioLevelObservers[i] = audioLevelObserver;
roomStates[i] = roomState;
}
runSocketServer();
// periodically clean up peers that disconnected without sending us
// a final "beacon"
setInterval(() => {
let now = Date.now();
for (let i = 0; i < roomStates.length; i++) {
Object.entries(roomStates[i].peers).forEach(([id, p]) => {
if (now - p.lastSeenTs > config.httpPeerStale) {
warn(`removing stale peer ${id}`);
closePeer(id);
}
});
}
}, 1000);
// periodically update video stats we're sending to peers
// setInterval(updatePeerStats, 3000);
updateProjects();
setInterval(updateProjects, 180000); // update projects every five minutes
}
main();
//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//
//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//
async function updateProjects() {
let url = process.env.PROJECT_DATABASE_URL;
https
.get(url, (res) => {
var body = "";
res.on("data", function (chunk) {
body += chunk;
});
res.on("end", function () {
// TODO parse JSON so we render HTML text correctly? i.e. so we don't end up with '</br>' or '&' ...
var json = JSON.parse(body);
projects = json;
log("Updated projects from database.");
io.sockets.emit("projects", projects);
});
})
.on("error", function (e) {
log("Got an error: ", e);
});
}
//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//
//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//
async function runSocketServer() {
// update all sockets at regular intervals
setInterval(() => {
io.sockets.emit("userPositions", clients);
}, 200);
// every 5 seconds, check for inactive clients and send them into cyberspace
setInterval(() => {
let now = Date.now();
for (let id in clients) {
if (now - clients[id].lastSeenTs > 60000) {
log("Culling inactive user with id", id);
clients[id].position = [1000, 1000, 1000];
}
}
}, 5000);
io.on("connection", (socket) => {
log(
"User " +
socket.id +
" connected, there are " +
io.engine.clientsCount +
" clients connected"
);
//Add a new client indexed by his id
clients[socket.id] = {
position: [1000, 0.5, 1000], // deal with phantom clients by putting them way away in the distance until they update their position
// position: [0, 0.5, 0],
// rotation: [0, 0, 0, 1] // stored as XYZW values of Quaternion
rotation: [0, 0, 0],
};
socket.emit("introduction", socket.id, Object.keys(clients));
// also give the client all existing clients positions:
socket.emit("userPositions", clients);
// Give new socket the projects database
socket.emit("projects", projects);
//Update everyone that the number of users has changed
io.sockets.emit(
"newUserConnected",
io.engine.clientsCount,
socket.id,
Object.keys(clients)
);
socket.on("move", (data) => {
let now = Date.now();
if (clients[socket.id]) {
clients[socket.id].position = data[0];
clients[socket.id].rotation = data[1];
clients[socket.id].lastSeenTs = now;
}
// io.sockets.emit('userPositions', clients);
});
// Handle the disconnection
socket.on("disconnect", () => {
//Delete this client from the object
delete clients[socket.id];
io.sockets.emit("userDisconnected", socket.id, Object.keys(clients));
log(
"User " +
socket.id +
" diconnected, there are " +
io.engine.clientsCount +
" clients connected"
);
});
//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//
//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//
// Mediasoup Signaling:
//
// -- our minimal signaling is just http polling --
//
// parse every request body for json, no matter the content-type. this
// lets us use sendBeacon or fetch interchangeably to POST to
// signaling endpoints. (sendBeacon can't set the Content-Type header)
//
// --> /signaling/sync
//
// client polling endpoint. send back our 'peers' data structure and
// 'activeSpeaker' info
//
// socket.on('sync', async (req, res) => {
socket.on("sync", async (data, callback) => {
// let { peerId } = req.body;
let peerId = socket.id;
try {
let allPeers = {};
for (let i = 0; i < roomStates.length; i++) {
Object.assign(allPeers, roomStates[i].peers);
}
let peerLoc = peerLocations[peerId.toString()];
if (peerLoc == undefined) {
throw new Error("No peerLoc found!");
}
// make sure this peer is connected. if we've disconnected the
// peer because of a network outage we want the peer to know that
// happened, when/if it returns
if (!roomStates[peerLoc].peers[peerId]) {
throw new Error("not connected");
}
// update our most-recently-seem timestamp -- we're not stale!
roomStates[peerLoc].peers[peerId].lastSeenTs = Date.now();
callback({
peers: allPeers,
// peers: roomStates[peerLoc].peers,
// activeSpeaker: roomStates[peerLoc].activeSpeaker,
// producers: roomStates[peerLoc].producers
});
} catch (e) {
console.error(e.message);
callback({ error: e.message });
}
});
// --> /signaling/join-as-new-peer
//
// adds the peer to the roomState data structure and creates a
// transport that the peer will use for receiving media. returns
// router rtpCapabilities for mediasoup-client device initialization
//
socket.on("join-as-new-peer", async (data, callback) => {
try {
// let { peerId } = req.body;
let peerId = socket.id;
let now = Date.now();
log("join-as-new-peer", peerId);
// assign random room:
let peerLoc = getRandomInt(0, numCPUs - 1);
log("assigning new peer to location in room ", peerLoc);
peerLocations[peerId.toString()] = peerLoc;
roomStates[peerLoc].peers[peerId] = {
joinTs: now,
lastSeenTs: now,
media: {},
consumerLayers: {},
stats: {},
};
callback({ routerRtpCapabilities: routers[peerLoc].rtpCapabilities });
} catch (e) {
console.error("error in /signaling/join-as-new-peer", e);
callback({ error: e });
}
});
// --> /signaling/leave
//
// removes the peer from the roomState data structure and and closes
// all associated mediasoup objects
//
socket.on("leave", async (data, callback) => {
try {
// let { peerId } = req.body;
let peerId = socket.id;
log("leave", peerId);
await closePeer(peerId);
callback({ left: true });
} catch (e) {
console.error("error in /signaling/leave", e);
callback({ error: e });
}
});
// --> /signaling/create-transport
//
// create a mediasoup transport object and send back info needed
// to create a transport object on the client side
//
socket.on("create-transport", async (data, callback) => {
try {
let peerId = socket.id;
let peerLoc = peerLocations[peerId.toString()];
// let { peerId, direction } = req.body;
let { direction } = data;
log("create-transport", peerId, direction);
let transport = await createWebRtcTransport({ peerId, direction });
roomStates[peerLoc].transports[transport.id] = transport;
let { id, iceParameters, iceCandidates, dtlsParameters } = transport;
callback({
transportOptions: {
id,
iceParameters,
iceCandidates,
dtlsParameters,
},
});
} catch (e) {
console.error("error in /signaling/create-transport", e);
callback({ error: e });
}
});
// --> /signaling/connect-transport
//
// called from inside a client's `transport.on('connect')` event
// handler.
//
socket.on("connect-transport", async (data, callback) => {
try {
let peerId = socket.id;
let peerLoc = peerLocations[peerId.toString()];
// let { peerId, transportId, dtlsParameters } = req.body,
let { transportId, dtlsParameters } = data,
transport = roomStates[peerLoc].transports[transportId];
if (!transport) {
err(
`connect-transport: server-side transport ${transportId} not found`
);
callback({ error: `server-side transport ${transportId} not found` });
return;
}
log("connect-transport", peerId, transport.appData);
await transport.connect({ dtlsParameters });
callback({ connected: true });
} catch (e) {
console.error("error in /signaling/connect-transport", e);
callback({ error: e });
}
});
// --> /signaling/close-transport
//
// called by a client that wants to close a single transport (for
// example, a client that is no longer sending any media).
//
socket.on("close-transport", async (data, callback) => {
try {
let peerId = socket.id;
let peerLoc = peerLocations[peerId.toString()];
// let { peerId, transportId } = req.body,
let { transportId } = data;
transport = roomStates[peerLoc].transports[transportId];
if (!transport) {
err(
`close-transport: server-side transport ${transportId} not found`
);
callback({ error: `server-side transport ${transportId} not found` });
return;
}
log("close-transport", peerId, transport.appData);
await closeTransport(transport, peerId);
callback({ closed: true });
} catch (e) {
console.error("error in /signaling/close-transport", e);
callback({ error: e.message });
}
});
// --> /signaling/close-producer
//
// called by a client that is no longer sending a specific track
//
socket.on("close-producer", async (data, callback) => {
try {
let peerId = socket.id;
let peerLoc = peerLocations[peerId.toString()];
// let { peerId, producerId } = req.body,
let { producerId } = data,
producer = roomStates[peerLoc].producers.find(
(p) => p.id === producerId
);
if (!producer) {
err(`close-producer: server-side producer ${producerId} not found`);
callback({ error: `server-side producer ${producerId} not found` });
return;
}
log("close-producer", peerId, producer.appData);
// await closeProducer(producer, peerId);
await closeProducerAndAllPipeProducers(producer, peerId);
callback({ closed: true });
} catch (e) {
console.error(e);
callback({ error: e.message });
}
});
// --> /signaling/send-track
//
// called from inside a client's `transport.on('produce')` event handler.
//
socket.on("send-track", async (data, callback) => {
try {
let peerId = socket.id;
let peerLoc = peerLocations[peerId.toString()];
// let { peerId, transportId, kind, rtpParameters,
let {
transportId,
kind,
rtpParameters,
paused = false,
appData,
} = data,
transport = roomStates[peerLoc].transports[transportId];
if (!transport) {
err(`send-track: server-side transport ${transportId} not found`);
callback({ error: `server-side transport ${transportId} not found` });
return;
}
let producer = await transport.produce({
kind,
rtpParameters,
paused,
appData: { ...appData, peerId, transportId },
});
// log("ID: ", peerId);
// log("ProducerID: ",producer.id);
// log(roomStates[peerLoc]);
// pipe to all other routers
log(
"Cloning Producer with ID: ",
producer.id,
" from peer with id ",
producer.appData.peerId
);
for (let i = 0; i < numCPUs; i++) {
if (i == peerLoc) {
continue;
} else {
let { pipeProducer } = await routers[peerLoc].pipeToRouter({
producerId: producer.id,
router: routers[i],
});
// await routers[peerLoc].pipeToRouter({ producerId: peerId, router: routers[i] })
roomStates[i].producers.push(pipeProducer);
log(
"Adding pipeProducer with id:",
pipeProducer.id,
" from peer with id ",
producer.appData.peerId,
" to room # ",
i
);
}
}
// if our associated transport closes, close ourself, too
producer.on("transportclose", () => {
log("producer's transport closed", producer.id);
closeProducerAndAllPipeProducers(producer, peerId);
// closeProducer(producer, peerId);
});
// monitor audio level of this producer. we call addProducer() here,
// but we don't ever need to call removeProducer() because the core
// AudioLevelObserver code automatically removes closed producers
// if (producer.kind === 'audio') {
// audioLevelObservers[peerLoc].addProducer({ producerId: producer.id });
// }
roomStates[peerLoc].producers.push(producer);
roomStates[peerLoc].peers[peerId].media[appData.mediaTag] = {
paused,
encodings: rtpParameters.encodings,
};
callback({ id: producer.id });
} catch (e) {}
});
// --> /signaling/recv-track
//
// create a mediasoup consumer object, hook it up to a producer here
// on the server side, and send back info needed to create a consumer
// object on the client side. always start consumers paused. client
// will request media to resume when the connection completes
//
socket.on("recv-track", async (data, callback) => {
try {
let peerId = socket.id;
let peerLoc = peerLocations[peerId.toString()];
let { mediaPeerId, mediaTag, rtpCapabilities } = data;
let producer = roomStates[peerLoc].producers.find(
(p) =>
p.appData.mediaTag === mediaTag && p.appData.peerId === mediaPeerId
);
if (!producer) {
let msg =
"server-side producer for " +
`${mediaPeerId}:${mediaTag} not found`;
err("recv-track: " + msg);
callback({ error: msg });
return;
}
if (
!routers[peerLoc].canConsume({
producerId: producer.id,
rtpCapabilities,
})
) {
let msg = `client cannot consume ${mediaPeerId}:${mediaTag}`;
err(`recv-track: ${peerId} ${msg}`);
callback({ error: msg });
return;
}
let transport = Object.values(roomStates[peerLoc].transports).find(
(t) =>
t.appData.peerId === peerId && t.appData.clientDirection === "recv"
);
if (!transport) {
let msg = `server-side recv transport for ${peerId} not found`;
err("recv-track: " + msg);
callback({ error: msg });
return;
}
let consumer = await transport.consume({
producerId: producer.id,
rtpCapabilities,
paused: true, // see note above about always starting paused
appData: { peerId, mediaPeerId, mediaTag },
});
// need both 'transportclose' and 'producerclose' event handlers,
// to make sure we close and clean up consumers in all
// circumstances
consumer.on("transportclose", () => {
log(`consumer's transport closed`, consumer.id);
closeConsumer(consumer, peerId);
});
consumer.on("producerclose", () => {
log(`consumer's producer closed`, consumer.id);
closeConsumer(consumer, peerId);
});
// stick this consumer in our list of consumers to keep track of,
// and create a data structure to track the client-relevant state
// of this consumer
roomStates[peerLoc].consumers.push(consumer);
roomStates[peerLoc].peers[peerId].consumerLayers[consumer.id] = {
currentLayer: null,
clientSelectedLayer: null,
};
// update above data structure when layer changes.
consumer.on("layerschange", (layers) => {
log(
`consumer layerschange ${mediaPeerId}->${peerId}`,
mediaTag,
layers
);
if (
roomStates[peerLoc].peers[peerId] &&
roomStates[peerLoc].peers[peerId].consumerLayers[consumer.id]
) {
roomStates[peerLoc].peers[peerId].consumerLayers[
consumer.id
].currentLayer = layers && layers.spatialLayer;
}
});
callback({
producerId: producer.id,
id: consumer.id,
kind: consumer.kind,
rtpParameters: consumer.rtpParameters,
type: consumer.type,
producerPaused: consumer.producerPaused,
});
} catch (e) {
console.error("error in /signaling/recv-track", e);
callback({ error: e });
}
});
// --> /signaling/pause-consumer
//
// called to pause receiving a track for a specific client
//
socket.on("pause-consumer", async (data, callback) => {
try {
let peerId = socket.id;
let peerLoc = peerLocations[peerId.toString()];
let { consumerId } = data,
consumer = roomStates[peerLoc].consumers.find(
(c) => c.id === consumerId
);
if (!consumer) {
err(`pause-consumer: server-side consumer ${consumerId} not found`);
callback({ error: `server-side producer ${consumerId} not found` });
return;
}
log("pause-consumer", consumer.appData);
await consumer.pause();
callback({ paused: true });
} catch (e) {
console.error("error in /signaling/pause-consumer", e);
callback({ error: e });
}
});
// --> /signaling/resume-consumer
//
// called to resume receiving a track for a specific client
//
socket.on("resume-consumer", async (data, callback) => {
try {
let peerId = socket.id;
let peerLoc = peerLocations[peerId.toString()];
let { consumerId } = data,
consumer = roomStates[peerLoc].consumers.find(
(c) => c.id === consumerId
);
if (!consumer) {
err(`pause-consumer: server-side consumer ${consumerId} not found`);
callback({ error: `server-side consumer ${consumerId} not found` });
return;
}
log("resume-consumer", consumer.appData);
await consumer.resume();
callback({ resumed: true });
} catch (e) {
console.error("error in /signaling/resume-consumer", e);
callback({ error: e });
}
});
// --> /signalign/close-consumer
//
// called to stop receiving a track for a specific client. close and
// clean up consumer object
//
socket.on("close-consumer", async (data, callback) => {
try {
let peerId = socket.id;
let peerLoc = peerLocations[peerId.toString()];
let { consumerId } = data,
consumer = roomStates[peerLoc].consumers.find(
(c) => c.id === consumerId
);
if (!consumer) {
err(`close-consumer: server-side consumer ${consumerId} not found`);
callback({ error: `server-side consumer ${consumerId} not found` });
return;
}
await closeConsumer(consumer, peerId);
callback({ closed: true });
} catch (e) {
console.error("error in /signaling/close-consumer", e);
callback({ error: e });
}
});
// --> /signaling/consumer-set-layers
//
// called to set the largest spatial layer that a specific client
// wants to receive
//
socket.on("consumer-set-layers", async (data, callback) => {
try {
let peerId = socket.id;
let peerLoc = peerLocations[peerId.toString()];
let { consumerId, spatialLayer } = data,
consumer = roomStates[peerLoc].consumers.find(
(c) => c.id === consumerId
);
if (!consumer) {
err(
`consumer-set-layers: server-side consumer ${consumerId} not found`
);
callback({ error: `server-side consumer ${consumerId} not found` });
return;
}
log("consumer-set-layers", spatialLayer, consumer.appData);
await consumer.setPreferredLayers({ spatialLayer });
callback({ layersSet: true });
} catch (e) {
console.error("error in /signaling/consumer-set-layers", e);
callback({ error: e });
}
});
// --> /signaling/pause-producer
//
// called to stop sending a track from a specific client
//
socket.on("pause-producer", async (data, callback) => {
try {
let peerId = socket.id;
let peerLoc = peerLocations[peerId.toString()];
let { producerId } = data,
producer = roomStates[peerLoc].producers.find(
(p) => p.id === producerId
);
if (!producer) {
err(`pause-producer: server-side producer ${producerId} not found`);
callback({ error: `server-side producer ${producerId} not found` });
return;
}
log("pause-producer", producer.appData);
await producer.pause();
roomStates[peerLoc].peers[peerId].media[
producer.appData.mediaTag
].paused = true;
callback({ paused: true });
} catch (e) {
console.error("error in /signaling/pause-producer", e);
callback({ error: e });
}
});
// --> /signaling/resume-producer
//
// called to resume sending a track from a specific client
//
socket.on("resume-producer", async (data, callback) => {
try {
let peerId = socket.id;
let peerLoc = peerLocations[peerId.toString()];
let { producerId } = data,
producer = roomStates[peerLoc].producers.find(
(p) => p.id === producerId
);
if (!producer) {
err(`resume-producer: server-side producer ${producerId} not found`);
callback({ error: `server-side producer ${producerId} not found` });
return;
}
log("resume-producer", producer.appData);
await producer.resume();
roomStates[peerLoc].peers[peerId].media[
producer.appData.mediaTag
].paused = false;
callback({ resumed: true });
} catch (e) {
console.error("error in /signaling/resume-producer", e);
callback({ error: e });
}
});
//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//
//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//*//
});
}
//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//
//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//==//
//
// start mediasoup with a single worker and router
//
async function startMediasoup() {
let roomState = {
// external
peers: {},
activeSpeaker: { producerId: null, volume: null, peerId: null },
// internal
transports: {},
producers: [],
consumers: [],
};
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 router = await worker.createRouter({ mediaCodecs });
return { worker, router, roomState };
}
function closePeer(peerId) {
log("closing peer", peerId);
let peerLoc = peerLocations[peerId.toString()];
for (let [id, transport] of Object.entries(roomStates[peerLoc].transports)) {
if (transport.appData.peerId === peerId) {
closeTransport(transport, peerId);
}
}
delete roomStates[peerLoc].peers[peerId];
}
async function closeTransport(transport, peerId) {
try {
let peerLoc = peerLocations[peerId.toString()];
log("closing transport", transport.id, transport.appData);