-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWAV2VGM.py
2213 lines (2088 loc) · 75.9 KB
/
WAV2VGM.py
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
# -----------------------------------------------------------------------------
# WAV2VGM
#
# Analyzes an input sound and decomposes it into a sum of sine waves.
#
# This is then resynthesized for Yamaha YMF262 (OPL3) music synth chip and
# output as VGM format file, playable on OPL3-capable sound cards or via
# emulation. (e.g. via Winamp or VGMPlay(
#
# Craig Iannello 2024/11/04
#
# -----------------------------------------------------------------------------
import os
import sys
import time
import math
import struct
import gzip
import random
import datetime
from pprint import pprint
import pygame
from pygame.locals import *
import numpy as np
from scipy import signal
import torch
import torch.nn as nn
from src import spect as sp
from src.OPL3 import OPL3
from src.w2vproj import W2VProj
from src import gene # Import
from src.model_definitions import OPL3Model # AI model defs
from copy import deepcopy
# randomize the PRNG
random.seed(datetime.datetime.now().timestamp())
# -----------------------------------------------------------------------------
screen_width=1920
screen_height=1080
#SLICE_FREQ = 86.1328125 # frequency at which the synth parameters are altered
# (exactly two specra per synth frame)
SLICE_FREQ = 91.552734375 # old setting for arduino
MAX_SYNTH_CHANS = 18 # polyphony of synth (num independent oscillators)
OPL3_MAX_FREQ = 6208.431 # highest freq we can assign to a voice (fnum, block)
SPECT_VERT_SCALE = 3 # set max vert spect axis to 7350 Hz max rather than the orig 22050 Hz
GENE_MAX_GENERATIONS = 500
SPECS_PER_FRAME = 3
# -----------------------------------------------------------------------------
NO_QUIT = 0 # neither
SOFT_QUIT = 1 # esc-pressed
HARD_QUIT = 2 # window close
best_vects = []
# opl emulator, register data, and helper functions for converting
# between binary and float32[] config vector for AI training and inference
opl3 = OPL3()
# these two objects are redundant and should be removed,
# (the whole deterministic wav2vgm code can be cleaned
# up a whole lot! )
regofs = [ # one not accounting for bank
0x00,0x01,0x02,0x03,
0x04,0x05,0x0a,0x0b,
0x0c,0x0d,0x10,0x11,
0x12,0x13,0x14,0x15,
0x00,0x01,0x02,0x03,
0x04,0x05,0x0a,0x0b,
0x0c,0x0d,0x10,0x11,
0x12,0x13,0x14,0x15,
]
# these are the operator indexes per each of the 18 output channels
# in 2-op mode.
opidxs_per_chan = [
(0,3),(1,4),(2,5),(6,9),(7,10),(8,11),(12,15),(13,16),(14,17),
(18,21),(19,22),(20,23),(24,27),(25,28),(26,29),(30,33),(31,34),(32,35)]
# todo: make folders we need which don't exist
tmpfolder = 'temp/'
infolder = 'input/'
outfolder = 'output/'
modelsfolder = "models/"
trainfolder = "training_sets/"
origspect=None
pygame.init()
try:
pygame.mixer.init(44100, -16, 1)
except pygame.error as e:
print(str(e))
exit()
print('One moment, one moment.')
if len(sys.argv)==2:
wavname = sys.argv[1]
else:
# default input file during dev, if no file specified on the commandline.
wavname = infolder
wavname += 'HAL 9000 - Human Error.wav'
#wavname += 'Grand Piano.wav'
#wavname += 'JFK Inaguration.wav'
#wavname += 'Ghouls and Ghosts - The Village Of Decay.wav'
#wavname += 'Portal-Still Alive.wav'
#wavname += 'Amiga-Leander-Intro.wav'
output_vgm_name = outfolder+os.path.basename(wavname[0:-3])+"vgz"
temp_regfile_name = tmpfolder+os.path.basename(wavname[0:-3])+'bin'
origspect = sp.spect(wav_filename=wavname,nperseg=4096,quiet=False,clip=False)
clock = pygame.time.Clock()
screen=pygame.display.set_mode([screen_width,screen_height])#,flags=pygame.FULLSCREEN)
pygame.display.set_caption(f'Mimic - Spectrogram - {wavname}')
pygame_icon = pygame.image.load('src/spect_icon.png')
pygame.display.set_icon(pygame_icon)
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_CROSSHAIR)
font = pygame.font.SysFont(None, 24)
smallfont = pygame.font.SysFont(None, 16)
roi=-1
cutoff_freq=-1
amp_cutoff=-1
amp_cutoff_y=-1
CLICKED_SPECTRUM = 0
CLICKED_SPECTROGRAM = 1
last_clicked = -1
T_AXIS_HEIGHT = 21
# -----------------------------------------------------------------------------
# draws the source spectrogram, scaled to the current display size and
# SPECT_VERT_SCALE factor.
# -----------------------------------------------------------------------------
def drawSpect(spect = None, xx=0,yy=0,ww=screen_width,hh=screen_height):
global screen, font, smallfont, roi
xx=int(xx)
yy=int(yy)
ww=int(ww)
hh=int(hh)
# draw spectrum
surf = pygame.transform.scale(spect.surf,(ww,hh*SPECT_VERT_SCALE-T_AXIS_HEIGHT))
screen.blit(surf, (xx, yy-(SPECT_VERT_SCALE-1)*hh))
# draw horizontal axis (time) labels and tickmarks
# hardcoded to 50 ticks per second
secs_per_t_tick = 1/50
pygame.draw.rect(screen, (40,40,40), (0,hh-T_AXIS_HEIGHT,screen_width,T_AXIS_HEIGHT))
tstart = 0 # todo zooming
onscreen_dur = spect.dur_secs # todo
t=tstart
while t<(tstart+onscreen_dur):
scr_x = int((t-tstart)*screen_width/(tstart+onscreen_dur))
ft = t-int(t)
if ((ft<0.005) and (t>0.1)) or (abs(ft-0.5)<0.005):
pygame.draw.line(screen, (255,255,255), (scr_x,hh-T_AXIS_HEIGHT+1),(scr_x,hh-T_AXIS_HEIGHT+6))
l='{:0.2f}'.format(t)
img = smallfont.render(l, True, (255,255,255))
w=img.get_width()
h=img.get_height()
screen.blit(img, (int(scr_x-w/2), hh-1-h))
else:
pygame.draw.line(screen, (192,192,192), (scr_x,hh-T_AXIS_HEIGHT+1),(scr_x,hh-T_AXIS_HEIGHT+3))
t+=secs_per_t_tick
# highlight selected spectrum on spectrogram (dotted)
if roi>=0:
scr_x = int(roi*screen_width/spect.maxrowidx)
scr_x1 = int((roi+1)*screen_width/spect.maxrowidx)-1
scr_y = int(screen_height/4)
scr_y1 = screen_height
for y in range(scr_y,scr_y1):
for x in range(scr_x,scr_x1):
if ((x&1)+(y&1))&1:
pygame.draw.line(screen, (255,255,255), (x,y),(x,y))
# show freq cutoff horiz line on spectrogram (dotted)
if cutoff_freq>=0:
hsr = spect.sample_rate/2
y = screen_height-1 -T_AXIS_HEIGHT - (cutoff_freq * (screen_height-T_AXIS_HEIGHT) / hsr)
for x in range(0,screen_width-1):
if (x&1) == 0:
pygame.draw.line(screen, (0,255,255), (x,y),(x,y))
pygame.display.update()
# -----------------------------------------------------------------------------
# draw string, in white, to screen at (x,y)
# -----------------------------------------------------------------------------
def plotText(s,x,y):
global screen, origspect
img = font.render(s, True, (255,255,255))
w=img.get_width()
h=img.get_height()
pygame.draw.rect(screen,(0,0,0),(x,y,w,h))
screen.blit(img, (x, y))
def plotColorText(s,c,x,y):
global screen, origspect
img = font.render(s, True, c)
w=img.get_width()
h=img.get_height()
pygame.draw.rect(screen,(0,0,0),(x,y,w,h))
screen.blit(img, (x, y))
# -----------------------------------------------------------------------------
# given a single spectrum (a vertical slice of spectrogram), identify
# all prominent peaks. Returns their freqs in Hz and heights in dBFS.
# -----------------------------------------------------------------------------
def getRankedPeaks(tsp, minv, maxv, do_limit_freqs=True,dist=5,prom=5):
hh = int(screen_height/4)
ll = len(tsp)
hsr = origspect.sample_rate/2
hnps = origspect.nperseg/2
# maybe todo: center-of-mass refinement of peak freqs?
mypeaks=[]
peaks = signal.find_peaks(tsp, height = -100, distance=dist, prominence=prom)
for peakidx,binnum in enumerate(peaks[0]):
peak_freq = hsr-binnum*hsr/hnps
if do_limit_freqs and (peak_freq>OPL3_MAX_FREQ):
continue
peak_height = peaks[1]['peak_heights'][peakidx]
peak_x = binnum*screen_width/ll
peak_y = hh-1-((peak_height-minv)*hh/(maxv-minv))
peak_prominence = peaks[1]['prominences'][peakidx]
mypeaks.append((peak_height,peak_freq,peak_x,peak_y,peak_prominence))
mypeaks.sort(key=lambda tup: -tup[0])
return mypeaks
# -----------------------------------------------------------------------------
# draw a single spectrum along the top of screen with peaks marked and
# optional cursors
# -----------------------------------------------------------------------------
def plotTestSpect(tsp,minv,maxv,gcolor=(255,255,255),yofs=0):
global screen
ll = len(tsp)
ww = int(screen_width)
hh = int(screen_height/4)
hsr = origspect.sample_rate/2
if minv==maxv: # dont wanna /0
return
# draw freq cutoff line
if cutoff_freq>=0:
x = screen_width-1 - (cutoff_freq * screen_width / hsr)
pygame.draw.line(screen, (0,255,255), (x,0+yofs),(x,hh+yofs))
# draw amp cutoff line
if amp_cutoff_y>=0:
pygame.draw.line(screen, (255,255,0), (0,amp_cutoff_y+yofs),(ww-1,amp_cutoff_y+yofs))
plotText("cutoff={}".format(amp_cutoff),0,amp_cutoff_y)
# draw spectrum peaks ith kinda-gradient colors
mypeaks=getRankedPeaks(tsp, minv, maxv, False)
for i,(peak_height,peak_freq,peak_x,peak_y,peak_prominence) in enumerate(mypeaks):
r = 255*(peak_height-minv)/(maxv-minv)
if i==0:
pygame.draw.line(screen, (255,255,0), (peak_x,(peak_y-10)+yofs),(peak_x,(peak_y+10)+yofs))
else:
pygame.draw.line(screen, (r,r/8,255-r), (peak_x,(peak_y-10)+yofs),(peak_x,(peak_y+10)+yofs))
# draw spectrum
for i in range(0,ll-1):
x0=int(i*screen_width/ll)
x1=int((i+1)*screen_width/ll)
v0=int((tsp[i]-minv)*hh/(maxv-minv))
v1=int((tsp[i+1]-minv)*hh/(maxv-minv))
if tsp[i]<minv or tsp[i+1]<minv:
continue
y0=hh-1-v0
y1=hh-1-v1
if x0>=ww and x1>ww:
break
try:
pygame.draw.line(screen, gcolor, (x0,y0+yofs),(x1,y1+yofs))
except Exception as e:
print(f'{e} {(x0,y0)=}-{(x1,y1)=} {i=} {screen_width=} {ll=}')
return mypeaks
# -----------------------------------------------------------------------------
# draw a single spectrum along the top of screen with peaks marked and
# optional cursors
# -----------------------------------------------------------------------------
def plotHalfSpect(tsp,minv,maxv,gcolor=(255,255,255),yofs=0):
global screen
ll = len(tsp)
ww = int(screen_width)
hh = int(screen_height/2)
hsr = origspect.sample_rate/2
if minv==maxv: # dont wanna /0
return
# opl freq cutoff line
x = screen_width-1 - (OPL3_MAX_FREQ * screen_width / hsr)
pygame.draw.line(screen, (0,255,255), (x,0+yofs),(x,hh+yofs))
# opl amp cutoff line
v0=int(((-48)-minv)*hh/(maxv-minv))
y0=hh-1-v0
pygame.draw.line(screen, (255,255,0), (0,y0+yofs),(ww-1,y0+yofs))
# draw spectrum
for i in range(0,ll-1):
x0=int(i*screen_width/ll)
x1=int((i+1)*screen_width/ll)
v0=int((tsp[i]-minv)*hh/(maxv-minv))
v1=int((tsp[i+1]-minv)*hh/(maxv-minv))
if tsp[i]<minv or tsp[i+1]<minv:
continue
y0=hh-1-v0
y1=hh-1-v1
if x0>=ww and x1>ww:
break
try:
pygame.draw.line(screen, gcolor, (x0,y0+yofs),(x1,y1+yofs))
except Exception as e:
print(f'plotHalfSpect(): Exception: {e} {(x0,y0)=}-{(x1,y1)=} {i=} {screen_width=} {ll=}')
# -----------------------------------------------------------------------------
# draw a single spectrum along the top of screen without peaks marked
# -----------------------------------------------------------------------------
def plotTestSpectSimple(tsp,minv, maxv,gcolor=(255,255,255)):
global screen
ll = len(tsp)
ww = int(screen_width)
hh = int(screen_height/4)
hsr = origspect.sample_rate/2
if minv==maxv: # dont wanna /0
return
for i in range(0,ll-1):
x0=int(i*screen_width/ll)
x1=int((i+1)*screen_width/ll)
v0=int((tsp[i]-minv)*hh/(maxv-minv))
v1=int((tsp[i+1]-minv)*hh/(maxv-minv))
if tsp[i]<minv or tsp[i+1]<minv:
continue
y0=hh-1-v0
y1=hh-1-v1
if x0>=ww and x1>ww:
break
pygame.draw.line(screen, gcolor, (x0,y0),(x1,y1))
# -----------------------------------------------------------------------------
# dBFS value per gradient keycolor
p0 = -115.0 # black
p1 = -75.0 # blue
p2 = -50.0 # red
p3 = -25.0 # yellow
p4 = 0.0 # white
# converts dBFS values to gradient colors
def fred(x):
if x<p1:
return 0
elif x<p2:
return (x-p1)*255/(p2-p1)
else:
return 255
def fgrn(x):
if x<p2:
return 0
elif x<p3:
return (x-p2)*255/(p3-p2)
else:
return 255
def fblu(x):
if x<p0:
return 0
elif x<p1:
return (x-p0)*255/(p1-p0)
elif x<p2:
return 255-((x-p2)*255/(p3-p2))
elif x<p3:
return 0
else:
return (x-p3)*255/(p4-p3)
def gradColor(x):
r=int(fred(x))
if r>255:
r=255
g=int(fgrn(x))
if g>255:
g=255
b=int(fblu(x))
if b>255:
b=255
c=(r,g,b)
return c
# -----------------------------------------------------------------------------
# draw single spectrum's peaks on its spot in the displayed spectrogram
# -----------------------------------------------------------------------------
def overlayPeaksOnSpectrum(roi,slen, tsp):
global screen
ll = len(tsp)
ww = int(screen_width)
hh = int(screen_height) - T_AXIS_HEIGHT
hsr = (origspect.sample_rate/2)/SPECT_VERT_SCALE
minv = origspect.minval
maxv = origspect.maxval
rx = roi*ww/slen
rw = (((roi+SPECS_PER_FRAME)*ww/slen)-rx)+1
# todo: draw a transparent black rect over the
# original spectrum so our detected peaks pop.
# curently, this bar is opaque, fully hiding the spectrum
pygame.draw.rect(screen, (0,0,0), (rx,0,rw,hh))
mypeaks=getRankedPeaks(tsp,minv, maxv,True)
s0 = 0
s1 = len(mypeaks)
points = []
for i,(peak_height,peak_freq,peak_x,peak_y,peak_prominence) in enumerate(mypeaks[s0:s1]):
adj_height = peak_height-maxv # normalize volume
c=gradColor(adj_height)
ry = hh-peak_freq*hh/hsr
pygame.draw.rect(screen, c, (rx,ry,rw,2))
if adj_height >= -48.0: # loud enough for OPL channel volume setting
points.append((float(peak_freq), float(adj_height)))
return points
# -----------------------------------------------------------------------------
# do peak detect on whole displayed spectrogram, find runs of peaks,
# and draw them
# -----------------------------------------------------------------------------
def analyzePeakRuns():
global origspect, roi
global screen
global screen_width
global screen_height
slen = len(origspect.spectrogram)
maxbin = origspect.maxval
# keeps track of runs of spectral peaks
freq_runs = {}
prior_peaks = []
for roi in range(0,slen,SPECS_PER_FRAME): # for each spectrum in spectrogram
# Check if user wants to close program
for event in pygame.event.get():
if event.type == pygame.QUIT:
return HARD_QUIT
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
return SOFT_QUIT
# draws a vertical slice of spectral peaks over top of
# spectrum[roi] of the spectrogram, and returns a list of peak
# (freq,height) values sorted by descending height
peaks = overlayPeaksOnSpectrum(roi,slen,origspect.spectrogram[roi][0:-1])
# see which peaks are new, and which are continuations of prior peaks.
# New ones set a new named run-record, and others get appended onto the
# existing one.
#print(f"{t:6.3f} ")
new_prior_peaks = []
for i,(f,h) in enumerate(peaks):
mindif = 50000
closest = None
for j,(pf,ph,rkey) in enumerate(prior_peaks):
fdif = abs(f-pf)
if fdif<mindif:
mindif = fdif
closest = (j,pf,ph,rkey)
continuation = False
if closest is not None:
if mindif<30:
#print(f'{f:0.1f}->{closest[1]:0.1f} ', end='')
continuation=True
rkey = closest[3]
freq_runs[rkey].append((roi,f,h))
if not continuation:
#print(f'{f:0.1f} ', end='')
rkey = (roi,f)
freq_runs[rkey] = [(roi,f,h)] # new run
new_prior_peaks.append((f,h,rkey))
prior_peaks = new_prior_peaks
#print()
pygame.display.update()
draw_runs = True
if draw_runs: # draw the freq runs in dif colors
num_frames = slen // SPECS_PER_FRAME
frames = [ None ] * num_frames
ll = len(origspect.spectrogram[roi][0:-1])
ww = int(screen_width)
hh = int(screen_height) - T_AXIS_HEIGHT
hsr = (origspect.sample_rate/2)/SPECT_VERT_SCALE
minv = origspect.minval
maxv = origspect.maxval
pygame.draw.rect(screen, (0,0,0), (0,0,ww,hh))
rkeys = []
for kidx, rkey in enumerate(freq_runs):
run = freq_runs[rkey]
if len(run)>=2:
#print(f'{rkey}:')
c0 = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
r,f,h = run[0]
#print(f' {(t,f,h)}')
r0 = r
if h>=-48.0 and f<=OPL3_MAX_FREQ:
frame = r // SPECS_PER_FRAME
if frames[frame] is None:
frames[frame] = [(kidx,f,h)]
else:
frames[frame].append((kidx,f,h))
x0 = int(r0*ww/slen)
y0 = hh-int(f*hh/hsr)
h0 = h
for r,f,h in run[1:]:
if h>=-48.0 and f<=OPL3_MAX_FREQ:
frame = r // SPECS_PER_FRAME
if frame>=len(frames):
break
if frames[frame] is None:
frames[frame] = [(kidx,f,h)]
else:
frames[frame].append((kidx,f,h))
r1 = r
x1 = int(r1*ww/slen)
y1 = hh-int(f*hh/hsr)
h1 = h
#print(f' {(t,f,h)}')
m = 1.0-(h/(-48))
rr = int(c0[0]*m)
gg = int(c0[1]*m)
bb = int(c0[2]*m)
c1 = (rr,gg,bb)
pygame.draw.line(screen, c1, (x0,y0),(x1,y1),2)
r0=r1
x0=x1
y0=y1
h0=h1
pygame.display.update()
#print()
# show cutoff freq as horiz line on peak runs spectrum
hsr = origspect.sample_rate/2
y = screen_height-1 -T_AXIS_HEIGHT - ( OPL3_MAX_FREQ * (screen_height-T_AXIS_HEIGHT) / hsr)
for x in range(0,screen_width-1):
if (x&1) == 0:
pygame.draw.line(screen, (0,255,255), (x,y),(x,y))
for roi in range(0,slen,SPECS_PER_FRAME):
x0 = int(roi*ww/slen)
pygame.draw.line(screen, (32,64,0), (x0,0),(x0,screen_height-1))
outframes = []
for frame in frames:
frame.sort(key=lambda x: -x[2])
chans = [ None ] * 18
for fi,frame in enumerate(frames):
#print(f'Frame {fi:3d}: ',end='')
unassigned = []
unupdated = [ i for i in range(0,18)]
for pi,f in enumerate(frame):
kidx,freq,h = f
if fi == 0:
if pi<=17:
chans[pi] = f
del unupdated[unupdated.index(pi)]
else:
chanat = None
for ch in range(0,18):
if chans[ch][0] == kidx:
chanat = ch
break
if chanat is not None:
chans[chanat] = f
del unupdated[unupdated.index(chanat)]
else:
unassigned.append(f)
for x,u in enumerate(unupdated):
if x<len(unassigned):
chans[u] = unassigned[x]
else:
chans[u] = (0,0,-99.0)
#print(f'{chans=} {unassigned=}')
outframes.append(deepcopy(chans))
#print(f'({kidx:d},{freq:0.1f},{int(h):d}), ',end='')
#print()
#exit()
#print('\nSynth output plan:\n')
yeahframes = []
for fi,o in enumerate(outframes):
#print(f'Frame #{fi:3d}: ',end='')
frame = []
for ci,(ki,fr,h) in enumerate(o):
ct = (ci, fr, h)
frame.append(ct)
yeahframes.append(frame)
#print()
#print('\n\n')
#for frame in yeahframes:
# print(frame)
#exit()
pygame.display.update()
return NO_QUIT, yeahframes
# -----------------------------------------------------------------------------
# WIP UI stuff
# -----------------------------------------------------------------------------
def handleMouseWheel(event):
global screen
global screen_width
global screen_height
mx, my = pygame.mouse.get_pos()
hsr = origspect.sample_rate/2
freq = hsr-(my*hsr/screen_height)
t = mx*origspect.dur_secs/screen_width
s='mx,my,x,y = {:4d},{:4d},{:2d},{:2d} freq={:5.2f}, t={:4.4f} '.format(mx,my,event.x, event.y, freq,t)
plotText(s,4,4)
pygame.display.update()
#print(event.flipped)
#print(event.which)
# -----------------------------------------------------------------------------
def newROI():
global screen, origspect
global screen_width
global screen_height
global roi
drawSpect(origspect,0,0,screen_width,screen_height)
if roi>=0 and roi<len(origspect.spectrogram[0:-1]):
plotTestSpect(origspect.spectrogram[roi][0:-1],origspect.minval,origspect.maxval)
pygame.display.update()
# -----------------------------------------------------------------------------
# WIP UI stuff
# -----------------------------------------------------------------------------
def handleMouseDown(event):
global screen, origspect
global screen_width
global screen_height
global roi,cutoff_freq,amp_cutoff, amp_cutoff_y
global last_clicked
mx, my = event.pos #pygame.mouse.get_pos()
#print(event)
hsr = origspect.sample_rate/2
if my<int(screen_height/4) and (roi>=0) and (roi<len(origspect.spectrogram)): # clicked on spectum up top
last_clicked = CLICKED_SPECTRUM
freq = hsr-(mx*hsr/screen_width)
if event.button == 1: # left click selects cutoff frequency on spectrogram
cutoff_freq = freq
elif event.button == 3: # right click selects cutoff amplitude on spectrum
amp_cutoff=origspect.maxval-(my*(origspect.maxval-origspect.minval)/(screen_height/4))
amp_cutoff_y=my
elif my>=int(screen_height/4): # clicked on spectrogram
last_clicked = CLICKED_SPECTROGRAM
freq = hsr-(my*hsr/(screen_height-T_AXIS_HEIGHT))
if event.button == 1: # left click selects spectrum in spectrogram
t = mx*origspect.dur_secs/screen_width
sx=int(mx*origspect.maxrowidx/screen_width)
sy=int(my*origspect.maxcolidx/(screen_height-T_AXIS_HEIGHT))
v=origspect.spectrogram[sx][sy]
roi = sx
print(f'ROI {sx}')
#s='mx,my = {:4d},{:4d} freq={:5.2f}, t={:4.4f}, v={:4.1f} '.format(mx,my,freq,t,v)
#plotText(s,4,4)
elif event.button == 3: # right click selects cutoff frequency on spectrogram
cutoff_freq = freq
newROI()
# -----------------------------------------------------------------------------
# Plays the sound that the spectrogram is made from
# -----------------------------------------------------------------------------
def playWave():
global origspect
swave = []
for s in origspect.samples:
i = int(s)
swave.append([i,i])
print('Playing original wave...')
s=pygame.sndarray.make_sound(np.array(swave, dtype="int16"))
pygame.mixer.Sound.play(s)
while pygame.mixer.get_busy():
pygame.time.Clock().tick(10)
# -----------------------------------------------------------------------------
def opToOfs(opidx):
global regofs
return regofs[opidx]
# -----------------------------------------------------------------------------
# resets the opl configuration to just the fixed-value parts
# -----------------------------------------------------------------------------
def initRegs():
global regofs
opl_regs = { (0,0x01): 0x20, (1,0x05): 0x01, (0,0x08): 0x00, (0,0xBD): 0, (1,0x04):0 }
for b in range(0,2):
for j in regofs:
opl_regs[(b,j+0x20)] = 0x20
opl_regs[(b,j+0x40)] = 0x20
opl_regs[(b,j+0x60)] = 0xff
opl_regs[(b,j+0x80)] = 0x0f
opl_regs[(b,j+0xe0)] = 0x00
for j in range(0,0x9):
opl_regs[(b,j+0xA0)] = 0x00
opl_regs[(b,j+0xB0)] = 0x00
opl_regs[(b,j+0xC0)] = 0xf0
return opl_regs
# -----------------------------------------------------------------------------
# genetic algo calls this to impose a mutation on a genome (float32[] cfg vect)
# -----------------------------------------------------------------------------
def mutatefcn(genome, desperation, permutables):
global opl3
ncdist = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,4,4,5,6,7]
numchanges = random.choice(ncdist) + desperation
coup = 0
if desperation>10:
coup = 0.1*(desperation-10)
if coup > 0.8:
coup = 0.8
for c in range(0,numchanges):
x = random.choice(permutables)
if random.random()<=(0.1+coup): # normally a 10% chance to fully re-randomize the element,
genome[x] = random.random()
else: # 90% chance for an incremental bump.
wb = opl3.vec_elem_bits[x]
mag = (1<<wb)-1
i = opl3.vecFltToInt(genome[x],wb)
if random.randint(0,1):
i+=1
else:
i-=1
if i<0:
i=0
elif i>mag:
i=mag
genome[x] = opl3.vecIntToFlt(i,wb)
return genome
# -----------------------------------------------------------------------------
# Given an OPL3 cfg vector and an ideal spectrum, goes through every element
# of the vector, tweaking each element up/down by one count, retaining any
# changes that improved the fit.
# Expensive, so only done by the genetic algorithm for generations where no
# improved offspring were seen.
# -----------------------------------------------------------------------------
def autoTweak(ospect, initfit, v, permutables):
global opl3
newv = deepcopy(v)
vl = len(newv)
tweaks = 0
lastfit = initfit
for j in range(0,len(permutables)):
x = permutables[j]
bw = opl3.vec_elem_bits[x]
mag = (1<<bw)-1
f = newv[x]
i = opl3.vecFltToInt(f, bw)
if i>0:
fa = opl3.vecIntToFlt(i-1,bw)
newv[x] = fa
fita, specta = opl3.fitness(ospect, newv)
if fita<lastfit:
lastfit = fita
newv[x] = fa
tweaks+=1
continue
if i<mag:
fb = opl3.vecIntToFlt(i+1,bw)
newv[x] = fb
fitb, spectb = opl3.fitness(ospect, newv)
if fitb<lastfit:
lastfit = fitb
newv[x] = fb
tweaks+=1
continue
newv[x]=f # no improvement, revert to orig val
return lastfit, newv, tweaks
# -----------------------------------------------------------------------------
# repeatedly calls calls the genetic algorithm's generate() method and shows
# the current best result.
#
# Returns the best OPL3 configuration achieved after either max iterations
# reached, or we stopped seeing improvements for a long time,
# -----------------------------------------------------------------------------
ga = None
def improveMatch(frame, tot_frames, ospect, permutables):
global screen,screen_width,screen_height
global GENE_MAX_GENERATIONS
global desperation
global ga
# width and height of test spectrum displayed during genetic loop
ww = screen_width
hh = screen_height//4
# y ofs to draw position of the display
yofs = screen_height//2
# blank whole bottom half so we can show convengence plot in bottom quarter
pygame.draw.rect(screen,(0,0,0),(0,yofs,ww,hh*2))
desperation = 0 # increased when even auto tweak fails.
lx = ly = px = py = 0
tstart = time.time()
initfit = None
best_spect = None
best_vec = None
best_fit = None
for gen in range(0,GENE_MAX_GENERATIONS):
for event in pygame.event.get():
if event.type == pygame.QUIT:
return HARD_QUIT
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
return SOFT_QUIT
elif event.key == pygame.K_RETURN:
ga.verifyAll()
return NO_QUIT
hfit = float(ga.p[0]['fit'])
hspect = deepcopy(ga.p[0]['spect'])
hgenome = deepcopy(ga.p[0]['genome'])
improved = False
quiet = True
if hspect is not None:
if initfit is None:
initfit = hfit
if best_fit is None:
best_fit = hfit + 1
tnow = time.time()
tdelt = tnow-tstart
if tdelt>=10.0:
quiet = False
tstart = tnow
print(f'Frame:{frame+1}/{tot_frames}, Gen.:{gen:3d}, fit:{hfit:14.9f}, tdelt:{tdelt:0.2f}, desperation:{int(desperation):2d}, ',end='')
sys.stdout.flush()
if hfit < best_fit:
improved = True
best_fit = hfit
desperation = 0
# show current best spectrum
best_spect = hspect
best_vec = hgenome
pygame.draw.rect(screen,(0,0,0),(0,yofs,ww,hh))
plotTestSpect(ospect,-115.0,0,gcolor=(255,255,255),yofs=yofs)
plotTestSpect(hspect,-115.0,0,gcolor=(255,255,0),yofs=yofs)
plotText("Test Spectrum",8,yofs+8)
plotText("Fitness",8,(screen_height-1)-24)
# show fitness plot in green
px = gen*ww//GENE_MAX_GENERATIONS
py = (screen_height-1)-int(hh*hfit/initfit)
if gen>0:
pygame.draw.line(screen,(0,255,0),(lx,ly),(px,py))
lx=px
ly=py
pygame.display.update()
tweaks = -1
if (not improved) and (best_spect is not None):
ogenome = deepcopy(hgenome)
fit, newv, tweaks = autoTweak(ospect, hfit, ogenome, permutables)
if tweaks == 0:
desperation += 1
if desperation >= 50:
print(' -- Moving on.\n')
fitness, tspect = opl3.fitness(ospect, ga.p[0]['genome'])
print(f'improveMatch(): Best fit was {ga.p[0]['fit']}. verification {fitness}')
ga.verifyAll()
return NO_QUIT
else:
ga.add(newv)
ga.generate(desperation, quiet)
if not quiet:
if tweaks != -1:
print(f', tweaks: {tweaks}')
else:
print()
fitness, tspect = opl3.fitness(ospect, ga.p[0]['genome'])
print(f'improveMatch(): Best fit was {ga.p[0]['fit']}. verification {fitness}')
ga.verifyAll()
return NO_QUIT
# -----------------------------------------------------------------------------
# brute force - start with sum of sines, then do GA
# -----------------------------------------------------------------------------
def do_brute(frame, tot_frames, ospect,permutables):
global opl3
global ga
ovects = []
try:
with open(temp_regfile_name,'rb') as f:
while True:
r = f.read(512)
if len(r)!=512:
break
v = opl3.rfToV(r)
ovects.append(v)
except Exception as e:
print(e)
peaks = getRankedPeaks(ospect, -115.0, 0, True, 5, 5)
# make original estimate by setting the OPL to
# generate a sine wave per each spectral peak
l = ''
vvals = []
for chan,p in enumerate(peaks):
pheight, pfreq, _, _, _ = p
if chan>=12:
break
if pheight<-48.0:
break
vfreq = pfreq/OPL3_MAX_FREQ
vamp = pheight/-48 # -48dBFS...0 dBFS : float 1.0...0.0
vvals.append([float(vfreq),float(vamp)])
ch = 0
rf = opl3.initRegFile()
v = opl3.rfToV(rf)
for vfreq, vamp in vvals: # for the loudest peaks, assign a sine
opl3.setNamedVecElemFloat(v,f'Freq.c{ch}',vfreq) # Peak freq
opl3.setNamedVecElemFloat(v,f'KeyOn.c{ch}',1.0) # Key ON
opl3.setNamedVecElemFloat(v,f'SnTyp.c{ch}',1.0) # 2-op AM
oidxs = opidxs_per_chan[ch]
for q,o in enumerate(oidxs):
opl3.setNamedVecElemFloat(v,f'AttnLv.o{o}',vamp) # amplitude
opl3.setNamedVecElemInt(v,f'FMul.o{o}',1) # op phase multiple
opl3.setNamedVecElemInt(v,f'KSAtnLv.o{o}',2) # some attenuation at higher freqs
ch+=1
if ch>=18:
break
del ga
ga = gene.gene(500, ospect, [i for i in range(0,222)], mutatefcn)
if len(ovects):
for i in range(len(ovects)):
ga.add(ovects[i])
for i in range(50):
ga.add(v)
if len(ovects):
for i in range(len(ovects)):
ga.add(ovects[i])
for i in range(50):
ga.add(v)
do_quit = improveMatch(frame, tot_frames, ospect, permutables)
regfile = None
if not do_quit:
regfile = opl3.vToRf(ga.p[0]['genome'])
return regfile, do_quit
# -----------------------------------------------------------------------------
# WIP EXPERIMENT-
# Tries to brute-force a solution using either a (slow) genetic algorithm or a
# convolutional neural-network.
# -----------------------------------------------------------------------------
def bruteForce(brute = False, genetic = False, ai = False):
global origspect
global screen
global screen_width
global screen_height
global opl3
global ga
global SPECS_PER_FRAME
ww = int(screen_width)
hh = int(screen_height//4)
slen = len(origspect.spectrogram)
# The spectragram has 172.265625 spectra/sec,
# so if we do every third spectrum in this brute-force
# loop, that'll be a frame rate of 57.421875 Hz.
try:
if ai:
model = OPL3Model()
model.load_state_dict(torch.load(modelsfolder+'torch_model.pth'))
model.eval() # Set the model to evaluation mode
except:
print('''
#########################################################
SORRY!
------
I couldn't find the AI model at 'models/torch_model.pth'.
Github doesn't want me to push my copy, as it is 600MB.
You can train one yourself with these provided utils:
'src/generate_training_set.py' - Makes training data
'src/pytorch_train_NN.py' - Trains the AI model
My results are currently pretty poor though, even with
a 1 GB training set and 600MB model.
If I start having success with the AI stuff, I will
share the model on my personal website and update
this message and the READMEs. Stay Tuned!
#########################################################
''')
return False
print('\n##############################################################################\n')
print(f'Starting Brute Force: {wavname}')
# init intermediate output file of opl3 reg settings for
# later conversion to a VGM. (TODO!)
# See if we have a work-in-progress file.
tmpfile = temp_regfile_name
try:
tsize = os.path.getsize(tmpfile)
except:
tsize = 0
# if file full, or empty, or len is not multiple of 512, start over.
if (tsize==0) or (tsize%512) or (tsize>=(512*(slen//SPECS_PER_FRAME))):
with open(tmpfile,'wb') as f:
start_roi = 0
start_frame = 0
print('Starting from the beginning.\n')
regfile = None
prior_best = None
else:
with open(tmpfile,'rb') as f:
while True:
rf = f.read(512)