-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstreamtofile.go
76 lines (68 loc) · 1.52 KB
/
streamtofile.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
package camtron
import (
"log"
"os"
"time"
)
var filePath = "./videos/"
var fileName string = filePath + "vid-" + time.Now().Format("2006_01_02_15_04_05") + ".webm"
var maxSize int = 1000000000
func StreamToFile(vidStream chan []byte) {
if _, err := os.Stat("videos"); err != nil {
if os.IsNotExist(err) {
os.Mkdir("videos", os.ModePerm)
}
}
var data []byte
for {
select {
case packet, ok := <-vidStream:
if !ok {
log.Print("WARNING: Failed to get packet")
}
if len(data) > 1000 {
if !writeVideoToFile(fileName, data, maxSize) {
return
}
data = nil
}
data = append(data, packet...)
case val, _ := <-Context:
log.Println("got signal " + val)
if val == "stop" {
writeVideoToFile(fileName, data, maxSize)
close(vidStream)
log.Println("INFO: Shutting stream to file")
data = nil
return
}
}
}
}
func writeVideoToFile(fileName string, video []byte, maxSize int) bool {
vidFile, fileOpenErr := os.OpenFile(fileName,
os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if fileOpenErr != nil {
log.Println(fileOpenErr)
}
defer vidFile.Close()
fileStat, statErr := vidFile.Stat()
if statErr != nil {
log.Println(statErr)
}
if fileStat.Size() > int64(maxSize) {
log.Println("Maximum file size reached")
return false
}
_, writeErr := vidFile.Write(video)
if writeErr != nil {
log.Println(writeErr)
return false
}
return true
}
func StartStreamToFileConsumer() {
vidStream := make(chan []byte, 10)
RegisterStream(vidStream)
go StreamToFile(vidStream)
}