-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecode.go
77 lines (66 loc) · 1.77 KB
/
decode.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
package go_m3u8
import (
"bufio"
"fmt"
"io"
"strings"
"unicode"
pl "github.com/globocom/go-m3u8/playlist"
"github.com/globocom/go-m3u8/tags"
"github.com/globocom/go-m3u8/tags/others"
"github.com/rs/zerolog/log"
)
type Source interface {
io.ReadCloser
}
func ParsePlaylist(src Source) (*pl.Playlist, error) {
playlist := pl.NewPlaylist()
scanner := bufio.NewScanner(src)
defer func() {
if err := src.Close(); err != nil {
log.Error().Err(err).Msg("error scanning playlist file")
}
}()
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
linePrefix := extractPrefix(line)
parser, exists := tags.Parsers[linePrefix]
if exists {
if err := parser.Parse(line, playlist); err != nil {
return nil, fmt.Errorf("error parsing tag %s: %w", linePrefix, err)
}
} else {
if err := pl.HandleMultiLineHLSElements(line, playlist); err != nil {
return nil, fmt.Errorf("error handling multi-line HLS element %q: %w", line, err)
}
}
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("failed to parse playlist at line: %q, error: %w", scanner.Text(), err)
}
return playlist, nil
}
// Lines that start with the character '#' are either comments or tags.
// Tags begin with #EXT. They are case sensitive. All other lines that begin with '#' are comments and SHOULD be ignored.
func extractPrefix(line string) string {
// check for blank lines
if line == "" {
return ""
}
// check for comments
isComment, err := others.CommentLineRegex.MatchString(line)
if err != nil {
log.Error().Err(err).Msgf("failed to parse line: %s", line)
return ""
}
if isComment {
return others.CommentLineTag
}
// check for tags and uri
for i, r := range line {
if r == ':' || unicode.IsSpace(r) {
return line[:i]
}
}
return line
}