Repository navigation
Expand file tree
/
Copy pathrunner.go
More file actions
306 lines (265 loc) · 8.26 KB
/
Copy pathrunner.go
File metadata and controls
306 lines (265 loc) · 8.26 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package main
import (
"fmt"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/go-cmd/cmd"
log "github.com/sirupsen/logrus"
)
var (
leeches map[string]*leech
)
type leech struct {
Config cameraConfig
stopEverything bool // If set to true, everything will stop
stopEverythingMu sync.Mutex
watcherStarted bool
stopWatcher chan int
progMsgsCounter int
progMsgsStringsPool []string
progMsgsPool []progressMessage
Stats progressMessage
command *cmd.Cmd
status <-chan cmd.Status
}
type progressMessage struct {
Frame uint64
Fps float32
Bitrate int
OutTime uint64 // miliseconds
DupFrames int
DropFrames int
}
func newLeech(c cameraConfig) *leech {
l := new(leech)
l.Config = cameraConfig{}
l.Config = c
l.Stats = progressMessage{}
l.stopWatcher = make(chan int, 1)
l.progMsgsStringsPool = make([]string, 0, 128)
l.progMsgsPool = make([]progressMessage, 0, 128)
return l
}
func (l *leech) Start() error {
var ffmpegArgs []string
var err error
l.setStopEverythingValue(false)
inputArgs := regexp.MustCompile("\\s+").Split(l.Config.InputOptions, -1)
filePath := fmt.Sprintf("%s/%s/%%Y-%%m-%%d/%%Y-%%m-%%d_%%H-%%M-%%S.mkv", l.Config.StoragePath, l.Config.Name)
ffmpegArgs = make([]string, 0, 30)
log.Debugf("Stream %s: Assembling ffmpeg command", l.Config.Name)
ffmpegArgs = append(ffmpegArgs, "-hide_banner", "-nostdin", "-nostats", "-progress", "pipe:1",
"-loglevel", l.Config.FfmpegLogLevel)
if len(inputArgs) > 0 {
for _, i := range inputArgs {
if i == "" {
continue
}
ffmpegArgs = append(ffmpegArgs, i)
}
}
ffmpegArgs = append(ffmpegArgs, "-i", l.Config.URL, "-codec", "copy",
"-f", "segment", "-segment_time", fmt.Sprint(l.Config.SegmentTime), "-reset_timestamps", "1",
"-segment_atclocktime", "1", "-strftime", "1", filePath)
log.Debug("Creating necessary subfolders (if needed)")
if err := l.createSubFolders(); err != nil {
log.Errorf("Error creating subfolder for camera %s segments: %v", l.Config.Name, err)
return err
}
l.command = cmd.NewCmdOptions(cmd.Options{Streaming: true}, l.Config.FfmpegPath, ffmpegArgs...)
l.status = l.command.Start()
log.Infof("Camera %s: ffmpeg leech started", l.Config.Name)
if !l.watcherStarted {
// Starting crash watcher if the program has been started
log.Debugf("Camera %s: starting watcher", l.Config.Name)
go func() {
l.watcherStarted = true
for {
log.Debugf("Camera %s: waiting watcher channel to send event", l.Config.Name)
<-l.status
if l.getStopEverythingValue() {
l.watcherStarted = false
return
}
l.stopWatcher <- 666
if err != nil {
log.Errorf("Camera %s: command was finished with error: %v", l.Config.Name, err)
}
time.Sleep(1 * time.Second)
log.Infof("Camera %s: restarting ffmpeg command with args %v", l.Config.Name, ffmpegArgs)
l.Start()
}
}()
}
// Starting routine creating folders for the next day
go func() {
for {
if l.getStopEverythingValue() {
return
}
t := time.Now()
hour := t.Hour()
minute := t.Minute()
if hour == 23 && minute > 50 && minute < 56 {
if err := l.createNextDaySubfolders(); err != nil {
log.Errorf("Error creating next-day subfolder for camera %s: %v", l.Config.Name, err)
}
}
time.Sleep(295 * time.Second)
}
}()
// Starting a goroutine which will be grabbing strings from stdout and stderr chans
log.Debugf("Camera %s: Starting output grabber", l.Config.Name)
go func() {
for {
if l.getStopEverythingValue() {
return
}
select {
case stdout := <-l.command.Stdout:
l.handleProgressMessage(stdout)
case stderr := <-l.command.Stderr:
l.sendLog(stderr)
case <-l.stopWatcher:
log.Infof("Camera %s: program output grabber routine destroyed", l.Config.Name)
return
}
}
}()
return nil
}
func (l *leech) setStopEverythingValue(val bool) {
l.stopEverythingMu.Lock()
defer l.stopEverythingMu.Unlock()
l.stopEverything = val
}
func (l *leech) getStopEverythingValue() bool {
l.stopEverythingMu.Lock()
defer l.stopEverythingMu.Unlock()
return l.stopEverything
}
func (l *leech) createSubFolders() error {
t := time.Now()
dateString := fmt.Sprintf("%d-%02d-%02d", t.Year(), t.Month(), t.Day())
path := fmt.Sprintf("%s/%s/%s", l.Config.StoragePath, l.Config.Name, dateString)
return os.MkdirAll(path, 0755)
}
func (l *leech) createNextDaySubfolders() error {
t := time.Now().AddDate(0, 0, 1)
dateString := fmt.Sprintf("%d-%02d-%02d", t.Year(), t.Month(), t.Day())
path := fmt.Sprintf("%s/%s/%s", l.Config.StoragePath, l.Config.Name, dateString)
return os.MkdirAll(path, 0755)
}
func (l *leech) Stop() error {
log.Infof("Camera %s: stopping", l.Config.Name)
l.setStopEverythingValue(true)
err := l.command.Stop()
if err != nil {
log.Errorf("Camera %s: error during command stop: %v", l.Config.Name, err)
return err
}
return nil
}
func (l *leech) handleProgressMessage(str string) {
possibleValues := []string{"frame=", "fps=", "bitrate=", "out_time_ms=", "dup_frames=", "drop_frames="}
if strings.Contains(str, "progress=") {
msg := progressMessage{}
for _, s := range l.progMsgsStringsPool {
if strings.Contains(s, "frame=") {
// handle "frame=1234" string
framecountStr := strings.TrimLeft(s, "frame=")
frame, err := strconv.ParseUint(framecountStr, 10, 64)
if err != nil {
log.Errorf("Failed to parse Uint in the string: \"%s\": %v", framecountStr, err)
continue
}
msg.Frame = frame
} else if strings.Contains(s, "fps=") {
// handle fps
fpsStr := strings.TrimLeft(s, "fps=")
fpsVal, err := strconv.ParseFloat(fpsStr, 32)
if err != nil {
log.Errorf("Failed to parse Float in the string: \"%s\": %v", fpsStr, err)
continue
}
msg.Fps = float32(fpsVal)
} else if strings.Contains(s, "bitrate=") {
bitrateStr := strings.TrimLeft(s, "bitrate=")
// Put -1 instead of bitrate if ffmpeg can't give it to us
var bitrateVal int64
if strings.Contains(bitrateStr, "N/A") {
bitrateVal = -1
} else {
var err error
bitrateSlice := strings.Split(bitrateStr, ".")
bitrateVal, err = strconv.ParseInt(bitrateSlice[0], 10, 0)
if err != nil {
log.Errorf("Failed to parse Int in the string: \"%s\": %v", bitrateSlice[0], err)
continue
}
}
msg.Bitrate = int(bitrateVal)
} else if strings.Contains(s, "out_time_ms=") {
outTimeStr := strings.TrimLeft(s, "out_time_ms=")
outtime, err := strconv.ParseUint(outTimeStr, 10, 64)
if err != nil {
log.Errorf("Failed to parse Uint in the string: \"%s\": %v", outTimeStr, err)
continue
}
msg.OutTime = outtime
} else if strings.Contains(s, "dup_frames=") {
dupFramesStr := strings.TrimLeft(s, "dup_frames=")
dupFramesVal, err := strconv.ParseInt(dupFramesStr, 10, 0)
if err != nil {
log.Errorf("Failed to parse Int in the string: \"%s\": %v", dupFramesStr, err)
continue
}
msg.DupFrames = int(dupFramesVal)
} else if strings.Contains(s, "drop_frames=") {
dropFramesStr := strings.TrimLeft(s, "drop_frames=")
dropFramesVal, err := strconv.ParseInt(dropFramesStr, 10, 0)
if err != nil {
log.Errorf("Failed to parse Int in the string: \"%s\": %v", dropFramesStr, err)
continue
}
msg.DropFrames = int(dropFramesVal)
}
}
l.progMsgsStringsPool = nil
l.progMsgsPool = append(l.progMsgsPool, msg)
l.progMsgsCounter++
if l.progMsgsCounter > 60 {
l.sendProgressReport()
l.progMsgsPool = nil
l.progMsgsCounter = 0
}
} else {
for _, val := range possibleValues {
if strings.Contains(str, val) {
l.progMsgsStringsPool = append(l.progMsgsStringsPool, str)
}
}
}
}
func (l *leech) sendProgressReport() {
var avgFPSTemp float32
var biteateAvgTemp int
lastIdx := len(l.progMsgsPool) - 1
l.Stats.Frame = l.progMsgsPool[lastIdx].Frame
l.Stats.OutTime = l.progMsgsPool[lastIdx].OutTime
l.Stats.DupFrames = l.progMsgsPool[lastIdx].DupFrames
l.Stats.DropFrames = l.progMsgsPool[lastIdx].DropFrames
for _, i := range l.progMsgsPool {
avgFPSTemp = avgFPSTemp + i.Fps
biteateAvgTemp = biteateAvgTemp + i.Bitrate
}
l.Stats.Fps = avgFPSTemp / float32(len(l.progMsgsPool))
l.Stats.Bitrate = biteateAvgTemp / len(l.progMsgsPool)
}
func (l *leech) sendLog(str string) {
log.Infof("%s ffmpeg output: %s", l.Config.Name, str)
}