/
C3toolbox.py
5460 lines (4826 loc) · 237 KB
/
C3toolbox.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
# -*- coding: cp1252 -*-
# -*- additions by: Alternity, kueller -*-
from reaper_python import *
import operator
import decimal
import base64
import math
import binascii
import os
import re
import sys
from C3notes import *
global end_event
global tracks_array
global maxlen
global end_of_track
global instrument_ticks
global measures_array
global notesname_array
global divisions_array
global sustains_array
global default_pause
global sustainspace_array
global sustains_array
global debug
global array_instruments
global array_levels
global array_levels_id
global config
global drumsanimations_array
global da_lh
global promarkers
global double_pedal_bpm
global twohit_drums
global chord_threshold
global phrase_char
###########################################################
#
# GLOBALS
#
###########################################################
correct_tqn = 480 #We take the TQN from the Reaper project but Magma wants 480 TQN.
#This array keeps track of the each track's ID. It HAS to be run every time a function is run because the user can change track's position, thus changing ID
tracks_array = { "PART DRUMS" : 999,
"PART GUITAR" : 999,
"PART BASS" : 999,
"PART VOCALS" : 999,
"PART KEYS" : 999,
"PART REAL_KEYS_X": 999,
"PART REAL_KEYS_H": 999,
"PART REAL_KEYS_M": 999,
"PART REAL_KEYS_E": 999,
"PART KEYS_ANIM_LH": 999,
"PART KEYS_ANIM_RH": 999,
"HARM1": 999,
"HARM2": 999,
"HARM3": 999,
"EVENTS": 999,
"BEAT": 999,
"PART DRUMS 2X": 999,
"VENUE": 999,
"PART RHYTHM": 999,
"PART REAL_GUITAR": 999,
"PART REAL_GUITAR_22": 999,
"PART REAL_BASS": 999,
"PART REAL_BASS_22": 999
}
array_instruments = {
"Drums" : "PART DRUMS",
"2x Drums" : "PART DRUMS 2X",
"Rhythm" : "PART RHYTHM",
"Guitar" : "PART GUITAR",
"Bass" : "PART BASS",
"Keys" : "PART KEYS",
"Pro Keys" : "PART REAL_KEYS",
"Vocals" : "PART VOCALS",
"Harmony 1" : "HARM1",
"Harmony 2" : "HARM2",
"Harmony 3" : "HARM3",
"Pro Guitar" : "PART REAL_GUITAR",
"Pro Guitar (22)" : "PART REAL_GUITAR_22",
"Pro Bass" : "PART REAL_BASS",
"Pro Bass (22)" : "PART REAL_BASS_22"
}
array_dropdownid = { "PART DRUMS" : 0,
"PART GUITAR" : 1,
"PART BASS" : 2,
"PART KEYS" : 3,
"PART REAL_KEYS_X": 4,
"PART REAL_KEYS_H": 4,
"PART REAL _KEYS_H": 4,
"PART REAL_KEYS_M": 4,
"PART REAL_KEYS_E": 4,
"PART DRUMS 2X": 5,
"PART RHYTHM": 6,
"PART VOCALS": 7,
"PART REAL_GUITAR": 8,
"PART REAL_GUITAR_22": 9,
"PART REAL_BASS": 10,
"PART REAL_BASS_22": 11
}
array_dropdownvocals = { "PART VOCALS" : 0,
"HARM1" : 1,
"HARM2" : 2,
"HARM3" : 3
}
array_partlyrics = { "PART VOCALS" : "vocals",
"HARM1" : "harm1",
"HARM2" : "harm2",
"HARM3" : "harm3"
}
array_dropdownid_chords = { "PART GUITAR" : 0,
"PART BASS" : 1,
"PART KEYS" : 2,
"PART RHYTHM": 3
}
array_levels = { "Expert" : ["x", "_X"], "Hard" : ["h", "_H"], "Medium" : ["m", "_M"], "Easy" : ["e", "_E"] }
array_levels_id = { 'x' : 0, 'h' : 1, 'm' : 2, 'e' : 3 }
array_drumkit = { 'x' : '3', 'h' : '2', 'm' : '1', 'e' : '0' }
sustains_array = { 70 : correct_tqn*0.5, \
160 : correct_tqn*0.75, \
999 : correct_tqn*1.25 } #Sustains length array based on BPM
sustainspace_array = { 70 : { 'x' : correct_tqn*0.125, 'h': correct_tqn*0.25, 'm' : correct_tqn*0.5, 'e' : correct_tqn }, \
160 : { 'x' : correct_tqn*0.25, 'h': correct_tqn*0.25, 'm' : correct_tqn, 'e' : correct_tqn } , \
999 : { 'x' : correct_tqn*0.5, 'h': correct_tqn*0.5, 'm' : correct_tqn*0.75, 'e' : correct_tqn } }
#Sustains length array based on BPM
phrases_space = correct_tqn*0.0625 #1/64th space
leveldvisions_array = { 'x' : 's', 'h' : 'e', 'm' : 'q', 'e' : 'h' }
divisions_array = { "w" : 1, "h" : 0.5, "q" : 0.25, "e" : 0.125, "s" : 0.0625, "t" : 0.03125, "f" : 0.015625 } #Grid division
nextdivisions_array = { "w" : "h", "h" : "q", "q" : "e", "e" : "s", "s" : "t", "t" : "f" } #Next grid division
promarkers = {98 : 110, 99 : 111, 100 : 112}
drumsanimations_array = { 96: [24, 24], 97 : [26, 28], 98 : [31, 31], 99 : [42, 42], 100 : [38, 39], 104 : [36, 37], 110 : [47, 47], 111 : [49, 49], 112 : [51, 51] }
#Animation notes. The arrays are for Hard and Soft, when available (if not, the same value is repeated)
#104 is not a real note, it's for the CRASH1 option instead of CRASH2
da_lh = { 24: 24, 26 : 27, 28 : 29, 31 : 30, 42 : 43, 36 : 34, 37 : 35, 38 : 44, 39 : 45, 47 : 46, 49 : 48, 51 : 50 }
#Left hand notes, except for the two snares, and the kick that remains the same
two_chords = [ '', 'GR', 'GY', 'RY', 'RB', 'YB', 'YO', 'BO' ]
one_chords = [ '', 'G', 'R', 'Y', 'B', 'O' ]
medium_chords_o = [ 'GR', 'GY', 'RY', 'RB', 'YB', 'BO' ]
medium_chords = [ 'GR', 'GY', 'RY', 'RB', 'YB' ]
medium_notes = [ 'G', 'R', 'Y', 'B' ]
easy_chords_o = [ 'G', 'R', 'Y', 'B', 'O']
easy_chords = [ 'G', 'R', 'Y']
easy_chords_order = { 'G' : 1, 'R' : 2, 'Y' : 3, 'B' : 4, 'O' : 5 }
easy_chords_translation = { 'GR' : ['G', 'G'], 'GY' : ['R', 'R'], 'RY' : ['Y', 'Y'], 'RB' : ['Y', 'B'], 'YB' : ['Y', 'B'], 'YO' : ['Y', 'O'], 'BO' : ['Y', 'O'] }
easy_notes = [ 'G', 'R', 'Y' ]
easy_singlenotes_array = { 'G' : 'G', 'R' : 'R', 'Y' : 'R', 'B' : 'Y', 'O' : 'Y' }
hard_chords_o = {'84, 86, 88' : [84, 88], '86, 87, 88' : [87, 88], '85, 87, 88' : [86, 88], '85, 86, 88' : [85, 88], '84, 85, 88' : [84, 87], '84, 87, 88' : [85, 88], '84, 86, 88' : [85, 88], '84, 87, 88' : [85, 88], '85, 86, 87' : [85, 87], '84, 86, 87' : [84, 87], '84, 85, 88' : [84, 87], '84, 85, 87' : [84, 86], '84, 85, 86' : [84, 85] }
hard_chords = {'84, 86, 88' : [84, 88], '86, 87, 88' : [87, 88], '85, 87, 88' : [86, 88], '85, 86, 88' : [86, 87], '84, 85, 88' : [84, 87], '84, 87, 88' : [85, 88], '84, 86, 88' : [85, 88], '84, 87, 88' : [85, 88], '85, 86, 87' : [85, 87], '84, 86, 87' : [85, 86], '84, 85, 88' : [84, 87], '84, 85, 87' : [84, 86], '84, 85, 86' : [84, 85] }
medium_chords_order = { 'GR' : 1, 'GY' : 2, 'RY' : 3, 'RB' : 4, 'YB' : 5, 'YO' : 6, 'BO' : 7, 'G' : 1, 'R' : 2, 'Y' : 3, 'B' : 4, 'O' : 5 }
octave_chords = { 'GO' : [ 'YO', 'RB', 'GY'], 'GB' : [ 'RB', 'GY', 'RY'], 'RO' : [ 'YO', 'RB', 'YB'] }
#This arrays fixes simultaneous hits. When two crashes are involved, hi ht and ride are mapped to crash1.
#If crash1 was selected as an option, it's mapped to crash2
twohit_drums = { '3142' : [da_lh[31], 42], '3136' : [da_lh[36], 38], '3137' : [da_lh[37], 39], '3138' : [da_lh[36], 38], '3139' : [da_lh[37], 39], '3149' : [da_lh[31], 49], '3151' : [da_lh[31], 51], \
'4749' : [da_lh[47], 49], '4751' : [da_lh[47], 51], \
'3642' : [da_lh[36], 38], '3647' : [36, da_lh[47]], '3649' : [36, da_lh[49]], \
'3742' : [da_lh[37], 39], '3747' : [37, da_lh[47]], '3749' : [37, da_lh[49]], \
'3842' : [da_lh[36], 38], '3847' : [38, da_lh[47]], '36849' : [38, da_lh[49]], \
'3942' : [da_lh[37], 39], '3947' : [39, da_lh[47]], '3949' : [39, da_lh[49]], \
'4247' : [da_lh[47], 42], '4251' : [da_lh[42], 51], \
'4951' : [da_lh[49], 51], '3849' : [38, da_lh[49]] }
double_pedal_bpm = 120 #The threshold under which we allow 1/16th kick notes on single pedal
maxlen = 1048576 #Used for the MIDI chunk editing and other functions
end_event = 0 #If no end_event is set or it's not set at the right position, looping through notes after the end_event will bring up an error
default_pause = correct_tqn*4*3 #The default space between notes that triggers an idle event
chord_threshold = 0.07 #7% is the defauly threshold for chords reduction
invalid_chars = ',:;"'
phrase_char = '@' #The character we use to tell the phrase markers script to start a new phrase
debug = 1
#DICTIONARY OF FREQUENTLY USED ARRAYS
# measures_array
# An array containing all measures with number, ticks of x.1, time signature, number of ticks per beat and BPM (a single value taken from the BPM marker nearest to x.1)
# 0. Measure number, 1. ticks of Mx.1, 2. denominator, 3. numerator, 4. ticks per beat, 5. BPM
# array_notes
# An array containing notes object, meaning a single element per note.
# 0. 'E' or 'e' (unselected or selected), 1. location, 2. pitch, 3. velocity, 4. duration, 5. noteonoffchannel (9n or 8n)
# 0. 'X' or 'x' (unselected or selected), 1. location, 2. pre-text, 3. text, 4. post-text, 5. event type code)
# Event type code: ff01: TEXT MARKER, ff03 : TRACKNAME, ff05 : LYRICS
###########################################################
###########################################################
#
# UTILITIES
#
###########################################################
def PM(message):
global config
if config['debug'] == '1':
RPR_ShowConsoleMsg(str(message))
def log(function, var):
#This function logs all functions and variables passed
#if config['log'] == '1':
#with open ("log.txt", "a") as myfile:
#myfile.write("appended text")
a=5
def get_curr_project_filename():
proj = RPR_EnumProjects(-1, "", 512)
if proj[2] == "":
return "Unsaved project"
else:
return proj[2]
def count_notes(array, start, end, notes, what, instrument):
#array of notes, start, end, which notes to count, note pitch (0) or note type (1), instrument is id
#start and end are optional
#Returns an array with notes as key and note count as value, sorted by value, descending
instrument_name = ''
for instrument_name, instrument_id in tracks_array.iteritems():
if instrument_id == instrument:
instrumentname = instrument_name
notes_dict = notesname_array[notesname_instruments_array[instrumentname]]
array_count = {}
for x in range(0, len(array)):
#PM("\n")
#PM(notes_dict[array[x][2]][1])
if array[x][2] not in notes_dict:
invalid_note_mb(array[x], instrumentname)
return {}
if (((start or end) and array[x][1] >= start and array[x][1] <= end) or (start == 0 and end == 0)) and ((what == 0 and array[x][2] in notes) or (what == 1 and notes_dict[array[x][2]][1] in notes)):
if str(array[x][2]) in array_count:
array_count[str(array[x][2])]+=1
else:
array_count[str(array[x][2])]= 1
array_count = sorted(array_count.iteritems(), key=operator.itemgetter(1), reverse=True)
return array_count
def mbt(position): #Returns an array with 0. measure, 1. beat, 2. ticks, 3. ticks relative to start of measure
for x in range(0, len(measures_array)):
if measures_array[x][1] <= position:
m = x+1
relative_position = position-measures_array[x][1]
b = int(math.floor(relative_position/measures_array[x][4]))+1
t = int(relative_position-((b-1)*measures_array[x][4]))
return [m, b, t, relative_position]
def invalid_note_mb(note, instrumentname):
m,b = mbt(int(note[1]))[:2]
RPR_MB("Invalid note %d found in %s at position %d.%d" % (note[2], instrumentname, m, b), "Invalid note", 0)
def selected_range(array): #Returns an array with the first selected note at 0 and last selected note at 1
#array must either be the notes or the events array, with absolute location at 1
first_note = "unset"
last_note = 0
#Loop through array elements and find the first selected note: set first_note variable
#Continue loop and set the first next selected note as last_note
#Continue loop and if a new selected note has a starting point higher than last_note, set last_note to it
for x in range(0,len(array)):
if array[x][0] == 'e' or array[x][0] == 'x':
#PM("\nlast_note: " + str(last_note) + " - " str()
if first_note == "unset":
first_note = array[x][1]
elif array[x][1] > last_note:
last_note = array[x][1]
return [first_note, last_note]
def selected_notes(array): #Returns an array with only selected notes and with non selected notes
array_valid = []
array_notes = []
for x in range(0, len(array)):
note = array[x]
if note[0] == 'e':
array_valid.append(note)
else:
array_notes.append(note)
return [array_valid, array_notes]
def note_objects(array): #Returns an array of note objects, meaning chords are one array element
#PM("\n\nnoteobjectsbefore: \n")
#PM(array)
#PM("\n\n")
noteobjects_array = []
# 0. 'E' or 'e' (selected or unselected) (array)
# 1. location
# 2. pitch (array)
# 3. velocity(array)
# 4. duration (array)
# 5. noteonoffchannel (9n or 8n) (array)
# 6. chord
location = array[0][1]
note_object = [[], [], [], [], [], [], []]
for x in range(0, len(array)):
note = array[x]
old_location = location
location = note[1]
#If the position changes, we need to first append to the main array the note_object array because there are no more notes on that location
if location != old_location:
note_object[6].sort()
noteobjects_array.append(note_object)
note_object = [[], [], [], [], [], [], []]
for j in range(0, 6):
note_object[j].append(note[j])
note_object[6].append(note[2])
note_object[6].sort()
noteobjects_array.append(note_object)
return noteobjects_array
def valid_notes(array, level, first_measure, last_measure, instrumentname, pro, selected):
#This function returns an array of notes not to be touched (OD, markers, etc.) and an array of notes of the level to be edited
notes_dict = notesname_array[notesname_instruments_array[instrumentname]]
array_validnotes = []
array_notes = []
for x in range(0,len(array)):
note = array[x]
this_measure = mbt(int(note[1]))[0]
if ((level != '' and notes_dict[note[2]][1] == level) or (level == '' and "notes" in notes_dict[note[2]][1])) and (selected == 0 or (selected and (this_measure >= first_measure and this_measure <= last_measure))):
array_validnotes.append(note)
else:
array_notes.append(note)
return [array_notes, array_validnotes]
def add_objects(array_notes, array_objects): #Adds objects as notes to the array_notes array
for x in range(0,len(array_objects)):
note = array_objects[x]
for j in range(0, len(note[6])):
if(len(note[4]) == 1):
length = note[4][0]
else:
length = note[4][j]
array_notes.append([note[0][j], note[1][0], note[2][j], note[3][j], length, note[5][j]])
return array_notes
def sections(array_notesevents, what):
#Returns an array with subsections in ticks
for x in range(0, len(array_notesevents)):
note = array_notesevents[x]
def level(array, instrument):
#Returns the selected level, instrument is id
instrument_name = ''
for instrument_name, instrument_id in tracks_array.iteritems():
if instrument_id == instrument:
instrumentname = instrument_name
notes_dict = notesname_array[notesname_instruments_array[instrumentname]]
#If it's pro keys, let's catch level right away and return it
if "KEYS_X" in instrumentname:
return 'x'
elif "KEYS_H" in instrumentname:
return 'h'
elif "KEYS_M" in instrumentname:
return 'm'
elif "KEYS_E" in instrumentname:
return 'e'
#If not, we need to loop through selected notes
for x in range(0, len(array)):
note = array[x]
if note[0] == 'e':
if note[2] not in notes_dict:
invalid_note_mb(note, instrumentname)
return None
if notes_dict[note[2]][1] == "notes_x":
return 'x'
elif notes_dict[note[2]][1] == "notes_h":
return 'h'
elif notes_dict[note[2]][1] == "notes_m":
return 'm'
elif notes_dict[note[2]][1] == "notes_e":
return 'e'
#If still no joy, return x
return 'x'
def remap_notes(array_chords, array_translation): #Remap all chords in a song to allowed chords
array_chords_sorted = sorted(array_chords.iteritems(), key=operator.itemgetter(1), reverse=True)
array_valid_chords = []
#We get the most used chords and build an array
for j in range(0, len(array_translation)):
chord = array_chords_sorted[j][0]
array_valid_chords.append(chord)
if len(chord) > 1:
onetwo_chords = two_chords
else:
onetwo_chords = one_chords
array_chords_sorted = []
array_valid_chords_letters = list(array_valid_chords)
#Now we need to sort it, so we convert chords in numbers
for j in range(0, len(array_valid_chords)):
chord = array_valid_chords[j]
chord_number = medium_chords_order[chord]
array_chords_sorted.append(chord_number)
array_chords_sorted.sort()
#We now have a sorted array of chords represented in numbers. Let's convert it back...
array_valid_chords = []
for j in range(0, len(array_chords_sorted)):
chord_number = array_chords_sorted[j]
chord = onetwo_chords[chord_number]
array_valid_chords.append(chord)
array_conversions = []
for j in range(0, len(array_translation)):
array_conversions.append([array_valid_chords[j], array_translation[j]])
return [array_conversions, array_valid_chords_letters]
###########################################################
###########################################################
#
# PREPPING AND COMMON FUNCTIONS
#
###########################################################
def get_trackid(): #Returns the id for the currently selected track
global tracks_array
sel = RPR_CountSelectedTracks(0)
if sel > 1 or sel == 0:
#More than one or no track selected, can't proceed
item = ""
else:
item = RPR_GetSelectedTrack(0,0)
source = RPR_GetSetMediaTrackInfo_String(item, "P_NAME", "", 0)[3]
if "DRUMS" in source and source != "PART DRUMS":
source = "PART DRUMS 2X"
elif "RHYTHM" in source:
source = "PART RHYTHM"
elif source == "PART REAL _KEYS_H":
source = "PART REAL_KEYS_H"
if source in tracks_array:
return tracks_array[source]
else:
#The selected track is unrecognised
return 999
def get_trackname(): #Returns the name for the currently selected track
instrument = get_trackid()
instrumentname = ''
for instrument_name, instrument_id in tracks_array.iteritems():
if instrument_id == instrument:
instrumentname = instrument_name
if instrumentname:
return instrumentname
def get_time_signatures(instrument_ticks):
#This function creates measures array, an array containing all measures with their TS, BPM, starting point, etc.
tsden_array = {'1048' : 16, '983' : 15, '917' : 14, '851' : 13, '786' : 12, '720' : 11, '655' : 10, '589' : 9, '524' : 8, '458' : 7, '393' : 6, '327' : 5, '262' : 4, '196' : 3, '131' : 2, '65': 1}
tsnum_array = {16 : 577, 15 : 41, 14 : 505, 13 : 969, 12 : 433, 11 : 897, 10 : 361, 9: 825, 8 : 289, 7 : 753, 6 : 217, 5 : 681, 4 : 145, 3: 609, 2 : 73, 1: 537}
#Examples:
#4/4: 262 and 148 (145 is 1, 145+3 is 4)
#7/8: 524 and 295 (289 is 1, 289+6 is 7)
maxlen = 1048576
trkptr = RPR_CSurf_TrackFromID(0,0)
# Get Envelope Pointer:
envptr = RPR_GetTrackEnvelopeByName( trkptr, 'Tempo map' )
envstr = ''
# Get Envelope Data:
envstate = RPR_GetSetEnvelopeState(envptr, envstr, maxlen)
nodes_array = []
timesigchanges_array = []
timesignature = '262148' #By default it's 4/4
chunk = ""+envstate[2]
vars_array = chunk.split("\n")
#Create an array of 0. seconds of the point, 1. BPM, 2. time signature denominator, 3. time signature numerator , 4. ticks since 0
for j in range(0, len(vars_array)):
if vars_array[j].startswith('PT '):
node = vars_array[j].split(" ")
#if node[1] == '0.000000000000':
# node[1] = 0
node_array = [float(node[1]), float(node[2])]
if len(node) > 4:
if node[4] != '0':
timesignature = str(node[4])
if len(timesignature) > 6:
numerator = timesignature[4:]
denominator = timesignature[:4]
else:
numerator = timesignature[3:]
denominator = timesignature[:3]
timesignature_denominator = tsden_array[denominator]
timesignature_numerator = (int(numerator)-tsnum_array[timesignature_denominator])+1
node_array.append(timesignature_numerator)
node_array.append(timesignature_denominator)
nodes_array.append(node_array)
#Create an array of TS changes: 0. BPM, 1. time signature denominator, 2. time signature numerator, 3. ticks passed since 0
ticks_passed = 0
if len(nodes_array) > 0:
old_ts = str(nodes_array[0][2])+str(nodes_array[0][3])
timesigchanges_array.append([nodes_array[0][0], nodes_array[0][2], nodes_array[0][3], 0])
nodes_array[0].append(0)
for j in range(1, len(nodes_array)):
ticks_per_second = (instrument_ticks*nodes_array[j-1][1])/60
time_passed = nodes_array[j][0]-nodes_array[j-1][0]
ticks_passed = (time_passed*ticks_per_second)+ticks_passed
ticks_passed = decimal.Decimal(ticks_passed)
ticks_passed = round(ticks_passed,10)
nodes_array[j].append(ticks_passed)
cur_ts = str(nodes_array[j][2])+str(nodes_array[j][3])
if(old_ts <> cur_ts):
timesigchanges_array.append([nodes_array[j][0], nodes_array[j][2], nodes_array[j][3], ticks_passed])
old_ts = str(nodes_array[j][2])+str(nodes_array[j][3])
#PM(nodes_array)
#Loop through the TS array and for each time signature span find out duration and then divide by numerator and denominator. The result is the number of measures in that ts
m = 0
x = 0 #This is needed in case we only have one time signature event
measures_array = [] #0. Measure number, 1. ticks of Mx.1, 2. denominator, 3. numerator, 4. ticks per beat, 5. BPM
for x in range(1, len(timesigchanges_array)):
duration = float(timesigchanges_array[x][3]-timesigchanges_array[x-1][3])
duration = round(duration, 0)
duration = int(duration)
divider = instrument_ticks/(timesigchanges_array[x-1][2]*0.25)
number_of_measures = round(round(duration/divider)/timesigchanges_array[x-1][1], 0)
number_of_measures = int(number_of_measures)
ticks_per_measure = duration/number_of_measures
ticks_per_beat = ticks_per_measure/timesigchanges_array[x][2]
for j in range(0, number_of_measures):
m+=1
ticks_start = float((timesigchanges_array[x-1][3])+(j*ticks_per_measure))
ticks_start = round(ticks_start, 0)
ticks_start = int(ticks_start)
measures_array.append([m, ticks_start, timesigchanges_array[x-1][1], timesigchanges_array[x-1][2], divider])
#Now we need to add all measures from the last (or in some cases only) BPM marker to the end of the song, marked by the end event
ticks_start = float(timesigchanges_array[len(timesigchanges_array)-1][3])
ticks_start = round(ticks_start, 0)
ticks_start = int(ticks_start)
ticks_per_measure = instrument_ticks/(timesigchanges_array[x][2]*0.25)
ticks = ticks_per_measure*timesigchanges_array[x][1]
ticks_per_beat = ticks/timesigchanges_array[x][2]
ticks_startmeasure = ticks_start
loop_measure = 0
while (ticks_startmeasure < end_event+ticks): #The whole loop runs for one measure longer than the end event
m+=1
ticks_startmeasure = ticks_start+(ticks*loop_measure)
loop_measure+=1
measures_array.append([m, ticks_startmeasure, timesigchanges_array[x][1], timesigchanges_array[x][2], ticks_per_measure])
#Now we add the BPM for each measure taking the BPM value of the measure from nodes_array
ok = 0
for x in range(0, len(measures_array)):
ticks_start = measures_array[x][1]
ok = 0
for j in reversed(range(0, len(nodes_array))):
#PM("\n")
#PM(str(int(round(float(ticks_start), 0)))+" <= "+str(int(float(nodes_array[j][4])))+" : "+str(nodes_array[j][1]))
if int(round(float(ticks_start), 0)) >= int(float(nodes_array[j][4])):
measures_array[x].append(nodes_array[j][1])
ok = 1
#PM("\n")
break
if ok == 0:
measures_array[x].append(nodes_array[j][1])
ok = 0
#PM("\n")
#PM(measures_array)
return measures_array
def process_instrument(instrument): #Creates an array of all notes/events
PM(instrument)
global end_event
global end_of_track
mi = RPR_GetMediaItem(0,instrument)
chunk = ""
maxlen = 1048576
(boolvar, mi, chunk, maxlen) = RPR_GetSetItemState(mi, chunk, maxlen)
vars_array = ""
notes_array = []
conto_vars_array = 0
vars_array = chunk.split("\n")
conto_vars_array = len(vars_array)
alertstring="real_keys_lh"+" - "+str(conto_vars_array)+"\n"
noteloc = 0
decval = ""
encText = ""
#CYCLING THROUGH CHUNK TO CREATE AN ARRAY OF NOTES
notestring = "a\n"
vars_array_string = ""
ticks = 0
end_firstpart = 0
start_secondpart = 0
for j in range(0, conto_vars_array):
note = ""
if vars_array[j].startswith('E ') or vars_array[j].startswith('e '):
note = vars_array[j].split(" ")
if len(note) >= 5:
decval = int(note[3], 16)
noteloc = noteloc + int(note[1])
notes_array.append(note[0]+" "+str(noteloc)+" "+note[2]+" "+str(decval)+" "+str(note[4]))
elif vars_array[j].startswith('<X') or vars_array[j].startswith('<x'):
note = vars_array[j].split(" ")
if len(note) >= 2:
noteloc = noteloc + int(note[1])
encText = vars_array[j+1]
encClose = vars_array[j+2]
notes_array.append(note[0]+" "+str(noteloc)+" "+note[2]+" "+str(encText)+" "+encClose)
if base64.b64decode(str(encText))[2:] == '[end]':
end_event = noteloc
elif "HASDATA" in vars_array[j]:
note = vars_array[j].split(" ")
ticks = int(note[2])
if ticks != 480:
result = RPR_MB( "One of the MIDI tracks isn't set to 480 ticks per beat. This will break Magma. CAT will now exit", "Invalid ticks per quarter", 0)
return
elif "<SOURCE MIDI" in vars_array[j]:
end_firstpart = j+2 #it's the last element before the MIDI notes/events chunk
elif "IGNTEMPO" in vars_array[j]:
start_secondpart = j-1 #it's the first element after the MIDI notes/events chunk
array_instrument = [ticks, notes_array, end_firstpart, start_secondpart]
end_of_track = notes_array[-1]
return array_instrument
def create_notes_array(notes): #instrument is the instrument shortname, NOT the instrument track number
array_rawnotes = [] #An array containing only notes in raw format, notes on and off
array_rawevents = [] #An array containing all text markers/events
array_notes = [] #An array containing only notes, with:
#0. 'E' or 'e' (unselected or selected), 1. location, 2. pitch, 3. velocity, 4. duration, 5. noteonoffchannel
array_events = [] #An array containing only text markers/events
#First off we sort the notes from the markers, so it's easier to loop through notes
for x in range(0, len(notes)):
if notes[x].startswith('E') or notes[x].startswith('e'):
array_rawnotes.append(notes[x])
else:
array_rawevents.append(notes[x])
#Now we loop through the notes to remove all note off events and set a length for the notes
for x in range(0, len(array_rawnotes)):
note_bit = array_rawnotes[x].split(" ")
if note_bit[2].startswith('9') and note_bit[4] != '00':
for y in range(x, len(array_rawnotes)):
cur_note = array_rawnotes[y].split(" ")
if x != y and cur_note[3] == note_bit[3] and int(cur_note[1]) > int(note_bit[1]) and (cur_note[2].startswith('8') or cur_note[4] == '00'):
#We have the note off for the current note on event
#PM(str(note_bit[0])+ str(note_bit[1])+str(note_bit[3])+str(note_bit[4])+ str(int(cur_note[1])-int(note_bit[1]))+ str(note_bit[2]))
#PM("\n")
array_notes.append([note_bit[0], int(note_bit[1]), int(note_bit[3]), note_bit[4], (int(cur_note[1])-int(note_bit[1])), note_bit[2]])
break
for x in range(0, len(array_rawevents)):
note_bit = array_rawevents[x].split(" ")
encText = note_bit[3]
event_header = str(binascii.a2b_base64(encText).encode("hex"))[:4]
lyric = base64.b64decode(str(encText))[2:]
array_events.append([note_bit[0], int(note_bit[1]), note_bit[2], str(lyric), note_bit[4], event_header])
return [array_notes, array_events]
def rebuild_array(array_notesevents):
global end_of_track
global correct_tqn
#Create a new temp array
array_temp = [] #This array will contain all events/notes and it will be used for sorting. Its content will then go in a raw text array
array_raw = []
#Loop through each note and convert the note on event in raw format to add it to the raw array
for x in range(0, len(array_notesevents[0])):
array_temp.append([array_notesevents[0][x][0], int(array_notesevents[0][x][1]), array_notesevents[0][x][5], (hex(int(array_notesevents[0][x][2])))[2:], array_notesevents[0][x][3]])
#and create a note off event with absolute location
array_temp.append([array_notesevents[0][x][0], int(array_notesevents[0][x][1])+int(array_notesevents[0][x][4]), str("8"+str(array_notesevents[0][x][5])[1:]),(hex(int(array_notesevents[0][x][2])))[2:], "00"])
for x in range(0, len(array_notesevents[1])):
hex_lyric = array_notesevents[1][x][5] + array_notesevents[1][x][3].encode("hex")
encoded_text = str(base64.encodestring(hex_lyric.decode('hex')))
#PM("encoded_text: "+encoded_text+"\n")
array_temp.append([array_notesevents[1][x][0], int(array_notesevents[1][x][1]), array_notesevents[1][x][2], encoded_text, array_notesevents[1][x][4]])
#Incorporate the events from array_rawevents and sort by absolute location
array_temp.sort(key=operator.itemgetter(1,0))
#We add the end of track event so the MIDI track doesn't cut off
end_of_track_array = end_of_track.split(" ")
end_of_track_time = int(end_of_track_array[1])
if array_temp[-1][1] > int(end_of_track_array[1]):
end_of_track_time = array_temp[-1][1]+correct_tqn
#array_temp.append([end_of_track_array[0], end_of_track_time, end_of_track_array[2], end_of_track_array[3], end_of_track_array[4]])
array_temp.append([end_of_track_array[0], end_of_track_time, end_of_track_array[2], (hex(int(end_of_track_array[3])))[2:], end_of_track_array[4]])
#Loop through the rawarray. Set location of all notes based on difference between location of note x and of note x-1 of the rawarray
if array_temp[0][0].startswith('E') or array_temp[0][0].startswith('e'):
array_raw.append(array_temp[0][0]+" "+str(array_temp[0][1])+" "+str(array_temp[0][2])+" "+str(array_temp[0][3])+" "+str(array_temp[0][4]))
else:
array_raw.append(array_temp[0][0]+" "+str(array_temp[0][1])+" "+str(array_temp[0][2])+"\n "+str(array_temp[0][3])+"\n"+str(array_temp[0][4]))
for x in range(1, len(array_temp)):
new_location = array_temp[x][1]-array_temp[x-1][1]
if array_temp[x][0].startswith('E') or array_temp[x][0].startswith('e'):
array_raw.append(array_temp[x][0]+" "+str(new_location)+" "+str(array_temp[x][2])+" "+str(array_temp[x][3])+" "+str(array_temp[x][4]))
else:
array_raw.append(array_temp[x][0]+" "+str(new_location)+" "+str(array_temp[x][2])+"\n "+array_temp[x][3]+"\n"+str(array_temp[x][4]))
#PM(array_raw)
return array_raw
def rebuild_chunk(notes_array, instrument, end, start):
#Let's start by putting the notes/events portion of the chunk back together. The array is already prepped here.
noteschunk = ""
for x in range(0, len(notes_array)):
if notes_array[x].startswith('E') or notes_array[x].startswith('e'):
noteschunk+=notes_array[x]+"\n"
else:
#event = notes_array[x].split("|")
#PM(notes_array[x])
#noteschunk+=event[0]+"\n"+event[1]+"\n"+event[2]+"\n"
noteschunk+=notes_array[x]+"\n"
#The notes/events portion of the chunk is done, now we loop through the whole chunk to find the spot where we need to snip
bi = RPR_GetMediaItem(0,instrument)
first_chunk = ""
second_chunk = ""
maxlen = 1048576
instrument = ""
subchunk = ""
(boolvar, bi, subchunk, maxlen) = RPR_GetSetItemState(bi, subchunk, maxlen)
vars_array = subchunk.split("\n")
for j in range(0, end+1):
first_chunk+=vars_array[j]+"\n"
for k in range(start, len(vars_array)):
second_chunk+=vars_array[k]
if k < vars_array :
second_chunk+="\n"
chunk = first_chunk+noteschunk+second_chunk
return chunk
def prep_tracks():
global maxlen
global tracks_array
num_mi = RPR_CountMediaItems(0)
for i in range(0, num_mi):
mi = RPR_GetMediaItem(0,i)
trackID = RPR_GetMediaItem_Track(mi)
trackname = RPR_GetSetMediaTrackInfo_String(trackID, "P_NAME", "", 0)[3]
chunk = ""
instrument = ""
(boolvar, mi, chunk, maxlen) = RPR_GetSetItemState(mi, chunk, maxlen)
#CYCLING THROUGH ALL TRACKS TO FIND THOSE RELEVANT
#This check needs to go off everytime a command is issued because if the user changes position of the tracks the IDs change
if "PART BASS" == trackname:
tracks_array["PART BASS"] = i
elif "PART DRUMS 2X" == trackname or "PART DRUMS 2x" == trackname or "PART DRUMS_2x" == trackname or "PART DRUMS_2X" == trackname:
tracks_array["PART DRUMS 2X"] = i
elif "PART DRUMS" == trackname:
tracks_array["PART DRUMS"] = i
elif "PART GUITAR" == trackname:
tracks_array["PART GUITAR"] = i
elif "PART VOCALS" == trackname:
tracks_array["PART VOCALS"] = i
elif "PART KEYS" == trackname:
tracks_array["PART KEYS"] = i
elif "KEYS_X" in trackname:
tracks_array["PART REAL_KEYS_X"] = i
elif "KEYS_H" in trackname:
tracks_array["PART REAL_KEYS_H"] = i
elif "KEYS_M" in trackname:
tracks_array["PART REAL_KEYS_M"] = i
elif "KEYS_E" in trackname:
tracks_array["PART REAL_KEYS_E"] = i
elif "PART KEYS_ANIM_RH" == trackname:
tracks_array["PART KEYS_ANIM_RH"] = i
elif "PART KEYS_ANIM_LH" == trackname:
tracks_array["PART KEYS_ANIM_LH"] = i
elif "HARM1" == trackname:
tracks_array["HARM1"] = i
elif "HARM2" == trackname:
tracks_array["HARM2"] = i
elif "HARM3" == trackname:
tracks_array["HARM3"] = i
elif "EVENTS" == trackname:
tracks_array["EVENTS"] = i
elif "BEAT" == trackname:
tracks_array["BEAT"] = i
elif "VENUE" == trackname:
tracks_array["VENUE"] = i
elif "PART REAL_GUITAR" == trackname:
tracks_array["PART REAL_GUITAR"] = i
elif "PART REAL_GUITAR_22" == trackname:
tracks_array["PART REAL_GUITAR_22"] = i
elif "PART REAL_BASS" == trackname:
tracks_array["PART REAL_BASS"] = i
elif "PART REAL_BASS_22" == trackname:
tracks_array["PART REAL_BASS_22"] = i
else:
instrument = "???"
#PM("\ntracks_array:\n")
#PM(tracks_array)
def write_midi(instrument, array, end_part, start_part):
global maxlen
rebuilt_array = rebuild_array(array)
chunk = rebuild_chunk(rebuilt_array, instrument, end_part, start_part)
mi = RPR_GetMediaItem(0,instrument)
(boolvar, mi, chunk, maxlen) = RPR_GetSetItemState(mi, chunk, maxlen)
###########################################################
###########################################################
#
# COMMANDS
#
###########################################################
def filter_notes(instrument): #Anything that's not a proper note or a text event is filtered out
global maxlen
if instrument == '':
instrument = get_trackid()
else:
instrument = tracks_array[instrument]
array_instrument_data = process_instrument(instrument)
array_instrument_notes = array_instrument_data[1]
end_part = array_instrument_data[2]
start_part = array_instrument_data[3]
array_notesevents = create_notes_array(array_instrument_notes)
write_midi(instrument, array_notesevents, end_part, start_part)
def polish_notes(instrument, grid, tolerance, selected):
#All notes off by tolerance on a grid are snapped
global maxlen
if instrument == '':
instrument = get_trackid()
else:
instrument = tracks_array[instrument]
array_instrument_data = process_instrument(instrument)
array_instrument_notes = array_instrument_data[1]
end_part = array_instrument_data[2]
start_part = array_instrument_data[3]
array_notesevents = create_notes_array(array_instrument_notes)
array_notes = array_notesevents[0]
array_events = array_notesevents[1]
for instrument_name, instrument_id in tracks_array.iteritems():
if instrument_id == instrument:
instrumentname = instrument_name
if "REAL_KEYS" in instrumentname or "KEYS_ANIM" in instrumentname or "VOCALS" in instrumentname:
level = "notes"
else:
level = "notes_x"
notes_dict = notesname_array[notesname_instruments_array[instrumentname]]
division = int(math.floor((correct_tqn*4)*divisions_array[grid]))
first_measure = 0
last_measure = 0
if(selected):
first_measure = mbt(int(selected_range(array_notes)[0]))[0]
last_measure = mbt(int(selected_range(array_notes)[1]))[0]
if first_measure == last_measure:
result = RPR_MB( "This command works from measure to measure, please selected notes from at least 2 different measures", "Invalid selection", 0)
return
for x in range(0, len(array_notes)):
note = array_notes[x]
if note[2] not in notes_dict:
invalid_note_mb(note, instrumentname)
return
position = mbt(note[1])[3]
if (selected and mbt(int(note[1]))[0] >= first_measure and mbt(int(note[1]))[0] <= last_measure) or selected == 0:
if "notes" in notes_dict[note[2]][1]:
grid_check = int(math.floor(position/division))
diff_after = position-(grid_check*division)
diff_before = division - (position-(grid_check*division))
if diff_after > 0 and diff_after < tolerance:
note[1] -= diff_after
elif diff_before > 0 and diff_before < tolerance : #Slightly off, snap
note[1] += diff_before
write_midi(instrument, [array_notes, array_events], end_part, start_part)
def cleanup_notes(instrument, grid, level, selected):
#All notes shorter than grid will be made 1/16th or the longest possible taking the following note into consideration
global maxlen
if instrument == '':
instrument = get_trackid()
else:
instrument = tracks_array[instrument]
array_instrument_data = process_instrument(instrument)
array_instrument_notes = array_instrument_data[1]
end_part = array_instrument_data[2]
start_part = array_instrument_data[3]
array_notesevents = create_notes_array(array_instrument_notes)
array_notes = array_notesevents[0]
array_events = array_notesevents[1]
leveltext = level
for instrument_name, instrument_id in tracks_array.iteritems():
if instrument_id == instrument:
instrumentname = instrument_name
if "REAL_KEYS" in instrumentname or "KEYS_ANIM" in instrumentname:
leveltext = "notes"
else:
leveltext = "notes_"+leveltext
notes_dict = notesname_array[notesname_instruments_array[instrumentname]]
division = int(math.floor((correct_tqn*4)*divisions_array[grid]))
first_measure = 0
last_measure = 0
array_validnotes = []
array_notes = []
if(selected):
first_measure = mbt(int(selected_range(array_notesevents[0])[0]))[0]
last_measure = mbt(int(selected_range(array_notesevents[0])[1]))[0]
if selected and first_measure == last_measure:
result = RPR_MB( "This command works from measure to measure, please selected notes from at least 2 different measures", "Invalid selection", 0)
return
for x in range(0,len(array_notesevents[0])):
note = array_notesevents[0][x]
#PM(note)
this_measure = mbt(int(note[1]))[0]
if note[2] in notes_dict and notes_dict[note[2]][1] == leveltext and (selected == 0 or (selected and (this_measure >= first_measure and this_measure <= last_measure))):
array_validnotes.append(note)
else:
array_notes.append(note)
array_validobjects = note_objects(array_validnotes)
for x in range(0,len(array_validobjects)):
note = array_validobjects[x]
duration = note[4][0]
new_length = 8
if (selected and mbt(int(note[1]))[0] >= first_measure and mbt(int(note[1]))[0] <= last_measure) or selected == 0:
if duration < division:
if x+1 == len(array_validobjects):
new_length = correct_tqn/4
elif note[1][0]+(correct_tqn/4) <= array_validobjects[x+1][1][0]:
new_length = correct_tqn/4
elif note[1][0]+(correct_tqn/8) <= array_validobjects[x+1][1][0]:
new_length = correct_tqn/8
elif note[1][0]+(correct_tqn/16) <= array_validobjects[x+1][1][0]:
new_length = correct_tqn/16
elif note[1][0]+(correct_tqn/32) <= array_validobjects[x+1][1][0]:
new_length = correct_tqn/32
else:
new_length = 8
for j in range(0, len(note[4])):
note[4][j] = new_length
array_notes = add_objects(array_notes, array_validobjects)
write_midi(instrument, [array_notes, array_events], end_part, start_part)
def create_beattrack(halve, sel): #Call with halve to create an halved beat track
global maxlen
if halve:
moltiplicatore = 2
else:
moltiplicatore = 1
#Get notes array
array_instrument_data = process_instrument(tracks_array["BEAT"])
array_instrument_notes = array_instrument_data[1]
end_part = array_instrument_data[2]
start_part = array_instrument_data[3]
array_notes = create_notes_array(array_instrument_notes)
array_beats = [] #0. 'e', 1. location, 2. pitch, 3. velocity, 4. duration, 5. noteonoffchannel
last_measure = len(measures_array)
first_measure = 1
if(sel):
array_beats_full = array_notes[0]
first_measure = mbt(int(selected_range(array_beats_full)[0]))[0]
last_measure = mbt(int(selected_range(array_beats_full)[1]))[0]
if first_measure == last_measure:
result = RPR_MB( "This command works from measure to measure, please selected notes from at least 2 different measures", "Invalid selection", 0)