diff --git a/app.js b/app.js index fd7dbf3..cf9ddee 100644 --- a/app.js +++ b/app.js @@ -1,4 +1,4 @@ -require('dotenv').config() +require('dotenv').config(); const express = require('express'); const app = express(); @@ -15,7 +15,7 @@ const mediasoup = require('mediasoup'); let worker; /** - * + * * videoCalls - Dictionary of Object(s) * '': { * router: Router, @@ -28,16 +28,16 @@ let worker; * initiatorConsumerVideo: Consumer, * initiatorConsumerAudio: Consumer, * initiatorConsumerTransport: Consumer Transport - * initiatorSockerId - * receiverSocketId + * initiatorSocket + * receiverSocket * } - * + * **/ let videoCalls = {}; let socketDetails = {}; app.get('/', (_req, res) => { - res.send('Hello from mediasoup app!') + res.send('Hello from mediasoup app!'); }); app.use('/sfu', express.static(path.join(__dirname, 'public'))); @@ -52,7 +52,7 @@ const httpsServer = https.createServer(options, app); const io = new Server(httpsServer, { allowEIO3: true, - origins: ["*:*"] + origins: ['*:*'], }); httpsServer.listen(process.env.PORT, () => { @@ -66,19 +66,19 @@ const createWorker = async () => { worker = await mediasoup.createWorker({ rtcMinPort: parseInt(process.env.RTC_MIN_PORT), rtcMaxPort: parseInt(process.env.RTC_MAX_PORT), - }) + }); console.log(`[createWorker] worker pid ${worker.pid}`); - - worker.on('died', error => { + + worker.on('died', (error) => { // This implies something serious happened, so kill the application console.error('mediasoup worker has died', error); setTimeout(() => process.exit(1), 2000); // exit in 2 seconds - }) + }); return worker; } catch (error) { - console.log(`ERROR | createWorker | ${error.message}`); + console.error(`[createWorker] | ERROR | error: ${error.message}`); } -} +}; // We create a Worker as soon as our application starts worker = createWorker(); @@ -87,57 +87,53 @@ worker = createWorker(); // 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 = [ +const mediaCodecs = [ { - kind : 'audio', - mimeType : 'audio/opus', - clockRate : 48000, - channels : 2 + kind: 'audio', + mimeType: 'audio/opus', + clockRate: 48000, + channels: 2, }, { - kind : 'video', - mimeType : 'video/VP8', - clockRate : 90000, - parameters : - { - 'x-google-start-bitrate' : 1000 + kind: 'video', + mimeType: 'video/VP8', + clockRate: 90000, + parameters: { + 'x-google-start-bitrate': 1000, }, - channels : 2 + channels: 2, }, { - kind : 'video', - mimeType : 'video/VP9', - clockRate : 90000, - parameters : - { - 'profile-id' : 2, - 'x-google-start-bitrate' : 1000 - } + kind: 'video', + mimeType: 'video/VP9', + clockRate: 90000, + parameters: { + 'profile-id': 2, + 'x-google-start-bitrate': 1000, + }, }, { - kind : 'video', - mimeType : 'video/h264', - clockRate : 90000, - parameters : - { - 'packetization-mode' : 1, - 'profile-level-id' : '4d0032', - 'level-asymmetry-allowed' : 1, - 'x-google-start-bitrate' : 1000 - } + kind: 'video', + mimeType: 'video/h264', + clockRate: 90000, + parameters: { + 'packetization-mode': 1, + 'profile-level-id': '4d0032', + 'level-asymmetry-allowed': 1, + 'x-google-start-bitrate': 1000, + }, }, { - kind : 'video', - mimeType : 'video/h264', - clockRate : 90000, - parameters : - { - 'packetization-mode' : 1, - 'profile-level-id' : '42e01f', - 'level-asymmetry-allowed' : 1, - 'x-google-start-bitrate' : 1000 - } - } + kind: 'video', + mimeType: 'video/h264', + clockRate: 90000, + parameters: { + 'packetization-mode': 1, + 'profile-level-id': '42e01f', + 'level-asymmetry-allowed': 1, + 'x-google-start-bitrate': 1000, + }, + }, ]; const closeCall = (callId) => { @@ -152,24 +148,23 @@ const closeCall = (callId) => { videoCalls[callId]?.receiverProducerTransport?.close(); videoCalls[callId]?.router?.close(); delete videoCalls[callId]; - } else { - console.log(`The call with id ${callId} has already been deleted`); + console.log(`[closeCall] | callId: ${callId}`); } } catch (error) { - console.log(`ERROR | closeCall | callid ${callId} | ${error.message}`); + console.error(`[closeCall] | ERROR | callId: ${callId} | error: ${error.message}`); } -} +}; /* - Handlers for WS events - These are created only when we have a connection with a peer */ -peers.on('connection', async socket => { +peers.on('connection', async (socket) => { console.log('[connection] socketId:', socket.id); // After making the connection successfully, we send the client a 'connection-success' event socket.emit('connection-success', { - socketId: socket.id + socketId: socket.id, }); // It is triggered when the peer is disconnected @@ -192,24 +187,22 @@ peers.on('connection', async socket => { 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}`); - videoCalls[callId].receiverSocketId = socket.id + videoCalls[callId] = { router: await worker.createRouter({ mediaCodecs }) }; + console.log(`[createRoom] Generate Router ID: ${videoCalls[callId].router.id}`); + videoCalls[callId].receiverSocket = socket; } else { - videoCalls[callId].initiatorSockerId = socket.id + videoCalls[callId].initiatorSocket = socket; } socketDetails[socket.id] = callId; // rtpCapabilities is set for callback - console.log('[getRtpCapabilities] callId', callId); - callbackResponse = { - rtpCapabilities :videoCalls[callId].router.rtpCapabilities + callbackResponse = { + rtpCapabilities: videoCalls[callId].router.rtpCapabilities, }; } else { - console.log(`[createRoom] missing callId ${callId}`); + console.log(`[createRoom] missing callId: ${callId}`); } } catch (error) { - console.log(`ERROR | createRoom | callId ${callId} | ${error.message}`); + console.error(`[createRoom] | ERROR | callId: ${callId} | error: ${error.message}`); } finally { callback(callbackResponse); } @@ -228,23 +221,27 @@ peers.on('connection', async socket => { const callId = socketDetails[socket.id]; console.log(`[createWebRtcTransport] socket ${socket.id} | sender ${sender} | callId ${callId}`); if (sender) { - if(!videoCalls[callId].receiverProducerTransport && !isInitiator(callId, socket.id)) { + if (!videoCalls[callId].receiverProducerTransport && !isInitiator(callId, socket.id)) { videoCalls[callId].receiverProducerTransport = await createWebRtcTransportLayer(callId, callback); - } else if(!videoCalls[callId].initiatorProducerTransport && isInitiator(callId, socket.id)) { + } else if (!videoCalls[callId].initiatorProducerTransport && isInitiator(callId, socket.id)) { videoCalls[callId].initiatorProducerTransport = await createWebRtcTransportLayer(callId, callback); } else { console.log(`producerTransport has already been defined | callId ${callId}`); callback(null); } } else if (!sender) { - if(!videoCalls[callId].receiverConsumerTransport && !isInitiator(callId, socket.id)) { + if (!videoCalls[callId].receiverConsumerTransport && !isInitiator(callId, socket.id)) { videoCalls[callId].receiverConsumerTransport = await createWebRtcTransportLayer(callId, callback); - } else if(!videoCalls[callId].initiatorConsumerTransport && isInitiator(callId, socket.id)) { + } else if (!videoCalls[callId].initiatorConsumerTransport && isInitiator(callId, socket.id)) { videoCalls[callId].initiatorConsumerTransport = await createWebRtcTransportLayer(callId, callback); } } } catch (error) { - console.log(`ERROR | createWebRtcTransport | callId ${socketDetails[socket.id]} | sender ${sender} | ${error.message}`); + console.error( + `[createWebRtcTransport] | ERROR | callId: ${socketDetails[socket.id]} | sender: ${sender} | error: ${ + error.message + }` + ); callback(error); } }); @@ -259,13 +256,12 @@ peers.on('connection', async socket => { if (typeof dtlsParameters === 'string') dtlsParameters = JSON.parse(dtlsParameters); console.log(`[transport-connect] socket ${socket.id} | callId ${callId}`); - if (!isInitiator(callId, socket.id)) { - await videoCalls[callId].receiverProducerTransport.connect({ dtlsParameters }); - } else { - await videoCalls[callId].initiatorProducerTransport.connect({ dtlsParameters }); - } + + isInitiator(callId, socket.id) + ? await videoCalls[callId].initiatorProducerTransport.connect({ dtlsParameters }) + : await videoCalls[callId].receiverProducerTransport.connect({ dtlsParameters }); } catch (error) { - console.log(`ERROR | transport-connect | callId ${socketDetails[socket.id]} | ${error.message}`); + console.error(`[transport-connect] | ERROR | callId: ${socketDetails[socket.id]} | error: ${error.message}`); } }); @@ -278,8 +274,9 @@ peers.on('connection', async socket => { try { const callId = socketDetails[socket.id]; if (typeof rtpParameters === 'string') rtpParameters = JSON.parse(rtpParameters); - - console.log(`[transport-produce] kind: ${kind} | socket: ${socket.id} | callId: ${callId}`); + + console.log(`[transport-produce] callId: ${callId} | kind: ${kind} | socket: ${socket.id}`); + if (kind === 'video') { if (!isInitiator(callId, socket.id)) { videoCalls[callId].receiverVideoProducer = await videoCalls[callId].receiverProducerTransport.produce({ @@ -287,35 +284,31 @@ peers.on('connection', async socket => { rtpParameters, }); - console.log(`[transport-produce] receiverVideoProducer Producer ID: ${videoCalls[callId].receiverVideoProducer.id} | kind: ${videoCalls[callId].receiverVideoProducer.kind}`); - videoCalls[callId].receiverVideoProducer.on('transportclose', () => { - const callId = socketDetails[socket.id]; - console.log('transport for this producer closed', callId) + console.log('transport for this producer closed', callId); closeCall(callId); }); // Send back to the client the Producer's id - callback && callback({ - id: videoCalls[callId].receiverVideoProducer.id - }); + callback && + callback({ + id: videoCalls[callId].receiverVideoProducer.id, + }); } else { videoCalls[callId].initiatorVideoProducer = await videoCalls[callId].initiatorProducerTransport.produce({ kind, rtpParameters, }); - console.log(`[transport-produce] initiatorVideoProducer Producer ID: ${videoCalls[callId].initiatorVideoProducer.id} | kind: ${videoCalls[callId].initiatorVideoProducer.kind}`); - videoCalls[callId].initiatorVideoProducer.on('transportclose', () => { - const callId = socketDetails[socket.id]; - console.log('transport for this producer closed', callId) + console.log('transport for this producer closed', callId); closeCall(callId); }); - callback && callback({ - id: videoCalls[callId].initiatorVideoProducer.id - }); + callback && + callback({ + id: videoCalls[callId].initiatorVideoProducer.id, + }); } } else if (kind === 'audio') { if (!isInitiator(callId, socket.id)) { @@ -324,40 +317,44 @@ peers.on('connection', async socket => { rtpParameters, }); - console.log(`[transport-produce] receiverAudioProducer Producer ID: ${videoCalls[callId].receiverAudioProducer.id} | kind: ${videoCalls[callId].receiverAudioProducer.kind}`); - videoCalls[callId].receiverAudioProducer.on('transportclose', () => { - const callId = socketDetails[socket.id]; - console.log('transport for this producer closed', callId) + console.log('transport for this producer closed', callId); closeCall(callId); }); // Send back to the client the Producer's id - callback && callback({ - id: videoCalls[callId].receiverAudioProducer.id - }); + callback && + callback({ + id: videoCalls[callId].receiverAudioProducer.id, + }); } else { videoCalls[callId].initiatorAudioProducer = await videoCalls[callId].initiatorProducerTransport.produce({ kind, rtpParameters, }); - console.log(`[transport-produce] initiatorAudioProducer Producer ID: ${videoCalls[callId].initiatorAudioProducer.id} | kind: ${videoCalls[callId].initiatorAudioProducer.kind}`); - videoCalls[callId].initiatorAudioProducer.on('transportclose', () => { - const callId = socketDetails[socket.id]; - console.log('transport for this producer closed', callId) + console.log('transport for this producer closed', callId); closeCall(callId); }); // Send back to the client the Producer's id - callback && callback({ - id: videoCalls[callId].initiatorAudioProducer.id - }); + callback && + callback({ + id: videoCalls[callId].initiatorAudioProducer.id, + }); } } + + const socketToEmit = isInitiator(callId, socket.id) + ? videoCalls[callId].receiverSocket + : videoCalls[callId].initiatorSocket; + + // callId - Id of the call + // kind - producer type: audio/video + socketToEmit?.emit('new-producer', { callId, kind }); } catch (error) { - console.log(`ERROR | transport-produce | callId ${socketDetails[socket.id]} | ${error.message}`); + console.error(`[transport-produce] | ERROR | callId: ${socketDetails[socket.id]} | error: ${error.message}`); } }); @@ -369,16 +366,17 @@ peers.on('connection', async socket => { try { const callId = socketDetails[socket.id]; console.log(`[transport-recv-connect] socket ${socket.id} | callId ${callId}`); + if (typeof dtlsParameters === 'string') dtlsParameters = JSON.parse(dtlsParameters); // await videoCalls[callId].consumerTransport.connect({ dtlsParameters }); - if(!isInitiator(callId, socket.id)) { + if (!isInitiator(callId, socket.id)) { await videoCalls[callId].receiverConsumerTransport.connect({ dtlsParameters }); - } else if(isInitiator(callId, socket.id)) { + } else if (isInitiator(callId, socket.id)) { await videoCalls[callId].initiatorConsumerTransport.connect({ dtlsParameters }); } } catch (error) { - console.log(`ERROR | transport-recv-connect | callId ${socketDetails[socket.id]} | ${error.message}`); + console.error(`[transport-recv-connect] | ERROR | callId: ${socketDetails[socket.id]} | error: ${error.message}`); } - }) + }); /* - The customer consumes after successfully connecting to consumerTransport @@ -388,197 +386,156 @@ peers.on('connection', async socket => { - The consumer does consumerTransport.consume(params) */ socket.on('consume', async ({ rtpCapabilities }, callback) => { - try { - const callId = socketDetails[socket.id]; - console.log(`[consume] socket ${socket.id} | callId ${callId} | rtpCapabilities: ${JSON.stringify(rtpCapabilities)}`); + const callId = socketDetails[socket.id]; + const socketId = socket.id; - console.log('[consume] callId', callId); - let canConsumeVideo, canConsumeAudio; - if (isInitiator(callId, socket.id)) { - canConsumeVideo = !!videoCalls[callId].receiverVideoProducer && !!videoCalls[callId].router.canConsume({ - producerId: videoCalls[callId].receiverVideoProducer.id, - rtpCapabilities - }); - canConsumeAudio = !!videoCalls[callId].receiverAudioProducer && !!videoCalls[callId].router.canConsume({ - producerId: videoCalls[callId].receiverAudioProducer.id, - rtpCapabilities - }); + console.log(`[consume] socket ${socketId} | callId: ${callId}`); - } else { - canConsumeVideo = !!videoCalls[callId].initiatorVideoProducer && !!videoCalls[callId].router.canConsume({ - producerId: videoCalls[callId].initiatorVideoProducer.id, - rtpCapabilities - }); + if (typeof rtpCapabilities === 'string') rtpCapabilities = JSON.parse(rtpCapabilities); - canConsumeAudio = !!videoCalls[callId].initiatorAudioProducer && !!videoCalls[callId].router.canConsume({ - producerId: videoCalls[callId].initiatorAudioProducer.id, - rtpCapabilities - }); - } - console.log('[consume] canConsumeVideo', canConsumeVideo); - console.log('[consume] canConsumeAudio', canConsumeAudio); - - if (canConsumeVideo && !canConsumeAudio) { - const videoParams = await consumeVideo(callId, socket.id, rtpCapabilities) - callback({ videoParams, audioParams: null }); - } else if (canConsumeVideo && canConsumeAudio) { - const videoParams = await consumeVideo(callId, socket.id, rtpCapabilities) - const audioParams = await consumeAudio(callId, socket.id, rtpCapabilities) - callback({ videoParams, audioParams }); - } else if (!canConsumeVideo && canConsumeAudio) { - const audioParams = await consumeAudio(callId, socket.id, rtpCapabilities) - const data = { videoParams: null, audioParams }; - callback(data); - } else { - console.log(`[consume] Can't consume | callId ${callId}`); - callback(null); - } - } catch (error) { - console.log(`ERROR | consume | callId ${socketDetails[socket.id]} | ${error.message}`) - callback({ params: { error } }); - } + callback({ + videoParams: await consumeVideo({ callId, socketId, rtpCapabilities }), + audioParams: await consumeAudio({ callId, socketId, rtpCapabilities }), + }); }); /* - Event sent by the consumer after consuming to resume the pause - - When consuming on consumerTransport, it is initially done with paused: true, here we will resume + - When consuming on consumerTransport, it is initially done with paused: true, here we will resume + - For the initiator we resume the initiatorConsumerAUDIO/VIDEO and for receiver the receiverConsumerAUDIO/VIDEO */ - socket.on('consumer-resume', async () => { + socket.on('consumer-resume', () => { try { const callId = socketDetails[socket.id]; - console.log(`[consumer-resume] callId ${callId}`) + const isInitiatorValue = isInitiator(callId, socket.id); + console.log(`[consumer-resume] callId: ${callId} | isInitiator: ${isInitiatorValue}`); + const consumerVideo = isInitiatorValue + ? videoCalls[callId].initiatorConsumerVideo + : videoCalls[callId].receiverConsumerVideo; + + const consumerAudio = isInitiatorValue + ? videoCalls[callId].initiatorConsumerAudio + : videoCalls[callId].receiverConsumerAudio; + + consumerVideo?.resume(); + consumerAudio?.resume(); + } catch (error) { + console.error( + `[consumer-resume] | ERROR | callId: ${socketDetails[socket.id]} | isInitiator: ${isInitiator} | error: ${ + error.message + }` + ); + } + }); + + socket.on('close-producer', ({ callId, kind }) => { + try { if (isInitiator(callId, socket.id)) { - console.log(`[consumer-resume] isInitiator true`); - await videoCalls[callId].initiatorConsumerVideo.resume(); - await videoCalls[callId].initiatorConsumerAudio.resume(); + console.log(`[close-producer] initiator --EMIT--> receiver | callId: ${callId} | kind: ${kind}`); + videoCalls[callId].receiverSocket.emit('close-producer', { callId, kind }); } else { - console.log(`[consumer-resume] isInitiator false`); - (videoCalls[callId].receiverConsumerVideo) && await videoCalls[callId].receiverConsumerVideo.resume(); - (videoCalls[callId].receiverConsumerVideo) && await videoCalls[callId].receiverConsumerAudio.resume(); + console.log(`[close-producer] receiver --EMIT--> initiator | callId: ${callId} | kind: ${kind}`); + videoCalls[callId].initiatorSocket.emit('close-producer', { callId, kind }); } } catch (error) { - console.log(`ERROR | consumer-resume | callId ${socketDetails[socket.id]} | ${error.message}`); + console.error(`[close-producer] | ERROR | callId: ${socketDetails[socket.id]} | error: ${error.message}`); } }); }); -const consumeVideo = async (callId, socketId, rtpCapabilities) => { +const canConsume = ({ callId, producerId, rtpCapabilities }) => { + return !!videoCalls[callId].router.canConsume({ + producerId, + rtpCapabilities, + }); +}; + +const consumeVideo = async ({ callId, socketId, rtpCapabilities }) => { + // Handlers for consumer transport https://mediasoup.org/documentation/v3/mediasoup/api/#consumer-on-transportclose + if (isInitiator(callId, socketId) && videoCalls[callId].receiverVideoProducer) { + const producerId = videoCalls[callId].receiverVideoProducer.id; + if (!canConsume({ callId, producerId, rtpCapabilities })) return null; - if(isInitiator(callId, socketId)) { videoCalls[callId].initiatorConsumerVideo = await videoCalls[callId].initiatorConsumerTransport.consume({ - producerId: videoCalls[callId].receiverVideoProducer.id, + producerId, rtpCapabilities, paused: true, }); - // https://mediasoup.org/documentation/v3/mediasoup/api/#consumer-on-transportclose - videoCalls[callId].initiatorConsumerVideo.on('transportclose', () => { - const callId = socketDetails[socket.id]; - console.log('transport close from consumer', callId); - closeCall(callId); - }); - - // https://mediasoup.org/documentation/v3/mediasoup/api/#consumer-on-producerclose - videoCalls[callId].initiatorConsumerVideo.on('producerclose', () => { - const callId = socketDetails[socket.id]; - console.log('producer of consumer closed', callId); - closeCall(callId); - }); - return { id: videoCalls[callId].initiatorConsumerVideo.id, - producerId: videoCalls[callId].receiverVideoProducer.id, + producerId, kind: 'video', rtpParameters: videoCalls[callId].initiatorConsumerVideo.rtpParameters, - } - } else { + }; + } else if (videoCalls[callId].initiatorVideoProducer) { + const producerId = videoCalls[callId].initiatorVideoProducer.id; + if (!canConsume({ callId, producerId, rtpCapabilities })) return null; + videoCalls[callId].receiverConsumerVideo = await videoCalls[callId].receiverConsumerTransport.consume({ - producerId: videoCalls[callId].initiatorVideoProducer.id, + producerId, rtpCapabilities, paused: true, }); - videoCalls[callId].receiverConsumerVideo.on('transportclose', () => { - const callId = socketDetails[socket.id]; - console.log('transport close from consumer', callId); - closeCall(callId); - }); - - videoCalls[callId].receiverConsumerVideo.on('producerclose', () => { - const callId = socketDetails[socket.id]; - console.log('producer of consumer closed', callId); - closeCall(callId); - }); - return { id: videoCalls[callId].receiverConsumerVideo.id, - producerId: videoCalls[callId].initiatorVideoProducer.id, + producerId, kind: 'video', rtpParameters: videoCalls[callId].receiverConsumerVideo.rtpParameters, - } - } -} - -const consumeAudio = async (callId, socketId, rtpCapabilities) => { - if(isInitiator(callId, socketId)) { - videoCalls[callId].initiatorConsumerAudio = await videoCalls[callId].initiatorConsumerTransport.consume({ - producerId: videoCalls[callId].receiverAudioProducer.id, - rtpCapabilities, - paused: true, - }); - - // https://mediasoup.org/documentation/v3/mediasoup/api/#consumer-on-transportclose - videoCalls[callId].initiatorConsumerAudio.on('transportclose', () => { - const callId = socketDetails[socket.id]; - console.log('transport close from consumer', callId); - closeCall(callId); - }); - - // https://mediasoup.org/documentation/v3/mediasoup/api/#consumer-on-producerclose - videoCalls[callId].initiatorConsumerAudio.on('producerclose', () => { - const callId = socketDetails[socket.id]; - console.log('producer of consumer closed', callId); - closeCall(callId); - }); - - return { - id: videoCalls[callId].initiatorConsumerAudio.id, - producerId: videoCalls[callId].receiverAudioProducer.id, - kind: 'audio', - rtpParameters: videoCalls[callId].initiatorConsumerAudio.rtpParameters, - } + }; } else { - videoCalls[callId].receiverConsumerAudio = await videoCalls[callId].receiverConsumerTransport.consume({ - producerId: videoCalls[callId].initiatorAudioProducer.id, - rtpCapabilities, - paused: true, - }); - - videoCalls[callId].receiverConsumerAudio.on('transportclose', () => { - const callId = socketDetails[socket.id]; - console.log('transport close from consumer', callId); - closeCall(callId); - }); - - videoCalls[callId].receiverConsumerAudio.on('producerclose', () => { - const callId = socketDetails[socket.id]; - console.log('producer of consumer closed', callId); - closeCall(callId); - }); - - return { - id: videoCalls[callId].receiverConsumerAudio.id, - producerId: videoCalls[callId].initiatorAudioProducer.id, - kind: 'audio', - rtpParameters: videoCalls[callId].receiverConsumerAudio.rtpParameters, - } + return null; } -} +}; + +const consumeAudio = async ({ callId, socketId, rtpCapabilities }) => { + try { + // Handlers for consumer transport https://mediasoup.org/documentation/v3/mediasoup/api/#consumer-on-transportclose + if (isInitiator(callId, socketId) && videoCalls[callId].receiverAudioProducer) { + const producerId = videoCalls[callId].receiverAudioProducer.id; + if (!canConsume({ callId, producerId, rtpCapabilities })) return null; + + videoCalls[callId].initiatorConsumerAudio = await videoCalls[callId].initiatorConsumerTransport.consume({ + producerId, + rtpCapabilities, + paused: true, + }); + + return { + id: videoCalls[callId].initiatorConsumerAudio.id, + producerId, + kind: 'audio', + rtpParameters: videoCalls[callId].initiatorConsumerAudio.rtpParameters, + }; + } else if (videoCalls[callId].initiatorAudioProducer) { + const producerId = videoCalls[callId].initiatorAudioProducer.id; + if (!canConsume({ callId, producerId, rtpCapabilities })) return null; + + videoCalls[callId].receiverConsumerAudio = await videoCalls[callId].receiverConsumerTransport.consume({ + producerId, + rtpCapabilities, + paused: true, + }); + + return { + id: videoCalls[callId].receiverConsumerAudio.id, + producerId, + kind: 'audio', + rtpParameters: videoCalls[callId].receiverConsumerAudio.rtpParameters, + }; + } else { + return null; + } + } catch (error) { + console.error(`[consumeAudio] | ERROR | error: ${error}`); + } +}; const isInitiator = (callId, socketId) => { - return (videoCalls[callId].initiatorSockerId === socketId); -} + return videoCalls[callId]?.initiatorSocket?.id === socketId; +}; /* - Called from at event 'createWebRtcTransport' and assigned to the consumer or producer transport @@ -589,26 +546,25 @@ const isInitiator = (callId, socketId) => { */ const createWebRtcTransportLayer = async (callId, callback) => { try { - console.log('[createWebRtcTransportLayer] callId', callId); + console.log(`[createWebRtcTransportLayer] callId: ${callId}`); // 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). - } + }, ], enableUdp: true, enableTcp: true, preferUdp: true, }; - + // 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}`) + let transport = await videoCalls[callId].router.createWebRtcTransport(webRtcTransport_options); // Handler for when DTLS(Datagram Transport Layer Security) changes - transport.on('dtlsstatechange', dtlsState => { + transport.on('dtlsstatechange', (dtlsState) => { console.log(`transport | dtlsstatechange | calldId ${callId} | dtlsState ${dtlsState}`); if (dtlsState === 'closed') { transport.close(); @@ -627,15 +583,15 @@ const createWebRtcTransportLayer = async (callId, callback) => { dtlsParameters: transport.dtlsParameters, }; - console.log('[createWebRtcTransportLayer] callback params', params); // Send back to the client the params callback({ params }); // Set transport to producerTransport or consumerTransport return transport; - } catch (error) { - console.log(`ERROR | createWebRtcTransportLayer | callId ${socketDetails[socket.id]} | ${error.message}`); + console.error( + `[createWebRtcTransportLayer] | ERROR | callId: ${socketDetails[socket.id]} | error: ${error.message}` + ); callback({ params: { error } }); } -} \ No newline at end of file +}; diff --git a/build.sh b/build.sh index 5ee5695..21971c9 100755 --- a/build.sh +++ b/build.sh @@ -9,14 +9,21 @@ else ## CLEANUP rm -fr dist/* fi + +if [ -d "node_modules" ]; then + rm -fr node_modules +fi + # Install dependencies #npm install ## PROJECT NEEDS echo "Building app... from $(git rev-parse --abbrev-ref HEAD)" #npm run-script build -cp -r {.env,app.js,package.json,server,public} dist/ - +cp -r {.env,app.js,package.json,server,public,doc,Dockerfile} dist/ +#cp -r ./* dist/ +dateString=$(date +"%Y%m%d-%H%M%S") +git log --pretty=format:"%ad%x09%an%x09%s" --no-merges -20 > "dist/git--$dateString.log" #Add version control for pm2 cd dist #Add version control for pm2 @@ -43,4 +50,4 @@ fi ## POST BUILD -cd - \ No newline at end of file +cd - diff --git a/doc/[video] Call waiting.png b/doc/[video] Call waiting.png new file mode 100644 index 0000000..508159b Binary files /dev/null and b/doc/[video] Call waiting.png differ diff --git a/doc/[video] Client - Mediasoup connect & produce.png b/doc/[video] Client - Mediasoup connect & produce.png new file mode 100644 index 0000000..6057e2d Binary files /dev/null and b/doc/[video] Client - Mediasoup connect & produce.png differ diff --git a/doc/[video] Client Android-iOS closed.png b/doc/[video] Client Android-iOS closed.png new file mode 100644 index 0000000..43006b0 Binary files /dev/null and b/doc/[video] Client Android-iOS closed.png differ diff --git a/doc/[video] Client-Client Workflow.png b/doc/[video] Client-Client Workflow.png new file mode 100644 index 0000000..8ab7e65 Binary files /dev/null and b/doc/[video] Client-Client Workflow.png differ diff --git a/doc/[video] Dispatcher closed.png b/doc/[video] Dispatcher closed.png new file mode 100644 index 0000000..1d26363 Binary files /dev/null and b/doc/[video] Dispatcher closed.png differ diff --git a/doc/[video] HUB - Dispatcher close call before accept_reject.png b/doc/[video] HUB - Dispatcher close call before accept_reject.png new file mode 100644 index 0000000..42a5524 Binary files /dev/null and b/doc/[video] HUB - Dispatcher close call before accept_reject.png differ diff --git a/doc/[video] HUB - Dispatcher close call.png b/doc/[video] HUB - Dispatcher close call.png new file mode 100644 index 0000000..e429fb2 Binary files /dev/null and b/doc/[video] HUB - Dispatcher close call.png differ diff --git a/doc/[video] HUB - Dispatcher dieconnect.png b/doc/[video] HUB - Dispatcher dieconnect.png new file mode 100644 index 0000000..d5d601d Binary files /dev/null and b/doc/[video] HUB - Dispatcher dieconnect.png differ diff --git a/doc/[video] Video Window closed.png b/doc/[video] Video Window closed.png new file mode 100644 index 0000000..affdbe6 Binary files /dev/null and b/doc/[video] Video Window closed.png differ diff --git a/public/bundle.js b/public/bundle.js index e9b17f7..a2b43cb 100644 --- a/public/bundle.js +++ b/public/bundle.js @@ -20353,7 +20353,7 @@ module.exports = yeast; },{}],94:[function(require,module,exports){ module.exports = { hubAddress: 'https://hub.dev.linx.safemobile.com/', - mediasoupAddress: 'https://testing.video.safemobile.org', + mediasoupAddress: 'https://testing.video.safemobile.org/', } },{}],95:[function(require,module,exports){ const io = require('socket.io-client') @@ -20449,10 +20449,23 @@ setTimeout(() => { console.log(`[MEDIA] ${config.mediasoupAddress} | connected: ${socket.connected} | existsProducer: ${existsProducer}`) if (!IS_PRODUCER && existsProducer && consumer === undefined) { goConnect() - // document.getElementById('btnRecvSendTransport').click(); } if (IS_PRODUCER && urlParams.get('testing') === 'true') { getLocalStream() } }) + + socket.on('new-producer', ({ callId, kind }) => { + console.log(`🟢 new-producer | callId: ${callId} | kind: ${kind} | Ready to consume`); + connectRecvTransport(); + }) + + socket.on('close-producer', ({ callId, kind }) => { + console.log(`🔴 close-producer | callId: ${callId} | kind: ${kind}`); + if (kind === 'video') { + consumerVideo.close() + remoteVideo.srcObject = null + } + else if (kind === 'audio') consumerAudio.close() + }) } if (IS_PRODUCER === true) { @@ -20731,6 +20744,8 @@ const connectSendTransport = async () => { // Enable Close call button const closeCallBtn = document.getElementById('btnCloseCall'); closeCallBtn.removeAttribute('disabled'); + + createRecvTransport(); } const createRecvTransport = async () => { @@ -20770,7 +20785,8 @@ const createRecvTransport = async () => { errback(error) } }) - connectRecvTransport() + // We call it in new-rpoducer, we don't need it here anymore + // connectRecvTransport() }) } @@ -20826,7 +20842,7 @@ const connectRecvTransport = async () => { console.log('remoteVideo PLAY') }) .catch((error) => { - displayError(`remoteVideo PLAY ERROR | ${error.message}`) + console.error(`remoteVideo PLAY ERROR | ${error.message}`) }) }) } @@ -20839,10 +20855,6 @@ const getVideoTrask = async (videoParams) => { rtpParameters: videoParams.rtpParameters }) - consumerVideo.on('transportclose', () => { - console.log('transport closed so consumer closed') - }) - return consumerVideo.track } @@ -20903,31 +20915,31 @@ const closeCall = () => { resetCallSettings() } -const consume = async () => { - console.log('[consume]') - console.log('createRecvTransport Consumer') - await socket.emit('createWebRtcTransport', { sender: false, callId, dispatcher: true }, ({ params }) => { - if (params.error) { - console.log('createRecvTransport | createWebRtcTransport | Error', params.error) - return - } - consumerTransport = device.createRecvTransport(params) - consumerTransport.on('connect', async ({ dtlsParameters }, callback, errback) => { - try { - await socket.emit('transport-recv-connect', { - dtlsParameters, - }) - callback() - } catch (error) { - errback(error) - } - }) +// const consume = async (kind) => { +// console.log(`[consume] kind: ${kind}`) +// console.log('createRecvTransport Consumer') +// await socket.emit('createWebRtcTransport', { sender: false, callId, dispatcher: true }, ({ params }) => { +// if (params.error) { +// console.log('createRecvTransport | createWebRtcTransport | Error', params.error) +// return +// } +// consumerTransport = device.createRecvTransport(params) +// consumerTransport.on('connect', async ({ dtlsParameters }, callback, errback) => { +// try { +// await socket.emit('transport-recv-connect', { +// dtlsParameters, +// }) +// callback() +// } catch (error) { +// errback(error) +// } +// }) - connectRecvTransport() - }) -} +// connectRecvTransport() +// }) +// } btnLocalVideo.addEventListener('click', getLocalStream) -btnRecvSendTransport.addEventListener('click', consume) +// btnRecvSendTransport.addEventListener('click', consume) btnCloseCall.addEventListener('click', closeCall) },{"./config":94,"mediasoup-client":66,"socket.io-client":82}]},{},[95]); diff --git a/public/config.js b/public/config.js index f631fc8..233f24c 100644 --- a/public/config.js +++ b/public/config.js @@ -1,4 +1,4 @@ module.exports = { hubAddress: 'https://hub.dev.linx.safemobile.com/', - mediasoupAddress: 'https://testing.video.safemobile.org', + mediasoupAddress: 'https://testing.video.safemobile.org/', } \ No newline at end of file diff --git a/public/index.html b/public/index.html index a44cd99..d8ce60e 100644 --- a/public/index.html +++ b/public/index.html @@ -75,7 +75,7 @@
- +
diff --git a/public/index.js b/public/index.js index 2d2faac..06625c0 100644 --- a/public/index.js +++ b/public/index.js @@ -91,10 +91,23 @@ setTimeout(() => { console.log(`[MEDIA] ${config.mediasoupAddress} | connected: ${socket.connected} | existsProducer: ${existsProducer}`) if (!IS_PRODUCER && existsProducer && consumer === undefined) { goConnect() - // document.getElementById('btnRecvSendTransport').click(); } if (IS_PRODUCER && urlParams.get('testing') === 'true') { getLocalStream() } }) + + socket.on('new-producer', ({ callId, kind }) => { + console.log(`🟢 new-producer | callId: ${callId} | kind: ${kind} | Ready to consume`); + connectRecvTransport(); + }) + + socket.on('close-producer', ({ callId, kind }) => { + console.log(`🔴 close-producer | callId: ${callId} | kind: ${kind}`); + if (kind === 'video') { + consumerVideo.close() + remoteVideo.srcObject = null + } + else if (kind === 'audio') consumerAudio.close() + }) } if (IS_PRODUCER === true) { @@ -373,6 +386,8 @@ const connectSendTransport = async () => { // Enable Close call button const closeCallBtn = document.getElementById('btnCloseCall'); closeCallBtn.removeAttribute('disabled'); + + createRecvTransport(); } const createRecvTransport = async () => { @@ -412,7 +427,8 @@ const createRecvTransport = async () => { errback(error) } }) - connectRecvTransport() + // We call it in new-rpoducer, we don't need it here anymore + // connectRecvTransport() }) } @@ -468,7 +484,7 @@ const connectRecvTransport = async () => { console.log('remoteVideo PLAY') }) .catch((error) => { - displayError(`remoteVideo PLAY ERROR | ${error.message}`) + console.error(`remoteVideo PLAY ERROR | ${error.message}`) }) }) } @@ -481,10 +497,6 @@ const getVideoTrask = async (videoParams) => { rtpParameters: videoParams.rtpParameters }) - consumerVideo.on('transportclose', () => { - console.log('transport closed so consumer closed') - }) - return consumerVideo.track } @@ -545,30 +557,30 @@ const closeCall = () => { resetCallSettings() } -const consume = async () => { - console.log('[consume]') - console.log('createRecvTransport Consumer') - await socket.emit('createWebRtcTransport', { sender: false, callId, dispatcher: true }, ({ params }) => { - if (params.error) { - console.log('createRecvTransport | createWebRtcTransport | Error', params.error) - return - } - consumerTransport = device.createRecvTransport(params) - consumerTransport.on('connect', async ({ dtlsParameters }, callback, errback) => { - try { - await socket.emit('transport-recv-connect', { - dtlsParameters, - }) - callback() - } catch (error) { - errback(error) - } - }) +// const consume = async (kind) => { +// console.log(`[consume] kind: ${kind}`) +// console.log('createRecvTransport Consumer') +// await socket.emit('createWebRtcTransport', { sender: false, callId, dispatcher: true }, ({ params }) => { +// if (params.error) { +// console.log('createRecvTransport | createWebRtcTransport | Error', params.error) +// return +// } +// consumerTransport = device.createRecvTransport(params) +// consumerTransport.on('connect', async ({ dtlsParameters }, callback, errback) => { +// try { +// await socket.emit('transport-recv-connect', { +// dtlsParameters, +// }) +// callback() +// } catch (error) { +// errback(error) +// } +// }) - connectRecvTransport() - }) -} +// connectRecvTransport() +// }) +// } btnLocalVideo.addEventListener('click', getLocalStream) -btnRecvSendTransport.addEventListener('click', consume) +// btnRecvSendTransport.addEventListener('click', consume) btnCloseCall.addEventListener('click', closeCall) \ No newline at end of file