Merge branch 'develop' into docker

This commit is contained in:
bmamihai 2023-01-05 01:14:56 +02:00
commit 1c353d7c88
5 changed files with 605 additions and 273 deletions

320
app.js
View File

@ -13,50 +13,47 @@ try {
} }
const mediasoup = require('mediasoup'); const mediasoup = require('mediasoup');
let worker let worker;
/** /**
* videoCalls
* |-> Router
* |-> Producer
* |-> Consumer
* |-> Producer Transport
* |-> Consumer Transport
* *
* videoCalls - Dictionary of Object(s)
* '<callId>': { * '<callId>': {
* router: Router, * router: Router,
* producer: Producer, * initiatorAudioProducer: Producer,
* producerTransport: Producer Transport, * initiatorVideoProducer: Producer,
* consumer: Consumer, * receiverVideoProducer: Producer,
* consumerTransport: Consumer Transport * receiverAudioProducer: Producer,
* initiatorProducerTransport: Producer Transport,
* receiverProducerTransport: Producer Transport,
* initiatorConsumerVideo: Consumer,
* initiatorConsumerAudio: Consumer,
* initiatorConsumerTransport: Consumer Transport
* initiatorSockerId
* receiverSocketId
* } * }
* *
**/ **/
let videoCalls = {} let videoCalls = {};
let socketDetails = {} let socketDetails = {};
app.get('/', (_req, res) => { 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'))) app.use('/sfu', express.static(path.join(__dirname, 'public')));
// SSL cert for HTTPS access // SSL cert for HTTPS access
const options = { const options = {
key: fs.readFileSync(process.env.SERVER_KEY, 'utf-8'), key: fs.readFileSync(process.env.SERVER_KEY, 'utf-8'),
cert: fs.readFileSync(process.env.SERVER_CERT, 'utf-8'), cert: fs.readFileSync(process.env.SERVER_CERT, 'utf-8'),
} };
const httpsServer = https.createServer(options, app); const httpsServer = https.createServer(options, app);
const io = new Server(httpsServer, { const io = new Server(httpsServer, {
allowEIO3: true, allowEIO3: true,
origins: ["*:*"], origins: ["*:*"]
// allowRequest: (req, next) => {
// console.log('req', req);
// next(null, true)
// }
}); });
// const io = new Server(server, { origins: '*:*', allowEIO3: true });
httpsServer.listen(process.env.PORT, () => { httpsServer.listen(process.env.PORT, () => {
console.log('Video server listening on port:', process.env.PORT); console.log('Video server listening on port:', process.env.PORT);
@ -141,32 +138,18 @@ const mediaCodecs = [
'x-google-start-bitrate' : 1000 'x-google-start-bitrate' : 1000
} }
} }
// {
// 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) => { const closeCall = (callId) => {
try { try {
if (callId && videoCalls[callId]) { if (callId && videoCalls[callId]) {
videoCalls[callId].producerVideo?.close(); videoCalls[callId].receiverVideoProducer?.close();
videoCalls[callId].producerAudio?.close(); videoCalls[callId].receiverAudioProducer?.close();
videoCalls[callId].consumerVideo?.close(); videoCalls[callId].initiatorConsumerVideo?.close();
videoCalls[callId].consumerAudio?.close(); videoCalls[callId].initiatorConsumerAudio?.close();
videoCalls[callId]?.consumerTransport?.close(); videoCalls[callId]?.initiatorConsumerTransport?.close();
videoCalls[callId]?.producerTransport?.close(); videoCalls[callId]?.receiverProducerTransport?.close();
videoCalls[callId]?.router?.close(); videoCalls[callId]?.router?.close();
delete videoCalls[callId]; delete videoCalls[callId];
} else { } else {
@ -212,9 +195,11 @@ peers.on('connection', async socket => {
console.log('[createRoom] callId', callId); console.log('[createRoom] callId', callId);
videoCalls[callId] = { router: await worker.createRouter({ mediaCodecs }) } videoCalls[callId] = { router: await worker.createRouter({ mediaCodecs }) }
console.log(`[createRoom] Router ID: ${videoCalls[callId].router.id}`); console.log(`[createRoom] Router ID: ${videoCalls[callId].router.id}`);
videoCalls[callId].receiverSocketId = socket.id
} else {
videoCalls[callId].initiatorSockerId = socket.id
} }
socketDetails[socket.id] = callId; socketDetails[socket.id] = callId;
// rtpCapabilities is set for callback // rtpCapabilities is set for callback
console.log('[getRtpCapabilities] callId', callId); console.log('[getRtpCapabilities] callId', callId);
callbackResponse = { callbackResponse = {
@ -232,7 +217,7 @@ peers.on('connection', async socket => {
/* /*
- Client emits a request to create server side Transport - Client emits a request to create server side Transport
- Depending on the sender, producerTransport or consumerTransport is created on that router - Depending on the sender, a producer or consumer is created is created on that router
- It will return parameters, these are required for the client to create the RecvTransport - It will return parameters, these are required for the client to create the RecvTransport
from the client. from the client.
- If the client is producer(sender: true) then it will use parameters for device.createSendTransport(params) - If the client is producer(sender: true) then it will use parameters for device.createSendTransport(params)
@ -241,20 +226,21 @@ peers.on('connection', async socket => {
socket.on('createWebRtcTransport', async ({ sender }, callback) => { socket.on('createWebRtcTransport', async ({ sender }, callback) => {
try { try {
const callId = socketDetails[socket.id]; const callId = socketDetails[socket.id];
console.log(`[createWebRtcTransport] sender ${sender} | callId ${callId}`); console.log(`[createWebRtcTransport] socket ${socket.id} | sender ${sender} | callId ${callId}`);
if (sender) { if (sender) {
if (!videoCalls[callId].producerTransport) { if(!videoCalls[callId].receiverProducerTransport && !isInitiator(callId, socket.id)) {
videoCalls[callId].producerTransport = await createWebRtcTransportLayer(callId, callback); videoCalls[callId].receiverProducerTransport = await createWebRtcTransportLayer(callId, callback);
} else if(!videoCalls[callId].initiatorProducerTransport && isInitiator(callId, socket.id)) {
videoCalls[callId].initiatorProducerTransport = await createWebRtcTransportLayer(callId, callback);
} else { } else {
console.log(`producerTransport has already been defined | callId ${callId}`); console.log(`producerTransport has already been defined | callId ${callId}`);
callback(null); callback(null);
} }
} else if (!sender) { } else if (!sender) {
if (!videoCalls[callId].consumerTransport) { if(!videoCalls[callId].receiverConsumerTransport && !isInitiator(callId, socket.id)) {
videoCalls[callId].consumerTransport = await createWebRtcTransportLayer(callId, callback); videoCalls[callId].receiverConsumerTransport = await createWebRtcTransportLayer(callId, callback);
} else { } else if(!videoCalls[callId].initiatorConsumerTransport && isInitiator(callId, socket.id)) {
console.log(`consumerTransport has already been defined | callId ${callId}`); videoCalls[callId].initiatorConsumerTransport = await createWebRtcTransportLayer(callId, callback);
callback(null);
} }
} }
} catch (error) { } catch (error) {
@ -272,16 +258,20 @@ peers.on('connection', async socket => {
const callId = socketDetails[socket.id]; const callId = socketDetails[socket.id];
if (typeof dtlsParameters === 'string') dtlsParameters = JSON.parse(dtlsParameters); if (typeof dtlsParameters === 'string') dtlsParameters = JSON.parse(dtlsParameters);
console.log(`[transport-connect] socket.id ${socket.id} | callId ${callId}`); console.log(`[transport-connect] socket ${socket.id} | callId ${callId}`);
await videoCalls[callId].producerTransport.connect({ dtlsParameters }); if (!isInitiator(callId, socket.id)) {
await videoCalls[callId].receiverProducerTransport.connect({ dtlsParameters });
} else {
await videoCalls[callId].initiatorProducerTransport.connect({ dtlsParameters });
}
} catch (error) { } catch (error) {
console.log(`ERROR | transport-connect | callId ${socketDetails[socket.id]} | ${error.message}`); console.log(`ERROR | transport-connect | callId ${socketDetails[socket.id]} | ${error.message}`);
} }
}); });
/* /*
- The event sent by the client (PRODUCER) after successfully connecting to producerTransport - The event sent by the client (PRODUCER) after successfully connecting to receiverProducerTransport/initiatorProducerTransport
- For the router with the id callId, we make produce on producerTransport - For the router with the id callId, we make produce on receiverProducerTransport/initiatorProducerTransport
- Create the handler on producer at the 'transportclose' event - Create the handler on producer at the 'transportclose' event
*/ */
socket.on('transport-produce', async ({ kind, rtpParameters, appData }, callback) => { socket.on('transport-produce', async ({ kind, rtpParameters, appData }, callback) => {
@ -289,20 +279,17 @@ peers.on('connection', async socket => {
const callId = socketDetails[socket.id]; const callId = socketDetails[socket.id];
if (typeof rtpParameters === 'string') rtpParameters = JSON.parse(rtpParameters); if (typeof rtpParameters === 'string') rtpParameters = JSON.parse(rtpParameters);
console.log(`[transport-produce] kind: ${kind} | socket.id: ${socket.id} | callId: ${callId}`); console.log(`[transport-produce] kind: ${kind} | socket: ${socket.id} | callId: ${callId}`);
console.log('kind', kind);
console.log('rtpParameters', rtpParameters);
if (kind === 'video') { if (kind === 'video') {
videoCalls[callId].producerVideo = await videoCalls[callId].producerTransport.produce({ if (!isInitiator(callId, socket.id)) {
videoCalls[callId].receiverVideoProducer = await videoCalls[callId].receiverProducerTransport.produce({
kind, kind,
rtpParameters, rtpParameters,
}); });
console.log(`[transport-produce] receiverVideoProducer Producer ID: ${videoCalls[callId].receiverVideoProducer.id} | kind: ${videoCalls[callId].receiverVideoProducer.kind}`);
console.log(`[transport-produce] Producer ID: ${videoCalls[callId].producerVideo.id} | kind: ${videoCalls[callId].producerVideo.kind}`); videoCalls[callId].receiverVideoProducer.on('transportclose', () => {
videoCalls[callId].producerVideo.on('transportclose', () => {
const callId = socketDetails[socket.id]; const callId = socketDetails[socket.id];
console.log('transport for this producer closed', callId) console.log('transport for this producer closed', callId)
closeCall(callId); closeCall(callId);
@ -310,17 +297,36 @@ peers.on('connection', async socket => {
// Send back to the client the Producer's id // Send back to the client the Producer's id
callback && callback({ callback && callback({
id: videoCalls[callId].producerVideo.id 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)
closeCall(callId);
});
callback && callback({
id: videoCalls[callId].initiatorVideoProducer.id
});
}
} else if (kind === 'audio') { } else if (kind === 'audio') {
videoCalls[callId].producerAudio = await videoCalls[callId].producerTransport.produce({ if (!isInitiator(callId, socket.id)) {
videoCalls[callId].receiverAudioProducer = await videoCalls[callId].receiverProducerTransport.produce({
kind, kind,
rtpParameters, rtpParameters,
}); });
console.log(`[transport-produce] Producer ID: ${videoCalls[callId].producerAudio.id} | kind: ${videoCalls[callId].producerAudio.kind}`); console.log(`[transport-produce] receiverAudioProducer Producer ID: ${videoCalls[callId].receiverAudioProducer.id} | kind: ${videoCalls[callId].receiverAudioProducer.kind}`);
videoCalls[callId].producerAudio.on('transportclose', () => { videoCalls[callId].receiverAudioProducer.on('transportclose', () => {
const callId = socketDetails[socket.id]; const callId = socketDetails[socket.id];
console.log('transport for this producer closed', callId) console.log('transport for this producer closed', callId)
closeCall(callId); closeCall(callId);
@ -328,8 +334,27 @@ peers.on('connection', async socket => {
// Send back to the client the Producer's id // Send back to the client the Producer's id
callback && callback({ callback && callback({
id: videoCalls[callId].producerAudio.id 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)
closeCall(callId);
});
// Send back to the client the Producer's id
callback && callback({
id: videoCalls[callId].initiatorAudioProducer.id
});
}
} }
} catch (error) { } catch (error) {
console.log(`ERROR | transport-produce | callId ${socketDetails[socket.id]} | ${error.message}`); console.log(`ERROR | transport-produce | callId ${socketDetails[socket.id]} | ${error.message}`);
@ -343,8 +368,13 @@ peers.on('connection', async socket => {
socket.on('transport-recv-connect', async ({ dtlsParameters }) => { socket.on('transport-recv-connect', async ({ dtlsParameters }) => {
try { try {
const callId = socketDetails[socket.id]; const callId = socketDetails[socket.id];
console.log(`[transport-recv-connect] socket.id ${socket.id} | callId ${callId}`); console.log(`[transport-recv-connect] socket ${socket.id} | callId ${callId}`);
await videoCalls[callId].consumerTransport.connect({ dtlsParameters }); // await videoCalls[callId].consumerTransport.connect({ dtlsParameters });
if(!isInitiator(callId, socket.id)) {
await videoCalls[callId].receiverConsumerTransport.connect({ dtlsParameters });
} else if(isInitiator(callId, socket.id)) {
await videoCalls[callId].initiatorConsumerTransport.connect({ dtlsParameters });
}
} catch (error) { } catch (error) {
console.log(`ERROR | transport-recv-connect | callId ${socketDetails[socket.id]} | ${error.message}`); console.log(`ERROR | transport-recv-connect | callId ${socketDetails[socket.id]} | ${error.message}`);
} }
@ -359,34 +389,46 @@ peers.on('connection', async socket => {
*/ */
socket.on('consume', async ({ rtpCapabilities }, callback) => { socket.on('consume', async ({ rtpCapabilities }, callback) => {
try { try {
console.log(`[consume] rtpCapabilities: ${JSON.stringify(rtpCapabilities)}`);
const callId = socketDetails[socket.id]; const callId = socketDetails[socket.id];
console.log(`[consume] socket ${socket.id} | callId ${callId} | rtpCapabilities: ${JSON.stringify(rtpCapabilities)}`);
console.log('[consume] callId', callId); console.log('[consume] callId', callId);
let canConsumeVideo, canConsumeAudio;
const canConsumeVideo = !!videoCalls[callId].producerVideo && !!videoCalls[callId].router.canConsume({ if (isInitiator(callId, socket.id)) {
producerId: videoCalls[callId].producerVideo.id, canConsumeVideo = !!videoCalls[callId].receiverVideoProducer && !!videoCalls[callId].router.canConsume({
producerId: videoCalls[callId].receiverVideoProducer.id,
rtpCapabilities rtpCapabilities
}) });
canConsumeAudio = !!videoCalls[callId].receiverAudioProducer && !!videoCalls[callId].router.canConsume({
const canConsumeAudio = !!videoCalls[callId].producerAudio && !!videoCalls[callId].router.canConsume({ producerId: videoCalls[callId].receiverAudioProducer.id,
producerId: videoCalls[callId].producerAudio.id,
rtpCapabilities rtpCapabilities
}) });
} else {
canConsumeVideo = !!videoCalls[callId].initiatorVideoProducer && !!videoCalls[callId].router.canConsume({
producerId: videoCalls[callId].initiatorVideoProducer.id,
rtpCapabilities
});
canConsumeAudio = !!videoCalls[callId].initiatorAudioProducer && !!videoCalls[callId].router.canConsume({
producerId: videoCalls[callId].initiatorAudioProducer.id,
rtpCapabilities
});
}
console.log('[consume] canConsumeVideo', canConsumeVideo); console.log('[consume] canConsumeVideo', canConsumeVideo);
console.log('[consume] canConsumeAudio', canConsumeAudio); console.log('[consume] canConsumeAudio', canConsumeAudio);
if (canConsumeVideo && !canConsumeAudio) { if (canConsumeVideo && !canConsumeAudio) {
console.log('1'); const videoParams = await consumeVideo(callId, socket.id, rtpCapabilities)
const videoParams = await consumeVideo(callId, rtpCapabilities)
console.log('videoParams', videoParams);
callback({ videoParams, audioParams: null }); callback({ videoParams, audioParams: null });
} else if (canConsumeVideo && canConsumeAudio) { } else if (canConsumeVideo && canConsumeAudio) {
console.log('2'); const videoParams = await consumeVideo(callId, socket.id, rtpCapabilities)
const videoParams = await consumeVideo(callId, rtpCapabilities) const audioParams = await consumeAudio(callId, socket.id, rtpCapabilities)
const audioParams = await consumeAudio(callId, rtpCapabilities)
callback({ videoParams, audioParams }); callback({ videoParams, audioParams });
} else if (!canConsumeVideo && canConsumeAudio) {
const audioParams = await consumeAudio(callId, socket.id, rtpCapabilities)
const data = { videoParams: null, audioParams };
callback(data);
} else { } else {
console.log(`[consume] Can't consume | callId ${callId}`); console.log(`[consume] Can't consume | callId ${callId}`);
callback(null); callback(null);
@ -405,69 +447,137 @@ peers.on('connection', async socket => {
try { try {
const callId = socketDetails[socket.id]; const callId = socketDetails[socket.id];
console.log(`[consumer-resume] callId ${callId}`) console.log(`[consumer-resume] callId ${callId}`)
await videoCalls[callId].consumerVideo.resume();
await videoCalls[callId].consumerAudio.resume(); if (isInitiator(callId, socket.id)) {
console.log(`[consumer-resume] isInitiator true`);
await videoCalls[callId].initiatorConsumerVideo.resume();
await videoCalls[callId].initiatorConsumerAudio.resume();
} else {
console.log(`[consumer-resume] isInitiator false`);
(videoCalls[callId].receiverConsumerVideo) && await videoCalls[callId].receiverConsumerVideo.resume();
(videoCalls[callId].receiverConsumerVideo) && await videoCalls[callId].receiverConsumerAudio.resume();
}
} catch (error) { } catch (error) {
console.log(`ERROR | consumer-resume | callId ${socketDetails[socket.id]} | ${error.message}`); console.log(`ERROR | consumer-resume | callId ${socketDetails[socket.id]} | ${error.message}`);
} }
}); });
}); });
const consumeVideo = async (callId, rtpCapabilities) => { const consumeVideo = async (callId, socketId, rtpCapabilities) => {
videoCalls[callId].consumerVideo = await videoCalls[callId].consumerTransport.consume({
producerId: videoCalls[callId].producerVideo.id, if(isInitiator(callId, socketId)) {
videoCalls[callId].initiatorConsumerVideo = await videoCalls[callId].initiatorConsumerTransport.consume({
producerId: videoCalls[callId].receiverVideoProducer.id,
rtpCapabilities, rtpCapabilities,
paused: true, paused: true,
}); });
// https://mediasoup.org/documentation/v3/mediasoup/api/#consumer-on-transportclose // https://mediasoup.org/documentation/v3/mediasoup/api/#consumer-on-transportclose
videoCalls[callId].consumerVideo.on('transportclose', () => { videoCalls[callId].initiatorConsumerVideo.on('transportclose', () => {
const callId = socketDetails[socket.id]; const callId = socketDetails[socket.id];
console.log('transport close from consumer', callId); console.log('transport close from consumer', callId);
closeCall(callId); closeCall(callId);
}); });
// https://mediasoup.org/documentation/v3/mediasoup/api/#consumer-on-producerclose // https://mediasoup.org/documentation/v3/mediasoup/api/#consumer-on-producerclose
videoCalls[callId].consumerVideo.on('producerclose', () => { videoCalls[callId].initiatorConsumerVideo.on('producerclose', () => {
const callId = socketDetails[socket.id]; const callId = socketDetails[socket.id];
console.log('producer of consumer closed', callId); console.log('producer of consumer closed', callId);
closeCall(callId); closeCall(callId);
}); });
return { return {
id: videoCalls[callId].consumerVideo.id, id: videoCalls[callId].initiatorConsumerVideo.id,
producerId: videoCalls[callId].producerVideo.id, producerId: videoCalls[callId].receiverVideoProducer.id,
kind: 'video', kind: 'video',
rtpParameters: videoCalls[callId].consumerVideo.rtpParameters, rtpParameters: videoCalls[callId].initiatorConsumerVideo.rtpParameters,
}
} else {
videoCalls[callId].receiverConsumerVideo = await videoCalls[callId].receiverConsumerTransport.consume({
producerId: videoCalls[callId].initiatorVideoProducer.id,
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,
kind: 'video',
rtpParameters: videoCalls[callId].receiverConsumerVideo.rtpParameters,
}
} }
} }
const consumeAudio = async (callId, rtpCapabilities) => { const consumeAudio = async (callId, socketId, rtpCapabilities) => {
videoCalls[callId].consumerAudio = await videoCalls[callId].consumerTransport.consume({ if(isInitiator(callId, socketId)) {
producerId: videoCalls[callId].producerAudio.id, videoCalls[callId].initiatorConsumerAudio = await videoCalls[callId].initiatorConsumerTransport.consume({
producerId: videoCalls[callId].receiverAudioProducer.id,
rtpCapabilities, rtpCapabilities,
paused: true, paused: true,
}); });
// https://mediasoup.org/documentation/v3/mediasoup/api/#consumer-on-transportclose // https://mediasoup.org/documentation/v3/mediasoup/api/#consumer-on-transportclose
videoCalls[callId].consumerAudio.on('transportclose', () => { videoCalls[callId].initiatorConsumerAudio.on('transportclose', () => {
const callId = socketDetails[socket.id]; const callId = socketDetails[socket.id];
console.log('transport close from consumer', callId); console.log('transport close from consumer', callId);
closeCall(callId); closeCall(callId);
}); });
// https://mediasoup.org/documentation/v3/mediasoup/api/#consumer-on-producerclose // https://mediasoup.org/documentation/v3/mediasoup/api/#consumer-on-producerclose
videoCalls[callId].consumerAudio.on('producerclose', () => { videoCalls[callId].initiatorConsumerAudio.on('producerclose', () => {
const callId = socketDetails[socket.id]; const callId = socketDetails[socket.id];
console.log('producer of consumer closed', callId); console.log('producer of consumer closed', callId);
closeCall(callId); closeCall(callId);
}); });
return { return {
id: videoCalls[callId].consumerAudio.id, id: videoCalls[callId].initiatorConsumerAudio.id,
producerId: videoCalls[callId].producerAudio.id, producerId: videoCalls[callId].receiverAudioProducer.id,
kind: 'audio', kind: 'audio',
rtpParameters: videoCalls[callId].consumerAudio.rtpParameters, 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,
}
}
}
const isInitiator = (callId, socketId) => {
return (videoCalls[callId].initiatorSockerId === socketId);
} }
/* /*

View File

@ -20353,7 +20353,7 @@ module.exports = yeast;
},{}],94:[function(require,module,exports){ },{}],94:[function(require,module,exports){
module.exports = { module.exports = {
hubAddress: 'https://hub.dev.linx.safemobile.com/', hubAddress: 'https://hub.dev.linx.safemobile.com/',
mediasoupAddress: 'https://video.safemobile.org', mediasoupAddress: 'https://testing.video.safemobile.org',
} }
},{}],95:[function(require,module,exports){ },{}],95:[function(require,module,exports){
const io = require('socket.io-client') const io = require('socket.io-client')
@ -20368,10 +20368,24 @@ const ASSET_NAME = urlParams.get('assetName') || null;
const ASSET_TYPE = urlParams.get('assetType') || null; const ASSET_TYPE = urlParams.get('assetType') || null;
let callId = parseInt(urlParams.get('callId')) || null; let callId = parseInt(urlParams.get('callId')) || null;
const IS_PRODUCER = urlParams.get('producer') === 'true' ? true : false const IS_PRODUCER = urlParams.get('producer') === 'true' ? true : false
let remoteVideo = document.getElementById('remoteVideo')
remoteVideo.defaultMuted = true
let produceAudio = false
console.log('[URL] ASSET_ID', ASSET_ID, '| ACCOUNT_ID', ACCOUNT_ID, '| callId', callId, ' | IS_PRODUCER', IS_PRODUCER) console.log('[URL] ASSET_ID', ASSET_ID, '| ACCOUNT_ID', ACCOUNT_ID, '| callId', callId, ' | IS_PRODUCER', IS_PRODUCER)
console.log('🟩 config', config) console.log('🟩 config', config)
produceAudioSelector = document.getElementById('produceAudio');
produceAudioSelector.addEventListener('change', e => {
if(e.target.checked) {
produceAudio = true
console.log('produce audio');
} else {
produceAudio = false
}
});
let socket, hub let socket, hub
let device let device
let rtpCapabilities let rtpCapabilities
@ -20381,6 +20395,21 @@ let producerVideo
let producerAudio let producerAudio
let consumer let consumer
let originAssetId let originAssetId
let consumerVideo // local consumer video(consumer not transport)
let consumerAudio // local consumer audio(consumer not transport)
const remoteSoundControl = document.getElementById('remoteSoundControl');
remoteSoundControl.addEventListener('click', function handleClick() {
console.log('remoteSoundControl.textContent', remoteSoundControl.textContent);
if (remoteSoundControl.textContent === 'Unmute') {
remoteVideo.muted = false
remoteSoundControl.textContent = 'Mute';
} else {
remoteVideo.muted = true
remoteSoundControl.textContent = 'Unmute';
}
});
// https://mediasoup.org/documentation/v3/mediasoup-client/api/#ProducerOptions // https://mediasoup.org/documentation/v3/mediasoup-client/api/#ProducerOptions
// https://mediasoup.org/documentation/v3/mediasoup-client/api/#transport-produce // https://mediasoup.org/documentation/v3/mediasoup-client/api/#transport-produce
@ -20502,7 +20531,7 @@ const streamSuccess = (stream) => {
const getLocalStream = () => { const getLocalStream = () => {
console.log('[getLocalStream]'); console.log('[getLocalStream]');
navigator.mediaDevices.getUserMedia({ navigator.mediaDevices.getUserMedia({
audio: true, audio: produceAudio ? true : false,
video: { video: {
qvga : { width: { ideal: 320 }, height: { ideal: 240 } }, qvga : { width: { ideal: 320 }, height: { ideal: 240 } },
vga : { width: { ideal: 640 }, height: { ideal: 480 } }, vga : { width: { ideal: 640 }, height: { ideal: 480 } },
@ -20580,7 +20609,7 @@ const createSendTransport = () => {
console.log('[createSendTransport'); console.log('[createSendTransport');
// see server's socket.on('createWebRtcTransport', sender?, ...) // see server's socket.on('createWebRtcTransport', sender?, ...)
// this is a call from Producer, so sender = true // this is a call from Producer, so sender = true
socket.emit('createWebRtcTransport', { sender: true, callId }, (value) => { socket.emit('createWebRtcTransport', { sender: true }, (value) => {
console.log(`[createWebRtcTransport] value: ${JSON.stringify(value)}`); console.log(`[createWebRtcTransport] value: ${JSON.stringify(value)}`);
@ -20651,34 +20680,36 @@ const connectSendTransport = async () => {
// this action will trigger the 'connect' and 'produce' events above // this action will trigger the 'connect' and 'produce' events above
// Produce video // Produce video
producerVideo = await producerTransport.produce(videoParams) let producerVideoHandler = await producerTransport.produce(videoParams)
console.log('videoParams', videoParams); console.log('videoParams', videoParams);
console.log('producerVideo', producerVideo); console.log('producerVideo', producerVideo);
producerVideo.on('trackended', () => { producerVideoHandler.on('trackended', () => {
console.log('track ended') console.log('track ended')
// close video track // close video track
}) })
producerVideo.on('transportclose', () => { producerVideoHandler.on('transportclose', () => {
console.log('transport ended') console.log('transport ended')
// close video track // close video track
}) })
// Produce audio // Produce audio
producerAudio = await producerTransport.produce(audioParams) if (produceAudio) {
let producerAudioHandler = await producerTransport.produce(audioParams)
console.log('audioParams', audioParams); console.log('audioParams', audioParams);
console.log('producerAudio', producerAudio); console.log('producerAudio', producerAudio);
producerAudio.on('trackended', () => { producerAudioHandler.on('trackended', () => {
console.log('track ended') console.log('track ended')
// close audio track // close audio track
}) })
producerAudio.on('transportclose', () => { producerAudioHandler.on('transportclose', () => {
console.log('transport ended') console.log('transport ended')
// close audio track // close audio track
}) })
}
const answer = { const answer = {
origin_asset_id: ASSET_ID, origin_asset_id: ASSET_ID,
@ -20762,32 +20793,93 @@ const connectRecvTransport = async () => {
await socket.emit('consume', { await socket.emit('consume', {
rtpCapabilities: device.rtpCapabilities, rtpCapabilities: device.rtpCapabilities,
callId callId
}, async ({ params }) => { }, async ({videoParams, audioParams}) => {
if (params.error) { console.log(`[consume] 🟩 videoParams`, videoParams)
console.log('Cannot Consume') console.log(`[consume] 🟩 audioParams`, audioParams)
return console.log('[consume] 🟩 consumerTransport', consumerTransport)
}
// Then consume with the local consumer transport
// which creates a consumer
consumer = await consumerTransport.consume({
id: params.id,
producerId: params.producerId,
kind: params.kind,
rtpParameters: params.rtpParameters
})
// destructure and retrieve the video track from the producer
const { track } = consumer
let stream = new MediaStream() let stream = new MediaStream()
stream.addTrack(track)
// stream.removeTrack(track)
remoteVideo.srcObject = stream
socket.emit('consumer-resume')
console.log('consumer', consumer);
// Maybe the unit does not produce video or audio, so we must only consume what is produced
if (videoParams) {
console.log('❗ Have VIDEO stream to consume');
stream.addTrack(await getVideoTrask(videoParams))
} else {
console.log('❗ Don\'t have VIDEO stream to consume');
}
if (audioParams) {
console.log('❗ Have AUDIO stream to consume');
let audioTrack = await getAudioTrask(audioParams)
stream.addTrack(audioTrack)
} else {
console.log('❗ Don\'t have AUDIO stream to consume');
}
socket.emit('consumer-resume')
remoteVideo.srcObject = stream
remoteVideo.setAttribute('autoplay', true)
remoteVideo.play()
.then(() => {
console.log('remoteVideo PLAY')
}) })
.catch((error) => {
displayError(`remoteVideo PLAY ERROR | ${error.message}`)
})
})
}
const getVideoTrask = async (videoParams) => {
consumerVideo = await consumerTransport.consume({
id: videoParams.id,
producerId: videoParams.producerId,
kind: videoParams.kind,
rtpParameters: videoParams.rtpParameters
})
consumerVideo.on('transportclose', () => {
console.log('transport closed so consumer closed')
})
return consumerVideo.track
}
const getAudioTrask = async (audioParams) => {
consumerAudio = await consumerTransport.consume({
id: audioParams.id,
producerId: audioParams.producerId,
kind: audioParams.kind,
rtpParameters: audioParams.rtpParameters
})
consumerAudio.on('transportclose', () => {
console.log('transport closed so consumer closed')
})
const audioTrack = consumerAudio.track
audioTrack.applyConstraints({
audio: {
advanced: [
{
echoCancellation: {exact: true}
},
{
autoGainControl: {exact: true}
},
{
noiseSuppression: {exact: true}
},
{
highpassFilter: {exact: true}
}
]
}
})
return audioTrack
} }
const closeCall = () => { const closeCall = () => {
@ -20811,8 +20903,31 @@ const closeCall = () => {
resetCallSettings() 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)
}
})
connectRecvTransport()
})
}
btnLocalVideo.addEventListener('click', getLocalStream) btnLocalVideo.addEventListener('click', getLocalStream)
btnRecvSendTransport.addEventListener('click', goConnect) btnRecvSendTransport.addEventListener('click', consume)
btnCloseCall.addEventListener('click', closeCall) btnCloseCall.addEventListener('click', closeCall)
},{"./config":94,"mediasoup-client":66,"socket.io-client":82}]},{},[95]); },{"./config":94,"mediasoup-client":66,"socket.io-client":82}]},{},[95]);

View File

@ -1,4 +1,4 @@
module.exports = { module.exports = {
hubAddress: 'https://hub.dev.linx.safemobile.com/', hubAddress: 'https://hub.dev.linx.safemobile.com/',
mediasoupAddress: 'https://video.safemobile.org', mediasoupAddress: 'https://testing.video.safemobile.org',
} }

View File

@ -34,6 +34,9 @@
<body> <body>
<body> <body>
<div id="video"> <div id="video">
<legend>Client options:</legend>
<input type="checkbox" id="produceAudio" name="produceAudio">
<label for="produceAudio">Produce audio</label><br>
<table> <table>
<thead> <thead>
<th>Local Video</th> <th>Local Video</th>
@ -43,12 +46,24 @@
<tr> <tr>
<td> <td>
<div id="sharedBtns"> <div id="sharedBtns">
<video id="localVideo" autoplay class="video" muted></video> <video
id="localVideo"
class="video"
autoplay
muted
playsinline
></video>
</div> </div>
</td> </td>
<td> <td>
<div id="sharedBtns"> <div id="sharedBtns">
<video id="remoteVideo" autoplay class="video" ></video> <video
id="remoteVideo"
class="video"
autoplay
muted
playsinline
></video>
</div> </div>
</td> </td>
</tr> </tr>
@ -61,33 +76,10 @@
<td> <td>
<div id="sharedBtns"> <div id="sharedBtns">
<button id="btnRecvSendTransport">Consume</button> <button id="btnRecvSendTransport">Consume</button>
<button id="remoteSoundControl">Unmute</button>
</div> </div>
</td> </td>
</tr> </tr>
<!-- <tr>
<td colspan="2">
<div id="sharedBtns">
<button id="btnRtpCapabilities">2. Get Rtp Capabilities</button>
<br />
<button id="btnDevice">3. Create Device</button>
</div>
</td>
</tr>
<tr>
<td>
<div id="sharedBtns">
<button id="btnCreateSendTransport">4. Create Send Transport</button>
<br />
<button id="btnConnectSendTransport">5. Connect Send Transport & Produce</button></td>
</div>
<td>
<div id="sharedBtns">
<button id="btnRecvSendTransport">6. Create Recv Transport</button>
<br />
<button id="btnConnectRecvTransport">7. Connect Recv Transport & Consume</button>
</div>
</td>
</tr> -->
</tbody> </tbody>
</table> </table>
<div id="closeCallBtn"> <div id="closeCallBtn">

View File

@ -10,10 +10,24 @@ const ASSET_NAME = urlParams.get('assetName') || null;
const ASSET_TYPE = urlParams.get('assetType') || null; const ASSET_TYPE = urlParams.get('assetType') || null;
let callId = parseInt(urlParams.get('callId')) || null; let callId = parseInt(urlParams.get('callId')) || null;
const IS_PRODUCER = urlParams.get('producer') === 'true' ? true : false const IS_PRODUCER = urlParams.get('producer') === 'true' ? true : false
let remoteVideo = document.getElementById('remoteVideo')
remoteVideo.defaultMuted = true
let produceAudio = false
console.log('[URL] ASSET_ID', ASSET_ID, '| ACCOUNT_ID', ACCOUNT_ID, '| callId', callId, ' | IS_PRODUCER', IS_PRODUCER) console.log('[URL] ASSET_ID', ASSET_ID, '| ACCOUNT_ID', ACCOUNT_ID, '| callId', callId, ' | IS_PRODUCER', IS_PRODUCER)
console.log('🟩 config', config) console.log('🟩 config', config)
produceAudioSelector = document.getElementById('produceAudio');
produceAudioSelector.addEventListener('change', e => {
if(e.target.checked) {
produceAudio = true
console.log('produce audio');
} else {
produceAudio = false
}
});
let socket, hub let socket, hub
let device let device
let rtpCapabilities let rtpCapabilities
@ -23,6 +37,21 @@ let producerVideo
let producerAudio let producerAudio
let consumer let consumer
let originAssetId let originAssetId
let consumerVideo // local consumer video(consumer not transport)
let consumerAudio // local consumer audio(consumer not transport)
const remoteSoundControl = document.getElementById('remoteSoundControl');
remoteSoundControl.addEventListener('click', function handleClick() {
console.log('remoteSoundControl.textContent', remoteSoundControl.textContent);
if (remoteSoundControl.textContent === 'Unmute') {
remoteVideo.muted = false
remoteSoundControl.textContent = 'Mute';
} else {
remoteVideo.muted = true
remoteSoundControl.textContent = 'Unmute';
}
});
// https://mediasoup.org/documentation/v3/mediasoup-client/api/#ProducerOptions // https://mediasoup.org/documentation/v3/mediasoup-client/api/#ProducerOptions
// https://mediasoup.org/documentation/v3/mediasoup-client/api/#transport-produce // https://mediasoup.org/documentation/v3/mediasoup-client/api/#transport-produce
@ -144,7 +173,7 @@ const streamSuccess = (stream) => {
const getLocalStream = () => { const getLocalStream = () => {
console.log('[getLocalStream]'); console.log('[getLocalStream]');
navigator.mediaDevices.getUserMedia({ navigator.mediaDevices.getUserMedia({
audio: true, audio: produceAudio ? true : false,
video: { video: {
qvga : { width: { ideal: 320 }, height: { ideal: 240 } }, qvga : { width: { ideal: 320 }, height: { ideal: 240 } },
vga : { width: { ideal: 640 }, height: { ideal: 480 } }, vga : { width: { ideal: 640 }, height: { ideal: 480 } },
@ -222,7 +251,7 @@ const createSendTransport = () => {
console.log('[createSendTransport'); console.log('[createSendTransport');
// see server's socket.on('createWebRtcTransport', sender?, ...) // see server's socket.on('createWebRtcTransport', sender?, ...)
// this is a call from Producer, so sender = true // this is a call from Producer, so sender = true
socket.emit('createWebRtcTransport', { sender: true, callId }, (value) => { socket.emit('createWebRtcTransport', { sender: true }, (value) => {
console.log(`[createWebRtcTransport] value: ${JSON.stringify(value)}`); console.log(`[createWebRtcTransport] value: ${JSON.stringify(value)}`);
@ -293,34 +322,36 @@ const connectSendTransport = async () => {
// this action will trigger the 'connect' and 'produce' events above // this action will trigger the 'connect' and 'produce' events above
// Produce video // Produce video
producerVideo = await producerTransport.produce(videoParams) let producerVideoHandler = await producerTransport.produce(videoParams)
console.log('videoParams', videoParams); console.log('videoParams', videoParams);
console.log('producerVideo', producerVideo); console.log('producerVideo', producerVideo);
producerVideo.on('trackended', () => { producerVideoHandler.on('trackended', () => {
console.log('track ended') console.log('track ended')
// close video track // close video track
}) })
producerVideo.on('transportclose', () => { producerVideoHandler.on('transportclose', () => {
console.log('transport ended') console.log('transport ended')
// close video track // close video track
}) })
// Produce audio // Produce audio
producerAudio = await producerTransport.produce(audioParams) if (produceAudio) {
let producerAudioHandler = await producerTransport.produce(audioParams)
console.log('audioParams', audioParams); console.log('audioParams', audioParams);
console.log('producerAudio', producerAudio); console.log('producerAudio', producerAudio);
producerAudio.on('trackended', () => { producerAudioHandler.on('trackended', () => {
console.log('track ended') console.log('track ended')
// close audio track // close audio track
}) })
producerAudio.on('transportclose', () => { producerAudioHandler.on('transportclose', () => {
console.log('transport ended') console.log('transport ended')
// close audio track // close audio track
}) })
}
const answer = { const answer = {
origin_asset_id: ASSET_ID, origin_asset_id: ASSET_ID,
@ -404,32 +435,93 @@ const connectRecvTransport = async () => {
await socket.emit('consume', { await socket.emit('consume', {
rtpCapabilities: device.rtpCapabilities, rtpCapabilities: device.rtpCapabilities,
callId callId
}, async ({ params }) => { }, async ({videoParams, audioParams}) => {
if (params.error) { console.log(`[consume] 🟩 videoParams`, videoParams)
console.log('Cannot Consume') console.log(`[consume] 🟩 audioParams`, audioParams)
return console.log('[consume] 🟩 consumerTransport', consumerTransport)
}
// Then consume with the local consumer transport
// which creates a consumer
consumer = await consumerTransport.consume({
id: params.id,
producerId: params.producerId,
kind: params.kind,
rtpParameters: params.rtpParameters
})
// destructure and retrieve the video track from the producer
const { track } = consumer
let stream = new MediaStream() let stream = new MediaStream()
stream.addTrack(track)
// stream.removeTrack(track)
remoteVideo.srcObject = stream
socket.emit('consumer-resume')
console.log('consumer', consumer);
// Maybe the unit does not produce video or audio, so we must only consume what is produced
if (videoParams) {
console.log('❗ Have VIDEO stream to consume');
stream.addTrack(await getVideoTrask(videoParams))
} else {
console.log('❗ Don\'t have VIDEO stream to consume');
}
if (audioParams) {
console.log('❗ Have AUDIO stream to consume');
let audioTrack = await getAudioTrask(audioParams)
stream.addTrack(audioTrack)
} else {
console.log('❗ Don\'t have AUDIO stream to consume');
}
socket.emit('consumer-resume')
remoteVideo.srcObject = stream
remoteVideo.setAttribute('autoplay', true)
remoteVideo.play()
.then(() => {
console.log('remoteVideo PLAY')
}) })
.catch((error) => {
displayError(`remoteVideo PLAY ERROR | ${error.message}`)
})
})
}
const getVideoTrask = async (videoParams) => {
consumerVideo = await consumerTransport.consume({
id: videoParams.id,
producerId: videoParams.producerId,
kind: videoParams.kind,
rtpParameters: videoParams.rtpParameters
})
consumerVideo.on('transportclose', () => {
console.log('transport closed so consumer closed')
})
return consumerVideo.track
}
const getAudioTrask = async (audioParams) => {
consumerAudio = await consumerTransport.consume({
id: audioParams.id,
producerId: audioParams.producerId,
kind: audioParams.kind,
rtpParameters: audioParams.rtpParameters
})
consumerAudio.on('transportclose', () => {
console.log('transport closed so consumer closed')
})
const audioTrack = consumerAudio.track
audioTrack.applyConstraints({
audio: {
advanced: [
{
echoCancellation: {exact: true}
},
{
autoGainControl: {exact: true}
},
{
noiseSuppression: {exact: true}
},
{
highpassFilter: {exact: true}
}
]
}
})
return audioTrack
} }
const closeCall = () => { const closeCall = () => {
@ -453,7 +545,30 @@ const closeCall = () => {
resetCallSettings() 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)
}
})
connectRecvTransport()
})
}
btnLocalVideo.addEventListener('click', getLocalStream) btnLocalVideo.addEventListener('click', getLocalStream)
btnRecvSendTransport.addEventListener('click', goConnect) btnRecvSendTransport.addEventListener('click', consume)
btnCloseCall.addEventListener('click', closeCall) btnCloseCall.addEventListener('click', closeCall)