-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtable.go
383 lines (322 loc) · 9.45 KB
/
table.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package stereophonic
import (
"errors"
"fmt"
"math"
"math/rand"
"sync"
"time"
"github.com/mkb218/gosndfile/sndfile"
)
// A table represents audio frame data, and associated important
// playback data (channels, samplerate, fileName)
// It's used to hold single-cycle waveforms or whole files.
// NB. this struct holds an *entire* sound file's audio data in memory.
// Perhaps it's not efficient, but memory is cheap boy!
// tables are essentially immutable after creation.
type table struct {
name string
channels int
sampleRate float64 // <--- float64 for convenience
samples []float64 // interleaved
nFrames int
sync.Mutex // lock when mutating the samples
}
// force immutability by disallowing setters
func (b *table) Name() string {
return b.name
}
func (b *table) Channels() int {
return b.channels
}
func (b *table) SampleRate() float64 {
return b.sampleRate
}
func (b *table) NFrames() int {
return b.nFrames
}
// create a new table from a sound file
// (most common use case for table)
func newTable(soundFileName string) (*table, error) {
b := &table{}
err := b.loadFile(soundFileName)
if err != nil {
return nil, err
}
return b, nil
}
// create a new table and fill it with a single cycle waveform
func newTableSine(frequency, phase, sampleRate float64) (*table, error) {
b := &table{}
err := b.loadSine(frequency, phase, sampleRate)
if err != nil {
return nil, err
}
return b, nil
}
// create a new table and fill it with a single cycle waveform
func newTableSaw(frequency, phase, sampleRate float64) (*table, error) {
b := &table{}
err := b.loadSaw(frequency, phase, sampleRate)
if err != nil {
return nil, err
}
return b, nil
}
// create a new table and fill it with a single cycle waveform
func newTableSquare(frequency, phase, sampleRate float64) (*table, error) {
b := &table{}
err := b.loadSquare(frequency, phase, sampleRate)
if err != nil {
return nil, err
}
return b, nil
}
// create a new table and fill it with noise of a certain duration in seconds
func newTableWhiteNoise(duration, sampleRate float64) (*table, error) {
b := &table{}
err := b.loadWhiteNoise(duration, sampleRate)
if err != nil {
return nil, err
}
return b, nil
}
// create a new table and fill it with an impulse train
func newTableImpulseTrain(frequency, phase, sampleRate float64) (*table, error) {
b := &table{}
err := b.loadImpulseTrain(frequency, phase, sampleRate)
if err != nil {
return nil, err
}
return b, nil
}
// fill a table with a sound file's samples
func (b *table) loadFile(soundFileName string) error {
var info sndfile.Info
// try to open the sound file
sf, err := sndfile.Open(soundFileName, sndfile.Read, &info)
if err != nil {
return err
}
defer sf.Close()
// create a buffer to read our sound file's frames into
// NB. the returned buffer of frame data
// contains samples that are *interleaved*
// ie. a stereo sound file is represented as a
// 1 dimensional array where left/right pairs of samples
// are located at index n, n+1 respectively
n := int64(sf.Format.Channels) * sf.Format.Frames
samples := make([]float64, n)
// try to read the (entire) soundfile in 1 go
framesRead, err := sf.ReadFrames(samples)
if err != nil {
return err
}
// lock self temporarily as we update it
b.Lock()
defer b.Unlock()
// modify self
b.name = soundFileName
b.channels = int(sf.Format.Channels)
b.sampleRate = float64(sf.Format.Samplerate)
b.samples = samples
b.nFrames = int(framesRead)
// return without error
return nil
}
// clamp phase
// make sure phase is in range [0, 1)
// else wrap around into the proper range
func clampPhase(phase float64) float64 {
if phase < 0 {
phase = math.Abs(phase)
}
if phase >= 1.0 {
phase = phase - math.Floor(phase)
}
return phase
}
// creates a mono buffer of audio suitable for holding a single
// cycle waveform given a certain frequency and sampleRate
// NB. this doesn't actually populate the buffer with a waveform, it
// only creates it
func createSingleCycle(frequency, sampleRate float64) []float64 {
var n int
switch frequency {
case 0.0:
n = 1 // dc offset
default:
n = int(math.Abs(sampleRate / frequency))
}
return make([]float64, n)
}
// generates a single cycle sine waveform inside the table
// The frequency should be >= 0 and <= the nyquist frequency (sampleRate/2)
// else aliasing will occur. The phase should be in the range [0, 1) and
// anything outside of that will be wrapped around.
func (b *table) loadSine(frequency, phase, sampleRate float64) error {
// check that the sample rate is valid
if sampleRate < 1 {
return errors.New(fmt.Sprintf("Cannot create a buffer with sample rate: %f", sampleRate))
}
// create the samples necessary to store the waveform
samples := createSingleCycle(frequency, sampleRate)
// create iteration variables
var (
tau float64 = 2.0 * math.Pi
omega float64 = tau * frequency
x float64
)
// make sure phase is in range [0, 1)
phase = clampPhase(phase)
// then convert phase to radians
phase = tau * phase
// iterate the samples, writing the waveform data to it
for i, _ := range samples {
x = float64(i) / sampleRate
samples[i] = math.Sin(omega*x + phase)
}
// update self
b.Lock()
defer b.Unlock()
b.name = "sine"
b.channels = 1
b.sampleRate = sampleRate
b.samples = samples
b.nFrames = len(samples)
return nil
}
// generates a single cycle sawtooth waveform inside the table
// The frequency should be >= 0 and <= the nyquist frequency (sampleRate/2)
// else aliasing will occur. The phase should be in the range [0, 1) and
// anything outside of that will be wrapped around.
func (b *table) loadSaw(frequency, phase, sampleRate float64) error {
// check that the sample rate is valid
if sampleRate < 1 {
return errors.New(fmt.Sprintf("Cannot create a buffer with sample rate: %f", sampleRate))
}
// create samples to store the waveform
samples := createSingleCycle(frequency, sampleRate)
// calculate correct starting phase and increment
phase = clampPhase(phase)
phase = phase*2.0 - 1.0
phaseIncrement := 1.0 / float64(len(samples))
// iterate samples
// ramp up sawtooth starting from phase
for i, _ := range samples {
samples[i] = phase
// update phase
phase += phaseIncrement
if phase > 1.0 {
phase = -1.0
}
}
// update self
b.Lock()
defer b.Unlock()
b.name = "saw"
b.channels = 1
b.sampleRate = sampleRate
b.samples = samples
b.nFrames = len(samples)
return nil
}
// generates a single cycle square waveform inside the table
// The frequency should be >= 0 and <= the nyquist frequency (sampleRate/2)
// else aliasing will occur. The phase should be in the range [0, 1) and
// anything outside of that will be wrapped around.
func (b *table) loadSquare(frequency, phase, sampleRate float64) error {
// check that the sample rate is valid
if sampleRate < 1 {
return errors.New(fmt.Sprintf("Cannot create a buffer with sample rate: %f", sampleRate))
}
// create the samples necessary to store the waveform
samples := createSingleCycle(frequency, sampleRate)
// we basically use a sawtooth waveform algorithm (see above)
// at twice the speed of the provided frequency
// to calculate when the square wave switches polarity
// calculate correct starting phase and increment
phase = clampPhase(phase)
phase = phase*2.0 - 1.0
// note the 2.0, not 1.0 (twice the speed)
phaseIncrement := 2.0 / float64(len(samples))
// iterate samples (very similar to saw waveform code above)
for i, _ := range samples {
if phase < 0 {
samples[i] = -1.0
} else {
samples[i] = 1.0
}
// update phase
phase += phaseIncrement
if phase > 1.0 {
phase = -1.0
}
}
// update self
b.Lock()
defer b.Unlock()
b.name = "square"
b.channels = 1
b.sampleRate = sampleRate
b.samples = samples
b.nFrames = len(samples)
return nil
}
// seed random number generator which will be used
// for generating noise
var (
rng = rand.New(rand.NewSource(time.Now().UnixNano()))
)
// generates white noise inside the buffer
func (b *table) loadWhiteNoise(duration, sampleRate float64) error {
// check that the sample rate is valid
if sampleRate < 1 {
return errors.New(fmt.Sprintf("Cannot create a buffer with sample rate: %f", sampleRate))
}
n := int(duration * sampleRate)
samples := make([]float64, n)
for i, _ := range samples {
samples[i] = rng.Float64()*2.0 - 1.0
}
// update self
b.Lock()
defer b.Unlock()
b.name = "white-noise"
b.channels = 1
b.sampleRate = sampleRate
b.samples = samples
b.nFrames = len(samples)
return nil
}
// generates a single cycle impulse train waveform inside the table
// The frequency should be >= 0 and <= the nyquist frequency (sampleRate/2)
// else aliasing will occur. The phase should be in the range [0, 1) and
// anything outside of that will be wrapped around.
func (b *table) loadImpulseTrain(frequency, phase, sampleRate float64) error {
// check that the sample rate is valid
if sampleRate < 1 {
return errors.New(fmt.Sprintf("Cannot create a buffer with sample rate: %f", sampleRate))
}
samples := createSingleCycle(frequency, sampleRate)
// make sure phase is valid [0, 1)
phase = clampPhase(phase)
// find phase's index into our samples
// i is between [0, N) where N == len(samples)
i := int(phase * float64(len(samples)))
if i > 0 {
// set impulse at len(samples) - phase
samples[len(samples)-i] = 1.0
} else {
samples[0] = 1.0
}
// update self
b.Lock()
defer b.Unlock()
b.name = "impulse-train"
b.channels = 1
b.sampleRate = sampleRate
b.samples = samples
b.nFrames = len(samples)
return nil
}