-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathgui.js
1985 lines (1752 loc) · 62.1 KB
/
gui.js
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import $ from 'jquery'
import gInstrumentPresets from './presets'
import * as sonantx from 'sonantx'
import * as LZString from 'lz-string'
import URI from 'urijs'
import _ from 'lodash'
import waveSinSel from './gui/wave-sin-sel.png'
import waveSqrSel from './gui/wave-sqr-sel.png'
import waveSawSel from './gui/wave-saw-sel.png'
import waveTriSel from './gui/wave-tri-sel.png'
import waveSin from './gui/wave-sin.png'
import waveSqr from './gui/wave-sqr.png'
import waveSaw from './gui/wave-saw.png'
import waveTri from './gui/wave-tri.png'
import boxCheck from './gui/box-check.png'
import boxUncheck from './gui/box-uncheck.png'
import progressPng from './gui/progress.gif'
import filtLp from './gui/filt-lp.png'
import filtLpSel from './gui/filt-lp-sel.png'
import filtHp from './gui/filt-hp.png'
import filtHpSel from './gui/filt-hp-sel.png'
import filtBp from './gui/filt-bp.png'
import filtBpSel from './gui/filt-bp-sel.png'
import filtN from './gui/filt-n.png'
import filtNSel from './gui/filt-n-sel.png'
import playGfxBg from './gui/playGfxBg.png'
import ledOff from './gui/led-off.png'
import ledOn from './gui/led-on.png'
import audioBufferToWav from 'audiobuffer-to-wav'
import { base64 } from 'rfc4648'
import packageJson from './package.json'
const audioCtx = new AudioContext()
console.log('Using sample rate', audioCtx.sampleRate)
// ------------------------------------------------------------------------------
// GUI class
// ------------------------------------------------------------------------------
const CGUI = function () {
// Edit modes
const EDIT_NONE = 0
const EDIT_SEQUENCE = 1
const EDIT_PATTERN = 2
// Edit/gui state
let mEditMode = EDIT_SEQUENCE
let mKeyboardOctave = 5
let mPatternRow = 0
let mPatternRow2 = 0
let mSeqCol = 0
let mSeqRow = 0
let mSeqCol2 = 0
let mSeqRow2 = 0
let mSelectingSeqRange = false
let mSelectingPatternRange = false
let mSeqCopyBuffer = []
let mPatCopyBuffer = []
// Resources
let mSong = {}
let mBufferSource = null
let mBufferSourceStartedTime = null
let mAudioBuffer = null
const mPlayGfxVUImg = new Image()
const mPlayGfxLedOffImg = new Image()
const mPlayGfxLedOnImg = new Image()
// Constant look-up-tables
const mNoteNames = [
'C-', 'C#', 'D-', 'D#', 'E-', 'F-', 'F#', 'G-', 'G#', 'A-', 'A#', 'B-'
]
const mBlackKeyPos = [
20, 1, 46, 3, 72, 5, 110, 8, 138, 10, 178, 13, 204, 15, 230, 17, 270, 20,
298, 22, 338, 25, 364, 27, 390, 29, 428, 32, 456, 34
]
// Prealoaded resources
const mPreload = []
// --------------------------------------------------------------------------
// Song import/export functions
// --------------------------------------------------------------------------
const calcSongLength = function (song) {
return Math.round((song.endPattern * 32 + 8) * song.rowLen / 44100)
}
const calcSamplesPerRow = function (bpm) {
return Math.round((60 * 44100 / 4) / bpm)
}
const getBPM = function () {
return Math.round((60 * 44100 / 4) / mSong.rowLen)
}
const makeNewSong = function () {
const song = {}
// Row length
song.rowLen = calcSamplesPerRow(120)
// Last pattern to play
song.endPattern = 2
song.songData = []
convertSong(song)
return song
}
const convertSong = function (song) {
let i, j, k
for (i = 0; i < 8; i++) {
let instr = song.songData[i]
if (instr === undefined) {
instr = {}
// Oscillator 1
instr.osc1_oct = 7
instr.osc1_det = 0
instr.osc1_detune = 0
instr.osc1_xenv = 0
instr.osc1_vol = 192
instr.osc1_waveform = 0
// Oscillator 2
instr.osc2_oct = 7
instr.osc2_det = 0
instr.osc2_detune = 0
instr.osc2_xenv = 0
instr.osc2_vol = 192
instr.osc2_waveform = 0
// Noise oscillator
instr.noise_fader = 0
// Envelope
instr.env_attack = 200
instr.env_sustain = 2000
instr.env_release = 20000
instr.env_master = 192
// Effects
instr.fx_filter = 0
instr.fx_freq = 11025
instr.fx_resonance = 255
instr.fx_delay_time = 0
instr.fx_delay_amt = 0
instr.fx_pan_freq = 0
instr.fx_pan_amt = 0
// LFO
instr.lfo_osc1_freq = 0
instr.lfo_fx_freq = 0
instr.lfo_freq = 0
instr.lfo_amt = 0
instr.lfo_waveform = 0
instr.p = []
instr.c = []
song.songData[i] = instr
}
// Patterns
for (j = 0; j < 48; j++) {
if (instr.p[j] === undefined) { instr.p[j] = 0 }
}
// Columns
for (j = 0; j < 10; j++) {
const col = instr.c[j]
if (col === undefined) {
const col2 = {}
col2.n = []
for (k = 0; k < 32; k++) {
col2.n[k] = 0
}
instr.c[j] = col2
}
}
}
// Calculate song length (not really part of the binary song data)
song.songLen = calcSongLength(song)
}
const compressSong = function (song) {
song = _.clone(song)
song.songData = _.map(song.songData, function (d) {
d = _.clone(d)
let lastNotZero = -1
const used = []
const usedIndex = {}
// search the last pattern and listing all patterns
_.each(d.p, function (p, i) {
if (p !== 0) { lastNotZero = i }
if (usedIndex[p] === undefined) {
used.push(p)
usedIndex[p] = true
}
})
// remove useless end of pattern list
d.p = d.p.slice(0, lastNotZero + 1)
// remove unused patterns
const lastPattern = _.max(used)
d.c = d.c.slice(0, lastPattern)
return d
})
song.songData = _.filter(song.songData, function (d) {
return d.p.length > 0
})
return song
}
const songToJSON = function (song, pretty) {
const csong = compressSong(song)
return JSON.stringify(csong, null, pretty ? ' ' : undefined)
}
// --------------------------------------------------------------------------
// Helper functions
// --------------------------------------------------------------------------
const preloadImage = function (url) {
const img = new Image()
img.src = url
mPreload.push(img)
}
const initPresets = function () {
const parent = document.getElementById('instrPreset')
let o, instr
for (let i = 0; i < gInstrumentPresets.length; ++i) {
instr = gInstrumentPresets[i]
o = document.createElement('option')
o.value = instr.osc1_oct ? '' + i : ''
o.appendChild(document.createTextNode(instr.name))
parent.appendChild(o)
}
}
const getElementPos = function (o) {
let left = 0; let top = 0
if (o.offsetParent) {
do {
left += o.offsetLeft
top += o.offsetTop
o = o.offsetParent
} while (o)
}
return [left, top]
}
const getEventElement = function (e) {
let o = null
if (!e) { e = window.event }
if (e.target) { o = e.target } else if (e.srcElement) { o = e.srcElement }
if (o.nodeType === 3) {
o = o.parentNode
}
return o
}
const getMousePos = function (e, rel) {
// Get the mouse document position
let p = [0, 0]
if (e.pageX || e.pageY) {
p = [e.pageX, e.pageY]
} else if (e.clientX || e.clientY) {
p = [e.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft,
e.clientY + document.body.scrollTop +
document.documentElement.scrollTop]
}
if (!rel) return p
// Get the element document position
const pElem = getElementPos(getEventElement(e))
return [p[0] - pElem[0], p[1] - pElem[1]]
}
const unfocusHTMLInputElements = function () {
document.getElementById('bpm').blur()
document.getElementById('instrPreset').blur()
}
const setEditMode = function (mode) {
mEditMode = mode
// Set the style for the different edit sections
document.getElementById('sequencer').className = (mEditMode === EDIT_SEQUENCE ? 'edit' : '')
document.getElementById('pattern').className = (mEditMode === EDIT_PATTERN ? 'edit' : '')
// Unfocus any focused input elements
if (mEditMode !== EDIT_NONE) {
unfocusHTMLInputElements()
}
}
const updateSongInfo = function () {
const bpm = getBPM()
document.getElementById('bpm').value = bpm
}
const updateSequencer = function (scrollIntoView, selectionOnly) {
let o
// Update sequencer element contents and selection
for (let i = 0; i < 48; ++i) {
for (let j = 0; j < 8; ++j) {
o = document.getElementById('sc' + j + 'r' + i)
if (!selectionOnly) {
const pat = mSong.songData[j].p[i]
if (pat > 0) { o.innerHTML = '' + (pat - 1) } else { o.innerHTML = '' }
}
if (i >= mSeqRow && i <= mSeqRow2 &&
j >= mSeqCol && j <= mSeqCol2) { o.className = 'selected' } else { o.className = '' }
}
}
// Scroll the row into view? (only when needed)
if (scrollIntoView) {
o = document.getElementById('spr' + mSeqRow)
if (o.scrollIntoView) {
const so = document.getElementById('sequencer')
const oy = o.offsetTop - so.scrollTop
if (oy < 0 || (oy + 10) > so.offsetHeight) o.scrollIntoView(oy < 0)
}
}
}
const updatePattern = function () {
const singlePattern = (mSeqCol === mSeqCol2 && mSeqRow === mSeqRow2)
for (let i = 0; i < 32; ++i) {
let noteName = ''
const pat = singlePattern ? mSong.songData[mSeqCol].p[mSeqRow] - 1 : -1
if (pat >= 0) {
const n = mSong.songData[mSeqCol].c[pat].n[i] - 87
if (n > 0) { noteName = mNoteNames[n % 12] + Math.floor(n / 12) }
}
const o = document.getElementById('pr' + i)
o.innerHTML = noteName
if (i >= mPatternRow && i <= mPatternRow2) { o.className = 'selected' } else { o.className = '' }
}
}
const setSelectedPatternRow = function (row) {
mPatternRow = row
mPatternRow2 = row
for (let i = 0; i < 32; ++i) {
const o = document.getElementById('pr' + i)
if (i === row) { o.className = 'selected' } else { o.className = '' }
}
}
const setSelectedPatternRow2 = function (row) {
mPatternRow2 = row >= mPatternRow ? row : mPatternRow
for (let i = 0; i < 32; ++i) {
const o = document.getElementById('pr' + i)
if (i >= mPatternRow && i <= mPatternRow2) { o.className = 'selected' } else { o.className = '' }
}
}
const setSelectedSequencerCell = function (col, row) {
mSeqCol = col
mSeqRow = row
mSeqCol2 = col
mSeqRow2 = row
updateSequencer(true, true)
}
const setSelectedSequencerCell2 = function (col, row) {
mSeqCol2 = col >= mSeqCol ? col : mSeqCol
mSeqRow2 = row >= mSeqRow ? row : mSeqRow
updateSequencer(false, true)
}
const addPatternNote = function (n) {
// playNote
if (mSong && mSong.songData[mSeqCol] && mSong.rowLen) {
const bpm = Math.round((60 * 44100 / 4) / mSong.rowLen)
const note = n + 87 - 75
console.log('playing note', note)
sonantx.generateSound(mSong.songData[mSeqCol], note, audioCtx.sampleRate, bpm).then((buffer) => {
const source = audioCtx.createBufferSource()
source.buffer = buffer
source.connect(audioCtx.destination)
source.start()
})
}
// Edit pattern
if (mEditMode === EDIT_PATTERN &&
mSeqCol === mSeqCol2 && mSeqRow === mSeqRow2 &&
mPatternRow === mPatternRow2) {
const pat = mSong.songData[mSeqCol].p[mSeqRow] - 1
if (pat >= 0) {
mSong.songData[mSeqCol].c[pat].n[mPatternRow] = n + 87
setSelectedPatternRow((mPatternRow + 1) % 32)
updatePattern()
return true
}
}
return false
}
const updateSlider = function (o, x) {
const props = o.sliderProps
let pos = (x - props.min) / (props.max - props.min)
pos = pos < 0 ? 0 : (pos > 1 ? 1 : pos)
if (props.nonLinear) {
pos = Math.sqrt(pos)
}
o.style.marginLeft = Math.round(191 * pos) + 'px'
}
const updateCheckBox = function (o, check) {
o.src = check ? boxCheck : boxUncheck
}
const clearPresetSelection = function () {
const o = document.getElementById('instrPreset')
o.selectedIndex = 0
}
const updateInstrument = function (resetPreset) {
const instr = mSong.songData[mSeqCol]
// Oscillator 1
document.getElementById('osc1_wave_sin').src = instr.osc1_waveform === 0 ? waveSinSel : waveSin
document.getElementById('osc1_wave_sqr').src = instr.osc1_waveform === 1 ? waveSqrSel : waveSqr
document.getElementById('osc1_wave_saw').src = instr.osc1_waveform === 2 ? waveSawSel : waveSaw
document.getElementById('osc1_wave_tri').src = instr.osc1_waveform === 3 ? waveTriSel : waveTri
updateSlider(document.getElementById('osc1_vol'), instr.osc1_vol)
updateSlider(document.getElementById('osc1_oct'), instr.osc1_oct)
updateSlider(document.getElementById('osc1_semi'), instr.osc1_det)
updateSlider(document.getElementById('osc1_det'), instr.osc1_detune)
updateCheckBox(document.getElementById('osc1_xenv'), instr.osc1_xenv)
// Oscillator 2
document.getElementById('osc2_wave_sin').src = instr.osc2_waveform === 0 ? waveSinSel : waveSin
document.getElementById('osc2_wave_sqr').src = instr.osc2_waveform === 1 ? waveSqrSel : waveSqr
document.getElementById('osc2_wave_saw').src = instr.osc2_waveform === 2 ? waveSawSel : waveSaw
document.getElementById('osc2_wave_tri').src = instr.osc2_waveform === 3 ? waveTriSel : waveTri
updateSlider(document.getElementById('osc2_vol'), instr.osc2_vol)
updateSlider(document.getElementById('osc2_oct'), instr.osc2_oct)
updateSlider(document.getElementById('osc2_semi'), instr.osc2_det)
updateSlider(document.getElementById('osc2_det'), instr.osc2_detune)
updateCheckBox(document.getElementById('osc2_xenv'), instr.osc2_xenv)
// Noise
updateSlider(document.getElementById('noise_vol'), instr.noise_fader)
// Envelope
updateSlider(document.getElementById('env_master'), instr.env_master)
updateSlider(document.getElementById('env_att'), instr.env_attack)
updateSlider(document.getElementById('env_sust'), instr.env_sustain)
updateSlider(document.getElementById('env_rel'), instr.env_release)
// LFO
document.getElementById('lfo_wave_sin').src = instr.lfo_waveform === 0 ? waveSinSel : waveSin
document.getElementById('lfo_wave_sqr').src = instr.lfo_waveform === 1 ? waveSqrSel : waveSqr
document.getElementById('lfo_wave_saw').src = instr.lfo_waveform === 2 ? waveSawSel : waveSaw
document.getElementById('lfo_wave_tri').src = instr.lfo_waveform === 3 ? waveTriSel : waveTri
updateSlider(document.getElementById('lfo_amt'), instr.lfo_amt)
updateSlider(document.getElementById('lfo_freq'), instr.lfo_freq)
updateCheckBox(document.getElementById('lfo_o1fm'), instr.lfo_osc1_freq)
updateCheckBox(document.getElementById('lfo_fxfreq'), instr.lfo_fx_freq)
// Effects
document.getElementById('fx_filt_lp').src = instr.fx_filter === 2 ? filtLpSel : filtLp
document.getElementById('fx_filt_hp').src = instr.fx_filter === 1 ? filtHpSel : filtHp
document.getElementById('fx_filt_bp').src = instr.fx_filter === 3 ? filtBpSel : filtBp
document.getElementById('fx_filt_n').src = instr.fx_filter === 4 ? filtNSel : filtN
updateSlider(document.getElementById('fx_freq'), instr.fx_freq)
updateSlider(document.getElementById('fx_res'), instr.fx_resonance)
updateSlider(document.getElementById('fx_dly_amt'), instr.fx_delay_amt)
updateSlider(document.getElementById('fx_dly_time'), instr.fx_delay_time)
updateSlider(document.getElementById('fx_pan_amt'), instr.fx_pan_amt)
updateSlider(document.getElementById('fx_pan_freq'), instr.fx_pan_freq)
// Clear the preset selection?
if (resetPreset) { clearPresetSelection() }
}
const updateSongRanges = function () {
let i, j, emptyRow
// Determine the last song pattern
mSong.endPattern = 49
for (i = 47; i >= 0; --i) {
emptyRow = true
for (j = 0; j < 8; ++j) {
if (mSong.songData[j].p[i] > 0) {
emptyRow = false
break
}
}
if (!emptyRow) break
mSong.endPattern--
}
// Determine song length
mSong.songLen = calcSongLength(mSong)
// Determine song speed
const bpm = parseInt(document.getElementById('bpm').value, 10)
if (bpm && (bpm > 40) && (bpm < 300)) {
mSong.rowLen = calcSamplesPerRow(bpm)
}
}
const showDialog = function () {
const e = document.getElementById('cover')
e.style.visibility = 'visible'
deactivateMasterEvents()
}
const hideDialog = function () {
const e = document.getElementById('cover')
e.style.visibility = 'hidden'
activateMasterEvents()
}
const showProgressDialog = function (msg) {
const parent = document.getElementById('dialog')
parent.innerHTML = ''
// Create dialog content
let o
o = document.createElement('img')
o.src = progressPng
parent.appendChild(o)
o = document.createTextNode(msg)
parent.appendChild(o)
showDialog()
}
const showOpenDialog = function () {
const parent = document.getElementById('dialog')
parent.innerHTML = ''
// Create dialog content
let o
o = document.createElement('h3')
parent.appendChild(o)
o.appendChild(document.createTextNode('Import JSON'))
parent.appendChild(document.createElement('br'))
let el = $('<textarea id="jsonTextArea" style="width: 200px; height: 100px"></textarea>')
o = el[0]
parent.appendChild(o)
parent.appendChild(document.createElement('br'))
el = $('<button id="jsonImportButton">Import</button>')
o = el[0]
parent.appendChild(o)
parent.appendChild(document.createTextNode(' '))
el = $('<button id="jsonCancelButton">Cancel</button>')
o = el[0]
parent.appendChild(o)
$('#jsonImportButton').click(function () {
const json = $('#jsonTextArea').val()
const song = JSON.parse(json)
newSong(song)
hideDialog()
})
$('#jsonCancelButton').click(function () {
hideDialog()
})
showDialog()
}
const showUrlDialog = function (url) {
const parent = document.getElementById('dialog')
parent.innerHTML = ''
// Create dialog content
let o
o = document.createElement('h3')
parent.appendChild(o)
o.appendChild(document.createTextNode('URL'))
parent.appendChild(document.createElement('br'))
let el = $('<input type="text" value="' + url + '"></input>')
o = el[0]
parent.appendChild(o)
parent.appendChild(document.createElement('br'))
el = $('<button id="urlExitButton">Exit</button>')
o = el[0]
parent.appendChild(o)
$('#urlExitButton').click(function () {
hideDialog()
})
showDialog()
}
// --------------------------------------------------------------------------
// Event handlers
// --------------------------------------------------------------------------
const newSong = function (song) {
if (song) {
mSong = song
convertSong(mSong)
} else { mSong = makeNewSong() }
// Update GUI
updateSongInfo()
updateSequencer()
updatePattern()
updateInstrument()
// Initialize the song
setEditMode(EDIT_SEQUENCE)
setSelectedPatternRow(0)
setSelectedSequencerCell(0, 0)
}
const openSong = function (e) {
showOpenDialog()
return false
}
const exportWAV = function (e) {
// This can hog the browser for quite some time, so warn...
if (!confirm('This can take quite some time. Do you want to continue?')) { return }
// Update song ranges
updateSongRanges()
// Generate audio data
const doneFun = function (audioBuffer) {
const uri = 'data:application/octet-stream;base64,' + base64.stringify(abToWav(audioBuffer))
downloadData(uri, 'sonant-x-export-song.wav')
}
generateAudio(doneFun)
return false
}
const exportWAVRange = function (e) {
// This can hog the browser for quite some time, so warn...
if (!confirm('This can take quite some time. Do you want to continue?')) { return }
// Update song ranges
updateSongRanges()
// Select range to play
const opts = {
firstRow: mSeqRow,
lastRow: mSeqRow2,
firstCol: mSeqCol,
lastCol: mSeqCol2,
numSeconds: ((mSeqRow2 - mSeqRow + 1) * 32 + 8) * mSong.rowLen / 44100
}
// Generate audio data
const doneFun = function (audioBuffer) {
const uri = 'data:application/octet-stream;base64,' + base64.stringify(abToWav(audioBuffer))
downloadData(uri, 'sonant-x-export-range.wav')
}
generateAudio(doneFun, opts)
return false
}
const exportJSON = function (e) {
// Update song ranges
updateSongRanges()
// Generate JS song data
const dataURI = 'data:text/javascript;base64,' + btoa(songToJSON(mSong, true))
downloadData(dataURI, 'sonant-x-export-song.json')
return false
}
const exportInstrument = function () {
if (mSeqCol !== mSeqCol2 || mSeqCol < 0 || mSeqCol >= mSong.songData.length) {
return
}
const instr = _.clone(mSong.songData[mSeqCol])
delete instr.p
delete instr.c
const dataURI = 'data:text/javascript;base64,' + btoa(JSON.stringify(instr, null, ' '))
downloadData(dataURI, 'sonant-x-export-instrument.json')
}
const exportURL = function (e) {
// Update song ranges
updateSongRanges()
const json = songToJSON(mSong, false)
const url = '' + new URI().fragment(URI.encode(LZString.compressToBase64(json)))
showUrlDialog(url)
return false
}
const setStatus = function (msg) {
document.getElementById('statusText').innerHTML = msg
// window.status = msg;
}
const generateAudio = function (doneFun, opts) {
// Show dialog
showProgressDialog('Generating sound...')
// Start time measurement
const d1 = new Date()
// Generate audio data\bm
// NOTE: We'd love to do this in a Web Worker instead! Currently we do it
// in a setInterval() timer loop instead in order not to block the main UI.
// TODO: handle correctly opts
const oSong = _.clone(mSong)
if (opts) {
oSong.songData = mSong.songData.slice(opts.firstCol, opts.lastCol + 1)
oSong.songData = _.map(oSong.songData, function (data) {
const ndata = _.clone(data)
ndata.p = data.p.slice(opts.firstRow, opts.lastRow + 1)
return ndata
})
oSong.endPattern = (opts.lastRow + 1) - opts.firstRow + 1
oSong.songLen = opts.numSeconds
}
sonantx.generateSong(compressSong(oSong), audioCtx.sampleRate).then((audioBuffer) => {
mAudioBuffer = audioBuffer
const d2 = new Date()
setStatus('Generation time: ' + (d2.getTime() - d1.getTime()) / 1000 + 's')
// Hide dialog
hideDialog()
// Call the callback function
doneFun(audioBuffer)
})
}
// ----------------------------------------------------------------------------
// Playback follower
// ----------------------------------------------------------------------------
let mFollowerTimerID = -1
let mFollowerFirstRow = 0
let mFollowerLastRow = 0
let mFollowerFirstCol = 0
let mFollowerLastCol = 0
let mFollowerActive = false
let mFollowerLastVULeft = 0
let mFollowerLastVURight = 0
const getSamplesSinceNote = function (t, chan) {
const nFloat = t * 44100 / mSong.rowLen
const n = Math.floor(nFloat)
const seqPos0 = Math.floor(n / 32) + mFollowerFirstRow
const patPos0 = n % 32
for (let k = 0; k < 32; ++k) {
let seqPos = seqPos0
let patPos = patPos0 - k
while (patPos < 0) {
--seqPos
if (seqPos < mFollowerFirstRow) return -1
patPos += 32
}
const pat = mSong.songData[chan].p[seqPos] - 1
if (pat >= 0 && mSong.songData[chan].c[pat].n[patPos] > 0) {
return (k + (nFloat - n)) * mSong.rowLen
}
}
return -1
}
const redrawPlayerGfx = function (t) {
let i
const o = document.getElementById('playGfxCanvas')
const w = mPlayGfxVUImg.width > 0 ? mPlayGfxVUImg.width : o.width
const h = mPlayGfxVUImg.height > 0 ? mPlayGfxVUImg.height : 51
const ctx = o.getContext('2d')
if (ctx) {
// Draw the VU meter BG
ctx.drawImage(mPlayGfxVUImg, 0, 0)
// Calculate singal powers
let pl = 0; let pr = 0
if (mFollowerActive && t >= 0) {
// Get the waveform
const wave = getData(mAudioBuffer, t, 1000)
// Calculate volume
let l, r
let sl = 0; let sr = 0; let l_old = 0; let r_old = 0
for (i = 1; i < wave.length; i += 2) {
l = wave[i - 1]
r = wave[i]
// Band-pass filter (low-pass + high-pass)
sl = 0.8 * l + 0.1 * sl - 0.3 * l_old
sr = 0.8 * r + 0.1 * sr - 0.3 * r_old
l_old = l
r_old = r
// Sum of squares
pl += sl * sl
pr += sr * sr
}
// Low-pass filtered mean power (RMS)
pl = Math.sqrt(pl / wave.length) * 0.2 + mFollowerLastVULeft * 0.8
pr = Math.sqrt(pr / wave.length) * 0.2 + mFollowerLastVURight * 0.8
mFollowerLastVULeft = pl
mFollowerLastVURight = pr
}
// Convert to angles in the VU meter
let a1 = pl > 0 ? 1.3 + 0.5 * Math.log(pl) : -1000
a1 = a1 < -1 ? -1 : a1 > 1 ? 1 : a1
a1 *= 0.57
let a2 = pr > 0 ? 1.3 + 0.5 * Math.log(pr) : -1000
a2 = a2 < -1 ? -1 : a2 > 1 ? 1 : a2
a2 *= 0.57
// Draw VU hands
ctx.strokeStyle = 'rgb(0,0,0)'
ctx.beginPath()
ctx.moveTo(w * 0.25, h * 2.1)
ctx.lineTo(w * 0.25 + h * 1.8 * Math.sin(a1), h * 2.1 - h * 1.8 * Math.cos(a1))
ctx.stroke()
ctx.beginPath()
ctx.moveTo(w * 0.75, h * 2.1)
ctx.lineTo(w * 0.75 + h * 1.8 * Math.sin(a2), h * 2.1 - h * 1.8 * Math.cos(a2))
ctx.stroke()
// Draw leds
ctx.fillStyle = 'rgb(0,0,0)'
ctx.fillRect(0, h, w, 20)
for (i = 0; i < 8; ++i) {
// Draw un-lit led
const x = Math.round(26 + 26.5 * i)
ctx.drawImage(mPlayGfxLedOffImg, x, h)
if (i >= mFollowerFirstCol && i <= mFollowerLastCol) {
// Get envelope profile for this channel
const env_a = mSong.songData[i].env_attack
let env_r = mSong.songData[i].env_sustain + mSong.songData[i].env_release
let env_tot = env_a + env_r
if (env_tot < 10000) {
env_tot = 10000
env_r = env_tot - env_a
}
// Get number of samples since last new note
const numSamp = getSamplesSinceNote(t, i)
if (numSamp >= 0 && numSamp < env_tot) {
// Calculate current envelope (same method as the synth, except sustain)
let alpha
if (numSamp < env_a) {
alpha = numSamp / env_a
} else {
alpha = 1 - (numSamp - env_a) / env_r
}
// Draw lit led with alpha blending
ctx.globalAlpha = alpha * alpha
ctx.drawImage(mPlayGfxLedOnImg, x, h)
ctx.globalAlpha = 1.0
}
}
}
}
}
const updateFollower = function () {
let i, o
// Calculate current song position
const t = (new Date().getTime() / 1000) - mBufferSourceStartedTime
const n = Math.floor(t * 44100 / mSong.rowLen)
const seqPos = Math.floor(n / 32) + mFollowerFirstRow
const patPos = n % 32
// Are we past the play range (i.e. stop the follower?)
if (seqPos > mFollowerLastRow) {
stopFollower()
// Reset pattern position
mPatternRow = 0
mPatternRow2 = 0
updatePattern()
return
}
const newSeqPos = (seqPos !== mSeqRow)
const newPatPos = newSeqPos || (patPos !== mPatternRow)
// Update the sequencer
if (newSeqPos) {
if (seqPos >= 0) {
mSeqRow = seqPos
mSeqRow2 = seqPos
updateSequencer(true, true)
}
for (i = 0; i < 48; ++i) {
o = document.getElementById('spr' + i)
o.className = (i === seqPos ? 'playpos' : '')
}
}
// Update the pattern
if (newPatPos) {
if (patPos >= 0) {
mPatternRow = patPos
mPatternRow2 = patPos
updatePattern()
}
for (i = 0; i < 32; ++i) {
o = document.getElementById('ppr' + i)
o.className = (i === patPos ? 'playpos' : '')
}
}
// Player graphics
redrawPlayerGfx(t)
}
const startFollower = function () {
// Update the sequencer selection
mSeqRow = mFollowerFirstRow
mSeqRow2 = mFollowerFirstRow
mSeqCol2 = mSeqCol
updateSequencer(true, true)
updatePattern()
// Start the follower
mFollowerActive = true
mFollowerTimerID = setInterval(updateFollower, 16)
}
const stopFollower = function () {
let i
if (mFollowerActive) {
// Stop the follower
if (mFollowerTimerID !== -1) {
clearInterval(mFollowerTimerID)
mFollowerTimerID = -1
}
// Clear the follower markers
for (i = 0; i < 48; ++i) {
document.getElementById('spr' + i).className = ''
}
for (i = 0; i < 32; ++i) {
document.getElementById('ppr' + i).className = ''
}
// Clear player gfx
redrawPlayerGfx(-1)
mFollowerActive = false
}
}
// ----------------------------------------------------------------------------
// (end of playback follower)
// ----------------------------------------------------------------------------
const playSong = function (e) {
// Stop the currently playing audio
stopPlaying()
// Update song ranges
updateSongRanges()
// Select range to play
mFollowerFirstRow = 0
mFollowerLastRow = mSong.endPattern - 2
mFollowerFirstCol = 0
mFollowerLastCol = 7
// Generate audio data
const doneFun = function (audioBuffer) {
if (mBufferSource !== null) {
mBufferSource.stop()
mBufferSource.disconnect()
mBufferSource = null
}
mBufferSource = audioCtx.createBufferSource()
mBufferSource.buffer = audioBuffer // Add Buffered Data to Object
mBufferSource.connect(audioCtx.destination) // Connect Sound Source to Output
mBufferSource.start()
mBufferSourceStartedTime = new Date().getTime() / 1000
// Start the follower
startFollower()
}
generateAudio(doneFun)
return false
}