-
Notifications
You must be signed in to change notification settings - Fork 1
/
hls.go
112 lines (109 loc) · 2.56 KB
/
hls.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
package rosso
import (
"154.pages.dev/encoding/hls"
"154.pages.dev/log"
"io"
"net/http"
"os"
"text/template"
)
func (h HttpStream) HLS(master hls.MasterPlaylist, index int) error {
variant, ok := master.Index(index)
if !ok {
line, err := new(template.Template).Parse(hls.ModeLine)
if err != nil {
return err
}
return line.Execute(os.Stdout, master)
}
var segment hls.MediaSegment
req, err := http.NewRequest("", variant.URI, nil)
if err != nil {
return err
}
req.URL = h.Base.ResolveReference(req.URL)
err = func() error {
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
text, err := io.ReadAll(res.Body)
if err != nil {
return err
}
segment.New(string(text))
return nil
}()
if err != nil {
return err
}
var mode hls.BlockMode
err = func() error {
res, err := http.Get(segment.Key.URI)
if err != nil {
return err
}
defer res.Body.Close()
key, err := io.ReadAll(res.Body)
if err != nil {
return err
}
return mode.New(key)
}()
if err != nil {
return err
}
file, err := os.Create(Name(h.Name) + variant.Ext())
if err != nil {
return err
}
defer file.Close()
log.TransportDebug()
defer log.TransportInfo()
var meter log.ProgressMeter
meter.Set(len(segment.URI))
for _, uri := range segment.URI {
// with HLS, the segment URL is relative to the master URL, and the
// fragment URL is relative to the segment URL.
req.URL, err = req.URL.Parse(uri)
if err != nil {
return err
}
err := func() error {
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
data, err := io.ReadAll(meter.Reader(res))
if err != nil {
return err
}
data = mode.Decrypt(data)
if _, err := file.Write(data); err != nil {
return err
}
return nil
}()
if err != nil {
return err
}
}
return nil
}
func (h *HttpStream) HlsMaster(uri string) (hls.MasterPlaylist, error) {
res, err := http.Get(uri)
if err != nil {
return nil, err
}
defer res.Body.Close()
h.Base = res.Request.URL
text, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
var master hls.MasterPlaylist
master.New(string(text))
return master, nil
}