-
Notifications
You must be signed in to change notification settings - Fork 0
/
write.go
110 lines (84 loc) · 1.73 KB
/
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package midi
import (
"bytes"
"encoding/binary"
"io"
)
func writeVariableLengthInteger(value uint32) []byte {
data := []byte{}
// Start xor with 0 byte
xor := byte(0x0)
for {
// Get first 7 bits
b := byte(value & 0x7F)
// Xor with current xor
b ^= xor
// Set xor to 0x80 = 10000000 in bits
xor = byte(0x80)
// Push byte to front
data = append([]byte{b}, data...)
// Shift to next 7 bits
value >>= 7
// Stop if value is zero
if value == 0 {
break
}
}
return data
}
// Chunk from file header
func (h *FileHeader) Chunk() *Chunk {
bytes := make([]byte, 6)
binary.BigEndian.PutUint16(bytes, uint16(h.Format))
binary.BigEndian.PutUint16(bytes[2:], h.NumTracks)
binary.BigEndian.PutUint16(bytes[4:], h.Division)
return &Chunk{
Type: HeaderType,
Length: uint32(6),
Data: bytes,
}
}
// Chunk from track
func (t *Track) Chunk() *Chunk {
var buf bytes.Buffer
for _, event := range t.Events {
event.WriteTo(&buf)
}
data := buf.Bytes()
return &Chunk{
Type: TrackType,
Length: uint32(len(data)),
Data: data,
}
}
// WriteTo writes a chunk to writer
func (c *Chunk) WriteTo(w io.Writer) (int64, error) {
// Length needs to be written as big endian
b := make([]byte, 4)
binary.BigEndian.PutUint32(b, c.Length)
n1, err := w.Write([]byte(c.Type))
if err != nil {
return 0, err
}
n2, err := w.Write(b)
if err != nil {
return 0, err
}
n3, err := w.Write(c.Data)
if err != nil {
return 0, err
}
return int64(n1) + int64(n2) + int64(n3), nil
}
// WriteTo writes a file to writer
func (mf *File) WriteTo(w io.Writer) (int64, error) {
var n int64
for _, chunk := range mf.Chunks {
nb, err := chunk.WriteTo(w)
if err != nil {
return 0, nil
}
n += nb
}
return n, nil
}