Compare commits

..

7 Commits

Author SHA1 Message Date
2e336a429e fix 2022-10-18 18:23:54 +03:00
b14e82fd87 fix 2022-10-18 18:22:19 +03:00
c4f72eddd5 fix 2022-10-18 18:21:07 +03:00
6e4ceb9977 fixes 2022-10-18 18:18:29 +03:00
2c00de1dd0 fix ssl cert/key 2022-10-18 18:13:24 +03:00
f96fd24e03 Fix https 2022-10-18 18:12:03 +03:00
fce2f30648 Fix https import 2022-10-18 18:07:04 +03:00
7 changed files with 944 additions and 898 deletions

1
.gitignore vendored
View File

@ -1,2 +1 @@
/node_modules /node_modules
/dist

108
app.js
View File

@ -5,12 +5,7 @@ const app = express();
const Server = require('socket.io'); const Server = require('socket.io');
const path = require('node:path'); const path = require('node:path');
const fs = require('node:fs'); const fs = require('node:fs');
let https; const https = require('https');
try {
https = require('node:https');
} catch (err) {
console.log('https support is disabled!');
}
const mediasoup = require('mediasoup'); const mediasoup = require('mediasoup');
let worker let worker
@ -42,8 +37,8 @@ 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('./server/ssl/key.pem', 'utf-8'),
cert: fs.readFileSync(process.env.SERVER_CERT, 'utf-8'), cert: fs.readFileSync('./server/ssl/cert.pem', 'utf-8'),
} }
const httpsServer = https.createServer(options, app); const httpsServer = https.createServer(options, app);
@ -63,12 +58,13 @@ httpsServer.listen(process.env.PORT, () => {
}); });
const peers = io.of('/'); const peers = io.of('/');
console.log('process.env.RTC_MIN_PORT', process.env.RTC_MIN_PORT);
console.log('process.env.RTC_MAX_PORT', process.env.RTC_MAX_PORT, process.env.RTC_MAX_PORT.length);
const createWorker = async () => { const createWorker = async () => {
try { try {
worker = await mediasoup.createWorker({ worker = await mediasoup.createWorker({
rtcMinPort: parseInt(process.env.RTC_MIN_PORT), rtcMinPort: process.env.RTC_MIN_PORT,
rtcMaxPort: parseInt(process.env.RTC_MAX_PORT), rtcMaxPort: process.env.RTC_MAX_PORT,
}) })
console.log(`[createWorker] worker pid ${worker.pid}`); console.log(`[createWorker] worker pid ${worker.pid}`);
@ -95,65 +91,16 @@ const mediaCodecs = [
kind: 'audio', kind: 'audio',
mimeType: 'audio/opus', mimeType: 'audio/opus',
clockRate: 48000, clockRate: 48000,
channels : 2 channels: 2,
}, },
{ {
kind: 'video', kind: 'video',
mimeType: 'video/VP8', mimeType: 'video/VP8',
clockRate: 90000, clockRate: 90000,
parameters : parameters: {
{ 'x-google-start-bitrate': 1000,
'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' : '42e01f',
'level-asymmetry-allowed' : 1,
'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) => {
@ -173,6 +120,16 @@ const closeCall = (callId) => {
} }
} }
const getRtpCapabilities = (callId, callback) => {
try {
console.log('[getRtpCapabilities] callId', callId);
const rtpCapabilities = videoCalls[callId].router.rtpCapabilities;
callback({ rtpCapabilities });
} catch (error) {
console.log(`ERROR | getRtpCapabilities | callId ${callId} | ${error.message}`);
}
}
/* /*
- Handlers for WS events - Handlers for WS events
- These are created only when we have a connection with a peer - These are created only when we have a connection with a peer
@ -199,9 +156,7 @@ peers.on('connection', async socket => {
- If the room already exists, it will not create it, but will only return rtpCapabilities - If the room already exists, it will not create it, but will only return rtpCapabilities
*/ */
socket.on('createRoom', async ({ callId }, callback) => { socket.on('createRoom', async ({ callId }, callback) => {
let callbackResponse = null;
try { try {
// We can continue with the room creation process only if we have a callId
if (callId) { if (callId) {
console.log(`[createRoom] socket.id ${socket.id} callId ${callId}`); console.log(`[createRoom] socket.id ${socket.id} callId ${callId}`);
if (!videoCalls[callId]) { if (!videoCalls[callId]) {
@ -210,19 +165,12 @@ peers.on('connection', async socket => {
console.log(`[createRoom] Router ID: ${videoCalls[callId].router.id}`); console.log(`[createRoom] Router ID: ${videoCalls[callId].router.id}`);
} }
socketDetails[socket.id] = callId; socketDetails[socket.id] = callId;
getRtpCapabilities(callId, callback);
// rtpCapabilities is set for callback
console.log('[getRtpCapabilities] callId', callId);
callbackResponse = {
rtpCapabilities :videoCalls[callId].router.rtpCapabilities
};
} else { } else {
console.log(`[createRoom] missing callId ${callId}`); console.log(`[createRoom] missing callId ${callId}`);
} }
} catch (error) { } catch (error) {
console.log(`ERROR | createRoom | callId ${callId} | ${error.message}`); console.log(`ERROR | createRoom | callId ${callId} | ${error.message}`);
} finally {
callback(callbackResponse);
} }
}); });
@ -243,19 +191,16 @@ peers.on('connection', async socket => {
videoCalls[callId].producerTransport = await createWebRtcTransportLayer(callId, callback); videoCalls[callId].producerTransport = 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);
} }
} else if (!sender) { } else if (!sender) {
if (!videoCalls[callId].consumerTransport) { if (!videoCalls[callId].consumerTransport) {
videoCalls[callId].consumerTransport = await createWebRtcTransportLayer(callId, callback); videoCalls[callId].consumerTransport = await createWebRtcTransportLayer(callId, callback);
} else { } else {
console.log(`consumerTransport has already been defined | callId ${callId}`); console.log(`consumerTransport has already been defined | callId ${callId}`);
callback(null);
} }
} }
} catch (error) { } catch (error) {
console.log(`ERROR | createWebRtcTransport | callId ${socketDetails[socket.id]} | sender ${sender} | ${error.message}`); console.log(`ERROR | createWebRtcTransport | callId ${socketDetails[socket.id]} | sender ${sender} | ${error.message}`);
callback(error);
} }
}); });
@ -285,9 +230,7 @@ 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] | socket.id', socket.id, '| callId', callId);
console.log('kind', kind);
console.log('rtpParameters', rtpParameters);
videoCalls[callId].producer = await videoCalls[callId].producerTransport.produce({ videoCalls[callId].producer = await videoCalls[callId].producerTransport.produce({
kind, kind,
rtpParameters, rtpParameters,
@ -301,9 +244,9 @@ 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({
id: videoCalls[callId].producer.id // id: videoCalls[callId].producer.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}`);
} }
@ -374,7 +317,6 @@ peers.on('connection', async socket => {
callback({ params }); callback({ params });
} else { } else {
console.log(`[canConsume] Can't consume | callId ${callId}`); console.log(`[canConsume] Can't consume | callId ${callId}`);
callback(null);
} }
} catch (error) { } catch (error) {
console.log(`ERROR | consume | callId ${socketDetails[socket.id]} | ${error.message}`) console.log(`ERROR | consume | callId ${socketDetails[socket.id]} | ${error.message}`)

View File

@ -1,48 +0,0 @@
#/!bin/bash
## PREBUILD PROCESS
# check dist dir to be present and empty
if [ ! -d "dist" ]; then
## MAKE DIR
mkdir "dist"
echo "Directory dist created."
else
## CLEANUP
rm -fr dist/*
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/
#Add version control for pm2
cd dist
#Add version control for pm2
version=$(git describe)
file_pkg="package.json"
key=" \"version\": \""
count=$(echo ${version%%-*} | grep -o "\." | wc -l)
if (( $count > 1 )); then
version=${version%%-*}
else
version="${version%%-*}.0"
fi
if [ -f "$file_pkg" ] && [ ! -z "$version" ]; then
version=" \"version\": \"$version\","
sed -i "s|^.*$key.*|${version//\//\\/}|g" $file_pkg
text=$(cat $file_pkg | grep -c "$version")
if [ $text -eq 0 ]; then
echo "Version couldn't be set"
else
echo "Version $version successfully applied to App"
fi
fi
## POST BUILD
cd -

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,5 @@
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://video.safemobile.org/mediasoup',
// mediasoupAddress: 'http://localhost:3000/mediasoup',
} }

View File

@ -43,7 +43,7 @@
<tr> <tr>
<td> <td>
<div id="sharedBtns"> <div id="sharedBtns">
<video id="localVideo" autoplay class="video" muted></video> <video id="localVideo" autoplay class="video" ></video>
</div> </div>
</td> </td>
<td> <td>

View File

@ -12,11 +12,7 @@ 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
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) let socket
let socket, hub
setTimeout(() => {
hub = io(config.hubAddress) hub = io(config.hubAddress)
const connectToMediasoup = () => { const connectToMediasoup = () => {
@ -40,7 +36,7 @@ setTimeout(() => {
if (IS_PRODUCER === true) { if (IS_PRODUCER === true) {
hub.on('connect', async () => { hub.on('connect', async () => {
console.log(`[HUB]! ${config.hubAddress} | connected: ${hub.connected}`) console.log(`[HUB] ${config.hubAddress} | connected: ${hub.connected}`)
connectToMediasoup() connectToMediasoup()
hub.emit( hub.emit(
@ -88,115 +84,69 @@ setTimeout(() => {
connectToMediasoup() connectToMediasoup()
} }
}, 1600);
let device let device
let rtpCapabilities let rtpCapabilities
let producerTransport let producerTransport
let consumerTransport let consumerTransport
let producerVideo let producer
let producerAudio
let consumer let consumer
let originAssetId let originAssetId
// let originAssetName = 'Adi'
// let originAssetTypeName = 'linx'
// 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
let videoParams = { let params = {
// mediasoup params
encodings: [ encodings: [
{ scaleResolutionDownBy: 4, maxBitrate: 500000 }, {
{ scaleResolutionDownBy: 2, maxBitrate: 1000000 }, rid: 'r0',
{ scaleResolutionDownBy: 1, maxBitrate: 5000000 }, maxBitrate: 100000,
{ scalabilityMode: 'S3T3_KEY' } scalabilityMode: 'S1T3',
},
{
rid: 'r1',
maxBitrate: 300000,
scalabilityMode: 'S1T3',
},
{
rid: 'r2',
maxBitrate: 900000,
scalabilityMode: 'S1T3',
},
], ],
// https://mediasoup.org/documentation/v3/mediasoup-client/api/#ProducerCodecOptions
codecOptions: { codecOptions: {
videoGoogleStartBitrate: 1000 videoGoogleStartBitrate: 1000
} }
// encodings: [
// {
// rid: 'r0',
// maxBitrate: 100000,
// scalabilityMode: 'S1T3',
// },
// {
// rid: 'r1',
// maxBitrate: 300000,
// scalabilityMode: 'S1T3',
// },
// {
// rid: 'r2',
// maxBitrate: 900000,
// scalabilityMode: 'S1T3',
// },
// ],
// // https://mediasoup.org/documentation/v3/mediasoup-client/api/#ProducerCodecOptions
// codecOptions: {
// videoGoogleStartBitrate: 1000
// }
}
let audioParams = {
codecOptions :
{
opusStereo : true,
opusDtx : true
}
} }
const streamSuccess = (stream) => { const streamSuccess = (stream) => {
console.log('[streamSuccess] device', device); console.log('[streamSuccess]');
localVideo.srcObject = stream localVideo.srcObject = stream
console.log('stream', stream); const track = stream.getVideoTracks()[0]
const videoTrack = stream.getVideoTracks()[0] params = {
const audioTrack = stream.getAudioTracks()[0] track,
...params
videoParams = {
track: videoTrack,
// codec : device.rtpCapabilities.codecs.find((codec) => codec.mimeType.toLowerCase() === 'video/vp9'),
// codec : 'video/vp9',
...videoParams
} }
audioParams = {
track: audioTrack,
...audioParams
}
console.log('[streamSuccess] videoParams', videoParams, ' | audioParams', audioParams);
goConnect() goConnect()
// console.log('[streamSuccess]');
// localVideo.srcObject = stream
// const track = stream.getVideoTracks()[0]
// videoParams = {
// track,
// ...videoParams
// }
// goConnect()
} }
const getLocalStream = () => { const getLocalStream = () => {
console.log('[getLocalStream]'); console.log('[getLocalStream]');
navigator.mediaDevices.getUserMedia({ navigator.mediaDevices.getUserMedia({
audio: true, audio: false,
video: { video: {
qvga : { width: { ideal: 320 }, height: { ideal: 240 } }, width: {
vga : { width: { ideal: 640 }, height: { ideal: 480 } }, min: 640,
hd : { width: { ideal: 1280 }, height: { ideal: 720 } } max: 1920,
},
height: {
min: 400,
max: 1080,
}
} }
}) })
// navigator.mediaDevices.getUserMedia({
// audio: false,
// video: {
// width: {
// min: 640,
// max: 1920,
// },
// height: {
// min: 400,
// max: 1080,
// }
// }
// })
.then(streamSuccess) .then(streamSuccess)
.catch(error => { .catch(error => {
console.log(error.message) console.log(error.message)
@ -217,7 +167,7 @@ const goCreateTransport = () => {
// server side to send/recive media // server side to send/recive media
const createDevice = async () => { const createDevice = async () => {
try { try {
console.log('[createDevice] 1 device', device); console.log('[createDevice]');
device = new mediasoupClient.Device() device = new mediasoupClient.Device()
// https://mediasoup.org/documentation/v3/mediasoup-client/api/#device-load // https://mediasoup.org/documentation/v3/mediasoup-client/api/#device-load
@ -228,7 +178,6 @@ const createDevice = async () => {
}) })
console.log('Device RTP Capabilities', device.rtpCapabilities) console.log('Device RTP Capabilities', device.rtpCapabilities)
console.log('[createDevice] 2 device', device);
// once the device loads, create transport // once the device loads, create transport
goCreateTransport() goCreateTransport()
@ -258,7 +207,6 @@ const getRtpCapabilities = () => {
} }
const createSendTransport = () => { const 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 }, ({ params }) => { socket.emit('createWebRtcTransport', { sender: true, callId }, ({ params }) => {
@ -269,7 +217,7 @@ const createSendTransport = () => {
return return
} }
console.log('[createWebRtcTransport] params', params) console.log(params)
// creates a new WebRTC Transport to send media // creates a new WebRTC Transport to send media
// based on the server's producer transport params // based on the server's producer transport params
@ -296,7 +244,7 @@ const createSendTransport = () => {
}) })
producerTransport.on('produce', async (parameters, callback, errback) => { producerTransport.on('produce', async (parameters, callback, errback) => {
console.log('[produce] parameters', parameters) console.log(parameters)
try { try {
// tell the server to create a Producer // tell the server to create a Producer
@ -322,44 +270,22 @@ const createSendTransport = () => {
} }
const connectSendTransport = async () => { const connectSendTransport = async () => {
console.log('[connectSendTransport] producerTransport');
// we now call produce() to instruct the producer transport // we now call produce() to instruct the producer transport
// to send media to the Router // to send media to the Router
// https://mediasoup.org/documentation/v3/mediasoup-client/api/#transport-produce // https://mediasoup.org/documentation/v3/mediasoup-client/api/#transport-produce
// this action will trigger the 'connect' and 'produce' events above // this action will trigger the 'connect' and 'produce' events above
producer = await producerTransport.produce(params)
producer.on('trackended', () => {
producerVideo = await producerTransport.produce(videoParams)
console.log('producerVideo', producerVideo);
producerVideo.on('trackended', () => {
console.log('track ended') console.log('track ended')
// close video track // close video track
}) })
producerVideo.on('transportclose', () => { producer.on('transportclose', () => {
console.log('transport ended') console.log('transport ended')
// close video track // close video track
}) })
// producerAudio = await producerTransport.produce(audioParams)
// console.log('producerAudio', producerAudio);
// producerAudio.on('trackended', () => {
// console.log('track ended')
// // close video track
// })
// producerAudio.on('transportclose', () => {
// console.log('transport ended')
// // close video track
// })
const answer = { const answer = {
origin_asset_id: ASSET_ID, origin_asset_id: ASSET_ID,
dest_asset_id: originAssetId || parseInt(urlParams.get('dest_asset_id')), dest_asset_id: originAssetId || parseInt(urlParams.get('dest_asset_id')),
@ -394,7 +320,7 @@ const createRecvTransport = async () => {
return return
} }
console.log('[createRecvTransport] params', params) console.log(params)
// creates a new WebRTC Transport to receive media // creates a new WebRTC Transport to receive media
// based on server's consumer transport params // based on server's consumer transport params
@ -427,8 +353,7 @@ const resetCallSettings = () => {
localVideo.srcObject = null localVideo.srcObject = null
remoteVideo.srcObject = null remoteVideo.srcObject = null
consumer = null consumer = null
producerVideo = null producer = null
producerAudio = null
producerTransport = null producerTransport = null
consumerTransport = null consumerTransport = null
device = undefined device = undefined