-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathv2m.py
executable file
·1750 lines (1421 loc) · 60.4 KB
/
v2m.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
#!/usr/bin/env python3
# by svsd_val
# jabber : [email protected]
# mail to: [email protected]
import sys
import os
import re
filepath=''
if ( len(sys.argv) < 2 ):
if sys.platform.startswith('win'):
from tkinter import Tk
from tkinter import filedialog as fd
root=Tk()
root.withdraw()
filepath= fd.askopenfilename(filetypes=(("Video Files", ".mpg .mkv .avi .webm .mp4"), ("All Files", "*.*")))
root.destroy()
print("get file [" + filepath +"]")
else:
print("halt, no args")
sys.exit( 0 )
else:
filepath = sys.argv[1]
if not os.path.exists( filepath ):
has_pytube = False
try:
from pytube import YouTube
has_pytube = True
except:
pass
if has_pytube:
print("Downloading video by url: %s ..." % filepath)
yt = YouTube( filepath )
videos = [ { 'itag' : i.itag, 'res' : int(re.sub('[^0-9]','', i.resolution)), 'progressive' : int(i.is_progressive) } for i in yt.streams.filter(file_extension='mp4') if i.mime_type.find("video") != -1 ]
print(videos)
videos = sorted( videos , key = lambda d : ( -d['progressive'], - d['res']) )
print('sorted by progressive (has video & audio in same file) and video resolution')
for i in videos:
print('processing: %s' % i)
filepath = "%s_%s_%s.mp4" % ( re.sub(r'[\W_]','_', yt.title), i['itag'], i['res'])
yt.streams.get_by_itag(i['itag']).download( "./" , filepath, skip_existing=True)
break
else:
print("file not exists [" + filepath +"], and no pytube has installed..., exit.")
sys.exit( 0 )
import math
import ntpath
import time
from os.path import expanduser
import cv2
import pygame
from midiutil.MidiFile import MIDIFile
from OpenGL.GL import *
from OpenGL.GLU import *
from pygame.locals import *
print(f'open file [{filepath}]')
vidcap = cv2.VideoCapture( filepath )
outputmid= ntpath.basename( filepath ) + '_output.mid'
settingsfile= filepath + '.ini'
import datetime
import video2midi.settings as settings
from video2midi.gl import *
from video2midi.midi import *
from video2midi.prefs import prefs
width=640
height=480
mpos = [0,0]
keygrab=0
keygrabid=-1
lastkeygrabid=-1
frame= 0
printed_for_frame=0
convertCvtColor=1
# For OpenCV 2.X ..
CAP_PROP_FRAME_COUNT =0
CAP_PROP_POS_FRAMES =0
CAP_PROP_POS_MSEC =0
CAP_PROP_FRAME_WIDTH =0
CAP_PROP_FRAME_HEIGHT=0
CAP_PROP_FPS =0
COLOR_BGR2RGB =0
print("OpenCV version:" + cv2.__version__ )
if cv2.__version__.startswith('2.'):
CAP_PROP_FRAME_COUNT = cv2.cv.CV_CAP_PROP_FRAME_COUNT
CAP_PROP_POS_FRAMES = cv2.cv.CV_CAP_PROP_POS_FRAMES
CAP_PROP_POS_MSEC = cv2.cv.CV_CAP_PROP_POS_MSEC
CAP_PROP_FRAME_WIDTH = cv2.cv.CV_CAP_PROP_FRAME_WIDTH
CAP_PROP_FRAME_HEIGHT = cv2.cv.CV_CAP_PROP_FRAME_HEIGHT
CAP_PROP_FPS = cv2.cv.CV_CAP_PROP_FPS
else:
# 3, 4 , etc ...
CAP_PROP_FRAME_COUNT = cv2.CAP_PROP_FRAME_COUNT
CAP_PROP_POS_FRAMES = cv2.CAP_PROP_POS_FRAMES
CAP_PROP_POS_MSEC = cv2.CAP_PROP_POS_MSEC
CAP_PROP_FRAME_WIDTH = cv2.CAP_PROP_FRAME_WIDTH
CAP_PROP_FRAME_HEIGHT = cv2.CAP_PROP_FRAME_HEIGHT
CAP_PROP_FPS = cv2.CAP_PROP_FPS
COLOR_BGR2RGB = cv2.COLOR_BGR2RGB
vidcap.set(CAP_PROP_POS_FRAMES, frame)
vidcap.set(cv2.CAP_PROP_BUFFERSIZE, 2)
success,image = vidcap.read()
debug_keys = 0
length = int(vidcap.get(CAP_PROP_FRAME_COUNT))
video_width = int(vidcap.get(CAP_PROP_FRAME_WIDTH))
video_height = int(vidcap.get(CAP_PROP_FRAME_HEIGHT))
fps = float(vidcap.get(CAP_PROP_FPS))
width = video_width
height = video_height
def fit_to_the_screen() -> None:
global width, height
infoObject = pygame.display.Info()
if (width > infoObject.current_w) or ( height > infoObject.current_h):
print("try fit window to the screen")
print("current window size: %sx%s" %(width,height))
print("current screen size: %sx%s" %(infoObject.current_w, infoObject.current_h))
ratio = ( width / infoObject.current_w)
width = int(width / ratio * 0.9 )
height = int(height / ratio *0.9)
print("new window size: %sx%s" %(width,height))
pygame.init()
fit_to_the_screen()
endframe = length
showoutputpath = 0
def resize_window() -> None:
global screen, width, height
if prefs.resize:
width = prefs.resize_width
height = prefs.resize_height
else:
width = video_width
height = video_height
fit_to_the_screen()
screen = pygame.display.set_mode((width,height), DOUBLEBUF|OPENGL|pygame.RESIZABLE)
doinit()
# set start frame
def getFrame(framenum:int = -1) -> None:
global image
global success
global width
global height
global convertCvtColor
global fps
if ( fps == 0 ):
return
goto_frame_by_msec=False
if ( framenum != -1 ):
#vidcap.set(CAP_PROP_POS_FRAMES, int(framenum) )
# problems with mpeg formats ...
if goto_frame_by_msec:
oldframenum = int(round(vidcap.get(1)))
frametime = framenum * 1000.0 / fps
print("go to frame time :" + str(frametime))
success = vidcap.set(CAP_PROP_POS_MSEC, frametime)
if not success:
print("Cannot set frame position from video file at " + str(framenum))
success = vidcap.set(CAP_PROP_POS_FRAMES, int(oldframenum) )
else:
success = vidcap.set(CAP_PROP_POS_FRAMES, framenum )
curframe = vidcap.get(CAP_PROP_POS_FRAMES)
if (curframe != framenum ):
print("OpenCV bug, Requesting frame " + str(framenum) + " but get position on " +str(curframe))
success,image = vidcap.read()
# if ( resize == 1 ):
# image = cv2.resize(image, (resize_width , resize_height))
# print "resize to "+str(resize_width) + "x"+ str(resize_height)
getFrame()
print("video " + str(width) + "x" + str(height) +" fps: " + str(fps))
# add some notes
channel = 0
volume = 100
basenote = prefs.octave * 12
notes=[]
notes_db=[]
notes_de=[]
notes_channel=[]
notes_tmp=[]
notes_pressed_color=[]
colorWindow_colorBtns_channel_labels=[]
colorWindow_colorBtns_channel_btns=[]
separate_note_id=-1
screen=0
colorBtns = []
#quantized notes to the grid.
use_snap_notes_to_grid = False
notes_grid_size=32
midi_file_format = 0
line_height = 20
running = 1
#cfg
home = expanduser("~")
inifile = os.path.join( home, '.v2m.ini')
if os.path.exists( 'v2m.ini' ):
inifile="v2m.ini"
print("local config file exists.")
def update_size() -> None:
global width, height
if ( prefs.resize == 1 ):
width = prefs.resize_width
height = prefs.resize_height
else:
fit_to_the_screen()
def loadsettings(cfgfile: str) -> None:
global colorBtns, colorWindow_colorBtns_channel_labels
settings.loadsettings(cfgfile)
settings.compatibleColors(colorBtns)
if len(colorWindow_colorBtns_channel_labels) > 0:
for i in range(len(colorBtns)):
colorWindow_colorBtns_channel_labels[i].text = "Ch:" + str(prefs.keyp_colors_channel[i]+1)
update_size
if 'glwindows' in globals():
glBindTexture(GL_TEXTURE_2D, Gl.bgImgGL)
loadImage(prefs.startframe)
settingsWindow_slider1.setvalue(prefs.keyp_delta)
settingsWindow_slider2.setvalue(prefs.minimal_duration * 100)
settingsWindow_slider3.setvalue(prefs.tempo)
settingsWindow_slider7.setvalue(prefs.keys_pos_cnt)
sparks_switch.switch_status = prefs.use_sparks
sparks_slider_delta.value = 0
sparks_slider_delta.id =-1
settingsWindow_rollcheck_button.switch_status = prefs.rollcheck
settingsWindow_rollcheck_priority_button.switch_status = prefs.rollcheck_priority
use_percolor_delta.switch_status = prefs.use_percolor_delta
notes_overlap_btn.switch_status = prefs.notes_overlap
ignore_notes_with_minimal_duration_btn.switch_status = prefs.ignore_minimal_duration
update_size
for i in range(144):
notes.append(0)
notes_db.append(0)
notes_de.append(0)
notes_channel.append(0)
notes_tmp.append(0)
notes_pressed_color.append([0,0,0])
prefs.keyp_colors_alternate.append([0,0,0])
prefs.keyp_colors_alternate_sensitivity.append(0)
def v_rotate(v, ang):
radAng = ang * math.pi/180
return [ (v[1] * math.cos(radAng)) - (v[0] * math.sin(radAng)), (v[1] * math.sin(radAng)) + (v[0] * math.cos(radAng)) ]
def updatekeys( append=0 ):
xx=0
if append == 1:
print(f'clear keys, set to {prefs.keys_pos_cnt}')
prefs.keys_pos = []
for idx in range (prefs.keys_pos_cnt):
i = idx // 12
j = idx % 12
# for i in range(12):
# for j in range(12):
if (append == 1) or (i*12+j > len(prefs.keys_pos)-1):
prefs.keys_pos.append( [0,0] )
prefs.keys_pos[i*12+j][0] = int(round( xx ))
prefs.keys_pos[i*12+j][1] = 0
if (j == 1) or ( j ==3 ) or ( j == 6 ) or ( j == 8) or ( j == 10 ):
prefs.keys_pos[i*12+j][1] = prefs.yoffset_blackkeys
xx += -prefs.whitekey_width
# keys_pos[i*12+j][0] = int(round( xx + whitekey_width *0.5 ))
# tune by wuzhuoqing
if (j == 1) or ( j == 6 ):
prefs.keys_pos[i*12+j][0] = int(round( xx + prefs.whitekey_width * prefs.blackkey_relative_position ))
if (j == 8 ):
prefs.keys_pos[i*12+j][0] = int(round( xx + prefs.whitekey_width * 0.5 ))
if ( j ==3 ) or ( j == 10 ):
prefs.keys_pos[i*12+j][0] = int(round( xx + prefs.whitekey_width * (1.0 - prefs.blackkey_relative_position) ))
xx += prefs.whitekey_width
for i in range(len(prefs.keys_pos)):
prefs.keys_pos[i] = v_rotate( prefs.keys_pos[i] , prefs.keys_angle )
prefs.keys_pos[i][0] = - prefs.keys_pos[i][0]
updatekeys( 1 )
loadsettings(inifile)
tStart = t0 = time.time()-1
frames = 0
def snap_to_grid( input_value , input_grid_size ):
quantized = int( (input_value - int(input_value)) * input_grid_size ) / input_grid_size
result = (quantized + int(input_value))
#print ("value before:", input_value , " after :", result)
return result
def framerate():
global t0, frames
t = time.time()
frames += 1
if t - t0 >= 1.0:
seconds = t - t0
if ( seconds != 0) :
fps = frames / seconds
print("%.0f frames in %3.1f seconds = %6.3f FPS" % (frames,seconds,fps))
t0 = t
frames = 0
def loadImage(idframe=130):
global image
global convertCvtColor
if running != 0:
getFrame(idframe)
#image2=cv2.resize(image, (int(video_width/4) , int(video_height/4)))
print("load image from video " + str(width) + "x" + str(height) + " frame: "+ str(idframe))
glPixelStorei(GL_UNPACK_ALIGNMENT,1)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
error_on_load=False
try:
if ( convertCvtColor == 1 ):
#print ("Loading RGB texture")
glTexImage2D(GL_TEXTURE_2D, 0, 3, video_width, video_height, 0, GL_RGB, GL_UNSIGNED_BYTE, cv2.cvtColor(image,COLOR_BGR2RGB) )
else:
#print ("Loading BGR texture")
glTexImage2D(GL_TEXTURE_2D, 0, 3, video_width, video_height, 0, GL_BGR, GL_UNSIGNED_BYTE, image )
return
except Exception as E:
error_on_load=True
print("Can't load image from video to OpenGL: %s" % E);
if error_on_load:
rvideo_width, rvideo_height = 512, 512
print("Trying resize video image to %sx%s" % (rvideo_width, rvideo_height));
try:
rimage = cv2.resize(image , (rvideo_width, rvideo_height))
if ( convertCvtColor == 1 ):
glTexImage2D(GL_TEXTURE_2D, 0, 3, rvideo_width, rvideo_height, 0, GL_RGB, GL_UNSIGNED_BYTE, cv2.cvtColor(rimage,COLOR_BGR2RGB) )
else:
glTexImage2D(GL_TEXTURE_2D, 0, 3, rvideo_width, rvideo_height, 0, GL_BGR, GL_UNSIGNED_BYTE, rimage )
except Exception as E:
print("Can't load image from video to OpenGL: %s" % E);
def update_channels(sender):
print( 'update_channels...' +str(sender.index))
i=abs(sender.index) -1
if (sender.index > 0):
prefs.keyp_colors_channel[i]= prefs.keyp_colors_channel[i] + 1
else:
prefs.keyp_colors_channel[i]= prefs.keyp_colors_channel[i] - 1
if (prefs.keyp_colors_channel[i] > 15):
prefs.keyp_colors_channel[i] = 15
if (prefs.keyp_colors_channel[i] < 0):
prefs.keyp_colors_channel[i] = 0
colorWindow_colorBtns_channel_labels[i].text = "Ch:" + str(prefs.keyp_colors_channel[i]+1)
def disable_color(sender):
print( 'disabled color...' +str(sender.index))
if sender.index < len(prefs.keyp_colors):
prefs.keyp_colors[ sender.index ] = [0,0,0]
# prefs.keyp_colors_channel[i]= prefs.keyp_colors_channel[i] + 1
def readkeycolor(i):
pixx=int(prefs.xoffset_whitekeys + prefs.keys_pos[i][0])
pixy=int(prefs.yoffset_whitekeys + prefs.keys_pos[i][1])
if ( pixx >= width ) or ( pixy >= height ) or ( pixx < 0 ) or ( pixy < 0 ): return
if ( prefs.resize == 1 ):
pixxo=pixx
pixyo=pixy
pixx= int(round( pixx * ( video_width / float(prefs.resize_width) )))
pixy= int(round( pixy * ( video_height / float(prefs.resize_height) )))
if ( pixx > video_width -1 ): pixx = video_width-1
if ( pixy > video_height-1 ): pixy= video_height-1
# print "original x:"+str(pixxo) + "x" +str(pixyo) + " mapped :" +str(pixx) +"x"+str(pixy)
keybgr=image[pixy,pixx]
key=[ keybgr[2], keybgr[1],keybgr[0] ]
prefs.keyp_colors_alternate[i] = key
def readcolors(sender):
for i in range( len(prefs.keys_pos) ):
readkeycolor(i)
def update_alternate_sensitivity(sender,value):
global lastkeygrabid
if ( lastkeygrabid != -1 ):
prefs.keyp_colors_alternate_sensitivity[ lastkeygrabid ] = value
def update_sparks_delta(sender,value):
if (sender.id == -1):
return
if (sender.id < len(prefs.keyp_colors)) :
prefs.keyp_colors_sparks_sensitivity[sender.id] = sender.value
#print("keyp_colors_sparks_sensitivity["+str(sender.id)+"] = "+ str(sender.value) )
def update_blackkey_relative_position(sender,value):
prefs.blackkey_relative_position = value * 0.001
updatekeys()
def update_sync_notes_start_pos_time_delta(sender,value):
prefs.sync_notes_start_pos_time_delta = value *0.001
def change_use_alternate_keys(sender):
global extra_label1
prefs.use_alternate_keys = not prefs.use_alternate_keys
update_alternate_label()
def update_alternate_label():
extra_label1.text = "Use alternate:"+str(prefs.use_alternate_keys)
def change_use_sparks(sender):
prefs.use_sparks = sender.switch_status
# sender.text = "use sparks:"+str(use_sparks)
def change_rollcheck(sender):
prefs.rollcheck = sender.switch_status
def change_rollcheck_priority(sender):
prefs.rollcheck_priority = sender.switch_status
def updatecolor(sender):
if (lastkeygrabid != -1):
readkeycolor(lastkeygrabid)
def update_sparks_y_pos (sender):
if (sender.text == 'y+'):
prefs.keyp_spark_y_pos = prefs.keyp_spark_y_pos -1
else:
prefs.keyp_spark_y_pos = prefs.keyp_spark_y_pos +1
def update_line_height(sender,value):
global line_height
line_height = value
def snap_notes_to_the_grid(sender):
global use_snap_notes_to_grid
use_snap_notes_to_grid = sender.switch_status
def raise_octave(*args):
global basenote
prefs.octave += 1
if (prefs.octave > 7): prefs.octave = 7
basenote = prefs.octave * 12
def lower_octave(*args):
global basenote
prefs.octave -= 1
if (prefs.octave < 0): prefs.octave = 0
basenote = prefs.octave * 12
def onPallete_click(sender, index):
selected_color_delta.color = sender.color
if index < len(prefs.percolor_delta):
selected_color_delta.setvalue( prefs.percolor_delta[ index ] )
sparks_slider_delta.id = Gl.keyp_colormap_id
sparks_slider_delta.color = prefs.keyp_colors[Gl.keyp_colormap_id]
sparks_slider_delta.setvalue( prefs.keyp_colors_sparks_sensitivity[Gl.keyp_colormap_id] )
def change_use_percolor_delta(sender):
prefs.use_percolor_delta = sender.switch_status
def update_percolor_delta(sender,value):
if (Gl.keyp_colormap_id == -1):
return
if (Gl.keyp_colormap_id < len(prefs.percolor_delta)):
prefs.percolor_delta[ Gl.keyp_colormap_id ] = sender.value
#print("changed percolor delta for color with id ["+str(sender.id)+"] = "+ str(sender.value) )
def showOrhideallwindows(sender):
if sender is None:
ShowHideButton.switch_status = not ShowHideButton.switch_status
print('switch hidden for all windows')
for i in glwindows:
#print("i.type =%s" % (str(type(i))) )
if isinstance(i, GLWindow ):
i.fullhidden = ShowHideButton.switch_status
def start_recreate_midi(sender):
global running
if prefs.autoclose == 1:
running = 0
else:
reconstruct()
def set_start_frame_to_current_frame(sender):
if sender.index == 0:
prefs.startframe = int(round(vidcap.get(1)))
else:
prefs.startframe = 0
print("set start frame = "+ str(prefs.startframe))
def sef_end_frame_to_current_frame(sender):
global endframe
if sender.index == 0:
endframe = int(round(vidcap.get(1)))
else:
endframe = length
print("set end frame = "+ str(endframe), sender.index)
def switch_notes_overlap(sender):
if sender is None:
prefs.notes_overlap = not prefs.notes_overlap
notes_overlap_btn.switch_status = prefs.notes_overlap
else:
prefs.notes_overlap = notes_overlap_btn.switch_status
def switch_sync_notes_start_pos(sender):
prefs.sync_notes_start_pos = sender.switch_status
def change_save_to_disk_per_channel(sender):
prefs.save_to_disk_per_channel = sender.switch_status
def switch_ignore_notes_with_minimal_duration(sender):
if sender is None:
prefs.ignore_minimal_duration = not prefs.ignore_minimal_duration
ignore_notes_with_minimal_duration_btn.switch_status = prefs.ignore_minimal_duration
else:
prefs.ignore_minimal_duration = ignore_notes_with_minimal_duration_btn.switch_status
def switch_resize_windows(sender):
prefs.resize = not prefs.resize
resize_window()
def scroll_by_steps( steps ):
global frame
frame+=steps
if (frame > length *0.99):
frame=math.trunc(length *0.99)
if (frame < 1):
frame=1
glBindTexture(GL_TEXTURE_2D, Gl.bgImgGL)
loadImage(frame)
def scroll_forward_by_frame(sender):
scroll_by_steps(1)
def scroll_fast_forward(sender):
scroll_by_steps(100)
def scroll_prev_by_frame(sender):
scroll_by_steps(-1)
def scroll_fast_prev(sender):
scroll_by_steps(-100)
def scroll_to_start(sender):
global frame
frame=0
glBindTexture(GL_TEXTURE_2D, Gl.bgImgGL)
loadImage(frame)
def scroll_to_end(sender):
global frame
frame=length-100
glBindTexture(GL_TEXTURE_2D, Gl.bgImgGL)
loadImage(frame)
def btndown_save_settings(sender):
settings.savesettings(settingsfile)
def btndown_load_settings(sender):
old_resize = prefs.resize
loadsettings( settingsfile )
update_alternate_label()
if (prefs.resize != old_resize):
resize_window()
def change_autoclose(sender):
prefs.autoclose = sender.switch_status
def rotate_cw(sender):
prefs.keys_angle -= 5
updatekeys()
def rotate_ccw(sender):
prefs.keys_angle += 5
updatekeys()
def update_keys_pos_cnt(sender,value):
prefs.keys_pos_cnt=int(value)
def change_cnt(sender):
print('change count')
updatekeys(1)
def is_black_key(key_id : int) -> bool:
j = key_id % 12
return (j == 1) or ( j == 3 ) or ( j == 6 ) or ( j == 8) or ( j == 10 )
def vertical_align_keys( separate_black_keys = 1, align = 1 ):
print(f"lastkeygrabid {lastkeygrabid}")
if lastkeygrabid < 0 or lastkeygrabid > len(prefs.keys_pos):
return
y = prefs.keys_pos[lastkeygrabid][align]
selected_black_key = is_black_key(lastkeygrabid)
for idx in range (len(prefs.keys_pos)):
if separate_black_keys == 1:
if selected_black_key:
if is_black_key(idx):
prefs.keys_pos[idx][align] = y
else:
if not is_black_key(idx):
prefs.keys_pos[idx][align] = y
else:
prefs.keys_pos[idx][align] = y
def valign(sender):
vertical_align_keys(align=1)
def halign(sender):
vertical_align_keys(align=0)
wh = ( (len(prefs.keyp_colors) // 2)+2 ) * 24 - 24
colorWindow = GLWindow(24, 50, 274, wh, "color map")
settingsWindow = GLWindow(24+275, 80, 550, 380, "Settings")
helpWindow = GLWindow(24+270, 50, 750, 535, "help")
extraWindow = GLWindow(24+270+550+6, 80, 510, 250, "extra/experimental")
sparksWindow = GLWindow(24+270+550+6, 300, 510, 185, "sparks & color settings")
glwindows = []
ShowHideButton = GLButton(0,0 ,13,13, 1, [128,128,128], "" , showOrhideallwindows ,switch=1, switch_status=0 )
ShowHideButton.active = 2
glwindows.append(ShowHideButton)
glwindows.append(colorWindow)
glwindows.append(settingsWindow)
glwindows.append(helpWindow)
glwindows.append(extraWindow)
glwindows.append(sparksWindow)
helpWindow.hidden=1
helpWindow_label1 = GLLabel(0,0, """h - on window title, show/hide the window
q - begin to recreate midi
s - set start frame, (mods : shift, set processing start frame to the beginning)
e - set end frame, (mods : shift, set processing end frame to the ending)
p - if key is set, force separate to 2 channels (on single color video)
o - enable or disable overlap notes
i - enable or disable ignore/lengthening of notes with minimal duration
r - enable or disable resize function
Mouse wheel - keys adjustment
Left mouse button - dragging the selected key / select color from the color map
CTRL + Left mouse button - update selected color in the color map
CTRL + 0 - disable selected color in the color map
Right mouse button - dragging all keys, if the key is selected, the transfer is carried out relative to it.
Arrows - keys adjustment (mods : shift) ( Atl+Arrows UP/Down - sparks position adjustment )
+(PLUS) / - (MINUS) - rotate keys by 5*
PageUp/PageDown - scrolling video (mods : shift)
Home/End - go to the beginning or end of the video
[ / ] - change base octave
F2 / F3 - save / load settings, F4 - move all windows to the mouse point
Escape - quit, TAB - Show/Hide all windows
Space - abort re-creation and save midi file to disk
4,6,8,2 on numpad - move the selected key by 1 pixel on each axis
1,3 - vertical / horizontal alignment""")
settingsWindow.appendChild( GLButton(260, 20 ,140,20,0 , [128,128,128], "start recreate midi" , start_recreate_midi , hint = "q - hot key") )
settingsWindow.appendChild( GLButton(260, 40 ,140,20,0 , [128,128,128], "set start frame" , set_start_frame_to_current_frame, hint = "s - hot key, (mods : shift + s, set processing start frame to the beginning)" ) )
settingsWindow.appendChild( GLButton(260+141, 40 ,140,20,0, [128,128,128], "set end frame" , sef_end_frame_to_current_frame , hint = "e - hot key, (mods : shift + e, set processing end frame to the ending)" ) )
notes_overlap_btn = GLButton(260, 80 ,140,20,0, [128,128,128], "notes overlap" , switch_notes_overlap , hint = "o - hot key", switch=1, switch_status=0)
ignore_notes_with_minimal_duration_btn = GLButton(260,100 ,272,20,0, [128,128,128], "ignore notes with minimal duration", switch_ignore_notes_with_minimal_duration, hint = "i - hot key", switch=1, switch_status=0)
settingsWindow.appendChild( notes_overlap_btn )
settingsWindow.appendChild( ignore_notes_with_minimal_duration_btn )
settingsWindow.appendChild( GLButton(260+141, 80 ,140,20,0, [128,128,128], "sync notes" , switch_sync_notes_start_pos , hint = "sync notes start pos", switch=1, switch_status=0) )
settingsWindow.appendChild( GLButton(260,120 ,140,20,0, [128,128,128], "resize window" , switch_resize_windows , hint = "r - hot key") )
exit_switch = GLButton(260+141, 120 ,140,20,1, [128,128,128], "auto-close" ,change_autoclose,switch=1, switch_status= prefs.autoclose, hint = "exit after the completion of the midi reconstruction" )
settingsWindow.appendChild( exit_switch )
settingsWindow.appendChild( GLButton(260 , 140 ,140,20,0, [128,128,128], "save settings" , btndown_save_settings , hint = "F2 - hot key, save current settings" ) )
settingsWindow.appendChild( GLButton(260+141, 140 ,140,20,0, [128,128,128], "load settings" , btndown_load_settings , hint = "F3 - hot key, load saved settings" ) )
navbtns_info = [
{'name' : "[<", 'hint' : 'Home - hot key, go to first frame',
'func' : scroll_to_start },
{'name' : "<<", 'hint' : 'PageDown - hot key, fast scroll backward',
'func' : scroll_fast_prev },
{'name' : " <", 'hint' : 'Shift+PageDown - shortcut, scroll backward by frame',
'func' : scroll_prev_by_frame },
{'name' : " >", 'hint' : 'Shift+PageUp - shortcut, scroll forward by frame',
'func' : scroll_forward_by_frame },
{'name' : ">>", 'hint' : 'PageUp - hot key,fast scroll forward',
'func' : scroll_fast_forward },
{'name' : " >]", 'hint' : 'End - hot key, go to last frame',
'func' : scroll_to_end },
{'name' : "R+", 'hint' : 'rotate the keys clockwise, hot key +',
'func' : rotate_cw },
{'name' : "R-", 'hint' : 'rotate the keys counterclockwise, hot key -',
'func' : rotate_ccw }
]
#btnfuncs = [ None, None, None, None, None, None ]
for i in range(len( navbtns_info )):
settingsWindow.appendChild( GLButton(260 + i * 32,230 ,32,20,0, [128,128,128], navbtns_info[i]['name'] , navbtns_info[i]['func'], hint = navbtns_info[i]['hint']) )
settingsWindow.appendChild( GLButton(260 , 295 ,140,20,0, [128,128,128], "update count", change_cnt , hint = "Change keys count" ) )
settingsWindow.appendChild( GLButton(260+141, 295 ,70,20,0, [128,128,128], "v. align", valign , hint = "vertical alignment of keys to the selected key" ) )
settingsWindow.appendChild( GLButton(260+141+70, 295 ,70,20,0, [128,128,128], "h. align", halign , hint = "horizontal alignment of keys to the selected key" ) )
helpWindow.appendChild(helpWindow_label1)
settingsWindow_label1 = GLLabel(1,0, "base octave: " + str(prefs.octave))
# + "\nnotes overlap: " + str(prefs.notes_overlap) + "\nignore minimal duration: " + str(prefs.ignore_minimal_duration))
settingsWindow.appendChild(settingsWindow_label1)
settingsWindow.appendChild( GLButton(130,0 ,20,20,1, [128,128,128], "+", raise_octave, hint = "] - hot key, move up base octave (+12 tones)" ) )
settingsWindow.appendChild( GLButton(150,0 ,20,20,1, [128,128,128], " -", lower_octave, hint = "[ - hot key, move down base octave (-12 tones)" ) )
settingsWindow_slider1 = GLSlider(1,40, 240,18, 0,130,prefs.keyp_delta,label="Sensitivity")
settingsWindow_slider1.round=1
settingsWindow.appendChild(settingsWindow_slider1)
settingsWindow_slider2 = GLSlider(1,90, 240,18, 0,200,prefs.minimal_duration*100,label="Minimal note duration (sec)")
settingsWindow_slider2.round=0
settingsWindow.appendChild(settingsWindow_slider2)
settingsWindow_slider3 = GLSlider(1,133, 240,18, 30,240,prefs.tempo,label="Output tempo for midi")
settingsWindow_slider3.round=0
settingsWindow.appendChild(settingsWindow_slider3)
settingsWindow_slider4 = GLSlider(1,175, 240,18, 0,2,midi_file_format,label="Output midi format")
settingsWindow_slider4.round=0
settingsWindow.appendChild(settingsWindow_slider4)
settingsWindow_slider5 = GLSlider(1,215, 240,18, 0,1000,prefs.blackkey_relative_position * 1000, update_blackkey_relative_position, label="black key relative pos")
settingsWindow_slider5.round=0
settingsWindow.appendChild(settingsWindow_slider5)
settingsWindow_slider6 = GLSlider(1,255, 240,18, 0,1000,prefs.sync_notes_start_pos_time_delta, update_sync_notes_start_pos_time_delta, label="sync notes time delta (ms)")
settingsWindow_slider6.round=0
settingsWindow.appendChild(settingsWindow_slider6)
settingsWindow_slider7 = GLSlider(1,295, 240,18, 12,144,prefs.keys_pos_cnt,update_keys_pos_cnt, label="Keys count")
settingsWindow_slider7.round=0
settingsWindow.appendChild(settingsWindow_slider7)
settingsWindow_rollcheck_button = GLButton(260,160 ,140,22,1, [128,128,128], "roll check" ,change_rollcheck,switch=1, switch_status=prefs.rollcheck )
settingsWindow.appendChild(settingsWindow_rollcheck_button)
settingsWindow.appendChild( GLButton(260+141, 160 ,140,20,1, [128,128,128], "per channel save" ,change_save_to_disk_per_channel,switch=1, switch_status= prefs.save_to_disk_per_channel, hint = "split the output midi per channels" ) )
settingsWindow_rollcheck_priority_button = GLButton(260,180 ,222,22,1, [128,128,128], "rollcheck white keys priority" ,change_rollcheck_priority,switch=1, switch_status=prefs.rollcheck_priority )
settingsWindow.appendChild(settingsWindow_rollcheck_priority_button)
# for i in range( len( keyp_colors ) ):
#keyp_colormap_colors_pos.append ([ (i % 2) * 32, ( i // 2 ) * 20 ])
print ('creating new colors '+str(len( prefs.keyp_colors )))
sparks_slider_delta = GLSlider(6,25, 150,18, -50,150,50,update_sparks_delta, label="Sparks delta")
for i in range( len( prefs.keyp_colors ) ):
cx,cy = (i % 2) * 130, ( i // 2 ) * 20
offsetx,offsety=4,4
colorBtns.append( GLColorButton(offsetx+cx,offsety+cy ,20,20,i, prefs.keyp_colors[i], onPallete_click ) )
colorWindow.appendChild(colorBtns[i])
colorWindow_label1 = GLLabel(offsetx+25+cx,offsety+cy , "Ch:" + str(prefs.keyp_colors_channel[i]+1) )
colorWindow_colorBtns_channel_labels.append( colorWindow_label1 )
colorWindow.appendChild(colorWindow_label1)
colorWindow_colorBtns_channel_btns.append( GLButton(offsetx+cx+70,offsety+cy ,20,20,(i+1), [128,128,128], "+" ,update_channels) )
colorWindow_colorBtns_channel_btns.append( GLButton(offsetx+cx+70+20,offsety+cy ,20,20,-(i+1), [128,128,128], "-" ,update_channels) )
colorWindow_colorBtns_channel_btns.append( GLButton(offsetx+cx+70+40,offsety+cy ,20,20,i, [128,128,128], "x" ,disable_color, hint="ctrl+0 - shortcut, disable selected color") )
for i in colorWindow_colorBtns_channel_btns:
colorWindow.appendChild( i )
extraWindow.appendChild( GLButton(5, 20 ,128,25,1, [128,128,128], "read colors" ,readcolors) )
extraWindow.appendChild( GLButton(135,20 ,128,25,1, [128,128,128], "update color" ,updatecolor) )
extraWindow.appendChild( GLButton(265,20 ,138,25,1, [128,128,128], "enable/disable" ,change_use_alternate_keys) )
extraWindow.appendChild( GLButton(265,45 ,155,22,1, [96 ,96 ,128], "snap notes to grid" ,snap_notes_to_the_grid,switch=1, switch_status=use_snap_notes_to_grid) )
extra_label1 = GLLabel(6,0, "Use alternate:"+str(prefs.use_alternate_keys) )
extraWindow.appendChild( extra_label1 )
#extra_label2 = GLLabel(0,67, "Selected key sensitivity:"+str(0) )
extra_slider1 = GLSlider(6,65, 240,18, -100,100,0,update_alternate_sensitivity, label="Selected key sensitivity")
#extra_slider1.showvalue=True
#showvaluesinlabel=0
extraWindow.appendChild(extra_slider1)
extra_label3 = GLLabel( 6,90, """to select the key press ctrl + left mouse button on the key rect.
to deselect the key press ctrl + left mouse button on empty space.""" )
extraWindow.appendChild( extra_label3 )
extraWindow_slider2 = GLSlider(5,155, 240,18, 0,2000, line_height, update_line_height, label="length of vertical key lines")
extraWindow_slider2.round=0
extraWindow.appendChild(extraWindow_slider2)
sparks_slider_height = GLSlider(160,25, 150,18, 1,60,1,None, label="Sparks height")
sparks_slider_height.round=0
sparks_switch = GLButton(313,24 ,100,22,1, [128,128,128], "use sparks" ,change_use_sparks,switch=1, switch_status=prefs.use_sparks )
sparksWindow.appendChild( sparks_slider_delta )
sparksWindow.appendChild( sparks_slider_height )
sparksWindow.appendChild( sparks_switch )
#
sparksWindow.appendChild( GLButton(413 ,24 ,32,22,1, [96,96,128], "y+" ,update_sparks_y_pos, hint="move sparks higher") )
sparksWindow.appendChild( GLButton(413+33,24 ,32,22,1, [96,96,128], "y-" ,update_sparks_y_pos, hint="move sparks lower") )
sparksWindow.appendChild( GLLabel( 6,50, "alt + up / down - move sparks label up or down " ))
selected_color_delta = GLSlider(6,100, 200,18, 0,130,50,update_percolor_delta, label="percolor sensitivity")
selected_color_delta.round=1
use_percolor_delta = GLButton(313,100 ,190,22,1, [128,128,128], "use percolor sensitivity" ,change_use_percolor_delta,switch=1, switch_status=prefs.use_sparks )
sparksWindow.appendChild( selected_color_delta )
sparksWindow.appendChild( use_percolor_delta )
#colorSettingsWindow.appendChild( GLButton(413 ,24 ,64,22,1, [96,96,128], "Pallette" , None ) )
#
#extra_slider2.showvalue=True
#extra.appendChild(extra_label2)
#loadsettings( settingsfile )
#frame=801
def getkeyp_pixel_pos( x:int, y:int ) -> list[int]:
pixx=int(prefs.xoffset_whitekeys + x)
pixy=int(prefs.yoffset_whitekeys + y)
if ( pixx >= width ) or ( pixy >= height ) or ( pixx < 0 ) or ( pixy < 0 ):
return [-1,-1]
#if ( prefs.resize == 1 ):
if 1==1: #disabled
pixx= int(round( pixx * ( video_width / float(width) )))
pixy= int(round( pixy * ( video_height / float(height) )))
if ( pixx > video_width -1 ): pixx = video_width-1
if ( pixy > video_height-1 ): pixy= video_height-1
return [pixx,pixy]
def iswhitekey( key_num: int ) -> int:
j = key_num % 12
if (j == 1) or ( j ==3 ) or ( j == 6 ) or ( j == 8) or ( j == 10 ):
return 1
return 0
def drawframe( lastimage = None):
global pyfont
global helptext
global mousex, mousey
global keyp_colormap_colors_pos
global keyp_colormap_pos
global frame, image
global printed_for_frame
global notes_tmp
global notes_pressed_color
#global old_spark_color
#global cur_spark_color
print_for_frame_debug = False
if printed_for_frame != frame:
print_for_frame_debug = True
printed_for_frame = frame
scale=1.0
mousex, mousey = pygame.mouse.get_pos()
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glViewport (0, 0, width, height)
glMatrixMode (GL_PROJECTION)
glLoadIdentity ()
glOrtho(0, width, height, 0, -1, 100)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glDisable(GL_DEPTH_TEST)
glScale(scale,scale,1)
glColor4f(1.0, 1.0, 1.0, 1.0)
glBindTexture(GL_TEXTURE_2D, Gl.bgImgGL)
glEnable(GL_TEXTURE_2D)
DrawQuad(0,0,width,height)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glColor4f(1.0, 0.5, 1.0, 0.5)
glPushMatrix()
glTranslatef(prefs.xoffset_whitekeys,prefs.yoffset_whitekeys,0)
glDisable(GL_TEXTURE_2D)
for i in range( len( prefs.keys_pos) ):
pixpos = getkeyp_pixel_pos(prefs.keys_pos[i][0],prefs.keys_pos[i][1])
if (pixpos[0] == -1) and (pixpos[1] == -1):
continue
if lastimage is not None:
keybgr=lastimage[ pixpos[1], pixpos[0] ]
else:
keybgr=image[ pixpos[1], pixpos[0] ]
key= [ keybgr[2], keybgr[1],keybgr[0] ]
keybgr=[0,0,0]
sparkkey=[0,0,0]
if prefs.use_sparks:
sh = int(sparks_slider_height.value)
if sh == 0:
sh = 1
for spark_y_add_pos in range (sh):
sparkpixpos = getkeyp_pixel_pos(prefs.keys_pos[i][0],prefs.keyp_spark_y_pos - spark_y_add_pos )
if not ((sparkpixpos[0] == -1) and (sparkpixpos[1] == -1)):
keybgr = image[ sparkpixpos[1], sparkpixpos[0] ]
sparkkey = [ sparkkey[0] + keybgr[2],
sparkkey[1] + keybgr[1],
sparkkey[2] + keybgr[0] ]
sparkkey = [ sparkkey[0] / sh, sparkkey[1] / sh,sparkkey[2] / sh]
#cur_spark_color[i] = sparkkey
else:
sparkkey = [0,0,0]
note=i
if ( note > 144 ):
print("skip note > 144")
continue
keypressed=0