-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathfirescrew.go
2019 lines (1756 loc) · 63 KB
/
firescrew.go
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"bytes"
"context"
"embed"
"mime/multipart"
_ "net/http/pprof"
"runtime"
_ "embed"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"image"
"image/color"
"image/color/palette"
"image/draw"
"image/gif"
"image/jpeg"
"image/png"
"io"
"log"
"math"
"math/rand"
"net"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/8ff/firescrew/pkg/firescrewServe"
"github.com/8ff/tuna"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/goki/freetype"
"github.com/goki/freetype/truetype"
ob "github.com/8ff/firescrew/pkg/objectPredict"
"github.com/8ff/prettyTimer"
"github.com/hybridgroup/mjpeg"
)
var Version string
var gifSliceMutex sync.Mutex
var gifSlice []image.RGBA
//go:embed assets/*
var assetsFs embed.FS
var everyNthFrame = 1 // Process every Nth frame, 1 = every frame
var interenceAvgInterval = 10 // Frames to average inference time over
var stream *mjpeg.Stream
type Prediction struct {
Object int `json:"object"`
ClassName string `json:"class_name"`
Box []float32 `json:"box"`
Top int `json:"top"`
Bottom int `json:"bottom"`
Left int `json:"left"`
Right int `json:"right"`
Confidence float32 `json:"confidence"`
Took float64 `json:"took"`
}
type Config struct {
CameraName string `json:"cameraName"`
PrintDebug bool `json:"printDebug"`
DeviceUrl string `json:"deviceUrl"`
LoStreamParamBypass StreamParams `json:"loStreamParamBypass"`
HiResDeviceUrl string `json:"hiResDeviceUrl"`
HiStreamParamBypass StreamParams `json:"hiStreamParamBypass"`
PixelMotionAreaThreshold float64 `json:"pixelMotionAreaThreshold"`
ObjectCenterMovementThreshold float64 `json:"objectCenterMovementThreshold"`
ObjectAreaThreshold float64 `json:"objectAreaThreshold"`
StreamDrawIgnoredAreas bool `json:"streamDrawIgnoredAreas"`
IgnoreAreasClasses []IgnoreAreaClass `json:"ignoreAreasClasses"`
EnableOutputStream bool `json:"enableOutputStream"`
OutputStreamAddr string `json:"outputStreamAddr"`
Motion struct {
OnnxModel string `json:"onnxModel"`
OnnxEnableCoreMl bool `json:"onnxEnableCoreMl"`
EmbeddedObjectScript string `json:"EmbeddedObjectScript"`
ConfidenceMinThreshold float64 `json:"confidenceMinThreshold"`
LookForClasses []string `json:"lookForClasses"`
NetworkObjectDetectServer string `json:"networkObjectDetectServer"`
EventGap int `json:"eventGap"`
PrebufferSeconds int `json:"prebufferSeconds"`
} `json:"motion"`
Video struct {
HiResPath string `json:"hiResPath"`
RecodeTsToMp4 bool `json:"recodeTsToMp4"`
OnlyRemuxMp4 bool `json:"onlyRemuxMp4"`
} `json:"video"`
Events struct {
Mqtt struct {
Host string `json:"host"`
Port int `json:"port"`
User string `json:"user"`
Pass string `json:"pass"`
Topic string `json:"topic"`
}
Slack struct {
Url string `json:"url"`
}
ScriptPath string `json:"scriptPath"`
Webhook string `json:"webhookUrl"`
} `json:"events"`
Notifications struct {
EnablePushoverAlerts bool `json:"enablePushoverAlerts"`
PushoverAppToken string `json:"pushoverAppToken"`
PushoverUserKey string `json:"pushoverUserKey"`
} `json:"notifications"`
}
type StreamParams struct {
Width int
Height int
FPS float64
}
type InferenceStats struct {
Avg float64
Min float64
Max float64
}
// TODO ADD MUTEX LOCK
type RuntimeConfig struct {
MotionTriggeredLast time.Time `json:"motionTriggredLast"`
MotionTriggered bool `json:"motionTriggered"`
// MotionTriggeredChan chan bool `json:"motionTriggeredChan"`
// MotionHiRecOn bool `json:"motionHiRecOn"`
HiResControlChannel chan RecordMsg
MotionVideo VideoMetadata
MotionMutex *sync.Mutex
TextFont *truetype.Font
LoResStreamParams StreamParams
HiResStreamParams StreamParams
objectPredictConn net.Conn
InferenceTimingBuffer []InferenceStats
modelReady bool
ObjectPredictClient *ob.Client
CodecName string
}
type IgnoreAreaClass struct {
Class []string `json:"class"`
Coordinates string `json:"coordinates"`
Top int `json:"top"`
Bottom int `json:"bottom"`
Left int `json:"left"`
Right int `json:"right"`
}
type ControlCommand struct {
StartRecording bool
Filename string
}
type TrackedObject struct {
BBox image.Rectangle
Center image.Point
Area float64
LastMoved time.Time
Class string
Confidence float32
}
type VideoMetadata struct {
ID string
MotionStart time.Time
MotionEnd time.Time
Objects []TrackedObject
RecodedToMp4 bool
Snapshots []string
VideoFile string
CameraName string
}
type Event struct {
Type string `json:"type"`
Timestamp time.Time `json:"timestamp"`
MotionTriggeredLast time.Time `json:"motionTriggeredLast"`
ID string `json:"id"`
MotionStart time.Time `json:"motionStart"`
MotionEnd time.Time `json:"motionEnd"`
Objects []TrackedObject `json:"objects"`
RecodedToMp4 bool `json:"recodedToMp4"`
Snapshots []string `json:"snapshots"`
VideoFile string `json:"videoFile"`
CameraName string `json:"cameraName"`
MetadataPath string `json:"metadataPath"`
PredictedObjects []Prediction `json:"predictedObjects"`
}
var lastPositions = []TrackedObject{}
var globalConfig Config
var runtimeConfig RuntimeConfig
var predictFrameCounter int
type Frame struct {
Data [][]byte
Pts time.Duration
}
type FrameMsg struct {
Frame image.Image
Error string
// Exited bool
ExitCode int
}
type StreamInfo struct {
Streams []struct {
Width int `json:"width"`
Height int `json:"height"`
CodecType string `json:"codec_type"`
CodecName string `json:"codec_name"`
RFrameRate float64 `json:"-"`
} `json:"streams"`
}
// RecordMsg struct to control recording
type RecordMsg struct {
Record bool
Filename string
}
func readConfig(path string) Config {
// Read the configuration file.
configFile, err := os.ReadFile(path)
if err != nil {
Log("error", fmt.Sprintf("Error reading config file: %v", err))
os.Exit(1)
}
// Parse the configuration file into a Config struct.
var config Config
err = json.Unmarshal(configFile, &config)
if err != nil {
Log("error", fmt.Sprintf("Error parsing config file: %v", err))
os.Exit(1)
}
// Split the coordinates string into separate integers.
for i, ignoreAreaClass := range config.IgnoreAreasClasses {
coords := strings.Split(ignoreAreaClass.Coordinates, ",")
if len(coords) == 4 {
config.IgnoreAreasClasses[i].Top, err = strconv.Atoi(coords[0])
if err != nil {
Log("error", fmt.Sprintf("Error parsing config file: %v", err))
os.Exit(1)
}
config.IgnoreAreasClasses[i].Bottom, err = strconv.Atoi(coords[1])
if err != nil {
Log("error", fmt.Sprintf("Error parsing config file: %v", err))
os.Exit(1)
}
config.IgnoreAreasClasses[i].Left, err = strconv.Atoi(coords[2])
if err != nil {
Log("error", fmt.Sprintf("Error parsing config file: %v", err))
os.Exit(1)
}
config.IgnoreAreasClasses[i].Right, err = strconv.Atoi(coords[3])
if err != nil {
Log("error", fmt.Sprintf("Error parsing config file: %v", err))
os.Exit(1)
}
} else {
Log("error", fmt.Sprintf("Error parsing config file: %v", errors.New("coordinates string must contain 4 comma separated integers")))
os.Exit(1)
}
}
if config.Motion.EmbeddedObjectScript == "" {
Log("error", fmt.Sprintf("Error parsing config file: %v", errors.New("embeddedObjectScript must be set")))
os.Exit(1)
}
if config.Motion.EmbeddedObjectScript != "objectDetectServerYolo.py" && config.Motion.EmbeddedObjectScript != "objectDetectServerCoral.py" && config.Motion.EmbeddedObjectScript != "objectDetectServerCoreML.py" {
Log("error", fmt.Sprintf("Error parsing config file: %v", errors.New("embeddedObjectScript must be either objectDetectServerYolo.py or objectDetectServerCoral.py")))
os.Exit(1)
}
// Print the configuration properties.
Log("info", "******************** CONFIG ********************")
Log("info", fmt.Sprintf("Print Debug: %t", config.PrintDebug))
Log("info", fmt.Sprintf("Device URL: %s", config.DeviceUrl))
Log("info", fmt.Sprintf("Lo-Res Param Bypass: Res: %dx%d FPS: %.2f", config.LoStreamParamBypass.Width, config.LoStreamParamBypass.Height, config.LoStreamParamBypass.FPS))
Log("info", fmt.Sprintf("Hi-Res Param Bypass: Res: %dx%d FPS: %.2f", config.HiStreamParamBypass.Width, config.HiStreamParamBypass.Height, config.HiStreamParamBypass.FPS))
Log("info", fmt.Sprintf("Hi-Res Device URL: %s", config.HiResDeviceUrl))
Log("info", fmt.Sprintf("Video HiResPath: %s", config.Video.HiResPath))
Log("info", fmt.Sprintf("Video RecodeTsToMp4: %t", config.Video.RecodeTsToMp4))
Log("info", fmt.Sprintf("Video OnlyRemuxMp4: %t", config.Video.OnlyRemuxMp4))
Log("info", fmt.Sprintf("Motion OnnxModel: %s", config.Motion.OnnxModel))
Log("info", fmt.Sprintf("Motion OnnxEnableCoreMl: %t", config.Motion.OnnxEnableCoreMl))
Log("info", fmt.Sprintf("Motion Embedded Object Script: %s", config.Motion.EmbeddedObjectScript))
Log("info", fmt.Sprintf("Motion Object Min Threshold: %f", config.Motion.ConfidenceMinThreshold))
Log("info", fmt.Sprintf("Motion LookForClasses: %v", config.Motion.LookForClasses))
Log("info", fmt.Sprintf("Motion Network Object Detect Server: %s", config.Motion.NetworkObjectDetectServer))
Log("info", fmt.Sprintf("Motion PrebufferSeconds: %d", config.Motion.PrebufferSeconds))
Log("info", fmt.Sprintf("Motion EventGap: %d", config.Motion.EventGap))
Log("info", fmt.Sprintf("Pixel Motion Area Threshold: %f", config.PixelMotionAreaThreshold))
Log("info", fmt.Sprintf("Object Center Movement Threshold: %f", config.ObjectCenterMovementThreshold))
Log("info", fmt.Sprintf("Object Area Threshold: %f", config.ObjectAreaThreshold))
Log("info", "Ignore Areas Classes:")
for _, ignoreAreaClass := range config.IgnoreAreasClasses {
Log("info", fmt.Sprintf(" Class: %v, Coordinates: %s", ignoreAreaClass.Class, ignoreAreaClass.Coordinates))
}
Log("info", fmt.Sprintf("Draw Ignored Areas: %t", config.StreamDrawIgnoredAreas))
Log("info", fmt.Sprintf("Enable Output Stream: %t", config.EnableOutputStream))
Log("info", fmt.Sprintf("Output Stream Address: %s", config.OutputStreamAddr))
Log("info", "************* EVENTS CONFIG *************")
Log("info", fmt.Sprintf("Events MQTT Host: %s", config.Events.Mqtt.Host))
Log("info", fmt.Sprintf("Events MQTT Port: %d", config.Events.Mqtt.Port))
Log("info", fmt.Sprintf("Events MQTT Topic: %s", config.Events.Mqtt.Topic))
Log("info", fmt.Sprintf("Events Slack URL: %s", config.Events.Slack.Url))
Log("info", fmt.Sprintf("Events Script Path: %s", config.Events.ScriptPath))
Log("info", fmt.Sprintf("Events Webhook URL: %s", config.Events.Webhook))
Log("info", "************************************************")
// Load font into runtime
fontBytes, err := assetsFs.ReadFile("assets/fonts/Changes.ttf")
if err != nil {
Log("error", fmt.Sprintf("Error reading font file: %v", err))
os.Exit(1)
}
font, err := freetype.ParseFont(fontBytes)
if err != nil {
Log("error", fmt.Sprintf("Error parsing font file: %v", err))
os.Exit(1)
}
runtimeConfig.TextFont = font
// Check if pushover tokens are provided if enabled
if config.Notifications.EnablePushoverAlerts {
if config.Notifications.PushoverAppToken == "" {
Log("error", fmt.Sprintf("Error parsing config file: %v", errors.New("pushoverAppToken must be set")))
os.Exit(1)
}
if config.Notifications.PushoverUserKey == "" {
Log("error", fmt.Sprintf("Error parsing config file: %v", errors.New("pushoverUserKey must be set")))
os.Exit(1)
}
}
return config
}
func eventHandler(eventType string, payload []byte) {
// Log the event type
// Log("event", fmt.Sprintf("Event: %s", eventType))
// Webhook URL
if globalConfig.Events.Webhook != "" {
resp, err := http.Post(globalConfig.Events.Webhook, "application/json", bytes.NewReader(payload))
if err != nil {
Log("error", fmt.Sprintf("Failed to post to webhook: %s", err))
} else {
defer resp.Body.Close()
}
}
// Script Path
if globalConfig.Events.ScriptPath != "" {
cmd := exec.Command(globalConfig.Events.ScriptPath)
stdin, err := cmd.StdinPipe()
if err != nil {
Log("error", fmt.Sprintf("Failed to get stdin pipe: %s", err))
return
}
go func() {
defer stdin.Close()
_, err := stdin.Write(payload)
if err != nil {
Log("error", fmt.Sprintf("Failed to write to stdin: %s", err))
}
}()
if err := cmd.Start(); err != nil {
Log("error", fmt.Sprintf("Failed to start script: %s", err))
}
}
// Send to Slack
if globalConfig.Events.Slack.Url != "" {
slackMessage := map[string]interface{}{
"text": fmt.Sprintf("Event: %s\nPayload: %s", eventType, string(payload)),
}
slackPayload, _ := json.Marshal(slackMessage)
resp, err := http.Post(globalConfig.Events.Slack.Url, "application/json", bytes.NewReader(slackPayload))
if err != nil {
Log("error", fmt.Sprintf("Failed to post to Slack: %s", err))
} else {
defer resp.Body.Close()
}
}
// Send to MQTT
if globalConfig.Events.Mqtt.Host != "" && globalConfig.Events.Mqtt.Port != 0 && globalConfig.Events.Mqtt.Topic != "" {
err := sendToMQTT(globalConfig.Events.Mqtt.Topic, string(payload), globalConfig.Events.Mqtt.Host, globalConfig.Events.Mqtt.Port, globalConfig.Events.Mqtt.User, globalConfig.Events.Mqtt.Pass)
if err != nil {
Log("error", fmt.Sprintf("Failed to send to MQTT: %s", err))
}
}
}
func Log(level, msg string) {
switch level {
case "info":
fmt.Printf("\x1b[32m%s [INFO] %s\x1b[0m\n", time.Now().Format("15:04:05"), msg)
case "notice":
fmt.Printf("\x1b[35m%s [NOTICE] %s\x1b[0m\n", time.Now().Format("15:04:05"), msg)
case "event":
fmt.Printf("\x1b[34m%s [EVENT] %s\x1b[0m\n", time.Now().Format("15:04:05"), msg)
case "error":
fmt.Printf("\x1b[31m%s [ERROR] %s\x1b[0m\n", time.Now().Format("15:04:05"), msg)
case "warning":
fmt.Printf("\x1b[33m%s [WARNING] %s\x1b[0m\n", time.Now().Format("15:04:05"), msg)
case "debug":
if globalConfig.PrintDebug {
fmt.Printf("\x1b[36m%s [DEBUG] %s\x1b[0m\n", time.Now().Format("15:04:05"), msg)
}
default:
fmt.Printf("%s [UNKNOWN] %s\n", time.Now().Format("15:04:05"), msg)
}
}
func getStreamInfo(rtspURL string) (StreamInfo, error) {
// Create a context that will time out
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "ffprobe", "-rtsp_transport", "tcp", "-v", "quiet", "-print_format", "json", "-show_streams", rtspURL)
output, err := cmd.Output()
if err != nil {
Log("debug", fmt.Sprintf("ffprobe output: %s", output))
return StreamInfo{}, err
}
Log("debug", fmt.Sprintf("ffprobe url: %s output: %s", rtspURL, output))
// Unmarshal into a temporary structure to get the raw frame rate
var rawInfo struct {
Streams []struct {
Width int `json:"width"`
Height int `json:"height"`
CodecType string `json:"codec_type"`
CodecName string `json:"codec_name"`
RFrameRate string `json:"r_frame_rate"`
} `json:"streams"`
}
if err := json.Unmarshal(output, &rawInfo); err != nil {
return StreamInfo{}, err
}
// Process the streams, converting the frame rate and filtering as needed
var info StreamInfo
for _, stream := range rawInfo.Streams {
if stream.Width == 0 || stream.Height == 0 {
continue // Skip streams with zero values
}
frParts := strings.Split(stream.RFrameRate, "/")
if len(frParts) == 2 {
numerator, err1 := strconv.Atoi(frParts[0])
denominator, err2 := strconv.Atoi(frParts[1])
if err1 != nil || err2 != nil || denominator == 0 {
return StreamInfo{}, fmt.Errorf("invalid frame rate: %s", stream.RFrameRate)
}
frameRate := float64(numerator) / float64(denominator) // Calculate FPS
info.Streams = append(info.Streams, struct {
Width int `json:"width"`
Height int `json:"height"`
CodecType string `json:"codec_type"`
CodecName string `json:"codec_name"`
RFrameRate float64 `json:"-"`
}{
Width: stream.Width,
Height: stream.Height,
CodecType: stream.CodecType,
CodecName: stream.CodecName,
RFrameRate: frameRate,
})
}
}
return info, nil
}
func CheckFFmpegAndFFprobe() (bool, error) {
if _, err := exec.LookPath("ffmpeg"); err != nil {
// Print PATH
path := os.Getenv("PATH")
Log("error", fmt.Sprintf("PATH: %s", path))
return false, fmt.Errorf("ffmpeg binary not found: %w", err)
}
if _, err := exec.LookPath("ffprobe"); err != nil {
// Print PATH
path := os.Getenv("PATH")
Log("error", fmt.Sprintf("PATH: %s", path))
return false, fmt.Errorf("ffprobe binary not found: %w", err)
}
return true, nil
}
func processRTSPFeed(rtspURL string, msgChannel chan<- FrameMsg) {
cmd := exec.Command(
"ffmpeg",
"-rtsp_transport", "tcp",
"-re",
"-i", rtspURL,
"-analyzeduration", "1000000",
"-probesize", "1000000",
"-vf", `select=not(mod(n\,5))`,
"-fps_mode", "vfr",
"-c:v", "png",
"-f", "image2pipe",
"-",
)
stderrBuffer := &bytes.Buffer{}
cmd.Stderr = stderrBuffer
pipe, err := cmd.StdoutPipe()
if err != nil {
msgChannel <- FrameMsg{Error: err.Error()}
return
}
defer pipe.Close()
err = cmd.Start()
if err != nil {
msgChannel <- FrameMsg{Error: err.Error()}
return
}
frameCount := 0
frameData := bytes.NewBuffer(nil)
isFrameStarted := false
buffer := make([]byte, 8192) // Buffer size
for {
n, err := pipe.Read(buffer)
if err == io.EOF {
break
} else if err != nil {
msgChannel <- FrameMsg{Error: err.Error()}
return
}
frameData.Write(buffer[:n])
if bytes.HasPrefix(frameData.Bytes(), []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}) {
isFrameStarted = true
}
if isFrameStarted && bytes.HasSuffix(frameData.Bytes(), []byte{0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82}) {
img, err := png.Decode(bytes.NewReader(frameData.Bytes()))
if err != nil {
msgChannel <- FrameMsg{Error: "Failed to decode PNG: " + err.Error()}
} else {
msgChannel <- FrameMsg{Frame: img}
}
frameCount++
frameData.Reset()
isFrameStarted = false
}
if frameData.Len() > 2*1024*1024 {
startIdx := bytes.Index(frameData.Bytes(), []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A})
if startIdx != -1 {
frameData.Next(startIdx)
isFrameStarted = true
} else {
frameData.Reset()
isFrameStarted = false
}
}
}
err = cmd.Wait()
exitCode := 0
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
exitCode = status.ExitStatus()
}
}
msgChannel <- FrameMsg{Error: "FFmpeg exited with error: " + err.Error(), ExitCode: exitCode}
}
if stderrBuffer.Len() > 0 {
msgChannel <- FrameMsg{Error: "FFmpeg STDERR: " + stderrBuffer.String()}
}
}
func recordRTSPStream(rtspURL string, controlChannel <-chan RecordMsg, prebufferDuration time.Duration) {
var file *os.File
recording := false
cmd := exec.Command("ffmpeg", "-rtsp_transport", "tcp", "-i", rtspURL, "-c", "copy", "-f", "mpegts", "pipe:1")
pipe, err := cmd.StdoutPipe()
if err != nil {
Log("error", fmt.Sprintf("Error creating pipe: %v", err))
return
}
err = cmd.Start()
if err != nil {
Log("error", fmt.Sprintf("Error starting ffmpeg: %v", err))
return
}
defer func() {
if recording && file != nil {
file.Close()
}
cmd.Wait()
}()
type chunkInfo struct {
Data []byte
Time time.Time
}
bufferSize := 4096
prebuffer := make([]chunkInfo, 0)
buffer := make([]byte, bufferSize)
for {
select {
case msg := <-controlChannel:
if msg.Record && !recording {
file, err = os.Create(msg.Filename)
if err != nil {
log.Fatal(err)
return
}
for _, chunk := range prebuffer { // Write prebuffered data
_, err := file.Write(chunk.Data)
if err != nil {
log.Fatal(err)
return
}
}
recording = true
} else if !msg.Record && recording {
file.Close()
recording = false
}
default:
n, err := pipe.Read(buffer)
if err != nil {
if err == io.EOF {
return
}
log.Fatal(err)
return
}
// Prebuffer handling
chunk := make([]byte, n)
copy(chunk, buffer[:n])
timestamp := time.Now()
prebuffer = append(prebuffer, chunkInfo{Data: chunk, Time: timestamp})
// Remove chunks that are older than prebufferDuration
for len(prebuffer) > 1 && timestamp.Sub(prebuffer[0].Time) > prebufferDuration {
prebuffer = prebuffer[1:]
}
if recording && file != nil {
_, err := file.Write(buffer[:n])
if err != nil {
log.Fatal(err)
return
}
}
}
}
}
func recodeToMP4(inputFile string) (string, error) {
// Check if the input file has a .ts extension
if !strings.HasSuffix(inputFile, ".ts") {
return "", fmt.Errorf("input file must have a .ts extension. Got: %s", inputFile)
}
// Remove the .ts extension and replace it with .mp4
outputFile := strings.TrimSuffix(inputFile, ".ts") + ".mp4"
var cmd *exec.Cmd
// Create the FFmpeg command
if globalConfig.Video.OnlyRemuxMp4 {
if runtimeConfig.CodecName == "hevc" {
cmd = exec.Command("ffmpeg", "-i", inputFile,
"-c:v", "copy",
"-c:a", "aac",
"-tag:v", "hvc1",
"-movflags", "+faststart",
"-hls_segment_type", "fmp4",
outputFile)
} else {
cmd = exec.Command("ffmpeg", "-i", inputFile, "-c", "copy", outputFile)
}
} else {
cmd = exec.Command("ffmpeg", "-i", inputFile, "-c:v", "libx264", "-c:a", "aac", outputFile)
}
// Capture the standard output and standard error
output, err := cmd.CombinedOutput()
if err != nil {
return "", fmt.Errorf("FFmpeg command failed: %v\n%s", err, output)
}
return outputFile, nil
}
func main() {
ptime := prettyTimer.NewTimingStats()
// Check if there is a config file argument, if there isnt give error and exit
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "Not enough arguments provided\n")
fmt.Println("Usage: firescrew [configfile]")
fmt.Println(" -t, --template, t\tPrints the template config to stdout")
fmt.Println(" -h, --help, h\t\tPrints this help message")
fmt.Println(" -s, --serve, s\tStarts the web server, requires: [path] [addr]")
return
}
switch os.Args[1] {
case "-t", "--template", "t":
// Dump template config to stdout
printTemplateFile()
return
case "-h", "--help", "h":
// Print help
fmt.Println("Usage: firescrew [configfile]")
fmt.Println(" -t, --template, t\tPrints the template config to stdout")
fmt.Println(" -h, --help, h\t\tPrints this help message")
fmt.Println(" -s, --serve, s\tStarts the web server, requires: [path] [addr]")
fmt.Println(" -v, --version, v\tPrints the version")
fmt.Println(" -update, --update, update\tUpdates firescrew to the latest version")
return
case "-s", "--serve", "s":
// This requires 2 more params, a path to files and an addr in form :8080
// Check if those params are provided if not give help message
if len(os.Args) < 4 {
fmt.Fprintf(os.Stderr, "Not enough arguments provided\n")
fmt.Fprintf(os.Stderr, ("Usage: firescrew -s [path] [addr]\n"))
return
}
err := firescrewServe.Serve(os.Args[2], os.Args[3])
if err != nil {
fmt.Fprintf(os.Stderr, "Error starting server: %v\n", err)
return
}
os.Exit(1)
case "-v", "--version", "v":
// Print version
fmt.Println(Version)
os.Exit(0)
case "-update", "--update", "update":
// Determine OS and ARCH
osRelease := runtime.GOOS
arch := runtime.GOARCH
// Build URL
e := tuna.SelfUpdate(fmt.Sprintf("https://github.com/8ff/firescrew/releases/download/latest/firescrew.%s.%s", osRelease, arch))
if e != nil {
fmt.Println(e)
os.Exit(1)
}
fmt.Println("Updated!")
os.Exit(0)
}
// Read the config file
globalConfig = readConfig(os.Args[1])
// Check if ffmpeg/ffprobe binaries are available
_, err := CheckFFmpegAndFFprobe()
if err != nil {
Log("error", fmt.Sprintf("Unable to find ffmpeg/ffprobe binaries. Please install them: %s", err))
os.Exit(2)
}
if globalConfig.LoStreamParamBypass.Width == 0 || globalConfig.LoStreamParamBypass.Height == 0 || globalConfig.LoStreamParamBypass.FPS == 0 {
// Print HI/LO stream details
hiResStreamInfo, err := getStreamInfo(globalConfig.HiResDeviceUrl)
if err != nil {
Log("error", fmt.Sprintf("Error getting stream info: ffprobe: %v", err))
os.Exit(3)
}
if len(hiResStreamInfo.Streams) == 0 {
Log("error", fmt.Sprintf("No HI res streams found at %s", globalConfig.HiResDeviceUrl))
os.Exit(3)
}
// Find stream with codec_type: video
streamIndex := -1
for index, stream := range hiResStreamInfo.Streams {
if stream.CodecType == "video" {
streamIndex = index
runtimeConfig.CodecName = stream.CodecName
if globalConfig.Video.OnlyRemuxMp4 {
if stream.CodecName != "h264" {
Log("warning", fmt.Sprintf("OnlyRemuxMp4 is enabled but the stream codec is not h264 or h265. Your videos may not play in WebUI. Codec: %s", stream.CodecName))
}
}
break
}
}
if streamIndex == -1 {
Log("error", fmt.Sprintf("No video stream found at %s", globalConfig.HiResDeviceUrl))
os.Exit(3)
}
runtimeConfig.HiResStreamParams = StreamParams{
Width: hiResStreamInfo.Streams[streamIndex].Width,
Height: hiResStreamInfo.Streams[streamIndex].Height,
FPS: hiResStreamInfo.Streams[streamIndex].RFrameRate,
}
} else {
runtimeConfig.HiResStreamParams = globalConfig.HiStreamParamBypass
}
if globalConfig.LoStreamParamBypass.Width == 0 || globalConfig.LoStreamParamBypass.Height == 0 || globalConfig.LoStreamParamBypass.FPS == 0 {
loResStreamInfo, err := getStreamInfo(globalConfig.DeviceUrl)
if err != nil {
Log("error", fmt.Sprintf("Error getting stream info: %v", err))
os.Exit(3)
}
if len(loResStreamInfo.Streams) == 0 {
Log("error", fmt.Sprintf("No LO res streams found at %s", globalConfig.DeviceUrl))
os.Exit(3)
}
// Find stream with codec_type: video
streamIndex := -1
for index, stream := range loResStreamInfo.Streams {
if stream.CodecType == "video" {
streamIndex = index
break
}
}
if streamIndex == -1 {
Log("error", fmt.Sprintf("No video stream found at %s", globalConfig.DeviceUrl))
os.Exit(3)
}
runtimeConfig.LoResStreamParams = StreamParams{
Width: loResStreamInfo.Streams[streamIndex].Width,
Height: loResStreamInfo.Streams[streamIndex].Height,
FPS: loResStreamInfo.Streams[streamIndex].RFrameRate,
}
} else {
runtimeConfig.LoResStreamParams = globalConfig.LoStreamParamBypass
}
// Print stream info from runtimeConfig
Log("info", "******************** STREAM INFO ********************")
Log("info", fmt.Sprintf("Lo-Res Stream Resolution: %dx%d FPS: %.2f", runtimeConfig.LoResStreamParams.Width, runtimeConfig.LoResStreamParams.Height, runtimeConfig.LoResStreamParams.FPS))
Log("info", fmt.Sprintf("Hi-Res Stream Resolution: %dx%d FPS: %.2f", runtimeConfig.HiResStreamParams.Width, runtimeConfig.HiResStreamParams.Height, runtimeConfig.HiResStreamParams.FPS))
Log("info", "*****************************************************")
// Define motion mutex
runtimeConfig.MotionMutex = &sync.Mutex{}
// Copy assets to local filesystem
path := copyAssetsToTemp()
// Start the object detector
if globalConfig.Motion.OnnxModel != "" {
var err error
runtimeConfig.ObjectPredictClient, err = ob.Init(ob.Config{Model: "yolov8n", EnableCoreMl: globalConfig.Motion.OnnxEnableCoreMl})
if err != nil {
fmt.Println("Cannot init model:", err)
return
}
defer runtimeConfig.ObjectPredictClient.Close() // Cleanup files
} else {
if globalConfig.Motion.NetworkObjectDetectServer == "" {
globalConfig.Motion.NetworkObjectDetectServer = "127.0.0.1:8555"
go startObjectDetector(path + "/" + globalConfig.Motion.EmbeddedObjectScript)
// Set networkObjectDetectServer path to 127.0.0.1:8555
// time.Sleep(10 * time.Second) // Give time to kill old instance if still running
// Wait until tcp connection is works to globalConfig.Motion.NetworkObjectDetectServer
Log("info", "Waiting for object detector to come up")
if !runtimeConfig.modelReady {
for {
conn, err := net.DialTimeout("tcp", globalConfig.Motion.NetworkObjectDetectServer, 1*time.Second)
if err != nil {
Log("warning", fmt.Sprintf("Waiting for object detector to start: %v", err))
time.Sleep(1 * time.Second)
} else {
conn.Close()
break
}
}
}
} else {
Log("info", fmt.Sprintf("Checking connection to: %s", globalConfig.Motion.NetworkObjectDetectServer))
for {
conn, err := net.DialTimeout("tcp", globalConfig.Motion.NetworkObjectDetectServer, 1*time.Second)
if err != nil {
Log("warning", fmt.Sprintf("Waiting for %s to respond: %v", globalConfig.Motion.NetworkObjectDetectServer, err))
time.Sleep(1 * time.Second)
} else {
conn.Close()
break
}
}
}
}
stream = mjpeg.NewStream()
if globalConfig.EnableOutputStream {
go startWebcamStream(stream)
}
// Define the last image
imgLast := image.NewRGBA(image.Rect(0, 0, runtimeConfig.HiResStreamParams.Width, runtimeConfig.HiResStreamParams.Height))
// Start HI Res prebuffering
runtimeConfig.HiResControlChannel = make(chan RecordMsg)
go func() {
for {
recordRTSPStream(globalConfig.HiResDeviceUrl, runtimeConfig.HiResControlChannel, time.Duration(globalConfig.Motion.PrebufferSeconds)*time.Second)
// defer close(runtimeConfig.HiResControlChannel)
time.Sleep(5 * time.Second)
Log("warning", "Restarting HI RTSP feed")
}
}()
frameChannel := make(chan FrameMsg)
go func(frameChannel chan FrameMsg) {
for {
processRTSPFeed(globalConfig.DeviceUrl, frameChannel)
// Log("warning", "EXITED")
//*********** EXITS BELOW ***********//
time.Sleep(5 * time.Second)
Log("warning", "Restarting LO RTSP feed")
}
}(frameChannel)
// go dumpRtspFrames(globalConfig.DeviceUrl, "/Volumes/RAMDisk/", 4) // 1 means mod every nTh frame
// go readFramesFromRam(frameChannel, "/Volumes/RAMDisk/")
for msg := range frameChannel {
if msg.Error != "" {
Log("error", msg.Error)
continue
}
if msg.Frame != nil {
ptime.Start() // DEBUG TIMER
rgba, ok := msg.Frame.(*image.RGBA)
if !ok {
// Convert to RGBA if it's not already
rgba = image.NewRGBA(msg.Frame.Bounds())
draw.Draw(rgba, rgba.Bounds(), msg.Frame, msg.Frame.Bounds().Min, draw.Src)
}
// Handle all motion stuff here
if runtimeConfig.MotionTriggered || (!runtimeConfig.MotionTriggered && CountChangedPixels(rgba, imgLast, uint8(30)) > int(globalConfig.PixelMotionAreaThreshold)) { // Use short-circuit to bypass pixel count if event is already triggered, otherwise we may not be able to identify all objects if motion is triggered
// If its been more than globalConfig.Motion.EventGap seconds since the last motion event, untrigger
if runtimeConfig.MotionTriggered && time.Since(runtimeConfig.MotionTriggeredLast) > time.Duration(globalConfig.Motion.EventGap)*time.Second {
go endMotionEvent() // End the motion event
}
// Only run this on every Nth frame
if predictFrameCounter%everyNthFrame == 0 {
if predictFrameCounter > 10000 {
predictFrameCounter = 0