-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
executable file
·85 lines (73 loc) · 1.87 KB
/
server.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const path = require("path");
const { spawn } = require("child_process");
const ws = require("ws");
const express = require("express");
const app = express();
const STREAM_URL =
"rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov";
const PROTOCOL = "http";
const HOST = "localhost";
const PORT = 3000;
const VERBOSE = true;
app.use(express.static(path.join(__dirname, "public")));
// Listen to ffmpeg.
app.post("/stream", (req, res) => {
// Don't timeout, this connection is infinate.
res.connection.setTimeout(0);
// Pipe the data to the clients in the WebSocket.
req.on("data", (data) => {
wsServer.clients.forEach((client) => {
if (client.readyState === ws.OPEN) {
client.send(data);
}
});
});
});
app.get("/", (_, res) => {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
const server = app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
const wsServer = new ws.Server({ server: server });
// Start ffmpeg.
const ffmpeg = spawn("ffmpeg", [
"-hide_banner",
"-i",
STREAM_URL,
"-f",
"mpegts",
"-codec:v",
"mpeg1video",
// "-s",
// "640x480",
"-b:v",
"800k",
"-bf",
"0",
"-r",
"20",
`${PROTOCOL}://${HOST}:${PORT}/stream`,
]);
ffmpeg.stderr.on("data", (data) => {
if (VERBOSE) {
console.log(`${data}`);
}
});
// Safely fill ffmpeg
const exitHandler = (options) => {
if (options.cleanup) {
ffmpeg.stderr.pause();
ffmpeg.stdout.pause();
ffmpeg.stdin.pause();
ffmpeg.kill();
}
if (options.exit) {
process.exit();
}
};
process.on("exit", exitHandler.bind(null, { cleanup: true }));
process.on("SIGINT", exitHandler.bind(null, { exit: true }));
process.on("SIGUSR1", exitHandler.bind(null, { exit: true }));
process.on("SIGUSR2", exitHandler.bind(null, { exit: true }));
process.on("uncaughtException", exitHandler.bind(null, { exit: true }));