-
Notifications
You must be signed in to change notification settings - Fork 80
/
server.js
235 lines (205 loc) · 6.1 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
const mediasoup = require('mediasoup');
const fs = require('fs');
const https = require('https');
const express = require('express');
const socketIO = require('socket.io');
const config = require('./config');
// Global variables
let worker;
let webServer;
let socketServer;
let expressApp;
let producer;
let consumer;
let producerTransport;
let consumerTransport;
let mediasoupRouter;
(async () => {
try {
await runExpressApp();
await runWebServer();
await runSocketServer();
await runMediasoupWorker();
} catch (err) {
console.error(err);
}
})();
async function runExpressApp() {
expressApp = express();
expressApp.use(express.json());
expressApp.use(express.static(__dirname));
expressApp.use((error, req, res, next) => {
if (error) {
console.warn('Express app error,', error.message);
error.status = error.status || (error.name === 'TypeError' ? 400 : 500);
res.statusMessage = error.message;
res.status(error.status).send(String(error));
} else {
next();
}
});
}
async function runWebServer() {
const { sslKey, sslCrt } = config;
if (!fs.existsSync(sslKey) || !fs.existsSync(sslCrt)) {
console.error('SSL files are not found. check your config.js file');
process.exit(0);
}
const tls = {
cert: fs.readFileSync(sslCrt),
key: fs.readFileSync(sslKey),
};
webServer = https.createServer(tls, expressApp);
webServer.on('error', (err) => {
console.error('starting web server failed:', err.message);
});
await new Promise((resolve) => {
const { listenIp, listenPort } = config;
webServer.listen(listenPort, listenIp, () => {
const listenIps = config.mediasoup.webRtcTransport.listenIps[0];
const ip = listenIps.announcedIp || listenIps.ip;
console.log('server is running');
console.log(`open https://${ip}:${listenPort} in your web browser`);
resolve();
});
});
}
async function runSocketServer() {
socketServer = socketIO(webServer, {
serveClient: false,
path: '/server',
log: false,
});
socketServer.on('connection', (socket) => {
console.log('client connected');
// inform the client about existence of producer
if (producer) {
socket.emit('newProducer');
}
socket.on('disconnect', () => {
console.log('client disconnected');
});
socket.on('connect_error', (err) => {
console.error('client connection error', err);
});
socket.on('getRouterRtpCapabilities', (data, callback) => {
callback(mediasoupRouter.rtpCapabilities);
});
socket.on('createProducerTransport', async (data, callback) => {
try {
const { transport, params } = await createWebRtcTransport();
producerTransport = transport;
callback(params);
} catch (err) {
console.error(err);
callback({ error: err.message });
}
});
socket.on('createConsumerTransport', async (data, callback) => {
try {
const { transport, params } = await createWebRtcTransport();
consumerTransport = transport;
callback(params);
} catch (err) {
console.error(err);
callback({ error: err.message });
}
});
socket.on('connectProducerTransport', async (data, callback) => {
await producerTransport.connect({ dtlsParameters: data.dtlsParameters });
callback();
});
socket.on('connectConsumerTransport', async (data, callback) => {
await consumerTransport.connect({ dtlsParameters: data.dtlsParameters });
callback();
});
socket.on('produce', async (data, callback) => {
const {kind, rtpParameters} = data;
producer = await producerTransport.produce({ kind, rtpParameters });
callback({ id: producer.id });
// inform clients about new producer
socket.broadcast.emit('newProducer');
});
socket.on('consume', async (data, callback) => {
callback(await createConsumer(producer, data.rtpCapabilities));
});
socket.on('resume', async (data, callback) => {
await consumer.resume();
callback();
});
});
}
async function runMediasoupWorker() {
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, exiting in 2 seconds... [pid:%d]', worker.pid);
setTimeout(() => process.exit(1), 2000);
});
const mediaCodecs = config.mediasoup.router.mediaCodecs;
mediasoupRouter = await worker.createRouter({ mediaCodecs });
}
async function createWebRtcTransport() {
const {
maxIncomingBitrate,
initialAvailableOutgoingBitrate
} = config.mediasoup.webRtcTransport;
const transport = await mediasoupRouter.createWebRtcTransport({
listenIps: config.mediasoup.webRtcTransport.listenIps,
enableUdp: true,
enableTcp: true,
preferUdp: true,
initialAvailableOutgoingBitrate,
});
if (maxIncomingBitrate) {
try {
await transport.setMaxIncomingBitrate(maxIncomingBitrate);
} catch (error) {
}
}
return {
transport,
params: {
id: transport.id,
iceParameters: transport.iceParameters,
iceCandidates: transport.iceCandidates,
dtlsParameters: transport.dtlsParameters
},
};
}
async function createConsumer(producer, rtpCapabilities) {
if (!mediasoupRouter.canConsume(
{
producerId: producer.id,
rtpCapabilities,
})
) {
console.error('can not consume');
return;
}
try {
consumer = await consumerTransport.consume({
producerId: producer.id,
rtpCapabilities,
paused: producer.kind === 'video',
});
} catch (error) {
console.error('consume failed', error);
return;
}
if (consumer.type === 'simulcast') {
await consumer.setPreferredLayers({ spatialLayer: 2, temporalLayer: 2 });
}
return {
producerId: producer.id,
id: consumer.id,
kind: consumer.kind,
rtpParameters: consumer.rtpParameters,
type: consumer.type,
producerPaused: consumer.producerPaused
};
}