forked from k-yle/rtsp-relay
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
196 lines (172 loc) · 5.66 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
// @ts-check
const { path: ffmpegPath } = require('@ffmpeg-installer/ffmpeg');
const { spawn } = require('child_process');
const ews = require('express-ws');
const ps = require('ps-node');
const { version } = require('./package.json');
/**
* @typedef {{
* url: string;
* additionalFlags?: string[];
* verbose?: boolean;
* transport?: 'udp' | 'tcp' | 'udp_multicast' | 'http';
* windowsHide?: boolean;
* }} Options
*
* @typedef {import("express").Application} Application
* @typedef {import("ws")} WebSocket
* @typedef {import("child_process").ChildProcessWithoutNullStreams} Stream
*/
class InboundStreamWrapper {
constructor() {
this.clients = 0;
}
/** @param {Options} props */
start({ url, additionalFlags = [], transport, windowsHide = true }) {
if (this.verbose) console.log('[rtsp-relay] Creating brand new stream');
// validate config
const txpConfigInvalid = additionalFlags.indexOf('-rtsp_transport');
// eslint-disable-next-line no-bitwise
if (~txpConfigInvalid) {
const val = additionalFlags[0o1 + txpConfigInvalid];
console.warn(
`[rtsp-relay] (!) Do not specify -rtsp_transport=${val} in additionalFlags, use the option \`transport: '${val}'\``,
);
}
this.stream = spawn(
ffmpegPath,
[
'-fflags', '-nobuffer',
'-flags', 'low_delay',
'-strict', 'experimental',
...(transport ? ['-rtsp_transport', transport] : []), // this must come before `-i [url]`, see #82
'-i',
url,
'-f', // force format
'mpegts',
'-codec:v', // specify video codec (MPEG1 required for jsmpeg)
'mpeg1video',
'-r',
'30', // 30 fps. any lower and the client can't decode it
...additionalFlags,
'-',
],
{ detached: false, windowsHide },
);
this.stream.stderr.on('data', () => {});
this.stream.stderr.on('error', (e) => console.log('err:error', e));
this.stream.stdout.on('error', (e) => console.log('out:error', e));
this.stream.on('error', (err) => {
if (this.verbose) {
console.warn(`[rtsp-relay] Internal Error: ${err.message}`);
}
});
this.stream.on('exit', (_code, signal) => {
if (signal !== 'SIGTERM') {
if (this.verbose) {
console.warn(
'[rtsp-relay] Stream died - will recreate when the next client connects',
);
}
this.stream = null;
}
});
}
/** @param {Options} options */
get(options) {
this.verbose = options.verbose;
this.clients += 1;
if (!this.stream) this.start(options);
return /** @type {Stream} */ (this.stream);
}
decrement() {
this.clients -= 1;
return this.clients;
}
/** @param {number} clientsLeft */
kill(clientsLeft) {
if (!this.stream) return; // the stream is currently dead
if (!clientsLeft) {
if (this.verbose) {
console.log('[rtsp-relay] no clients left; destroying stream');
}
this.stream.kill('SIGTERM');
this.stream = null;
// next time it is requested it will be recreated
return;
}
if (this.verbose) {
console.log(
'[rtsp-relay] there are still some clients so not destroying stream',
);
}
}
}
/** @type {ReturnType<ews>} */
let wsInstance;
/**
* @param {Application} app the express application
* @param {import("http").Server | import("https").Server} [server] optional - if you use HTTPS you will need to pass in the server
*/
module.exports = (app, server) => {
if (!wsInstance) wsInstance = ews(app, server);
const wsServer = wsInstance.getWss();
/**
* This map stores all the streams in existance, keyed by the URL.
* This means we only ever create one InboundStream per URL.
* @type {{ [url: string]: InboundStreamWrapper }}
*/
const Inbound = {};
return {
/**
* You must include a script tag in the HTML to import this script
*
* Alternatively, if you have set up a build process for front-end
* code, you can import it instead:
* ```js
* import { loadPlayer } from "rtsp-relay/browser";
* ```
*/
scriptUrl: `https://cdn.jsdelivr.net/npm/rtsp-relay@${version}/browser/index.js`,
killAll() {
ps.lookup({ command: 'ffmpeg' }, (err, list) => {
if (err) throw err;
list
.filter((p) => p.arguments.includes('mpeg1video'))
.forEach(({ pid }) => ps.kill(pid));
});
},
/** @param {Options} props */
proxy({ url, verbose, ...options }) {
if (!url) throw new Error('URL to rtsp stream is required');
// TODO: node15 use ||=
if (!Inbound[url]) Inbound[url] = new InboundStreamWrapper();
/** @param {WebSocket} ws */
function handler(ws) {
// these should be detected from the source stream
const [width, height] = [0x0, 0x0];
const streamHeader = Buffer.alloc(0x8);
streamHeader.write('jsmp');
streamHeader.writeUInt16BE(width, 0x4);
streamHeader.writeUInt16BE(height, 0x6);
ws.send(streamHeader, { binary: true });
if (verbose) console.log('[rtsp-relay] New WebSocket Connection');
const streamIn = Inbound[url].get({ url, verbose, ...options });
/** @param {Buffer} chunk */
function onData(chunk) {
if (ws.readyState === ws.OPEN) ws.send(chunk);
}
ws.on('close', () => {
const c = Inbound[url].decrement();
if (verbose) {
console.log(`[rtsp-relay] WebSocket Disconnected ${c} left`);
}
Inbound[url].kill(c);
streamIn.stdout.off('data', onData);
});
streamIn.stdout.on('data', onData);
}
return handler;
},
};
};