-
Notifications
You must be signed in to change notification settings - Fork 3
/
text.go
296 lines (256 loc) · 6.81 KB
/
text.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package beatnik
// Parser of text format.
import (
"fmt"
"regexp"
"strconv"
"strings"
)
var (
hitToken = regexp.MustCompile("^\\(?([0-9A-Z]+(?:\\+*|-*)" +
"(?:,[0-9A-Z]+(?:\\+*|-*))*)((?:\\.*|~*)>?)\\)?$")
noteToken = regexp.MustCompile("^([0-9A-Z]+)(\\+*|-*)$")
waitToken = regexp.MustCompile("^(?:\\.*|~*)>?$")
directiveToken = regexp.MustCompile("^([^:]+):(.*)$")
tokenizer = regexp.MustCompile("(?m)\\s+")
comment = regexp.MustCompile("#[^\n]*")
// Maps +- notation to actual velocities.
velocities = map[string]Velocity{
"-----": PPP,
"----": PP,
"---": P,
"--": MP,
"-": MF,
"": F,
"+": FF,
"++": FFF,
}
// Maps notation to note duration in ticks.
durations = map[string]uint{
"~~": 96 * 4,
"~": 96 * 2,
"": 96,
".": 96 / 2,
"..": 96 / 4,
"...": 96 / 8,
"....": 96 / 16,
".....": 96 / 32,
}
// Maps kit name to the kit.
kits = map[string]map[string]byte{
"windows": windowsSynth,
"ezdrummer2": ezDrummer2,
}
// Maps directive name (in text syntax) to its handler.
directives = map[string]directive{
"bpm": setBPM,
"kit": setKit,
"loop": addLoop,
}
)
func init() {
// Add triplets to durations.
for d := range durations {
durations[d+">"] = durations[d] * 2 / 3
}
}
// trackBuilder is a track with metadata for building.
type trackBuilder struct {
Track
kit drumKit
loops []*loop // A stack of loops.
}
// newTrackBuilder returns a new builder with default parameters.
func newTrackBuilder() *trackBuilder {
t := &trackBuilder{}
setKit(t, "windows")
return t
}
// ParseTrack parses hit notations separated by whitespaces.
func ParseTrack(s string) (*Track, error) {
t := newTrackBuilder()
for i, token := range tokenize(s) {
switch {
case hitToken.MatchString(token):
if halfParenthesized(token) {
return nil, fmt.Errorf(
"token #%v: grace notes should have parenthesis on both sides", i)
}
// Check for grace.
grace := false
if parenthesized(token) {
grace = true
token = token[1 : len(token)-1]
}
// Parse hit.
h, err := t.parseHit(token)
if err != nil {
return nil, fmt.Errorf("token #%v: %v", i, err)
}
if grace {
// Shorten last hit.
if len(t.Hits) > 0 {
last := t.Hits[len(t.Hits)-1]
if last.T <= h.T {
return nil, fmt.Errorf("token #%v: grace note is too long: "+
"%v ticks, should be less than %v",
i, h.T, last.T)
}
last.T -= h.T
}
}
t.Hits = append(t.Hits, h)
case waitToken.MatchString(token):
d := durations[token]
if d == 0 {
return nil, fmt.Errorf("token #%v: bad duration: %q", i+1, token)
}
if len(t.Hits) == 0 {
return nil, fmt.Errorf("token #%v: duration with no preceding note", i+1)
}
t.Hits[len(t.Hits)-1].T += d
case directiveToken.MatchString(token):
if err := t.parseDirective(token); err != nil {
return nil, fmt.Errorf("token #%v: %v", i, err)
}
default:
return nil, fmt.Errorf("token #%v: unrecognized token: %q", i+1, token)
}
}
if len(t.loops) > 0 {
return nil, fmt.Errorf("track has %v unended loops", len(t.loops))
}
return &t.Track, nil
}
// tokenize extracts tokens from a text and returns them in a slice.
// Comments are removed.
func tokenize(s string) []string {
s = comment.ReplaceAllString(s, "")
var result []string
for _, t := range tokenizer.Split(s, -1) {
if t == "" {
continue
}
result = append(result, t)
}
return result
}
// parseHit parses a single hit token and returns the constructed hit.
func (t *trackBuilder) parseHit(s string) (*Hit, error) {
m := hitToken.FindStringSubmatch(s)
if m == nil {
return nil, fmt.Errorf("bad hit: %q", s)
}
notes, err := t.parseNotes(m[1])
if err != nil {
return nil, err
}
d := durations[m[2]]
if d == 0 {
return nil, fmt.Errorf("bad duration: %q", m[2])
}
return &Hit{notes, d}, nil
}
// parseNotes parses the notes section of a hit token.
func (t *trackBuilder) parseNotes(s string) (map[byte]Velocity, error) {
notes := map[byte]Velocity{}
for _, part := range strings.Split(s, ",") {
m := noteToken.FindStringSubmatch(part)
if m == nil {
return nil, fmt.Errorf("bad note token: %q", part)
}
note, v := t.kit[m[1]], velocities[m[2]]
if note == 0 {
return nil, fmt.Errorf("bad drum number: %q", m[1])
}
if v == 0 {
return nil, fmt.Errorf("bad velocity: %q", m[2])
}
notes[note] = v
}
return notes, nil
}
// parenthesized returns true if s starts and ends with parenthesis.
func parenthesized(s string) bool {
return len(s) > 0 && s[0] == '(' && s[len(s)-1] == ')'
}
// halfParenthesized returns true if s only starts or only ends with parenthesis.
func halfParenthesized(s string) bool {
return len(s) > 0 &&
((s[0] == '(' && s[len(s)-1] != ')') ||
(s[0] != '(' && s[len(s)-1] == ')'))
}
// ----- DIRECTIVES ------------------------------------------------------------
// A directive is a function that alters the track itself.
type directive func(*trackBuilder, string) error
// parseDirective parses a directive token and runs it.
func (t *trackBuilder) parseDirective(s string) error {
m := directiveToken.FindStringSubmatch(s)
if m == nil {
return fmt.Errorf("bad directive: %q", s)
}
d := directives[m[1]]
if d == nil {
return fmt.Errorf("unknown directive: %q", m[1])
}
return d(t, m[2])
}
// setBPM changes a track's bpm.
func setBPM(t *trackBuilder, s string) error {
bpm, err := strconv.Atoi(s)
if err != nil {
return fmt.Errorf("bad input to BPM: %v", err)
}
if bpm < 1 || bpm > 500 {
return fmt.Errorf("bad BPM: %v, must be between 1 and 500", bpm)
}
t.BPM = uint(bpm)
return nil
}
func setKit(t *trackBuilder, s string) error {
kit, ok := kits[s]
if !ok {
return fmt.Errorf("unrecognized drum kit: %s", s)
}
// Initialize kit with mapping from string to byte ("38": byte(38)).
t.kit = drumKit{}
byteMax := int(^byte(0))
for i := 1; i <= byteMax; i++ {
t.kit[fmt.Sprint(i)] = byte(i)
}
for k, v := range kit {
t.kit[k] = v
}
return nil
}
// A loop represents an unended loop during parsing.
type loop struct {
start int // Index of first hit in the loop.
n int // Number of repetitions.
}
// addLoop handles a loop directive.
func addLoop(t *trackBuilder, s string) error {
if s != "end" {
n, err := strconv.Atoi(s)
if err != nil || n <= 0 {
return fmt.Errorf("bad input to loop: %v, should be a positive "+
"number or end", err)
}
t.loops = append(t.loops, &loop{len(t.Hits), n})
return nil
}
// s == "end"
if len(t.loops) == 0 {
return fmt.Errorf("loop end without loop start")
}
lp := t.loops[len(t.loops)-1]
t.loops = t.loops[:len(t.loops)-1] // Pop last loop.
rep := t.Hits[lp.start:]
// Up to n-1 because the first repetition is already written.
for i := 0; i < lp.n-1; i++ {
for _, hit := range rep {
t.Hits = append(t.Hits, hit.copy())
}
}
return nil
}