-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
63 lines (51 loc) · 1.48 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const child_process = require('child_process')
const express = require('express')
const WebSocketServer = require('ws').Server
const http = require('http')
const config = require('./config')
const app = express()
const server = http.createServer(app).listen(config.encoding_port, () => {
console.log(`Started Encoding Server on localhost:${config.encoding_port}`)
})
const wss = new WebSocketServer({ server })
wss.on('connection', (ws, req) => {
let match
const url_regex = req.url.match(/^\/rtmp\/([a-zA-Z]+)\/(.*)$/)
if ( !(match = url_regex) ) {
ws.terminate() // No match, reject the connection.
return
}
const service = match[1]
if(! (service in config.services)){
ws.terminate()
return
}
const rtmpUrl = decodeURIComponent(match[2])
console.log('Target RTMP URL:', rtmpUrl)
const ffmpeg = child_process.spawn('ffmpeg', [
'-f', 'lavfi', '-i', 'anullsrc',
'-i', '-',
'-shortest',
'-vcodec', 'libx264',
'-acodec', 'aac',
'-f', 'flv',
rtmpUrl
])
ffmpeg.on('close', (code, signal) => {
console.log('FFmpeg child process closed, code ' + code + ', signal ' + signal)
ws.terminate()
})
ffmpeg.stdin.on('error', (e) => {
console.log('FFmpeg STDIN Error', e)
})
ffmpeg.stderr.on('data', (data) => {
console.log('FFmpeg STDERR:', data.toString())
})
ws.on('message', (msg) => {
console.log('DATA', msg)
ffmpeg.stdin.write(msg)
})
ws.on('close', (e) => {
ffmpeg.kill('SIGINT')
})
})