-
Notifications
You must be signed in to change notification settings - Fork 87
/
http_playlists.go
78 lines (67 loc) · 1.93 KB
/
http_playlists.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
package hls
import (
"fmt"
"github.com/shimberger/gohls/fileindex"
log "github.com/sirupsen/logrus"
"net/http"
"net/url"
)
// Encodes a string like Javascript's encodeURIComponent()
func urlEncoded(str string) (string, error) {
u, err := url.Parse(str)
if err != nil {
return "", err
}
return u.String(), nil
}
type PlaylistHandler struct {
idx fileindex.Index
rootUri string
segmentsPath string
}
func NewPlaylistHandler(idx fileindex.Index, rootUri string, segmentsPath string) *PlaylistHandler {
return &PlaylistHandler{idx, rootUri, segmentsPath}
}
func (s *PlaylistHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Debugf("Playlist request: %v", r.URL.Path)
s.idx.WaitForReady()
entry, err := s.idx.Get(r.URL.Path)
if err != nil {
ServeJson(404, err, w)
return
}
file := entry.Path()
vinfo, err := GetVideoInformation(file)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
duration := vinfo.Duration
baseurl := fmt.Sprintf("http://%v", r.Host)
id, err := urlEncoded(r.URL.Path)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header()["Content-Type"] = []string{"application/vnd.apple.mpegurl"}
w.Header()["Access-Control-Allow-Origin"] = []string{"*"}
fmt.Fprint(w, "#EXTM3U\n")
fmt.Fprint(w, "#EXT-X-VERSION:3\n")
fmt.Fprint(w, "#EXT-X-MEDIA-SEQUENCE:0\n")
fmt.Fprint(w, "#EXT-X-ALLOW-CACHE:YES\n")
fmt.Fprint(w, "#EXT-X-TARGETDURATION:"+fmt.Sprintf("%.f", hlsSegmentLength)+"\n")
fmt.Fprint(w, "#EXT-X-PLAYLIST-TYPE:VOD\n")
leftover := duration
segmentIndex := 0
for leftover > 0 {
if leftover > hlsSegmentLength {
fmt.Fprintf(w, "#EXTINF: %f,\n", hlsSegmentLength)
} else {
fmt.Fprintf(w, "#EXTINF: %f,\n", leftover)
}
fmt.Fprintf(w, baseurl+s.segmentsPath+"%v/%v.ts\n", id, segmentIndex)
segmentIndex++
leftover = leftover - hlsSegmentLength
}
fmt.Fprint(w, "#EXT-X-ENDLIST\n")
}