mediasoup/app.js

334 lines
11 KiB
JavaScript
Raw Normal View History

/**
* integrating mediasoup server with a node.js application
*/
2022-09-19 14:40:57 +00:00
require('dotenv').config()
2022-09-19 14:43:39 +00:00
const express = require('express');
const app = express();
2022-09-19 14:40:57 +00:00
const path = require('node:path');
let https;
try {
https = require('node:https');
} catch (err) {
console.log('https support is disabled!');
}
const mediasoup = require('mediasoup');
/* Please follow mediasoup installation requirements */
/* https://mediasoup.org/documentation/v3/mediasoup/installation/ */
2022-09-19 14:40:57 +00:00
// import express from 'express'
// const app = express()
2022-09-19 14:03:58 +00:00
// const app = require('express')();
// import https from 'httpolyglot'
2022-09-19 14:40:57 +00:00
// import https from "https";
// import fs from 'fs'
// import path from 'path'
2022-07-23 07:32:54 +00:00
2022-09-19 14:03:58 +00:00
// import Server from 'socket.io'
2022-09-19 14:40:57 +00:00
// import mediasoup from 'mediasoup'
2022-09-19 14:03:58 +00:00
// import * as https from "http";
2022-09-19 14:40:57 +00:00
// import Server from "socket.io";
2022-09-19 14:03:58 +00:00
// import middleware from 'socketio-wildcard'
// const app = express.default();
let worker
2022-09-13 19:24:10 +00:00
/**
* videoCalls
* |-> Router
* |-> Producer
* |-> Consumer
* |-> Producer Transport
* |-> Consumer Transport
*
* '<callId>': {
* router: Router,
* producer: Producer,
* producerTransport: Producer Transport,
* consumer: Consumer,
* consumerTransport: Consumer Transport
* }
*
**/
let videoCalls = {}
let socketDetails = {}
2022-07-23 07:32:54 +00:00
app.get('/', (_req, res) => {
2022-07-23 07:32:54 +00:00
res.send('Hello from mediasoup app!')
})
app.use('/sfu', express.static(path.join(__dirname, 'public')))
// SSL cert for HTTPS access
const options = {
key: fs.readFileSync('./server/ssl/key.pem', 'utf-8'),
cert: fs.readFileSync('./server/ssl/cert.pem', 'utf-8')
}
2022-09-19 14:40:57 +00:00
// const httpsServer = https.createServer(options, app);
// const io = new Server(httpsServer, { allowEIO3: true });
const server = https.createServer(app);
const io = require('socket.io')(server, options);
2022-09-19 14:03:58 +00:00
// const io = new Server(server, { origins: '*:*', allowEIO3: true });
2022-09-19 14:03:58 +00:00
// io.use(middleware);
// const httpsServer = https.createServer(options, app)
2022-09-19 14:13:48 +00:00
httpsServer.listen(process.env.PORT, () => {
console.log('Listening on port:', process.env.PORT)
})
2022-07-23 07:32:54 +00:00
2022-09-19 14:03:58 +00:00
// const io = new Server(httpsServer, {
// allowEIO3: true
// });
2022-07-23 07:32:54 +00:00
// socket.io namespace (could represent a room?)
2022-07-23 07:32:54 +00:00
const peers = io.of('/mediasoup')
const createWorker = async () => {
worker = await mediasoup.createWorker({
rtcMinPort: 2000,
rtcMaxPort: 2020,
})
console.log(`[createWorker] worker pid ${worker.pid}`)
2022-07-23 07:32:54 +00:00
worker.on('died', error => {
// This implies something serious happened, so kill the application
console.error('mediasoup worker has died', error)
2022-07-23 07:32:54 +00:00
setTimeout(() => process.exit(1), 2000) // exit in 2 seconds
})
return worker
}
// We create a Worker as soon as our application starts
worker = createWorker()
// This is an Array of RtpCapabilities
// https://mediasoup.org/documentation/v3/mediasoup/rtp-parameters-and-capabilities/#RtpCodecCapability
// list of media codecs supported by mediasoup ...
// https://github.com/versatica/mediasoup/blob/v3/src/supportedRtpCapabilities.ts
const mediaCodecs = [
{
kind: 'audio',
mimeType: 'audio/opus',
clockRate: 48000,
channels: 2,
},
{
kind: 'video',
mimeType: 'video/VP8',
clockRate: 90000,
parameters: {
'x-google-start-bitrate': 1000,
},
},
]
const closeCall = (callId) => {
if (videoCalls[callId]) {
videoCalls[callId].producer?.close();
videoCalls[callId].consumer?.close();
videoCalls[callId]?.consumerTransport.close();
videoCalls[callId]?.producerTransport.close();
videoCalls[callId].router.close();
delete videoCalls[callId];
}
}
const getRtpCapabilities = (callId, callback) => {
console.log('[getRtpCapabilities] callId', callId);
const rtpCapabilities = videoCalls[callId].router.rtpCapabilities;
callback({ rtpCapabilities });
}
2022-09-13 16:56:06 +00:00
2022-07-23 07:32:54 +00:00
peers.on('connection', async socket => {
console.log('[connection] socketId:', socket.id)
2022-07-29 09:22:35 +00:00
socket.emit('connection-success', {
socketId: socket.id
2022-07-29 09:22:35 +00:00
})
2022-07-23 07:32:54 +00:00
socket.on('disconnect', () => {
// do some cleanup
console.log('peer disconnected | socket.id', socket.id)
delete socketDetails[socket.id];
2022-07-23 07:32:54 +00:00
})
socket.on('createRoom', async ({ callId }, callback) => {
if (callId) {
console.log(`[createRoom] socket.id ${socket.id} callId ${callId}`);
if (!videoCalls[callId]) {
console.log('[createRoom] callId', callId);
videoCalls[callId] = { router: await worker.createRouter({ mediaCodecs }) }
console.log(`[createRoom] Router ID: ${videoCalls[callId].router.id}`);
}
socketDetails[socket.id] = callId;
getRtpCapabilities(callId, callback);
} else {
console.log(`[createRoom] missing callId ${callId}`);
}
})
// Client emits a request to create server side Transport
// We need to differentiate between the producer and consumer transports
socket.on('createWebRtcTransport', async ({ sender, callId }, callback) => {
console.log(`[createWebRtcTransport] Is this a sender request? ${sender} | callId ${callId}`)
// The client indicates if it is a producer or a consumer
// if sender is true, indicates a producer else a consumer
if (sender)
videoCalls[callId].producerTransport = await createWebRtcTransportLayer(callId, callback)
else
videoCalls[callId].consumerTransport = await createWebRtcTransportLayer(callId, callback)
})
// see client's socket.emit('transport-connect', ...)
socket.on('transport-connect', async ({ dtlsParameters }) => {
const callId = socketDetails[socket.id];
console.log(`[transport-connect] socket.id ${socket.id} | callId ${callId} | DTLS PARAMS... ${dtlsParameters}`)
await videoCalls[callId].producerTransport.connect({ dtlsParameters })
})
// see client's socket.emit('transport-produce', ...)
socket.on('transport-produce', async ({ kind, rtpParameters, appData }) => {
const callId = socketDetails[socket.id];
console.log('[transport-produce] | socket.id', socket.id, '| callId', callId);
// call produce based on the prameters from the client
videoCalls[callId].producer = await videoCalls[callId].producerTransport.produce({
kind,
rtpParameters,
2022-07-23 07:32:54 +00:00
})
console.log(`[transport-produce] Producer ID: ${videoCalls[callId].producer.id} | kind: ${videoCalls[callId].producer.kind}`)
videoCalls[callId].producer.on('transportclose', () => {
const callId = socketDetails[socket.id];
2022-08-11 19:11:49 +00:00
console.log('transport for this producer closed', callId)
closeCall(callId);
2022-08-11 09:18:01 +00:00
})
})
// see client's socket.emit('transport-recv-connect', ...)
socket.on('transport-recv-connect', async ({ dtlsParameters }) => {
const callId = socketDetails[socket.id];
console.log(`[transport-recv-connect] socket.id ${socket.id} | callId ${callId} | DTLS PARAMS: ${dtlsParameters}`);
await videoCalls[callId].consumerTransport.connect({ dtlsParameters })
})
socket.on('consume', async ({ rtpCapabilities }, callback) => {
const callId = socketDetails[socket.id];
console.log('[consume] callId', callId);
try {
// console.log('consume', rtpCapabilities, callId);
// check if the router can consume the specified producer
if (videoCalls[callId].router.canConsume({
producerId: videoCalls[callId].producer.id,
rtpCapabilities
})) {
2022-09-13 18:15:51 +00:00
console.log('[consume] Can consume', callId);
// transport can now consume and return a consumer
videoCalls[callId].consumer = await videoCalls[callId].consumerTransport.consume({
producerId: videoCalls[callId].producer.id,
rtpCapabilities,
paused: true,
})
// https://mediasoup.org/documentation/v3/mediasoup/api/#consumer-on-transportclose
videoCalls[callId].consumer.on('transportclose', () => {
2022-09-15 06:56:32 +00:00
const callId = socketDetails[socket.id];
console.log('transport close from consumer', callId);
closeCall();
2022-08-11 09:18:01 +00:00
})
// https://mediasoup.org/documentation/v3/mediasoup/api/#consumer-on-producerclose
videoCalls[callId].consumer.on('producerclose', () => {
2022-09-15 06:56:32 +00:00
const callId = socketDetails[socket.id];
console.log('producer of consumer closed', callId);
closeCall();
})
// from the consumer extract the following params
// to send back to the Client
const params = {
id: videoCalls[callId].consumer.id,
producerId: videoCalls[callId].producer.id,
kind: videoCalls[callId].consumer.kind,
rtpParameters: videoCalls[callId].consumer.rtpParameters,
}
2022-08-18 06:34:22 +00:00
// send the parameters to the client
callback({ params })
2022-09-13 18:33:04 +00:00
} else {
console.log('[canConsume] Can\'t consume')
2022-07-23 07:32:54 +00:00
}
} catch (error) {
2022-09-13 18:33:04 +00:00
console.log('[consume] Error', error.message)
callback({
params: {
error: error
}
})
}
})
2022-07-23 07:32:54 +00:00
socket.on('consumer-resume', async () => {
const callId = socketDetails[socket.id];
console.log(`[consumer-resume] callId ${callId}`)
await videoCalls[callId].consumer.resume()
2022-07-23 07:32:54 +00:00
})
})
const createWebRtcTransportLayer = async (callId, callback) => {
2022-07-23 07:32:54 +00:00
try {
2022-08-12 11:56:20 +00:00
console.log('[createWebRtcTransportLayer] callId', callId);
2022-07-23 07:32:54 +00:00
// https://mediasoup.org/documentation/v3/mediasoup/api/#WebRtcTransportOptions
const webRtcTransport_options = {
listenIps: [
{
ip: process.env.IP, // Listening IPv4 or IPv6.
announcedIp: process.env.ANNOUNCED_IP, // Announced IPv4 or IPv6 (useful when running mediasoup behind NAT with private IP).
2022-07-23 07:32:54 +00:00
}
],
enableUdp: true,
enableTcp: true,
preferUdp: true,
}
2022-08-12 11:56:20 +00:00
2022-08-16 11:21:02 +00:00
// console.log('webRtcTransport_options', webRtcTransport_options);
// https://mediasoup.org/documentation/v3/mediasoup/api/#router-createWebRtcTransport
let transport = await videoCalls[callId].router.createWebRtcTransport(webRtcTransport_options)
console.log(`callId: ${callId} | transport id: ${transport.id}`)
2022-07-23 07:32:54 +00:00
transport.on('dtlsstatechange', dtlsState => {
if (dtlsState === 'closed') {
transport.close()
}
})
transport.on('close', () => {
console.log('transport closed')
})
2022-08-16 11:21:02 +00:00
const params = {
id: transport.id,
iceParameters: transport.iceParameters,
iceCandidates: transport.iceCandidates,
dtlsParameters: transport.dtlsParameters,
}
2022-07-23 07:32:54 +00:00
// send back to the client the following prameters
callback({
// https://mediasoup.org/documentation/v3/mediasoup-client/api/#TransportOptions
2022-08-16 11:21:02 +00:00
params
2022-07-23 07:32:54 +00:00
})
return transport
} catch (error) {
2022-08-12 11:56:20 +00:00
console.log('[createWebRtcTransportLayer] ERROR', JSON.stringify(error));
2022-07-23 07:32:54 +00:00
callback({
params: {
error: error
}
})
}
}