@klabsio/node-ffmpeg-stream 0.0.0-stage → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +261 -3
- package/ffmpegStream.js +368 -0
- package/index.js +1 -0
- package/package.json +44 -6
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2021 Kannan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,261 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# node-ffmpeg-stream
|
|
2
|
+
|
|
3
|
+
`node-ffmpeg-stream` uses FFmpeg to:
|
|
4
|
+
|
|
5
|
+
- Convert an RTSP input into an MPEG-TS stream delivered over WebSocket.
|
|
6
|
+
- Record a time-limited clip to a file or return it as a Base64 data URL.
|
|
7
|
+
- Capture a still image to a file or return it as a Base64 data URL.
|
|
8
|
+
|
|
9
|
+
The library manages FFmpeg processes; it does not include FFmpeg or provide a
|
|
10
|
+
camera. Supply an RTSP source that your FFmpeg installation can access.
|
|
11
|
+
|
|
12
|
+
## Dependencies and requirements
|
|
13
|
+
|
|
14
|
+
`npm install @klabsio/node-ffmpeg-stream` installs the Node.js package and its npm
|
|
15
|
+
dependency, `ws` (the WebSocket server library), automatically. You do not need
|
|
16
|
+
to install `ws` separately.
|
|
17
|
+
|
|
18
|
+
You must provide these runtime requirements:
|
|
19
|
+
|
|
20
|
+
- Node.js 18 or newer.
|
|
21
|
+
- FFmpeg installed and available as `ffmpeg` on `PATH`, or an explicit
|
|
22
|
+
`ffmpegPath` in the operation's options.
|
|
23
|
+
- Network access from the server to the RTSP camera or media source.
|
|
24
|
+
|
|
25
|
+
For browser playback of the WebSocket video, the demo uses a local JSMpeg
|
|
26
|
+
browser player file. Recording and snapshot operations do not require a browser
|
|
27
|
+
player.
|
|
28
|
+
|
|
29
|
+
### Install FFmpeg on Windows
|
|
30
|
+
|
|
31
|
+
FFmpeg is a separate program, not an npm dependency. Download a Windows build
|
|
32
|
+
from [ffmpeg.org](https://ffmpeg.org/download.html), extract it, and add the
|
|
33
|
+
folder containing `ffmpeg.exe` (usually `C:\ffmpeg\bin`) to your Windows
|
|
34
|
+
`Path`. Open a new terminal and verify it is available:
|
|
35
|
+
|
|
36
|
+
```powershell
|
|
37
|
+
ffmpeg -version
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Alternatively, pass the full executable path as `ffmpegPath` in the stream or
|
|
41
|
+
recording/snapshot options, for example:
|
|
42
|
+
`C:\ffmpeg\bin\ffmpeg.exe`.
|
|
43
|
+
|
|
44
|
+
### JSMpeg browser player
|
|
45
|
+
|
|
46
|
+
The demo includes `demo/jsmpeg.min.js`, so playback does not depend on an
|
|
47
|
+
external CDN. The bundled JSMpeg player is MIT-licensed; see
|
|
48
|
+
[`demo/JSMPEG-LICENSE.txt`](./demo/JSMPEG-LICENSE.txt). If you replace the
|
|
49
|
+
player bundle, keep the applicable license notice.
|
|
50
|
+
|
|
51
|
+
Install the package:
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
npm install @klabsio/node-ffmpeg-stream
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Download FFmpeg from [ffmpeg.org](https://ffmpeg.org/download.html) and check
|
|
58
|
+
that it is available:
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
ffmpeg -version
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## RTSP to WebSocket
|
|
65
|
+
|
|
66
|
+
Create a stream in your Node.js server:
|
|
67
|
+
|
|
68
|
+
```js
|
|
69
|
+
const { Stream } = require('@klabsio/node-ffmpeg-stream');
|
|
70
|
+
|
|
71
|
+
const stream = new Stream({
|
|
72
|
+
name: 'lobby-camera',
|
|
73
|
+
url: process.env.CAMERA_RTSP_URL,
|
|
74
|
+
wsPort: 7070,
|
|
75
|
+
options: {
|
|
76
|
+
'-r': 30,
|
|
77
|
+
'-stats': ''
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
stream.on('exitWithError', (error) => {
|
|
82
|
+
console.error('Camera stream failed:', error.message);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
// When your application no longer needs the stream:
|
|
86
|
+
stream.stop();
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`wsPort` is the local TCP port used by the WebSocket server. Use `0` to let
|
|
90
|
+
the operating system choose an available port. `options` contains additional
|
|
91
|
+
FFmpeg flags; use an empty string for a flag that takes no value. The library
|
|
92
|
+
sets RTSP-over-TCP input and MPEG-TS/MPEG-1 video output options itself.
|
|
93
|
+
|
|
94
|
+
The existing `stopStream()` method remains available as an alias for `stop()`.
|
|
95
|
+
`Stream` emits `data` for FFmpeg output, `stderr` for FFmpeg diagnostic output,
|
|
96
|
+
`listening` with the bound WebSocket address once the server is ready, `exit`
|
|
97
|
+
when FFmpeg exits, and `exitWithError` if it cannot start or exits unsuccessfully.
|
|
98
|
+
|
|
99
|
+
The WebSocket endpoint sends MPEG-TS data suitable for a compatible client such
|
|
100
|
+
as JSMpeg. A minimal browser example:
|
|
101
|
+
|
|
102
|
+
```html
|
|
103
|
+
<canvas id="stream"></canvas>
|
|
104
|
+
<script src="/jsmpeg.min.js"></script>
|
|
105
|
+
<script>
|
|
106
|
+
const player = new JSMpeg.Player('ws://localhost:7070', {
|
|
107
|
+
canvas: document.getElementById('stream')
|
|
108
|
+
});
|
|
109
|
+
</script>
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Serve the client library from your application or another trusted source.
|
|
113
|
+
Do not expose an unauthenticated camera stream to an untrusted network; this
|
|
114
|
+
package does not implement WebSocket authentication or access control.
|
|
115
|
+
|
|
116
|
+
### Run the browser demo
|
|
117
|
+
|
|
118
|
+
The [`demo/`](./demo/) folder contains a minimal HTML/JavaScript client. To try
|
|
119
|
+
it:
|
|
120
|
+
|
|
121
|
+
1. Set `CAMERA_RTSP_URL` to an RTSP URL the server can access.
|
|
122
|
+
2. Put `ffmpeg.exe` in the `demo/` folder, or edit the `ffmpegPath` setting in
|
|
123
|
+
the demo server to point to your FFmpeg executable.
|
|
124
|
+
3. Start the included demo server, which starts `Stream` on port `7070`:
|
|
125
|
+
|
|
126
|
+
```sh
|
|
127
|
+
node demo/server.js
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
4. Serve the `demo/` folder using a local static-file server (for example,
|
|
131
|
+
VS Code Live Server), then open its `index.html` page in a browser.
|
|
132
|
+
5. Leave the WebSocket URL as `ws://localhost:7070` when running locally, then
|
|
133
|
+
select **Connect**.
|
|
134
|
+
|
|
135
|
+
To serve the page with Express instead of a separate static-file server, install
|
|
136
|
+
the development dependencies and start the included Express demo server:
|
|
137
|
+
|
|
138
|
+
```sh
|
|
139
|
+
npm install
|
|
140
|
+
node demo/express-server.js
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
The Express server also expects `ffmpeg.exe` in `demo/`. Open
|
|
144
|
+
`http://localhost:3000`; the WebSocket stream remains on port `7070`.
|
|
145
|
+
|
|
146
|
+
If your application uses HTTPS, use a secure WebSocket URL (`wss://`) and
|
|
147
|
+
configure your server or reverse proxy to provide TLS; browsers generally
|
|
148
|
+
block insecure `ws://` connections from HTTPS pages.
|
|
149
|
+
|
|
150
|
+
## Record a clip
|
|
151
|
+
|
|
152
|
+
`recordVideo(input, callback)` uses the callback-based API from earlier
|
|
153
|
+
versions. The clip duration defaults to 5 seconds. A stored recording returns
|
|
154
|
+
a success response describing its path:
|
|
155
|
+
|
|
156
|
+
```js
|
|
157
|
+
const { RecordNSnap } = require('@klabsio/node-ffmpeg-stream');
|
|
158
|
+
|
|
159
|
+
const capture = new RecordNSnap();
|
|
160
|
+
|
|
161
|
+
capture.recordVideo({
|
|
162
|
+
url: process.env.CAMERA_RTSP_URL,
|
|
163
|
+
second: 30,
|
|
164
|
+
filePath: './recordings',
|
|
165
|
+
fileName: 'lobby.mp4',
|
|
166
|
+
recordType: 'store'
|
|
167
|
+
}, (result) => {
|
|
168
|
+
if (result.status !== 'Success') {
|
|
169
|
+
console.error('Recording failed:', result.error || result.response);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
console.log(result.response);
|
|
173
|
+
});
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
For a Base64 data URL instead of a stored file, use `recordType: 'download'`
|
|
177
|
+
and provide `fileMimeType`:
|
|
178
|
+
|
|
179
|
+
```js
|
|
180
|
+
capture.recordVideo({
|
|
181
|
+
url: process.env.CAMERA_RTSP_URL,
|
|
182
|
+
second: 10,
|
|
183
|
+
fileName: 'clip.mp4',
|
|
184
|
+
fileMimeType: 'video/mp4',
|
|
185
|
+
recordType: 'download'
|
|
186
|
+
}, (result) => {
|
|
187
|
+
if (result.status === 'Success') {
|
|
188
|
+
// result.response is a data:video/mp4;base64,... URL
|
|
189
|
+
res.send(result.response);
|
|
190
|
+
} else {
|
|
191
|
+
res.status(500).send(result.error || result.response);
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
`filePath` defaults to the current working directory. The output extension
|
|
197
|
+
should match a container supported by your FFmpeg build. Download mode creates
|
|
198
|
+
a temporary output file and removes it after reading it.
|
|
199
|
+
|
|
200
|
+
## Capture a snapshot
|
|
201
|
+
|
|
202
|
+
Use `takeSnap(input, callback)` to save an image:
|
|
203
|
+
|
|
204
|
+
```js
|
|
205
|
+
capture.takeSnap({
|
|
206
|
+
url: process.env.CAMERA_RTSP_URL,
|
|
207
|
+
imagePath: './snapshots',
|
|
208
|
+
imageName: 'lobby.jpg',
|
|
209
|
+
snapType: 'store'
|
|
210
|
+
}, (result) => {
|
|
211
|
+
if (result.status !== 'Success') {
|
|
212
|
+
console.error('Snapshot failed:', result.error || result.response);
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
console.log(result.response);
|
|
216
|
+
});
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
For a data URL, use `snapType: 'download'` and provide `imageMimeType`
|
|
220
|
+
(for example, `image/jpeg`). The success response contains the data URL in
|
|
221
|
+
`base64`, the file name in `filename`, and the MIME type in `imagetype`.
|
|
222
|
+
Snapshots default to a two-second seek before capture. The output file name
|
|
223
|
+
defaults to a timestamped JPEG name.
|
|
224
|
+
|
|
225
|
+
## FFmpeg executable path
|
|
226
|
+
|
|
227
|
+
If FFmpeg is not on `PATH`, set `ffmpegPath` on a stream or operation:
|
|
228
|
+
|
|
229
|
+
```js
|
|
230
|
+
const stream = new Stream({
|
|
231
|
+
name: 'lobby-camera',
|
|
232
|
+
url: process.env.CAMERA_RTSP_URL,
|
|
233
|
+
wsPort: 7070,
|
|
234
|
+
ffmpegPath: 'C:\\tools\\ffmpeg\\bin\\ffmpeg.exe'
|
|
235
|
+
});
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
The same `ffmpegPath` option is supported by `recordVideo` and `takeSnap`.
|
|
239
|
+
|
|
240
|
+
## Running tests
|
|
241
|
+
|
|
242
|
+
The test suite uses Node's built-in test runner and mocks FFmpeg, so it does
|
|
243
|
+
not require a camera, network stream, or special output drive:
|
|
244
|
+
|
|
245
|
+
```sh
|
|
246
|
+
npm test
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
## Troubleshooting
|
|
250
|
+
|
|
251
|
+
- **FFmpeg not found:** run `ffmpeg -version` in the same environment as the
|
|
252
|
+
Node.js process, or set `ffmpegPath`.
|
|
253
|
+
- **RTSP connection fails:** check the camera URL, credentials, network route,
|
|
254
|
+
and that FFmpeg can reach the camera from the server.
|
|
255
|
+
- **Recording or snapshot fails:** check that the output folder exists and
|
|
256
|
+
that the Node.js process can write to it. Check the returned `error` field
|
|
257
|
+
for FFmpeg diagnostics.
|
|
258
|
+
- **No browser video:** confirm the client can connect to the configured
|
|
259
|
+
WebSocket port and supports the MPEG-TS/MPEG-1 stream output.
|
|
260
|
+
|
|
261
|
+
Avoid logging RTSP URLs if they contain credentials.
|
package/ffmpegStream.js
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const childProcess = require('child_process');
|
|
4
|
+
const EventEmitter = require('events');
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const WebSocket = require('ws');
|
|
8
|
+
|
|
9
|
+
function ffmpegPath(input) {
|
|
10
|
+
return input.ffmpegPath || 'ffmpeg';
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function outputPath(directory, fileName) {
|
|
14
|
+
return path.join(directory || '', fileName);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function validateCallback(callback) {
|
|
18
|
+
if (typeof callback !== 'function') {
|
|
19
|
+
throw new TypeError('A callback function is required.');
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function runFFmpeg(executable, args, callback) {
|
|
24
|
+
let child;
|
|
25
|
+
let stderr = '';
|
|
26
|
+
let completed = false;
|
|
27
|
+
|
|
28
|
+
const finish = (error) => {
|
|
29
|
+
if (completed) {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
completed = true;
|
|
33
|
+
callback(error, stderr);
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
try {
|
|
37
|
+
child = childProcess.spawn(executable, args, { stdio: ['ignore', 'ignore', 'pipe'] });
|
|
38
|
+
} catch (error) {
|
|
39
|
+
finish(error);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
child.stderr.on('data', (chunk) => {
|
|
44
|
+
stderr = (stderr + chunk.toString()).slice(-4096);
|
|
45
|
+
});
|
|
46
|
+
child.once('error', finish);
|
|
47
|
+
child.once('close', (code, signal) => {
|
|
48
|
+
if (code === 0) {
|
|
49
|
+
finish(null);
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const message = signal
|
|
54
|
+
? `FFmpeg was terminated by signal ${signal}.`
|
|
55
|
+
: `FFmpeg exited with code ${code}.`;
|
|
56
|
+
finish(new Error(stderr.trim() || message));
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function failureResponse(error, response) {
|
|
61
|
+
return {
|
|
62
|
+
status: 'Failed',
|
|
63
|
+
response: response || '',
|
|
64
|
+
error: error || ''
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
class Stream extends EventEmitter {
|
|
69
|
+
constructor(input) {
|
|
70
|
+
super();
|
|
71
|
+
if (!input || !input.url) {
|
|
72
|
+
throw new TypeError('RTSP URL required.');
|
|
73
|
+
}
|
|
74
|
+
if (!Number.isInteger(input.wsPort) || input.wsPort < 0 || input.wsPort > 65535) {
|
|
75
|
+
throw new TypeError('wsPort must be a valid port number.');
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
this.name = input.name || 'stream';
|
|
79
|
+
this.wsCount = 0;
|
|
80
|
+
this.startStream(input);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
start(input) {
|
|
84
|
+
this.startStream(input);
|
|
85
|
+
return this;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
setOptions(input) {
|
|
89
|
+
const userOptions = input.options || {};
|
|
90
|
+
const options = {
|
|
91
|
+
'-rtsp_transport': 'tcp',
|
|
92
|
+
'-i': input.url,
|
|
93
|
+
'-pix_fmt': 'yuv420p',
|
|
94
|
+
'-f': 'mpegts',
|
|
95
|
+
'-codec:v': 'mpeg1video',
|
|
96
|
+
'-codec:a': 'mp2',
|
|
97
|
+
'-r': userOptions['-r'] || 30
|
|
98
|
+
};
|
|
99
|
+
const params = [];
|
|
100
|
+
|
|
101
|
+
for (const [key, value] of Object.entries(options)) {
|
|
102
|
+
params.push(key);
|
|
103
|
+
if (String(value) !== '') {
|
|
104
|
+
params.push(String(value));
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
for (const [key, value] of Object.entries(userOptions)) {
|
|
109
|
+
if (key !== '-r') {
|
|
110
|
+
params.push(key);
|
|
111
|
+
if (String(value) !== '') {
|
|
112
|
+
params.push(String(value));
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
params.push('-');
|
|
118
|
+
return params;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
startStream(input) {
|
|
122
|
+
this.stopping = false;
|
|
123
|
+
this.processFailureHandled = false;
|
|
124
|
+
this.wss = new WebSocket.Server({ port: input.wsPort });
|
|
125
|
+
this.wss.once('listening', () => {
|
|
126
|
+
this.emit('listening', this.wss.address());
|
|
127
|
+
});
|
|
128
|
+
this.wss.on('connection', (socket, request) => {
|
|
129
|
+
this.wsCount = this.wss.clients.size;
|
|
130
|
+
this.onSocketConnect(socket, request);
|
|
131
|
+
});
|
|
132
|
+
this.wss.on('error', (error) => this.emitError(error));
|
|
133
|
+
this.wss.on('close', () => {
|
|
134
|
+
this.emit('close');
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
try {
|
|
138
|
+
this.child = childProcess.spawn(
|
|
139
|
+
input.ffmpegPath || 'ffmpeg',
|
|
140
|
+
this.setOptions(input),
|
|
141
|
+
{ stdio: ['ignore', 'pipe', 'pipe'] }
|
|
142
|
+
);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
this.handleProcessError(error);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
this.child.stdout.on('data', (data) => {
|
|
149
|
+
this.wss.clients.forEach((client) => {
|
|
150
|
+
if (client.readyState === WebSocket.OPEN) {
|
|
151
|
+
client.send(data);
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
this.emit('data', data);
|
|
155
|
+
});
|
|
156
|
+
this.child.stderr.on('data', (data) => {
|
|
157
|
+
this.emit('stderr', data);
|
|
158
|
+
});
|
|
159
|
+
this.child.once('error', (error) => this.handleProcessError(error));
|
|
160
|
+
this.child.once('close', (code, signal) => {
|
|
161
|
+
this.exitCode = code;
|
|
162
|
+
this.exitSignal = signal;
|
|
163
|
+
if (code !== 0 && !this.stopping) {
|
|
164
|
+
this.handleProcessError(new Error(
|
|
165
|
+
signal ? `FFmpeg was terminated by signal ${signal}.` : `FFmpeg exited with code ${code}.`
|
|
166
|
+
));
|
|
167
|
+
} else {
|
|
168
|
+
this.closeWebSocketServer();
|
|
169
|
+
this.emit('exit', code, signal);
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
handleProcessError(error) {
|
|
175
|
+
if (this.processFailureHandled) {
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
this.processFailureHandled = true;
|
|
179
|
+
this.exitCode = this.exitCode === undefined ? 1 : this.exitCode;
|
|
180
|
+
this.closeWebSocketServer();
|
|
181
|
+
this.emit('exitWithError', error);
|
|
182
|
+
this.emitError(error);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
emitError(error) {
|
|
186
|
+
if (this.listenerCount('error') > 0) {
|
|
187
|
+
this.emit('error', error);
|
|
188
|
+
} else {
|
|
189
|
+
console.error(`${this.name}: ${error.message}`);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
closeWebSocketServer() {
|
|
194
|
+
if (this.wss && !this.webSocketServerClosed) {
|
|
195
|
+
if (!this.wss.address()) {
|
|
196
|
+
if (!this.webSocketClosePending) {
|
|
197
|
+
this.webSocketClosePending = true;
|
|
198
|
+
this.wss.once('listening', () => {
|
|
199
|
+
this.webSocketClosePending = false;
|
|
200
|
+
this.closeWebSocketServer();
|
|
201
|
+
});
|
|
202
|
+
this.wss.once('close', () => {
|
|
203
|
+
this.webSocketServerClosed = true;
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
this.webSocketServerClosed = true;
|
|
209
|
+
this.wss.clients.forEach((client) => client.terminate());
|
|
210
|
+
this.wss.close();
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
onSocketConnect(socket, request) {
|
|
215
|
+
this.wsCount = this.wss.clients.size;
|
|
216
|
+
socket.remoteAddress = request.socket.remoteAddress;
|
|
217
|
+
this.emit('connection', socket, request);
|
|
218
|
+
socket.once('close', () => {
|
|
219
|
+
this.wsCount = this.wss.clients.size;
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
stop() {
|
|
224
|
+
return this.stopStream();
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
stopStream() {
|
|
228
|
+
if (this.stopping) {
|
|
229
|
+
return this;
|
|
230
|
+
}
|
|
231
|
+
this.stopping = true;
|
|
232
|
+
if (this.child && this.child.exitCode === null && !this.child.killed) {
|
|
233
|
+
this.child.kill();
|
|
234
|
+
}
|
|
235
|
+
this.closeWebSocketServer();
|
|
236
|
+
return this;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
class RecordNSnap extends EventEmitter {
|
|
241
|
+
recordVideo(input, callback) {
|
|
242
|
+
validateCallback(callback);
|
|
243
|
+
if (!input || !input.url) {
|
|
244
|
+
callback(failureResponse('', 'Rtsp URL required'));
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
if (input.recordType && input.recordType.toLowerCase() === 'download' && !input.fileMimeType) {
|
|
248
|
+
callback(failureResponse('', 'File Mime type(fileMimeType) is required for download URL.'));
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const fileName = input.fileName || `record_${this.getCurrentDatewithTime()}.mp4`;
|
|
253
|
+
const file = outputPath(input.filePath, fileName);
|
|
254
|
+
const args = [
|
|
255
|
+
'-rtsp_transport', 'tcp',
|
|
256
|
+
'-i', input.url,
|
|
257
|
+
'-t', String(input.second || 5),
|
|
258
|
+
file
|
|
259
|
+
];
|
|
260
|
+
|
|
261
|
+
runFFmpeg(ffmpegPath(input), args, (error) => {
|
|
262
|
+
if (error) {
|
|
263
|
+
callback(failureResponse(error));
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
if (input.recordType && input.recordType.toLowerCase() === 'download') {
|
|
268
|
+
fs.readFile(file, (readError, contents) => {
|
|
269
|
+
if (readError) {
|
|
270
|
+
callback(failureResponse(readError));
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
fs.unlink(file, (unlinkError) => {
|
|
274
|
+
if (unlinkError) {
|
|
275
|
+
callback(failureResponse(unlinkError));
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
callback({
|
|
279
|
+
status: 'Success',
|
|
280
|
+
response: `data:${input.fileMimeType};base64,${contents.toString('base64')}`,
|
|
281
|
+
error: ''
|
|
282
|
+
});
|
|
283
|
+
});
|
|
284
|
+
});
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
callback({
|
|
289
|
+
status: 'Success',
|
|
290
|
+
response: `Recorded file stored into the given path [ ${file} ]`,
|
|
291
|
+
error: ''
|
|
292
|
+
});
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
takeSnap(input, callback) {
|
|
297
|
+
validateCallback(callback);
|
|
298
|
+
if (!input || !input.url) {
|
|
299
|
+
callback(failureResponse('', 'Rtsp URL required'));
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (input.snapType && input.snapType.toLowerCase() === 'download' && !input.imageMimeType) {
|
|
303
|
+
callback(failureResponse('', 'Image Mime type(imageMimeType) is required for download URL.'));
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const fileName = input.imageName || `snapshot_${this.getCurrentDatewithTime()}.jpg`;
|
|
308
|
+
const file = outputPath(input.imagePath, fileName);
|
|
309
|
+
const args = [
|
|
310
|
+
'-rtsp_transport', 'tcp',
|
|
311
|
+
'-ss', '2',
|
|
312
|
+
'-i', input.url,
|
|
313
|
+
'-y',
|
|
314
|
+
'-f', 'image2',
|
|
315
|
+
'-qscale', '0',
|
|
316
|
+
'-frames', '1',
|
|
317
|
+
file
|
|
318
|
+
];
|
|
319
|
+
|
|
320
|
+
runFFmpeg(ffmpegPath(input), args, (error) => {
|
|
321
|
+
if (error) {
|
|
322
|
+
callback(failureResponse(error));
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
if (input.snapType && input.snapType.toLowerCase() === 'download') {
|
|
327
|
+
fs.readFile(file, (readError, contents) => {
|
|
328
|
+
if (readError) {
|
|
329
|
+
callback(failureResponse(readError, 'File creation failed. Please try again...'));
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
fs.unlink(file, (unlinkError) => {
|
|
333
|
+
if (unlinkError) {
|
|
334
|
+
callback(failureResponse(unlinkError));
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
callback({
|
|
338
|
+
status: 'Success',
|
|
339
|
+
base64: `data:${input.imageMimeType};base64,${contents.toString('base64')}`,
|
|
340
|
+
filename: fileName,
|
|
341
|
+
imagetype: input.imageMimeType,
|
|
342
|
+
message: ''
|
|
343
|
+
});
|
|
344
|
+
});
|
|
345
|
+
});
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
callback({
|
|
350
|
+
status: 'Success',
|
|
351
|
+
response: `Snapshot image stored into the given path [ ${file} ]`,
|
|
352
|
+
error: ''
|
|
353
|
+
});
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
getCurrentDatewithTime() {
|
|
358
|
+
const date = new Date();
|
|
359
|
+
const pad = (value) => String(value).padStart(2, '0');
|
|
360
|
+
return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}` +
|
|
361
|
+
`${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
module.exports = {
|
|
366
|
+
Stream,
|
|
367
|
+
RecordNSnap
|
|
368
|
+
};
|
package/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
module.exports = require('./ffmpegStream.js')
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@klabsio/node-ffmpeg-stream",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@klabsio/node-ffmpeg-stream",
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "Stream RTSP video over WebSocket and capture recordings or snapshots with FFmpeg",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"files": [
|
|
7
|
+
"index.js",
|
|
8
|
+
"ffmpegStream.js"
|
|
9
|
+
],
|
|
10
|
+
"publishConfig": {
|
|
11
|
+
"access": "public"
|
|
12
|
+
},
|
|
13
|
+
"scripts": {
|
|
14
|
+
"test": "node --test"
|
|
15
|
+
},
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=18"
|
|
18
|
+
},
|
|
19
|
+
"keywords": [
|
|
20
|
+
"node",
|
|
21
|
+
"rtsp",
|
|
22
|
+
"websocket",
|
|
23
|
+
"ffmpeg",
|
|
24
|
+
"stream",
|
|
25
|
+
"recording",
|
|
26
|
+
"snapshot"
|
|
27
|
+
],
|
|
28
|
+
"author": "Kannan Krishnan",
|
|
29
|
+
"license": "MIT",
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"ws": "^8.18.3"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"express": "^5.1.0"
|
|
35
|
+
},
|
|
36
|
+
"repository": {
|
|
37
|
+
"type": "git",
|
|
38
|
+
"url": "git+https://github.com/uk2nk/node-ffmpeg-stream.git"
|
|
39
|
+
},
|
|
40
|
+
"bugs": {
|
|
41
|
+
"url": "https://github.com/uk2nk/node-ffmpeg-stream/issues"
|
|
42
|
+
},
|
|
43
|
+
"homepage": "https://github.com/uk2nk/node-ffmpeg-stream#readme"
|
|
44
|
+
}
|