I wanted to forward an rtp stream automaticly when someone joins the videoroom, so I wrote the following nodejs script.
const express = require('express');
const bodyParser = require('body-parser');
const http = require('http');
// Create server for janus events
const janusEventPort = 8081;
const janusEventApp = express();
const janusEventServer = http.createServer(janusEventApp);
// Janus api
const janusApiPort = 8088;
const janusApiPath = "/janus";
const janusApiTransactionId = "xxx";
const janusApiPost = function(path, data, callback) {
const dataStr = JSON.stringify(data);
const options = {
hostname: 'localhost',
port: janusApiPort,
path: path,
method: 'POST',
headers:{
'Content-Type': 'application/json',
'Content-Length': dataStr.length
}
};
const req = http.request(options, res => {
let body = '';
res.on('data', chunk => {
body += chunk;
});
res.on('end', () => {
if (callback) callback(JSON.parse(body));
});
});
req.write(dataStr);
req.end();
}
// RTP forward
const rtpPort = 8004;
const rtpHost = 'localhost';
const roomSecret = 'xxx';
const rtpForward = function(roomData) {
var sessionId;
var handleId;
// Forward stream
const forward = function() {
janusApiPost(janusApiPath + '/' + sessionId + '/' + handleId, {
"janus": "message",
"body": {
"request": "rtp_forward",
"room": roomData.room,
"publisher_id": roomData.id,
"host": rtpHost,
"video_port": rtpPort,
"secret": roomSecret
},
"transaction": janusApiTransactionId
});
}
// Attach plugin
const attachPlugin = function() {
janusApiPost(janusApiPath + '/' + sessionId, {
"janus": "attach",
"plugin": "janus.plugin.videoroom",
"transaction": janusApiTransactionId
}, data => {
forward();
});
}
// Create session
janusApiPost(janusApiPath, {
"janus": "create",
"transaction": janusApiTransactionId
}, data => {
attachPlugin();
});
}
// React to published event in videoroom
janusEventApp.use(bodyParser.raw({inflate:false,type:'application/json'}));
janusEventApp.post('/', function(req, res) {
const data = JSON.parse(req.body.toString());
// Send publisher data to rtpForward function
if (data.event.plugin === "janus.plugin.videoroom" && data.event.data.event === "published") rtpForward(data.event.data);
res.sendStatus(200);
});
// Start server
janusEventServer.listen(janusEventPort);