forked from illuspas/Node-Media-Server
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathffmpeg.service.js
More file actions
82 lines (70 loc) · 2.17 KB
/
ffmpeg.service.js
File metadata and controls
82 lines (70 loc) · 2.17 KB
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
const ffmpeg = require("fluent-ffmpeg");
const fs = require("fs");
const { spawn } = require("child_process");
const path = require("path");
const { Writable, Duplex, Readable } = require("stream");
const { Stream, PassThrough } = require("stream").PassThrough;
function FfmpegService() {
this.list = [];
}
const config = {
STREAM: "rtmp://0.0.0.0/live",
};
FfmpegService.instance = function () {
if (FfmpegService._instance == undefined) {
FfmpegService._instance = new FfmpegService();
}
return FfmpegService._instance;
};
FfmpegService.prototype.createAndGet = function (channel) {
let connId = this.list.findIndex((conn) => conn.channel == channel);
if (connId == -1) {
// Create new connection
let command = ffmpeg(`${config.STREAM}${channel}/${channel}`)
.addInputOption("-re")
.addOutputOption("-f mp3")
.addOutputOption(`-b:a 32k`);
let ffstream = command.pipe();
let conn = {
channel: channel,
stream: ffstream,
command: command,
callbacks: [],
};
command.addListener("end", function () {
FfmpegService.instance().removeChannel(channel);
console.log(`Close channel ${channel}`);
});
command.on("error", function (err, stdout, stderr) {
FfmpegService.instance().removeChannel(channel);
console.log(`Error channel ${channel}`);
});
ffstream.on("data", function (chunk) {
for (let i = 0; i < conn.callbacks.length; i++) {
conn.callbacks[i](chunk);
}
});
console.log(`Listen to new connection ${Date.now()}`);
this.list.push(conn);
return conn;
}
console.log(`Listen to existed connection ${Date.now()}`);
return this.list[connId];
};
FfmpegService.prototype.updateStream = function (channel, stream) {
let connId = this.list.findIndex((conn) => conn.channel == channel);
if (connId > -1) {
this.list[connId] = {
stream: stream,
...this.list[connId],
};
}
};
FfmpegService.prototype.removeChannel = function (channel) {
let connId = this.list.findIndex((conn) => conn.channel == channel);
if (connId > -1) {
this.list.splice(connId, 1);
}
console.log(this.list);
};
module.exports = FfmpegService;