-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.js
More file actions
248 lines (223 loc) · 6.74 KB
/
main.js
File metadata and controls
248 lines (223 loc) · 6.74 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
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
const minimist = require("minimist")
const ffmpeg = require("fluent-ffmpeg")
const fs = require("fs")
const args = minimist(process.argv.slice(2))
class StreamMonitor {
constructor({
nameStream,
rtspUrl,
streamUrl,
backupUrl = "offline.mp4",
resolution = "1280:720",
stuckThreshold = 5,
checkInterval = 3
}) {
this.nameStream = nameStream
this.rtspUrl = rtspUrl
this.backupUrl = backupUrl
this.streamUrl = streamUrl
this.resolution = resolution
this.stuckThreshold = stuckThreshold
this.checkInterval = checkInterval
this.lastFrameTime = Date.now()
this.lastStreamTime = null
this.isStreamStuck = false
this.currentSource = null
this.checkMainStreamInterval = null
//this.checkStreamInterval = null
this.stderrLine = ""
this.currentFF = null
this.ffCheck = null
this.init()
}
init() {
this.startStream(this.rtspUrl)
this.monitorStream()
}
startStream(source, loop = false) {
if (this.currentFF) this.currentFF.kill("SIGINT")
const isImage = source.endsWith(".jpg")
this.currentFF = ffmpeg(source)
.inputOptions(isImage ? ["-loop 1"] : loop ? ["-stream_loop -1"] : [])
.videoCodec("libx264")
.outputOptions([
"-preset veryfast",
"-c:a aac",
"-ar 44100",
"-b:a 128k",
"-f flv",
"-fflags",
"nobuffer",
"-rtsp_transport",
"tcp",
"-rtbufsize",
"10M",
"-rw_timeout",
"2000000",
"-r",
"10"
])
.videoFilter("scale=" + this.resolution)
.outputOptions(isImage ? ["-filter_complex", "anullsrc=r=44100:cl=stereo", "-shortest"] : [])
.output(this.streamUrl)
.on("start", (commandLine) => {
console.log(`Streaming ${this.nameStream} started with source: ${source} > ${commandLine}`)
this.currentSource = source
})
.on("stderr", (i) => {
this.stderrLine = i
})
.on("error", (i) => {
console.error(`Stream main ${this.nameStream} is error with source ${this.currentSource}: ${i.message}`)
this.stderrLine = i.message
})
.on("end", () => {
console.log(`Stream main ${this.nameStream} is ended for source ${this.currentSource}`)
this.stderrLine = "end"
})
this.currentFF.run()
}
monitorStream() {
setInterval(() => {
this.checkIfStreamIsStuck()
}, 1000)
}
checkIfStreamIsStuck() {
const timeMatch = this.stderrLine.match(/time=\s*([\d:.]+)/)
if (timeMatch) {
const currentTime = timeMatch[1]
const currentMillis = this.timeToMillis(currentTime)
if (this.lastStreamTime && currentMillis === this.lastStreamTime) {
if (!this.isStreamStuck && Date.now() - this.lastFrameTime > 1000 * this.stuckThreshold) {
console.log(`Stream ${this.nameStream} is stuck. Switching to backup.`)
this.isStreamStuck = true
this.startStream(this.backupUrl, true)
}
} else {
if (this.currentSource === this.rtspUrl) {
this.lastStreamTime = currentMillis
this.lastFrameTime = Date.now()
console.log(`LIVE ${this.nameStream}: ${this.stderrLine}`)
this.isStreamStuck = false
} else {
console.error(`OFFLINE ${this.nameStream}: ${this.stderrLine}`)
}
}
} else {
console.error(`NoTime ${this.nameStream}: ${this.stderrLine}`)
if (!this.isStreamStuck && Date.now() - this.lastFrameTime > 1000 * (this.stuckThreshold + 5)) {
console.log(`Stream ${this.nameStream} is done/error. Switching to backup.`)
this.isStreamStuck = true
this.startStream(this.backupUrl, true)
}
}
if (this.isStreamStuck) {
this.checkMainStream()
}
}
checkMainStream() {
if (!this.checkMainStreamInterval) {
this.checkMainStreamInterval = setTimeout(() => {
console.log(`Checking if stream ${this.nameStream} is live?`)
if (this.ffCheck) this.ffCheck.kill("SIGINT")
this.ffCheck = ffmpeg(this.rtspUrl)
.videoCodec("libx264")
.outputOptions([
"-preset veryfast",
"-c:a aac",
"-ar 44100",
"-b:a 128k",
"-f flv",
"-rw_timeout",
"2000000",
"-r",
"1"
])
.inputOptions("-t 1")
.videoFilter("scale=" + this.resolution)
.output(this.streamUrl)
.on("start", () => {
console.log(`Check stream ${this.nameStream} start !`)
})
.on("stderr", (i) => {
console.log(`stderr ${this.nameStream}: ${i}`)
const timeMatch = i.match(/time=\s*([\d:.]+)/)
if (timeMatch) {
try {
if (this.ffCheck) this.ffCheck.kill("SIGINT")
} catch (error) {
console.log(error)
}
const currentTime = timeMatch[1]
const currentMillis = this.timeToMillis(currentTime)
this.lastFrameTime = Date.now()
this.lastStreamTime = currentMillis
this.isStreamStuck = false
this.startStream(this.rtspUrl)
console.log(`Stream ${this.nameStream} main is back live`)
}
// Timeout wait load
if (this.checkStreamInterval) clearInterval(this.checkStreamInterval)
this.checkStreamInterval = setTimeout(() => {
clearInterval(this.checkMainStreamInterval)
this.checkMainStreamInterval = null
}, 1000 * 5)
})
.on("error", (i) => {
console.error(`Stream backup error: ${i.message}`)
clearInterval(this.checkMainStreamInterval)
this.checkMainStreamInterval = null
})
.on("end", () => {
console.log(`Streaming check for ${this.nameStream} > backup ended`)
clearInterval(this.checkMainStreamInterval)
this.checkMainStreamInterval = null
})
.run()
}, 1000 * this.checkInterval)
}
}
timeToMillis(timeString) {
const timeParts = timeString.split(":")
let millis = 0
if (timeParts.length === 3) {
millis += parseInt(timeParts[0]) * 3600000
millis += parseInt(timeParts[1]) * 60000
millis += parseFloat(timeParts[2]) * 1000
} else if (timeParts.length === 2) {
millis += parseInt(timeParts[0]) * 60000
millis += parseFloat(timeParts[1]) * 1000
}
return millis
}
}
// Helper function to parse command-line arguments
function loadStreamsFromArgsOrConfig() {
const streams = []
// Parse arguments for streams in the form of STREAM1_nameStream, STREAM1_rtspUrl, STREAM1_streamUrl, etc.
Object.keys(args).forEach((key) => {
const match = key.match(/STREAM(\d+)_(.+)/)
if (match) {
const [, streamNumber, property] = match
const index = parseInt(streamNumber) - 1
if (!streams[index]) streams[index] = {}
streams[index][property] = args[key]
}
})
// If no valid streams from arguments, load config.json
if (streams.length === 0 || !streams[0].nameStream) {
try {
const config = JSON.parse(fs.readFileSync("config.json"))
return config.camera
} catch (err) {
console.error("Error reading config.json:", err)
process.exit(1)
}
}
return streams
}
// Load streams and start monitoring
const streams = loadStreamsFromArgsOrConfig()
streams.forEach((stream) => {
new StreamMonitor(stream)
})