forked from zencoder/go-dash
/
mpd_read_write.go
87 lines (78 loc) · 1.73 KB
/
mpd_read_write.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
package mpd
import (
"bufio"
"bytes"
"encoding/xml"
"io"
"os"
)
// Reads an MPD XML file from disk into a MPD object.
// path - File path to an MPD on disk
func ReadFromFile(path string) (*MPD, error) {
f, err := os.OpenFile(path, os.O_RDONLY, 0666)
if err != nil {
return nil, err
}
defer f.Close()
return Read(f)
}
// Reads a string into a MPD object.
// xmlStr - MPD manifest data as a string.
func ReadFromString(xmlStr string) (*MPD, error) {
b := bytes.NewBufferString(xmlStr)
return Read(b)
}
// Reads from an io.Reader interface into an MPD object.
// r - Must implement the io.Reader interface.
func Read(r io.Reader) (*MPD, error) {
var mpd MPD
d := xml.NewDecoder(r)
err := d.Decode(&mpd)
if err != nil {
return nil, err
}
return &mpd, nil
}
// Writes an MPD object to a file on disk.
// path - Output path to write the manifest to.
func (m *MPD) WriteToFile(path string) error {
// Open the file to write the XML to
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
return err
}
defer f.Close()
if err = m.Write(f); err != nil {
return err
}
if err = f.Sync(); err != nil {
return err
}
return err
}
// Writes an MPD object to a string.
func (m *MPD) WriteToString() (string, error) {
var b bytes.Buffer
w := bufio.NewWriter(&b)
err := m.Write(w)
if err != nil {
return "", err
}
err = w.Flush()
if err != nil {
return "", err
}
return b.String(), err
}
// Writes an MPD object to an io.Writer interface
// w - Must implement the io.Writer interface.
func (m *MPD) Write(w io.Writer) error {
b, err := xml.MarshalIndent(m, "", " ")
if err != nil {
return err
}
_, _ = w.Write([]byte(xml.Header))
_, _ = w.Write(b)
_, _ = w.Write([]byte("\n"))
return nil
}