-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
80 lines (69 loc) · 1.59 KB
/
main.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
package main
import (
"log"
"net/http"
"os"
"runtime"
"strings"
"time"
"github.com/9glt/go-signals"
)
var (
ffmpeg = &FFmpeg{}
)
func getFullPath() string {
return os.Getenv("APP_ROOT") + "/" + os.Getenv("APP_NAME")
}
func resetFFMPEG() {
input := `-xerror -nostats -nostdin -i {url} -codec copy -map 0:0 -map 0:1 -map_metadata 0 -hls_flags delete_segments -hls_time 10 -segment_list_size 6 -hls_segment_filename file%07d.ts stream.m3u8`
input = strings.ReplaceAll(input, "{url}", os.Args[1])
argz := strings.Split(input, " ")
ffmpeg = New(argz, getFullPath())
}
func main() {
if len(os.Args) < 2 {
log.Fatal("URL is required")
}
if len(os.Args) > 1 && os.Args[1] == "" {
log.Fatal("URL is required")
}
if os.Getenv("APP_ROOT") == "" {
log.Fatal("Output ROOT is required")
}
if os.Getenv("APP_NAME") == "" {
log.Fatal("Name is required")
}
os.MkdirAll(getFullPath(), 0777)
resetFFMPEG()
go func() {
for {
time.Sleep(5 * time.Second)
if ffmpeg.running {
if ffmpeg.HitExpired() {
ffmpeg.Stop()
ffmpeg.Wait()
resetFFMPEG()
}
}
}
}()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// log.Printf("Request: %s", r.URL.RequestURI())
if strings.Contains(r.URL.Path, "stream.m3u8") {
if ffmpeg.Start() != nil {
time.Sleep(3 * time.Second)
}
}
ffmpeg.Hit()
w.Header().Add("Expires", "0")
http.FileServer(http.Dir(getFullPath())).ServeHTTP(w, r)
})
signals.INT(func() {
if ffmpeg.running {
ffmpeg.Stop()
}
os.Exit(1)
})
log.Fatal(http.ListenAndServe(os.Getenv("APP_BIND"), nil))
runtime.Goexit()
}