/
pentlyas.py
executable file
·2640 lines (2333 loc) · 98.9 KB
/
pentlyas.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
# -*- coding: utf-8 -*-
#
# Pently audio engine
# Music assembler
#
# Copyright 2015-2019 Damian Yerrick
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
# 3. This notice may not be removed or altered from any source distribution.
#
from __future__ import with_statement, division, print_function
# The above features are available by default in Python 3, but
# declaring them anyway makes a cleaner error message on Python 2
# for Windows, which is the default IDLE on many Windows PCs
import os
import sys
import json
import re
import argparse
try:
from collections import ChainMap
except ImportError:
print("pentlyas.py: Python 3.3 or later is required", file=sys.stderr)
scaledegrees = {
'c': 0, 'd': 1, 'e': 2, 'f': 3, 'g': 4, 'a': 5, 'h': 6, 'b': 6
}
notenamesemis = {
'c': 0, 'd': 2, 'e': 4, 'f': 5, 'g': 7, 'a': 9, 'h': 11
}
accidentalmeanings = {
'': 0, 'b': -1, 'bb': -2, '-': -1, '--': -2, 'es': -1, 'eses': -2,
'#': 1, '##': 2, '+': 1, '++': 2, 's': 1, 'ss': 2, 'x': 2,
'is': 1, 'isis': 2,
}
duraugmentnums = {
'': 4, '.': 6, '..': 7, 'g': 0
}
dotted_names = {4: '', 6: 'dotted ', 7: 'double dotted '}
timesignames = {
'c': (4, 4), # common time
'¢': (2, 2), # cut time (you are encoding your file UTF-8 right?)
'o': (3, 4), # perfect time
}
channeltypes = {'pulse': 0, 'triangle': 2, 'noise': 3}
durcodes = {
1: '0', 2: 'D_8', 3: 'D_D8', 4: 'D_4',
6: 'D_D4', 8: 'D_2', 12: 'D_D2', 16: 'D_1'
}
volcodes = {
# Musical names
'pp': 1, 'mp': 2, 'mf': 3, 'ff': 4,
# Names from https://en.wikipedia.org/wiki/Music_Macro_Language#Modern_MML
'v1': 1, 'v2': 2, 'v3': 3, 'v4': 4,
}
pitched_tracks = {'pulse1': 0, 'pulse2': 1, 'triangle': 2, 'attack': 4}
track_suffixes = ['Sq1', 'Sq2', 'Tri', 'Noise', 'Attack']
pattern_pitchoffsets = [
'N_C', 'N_CS', 'N_D', 'N_DS', 'N_E', 'N_F',
'N_FS', 'N_G', 'N_GS', 'N_A', 'N_AS', 'N_B',
'N_CH', 'N_CSH', 'N_DH', 'N_DSH', 'N_EH', 'N_FH',
'N_FSH', 'N_GH', 'N_GSH', 'N_AH', 'N_ASH', 'N_BH',
'N_CHH'
]
default_arp_names = {
'OF': '00', # off
'M': '47', # major
'm': '37', # minor
'maj7': '4B', # major 7
'm7': '3A', # minor 7
'dom7': '4A', # dominant 7
'dim': '36', # diminished
'dim7': '39', # diminished 7
'aug': '48', # augmented
}
# The concepts of musical pitch and time ############################
class PentlyPitchContext(object):
"""
Six octave modes are recognized at various places:
'drum' -- any word of 2+ characters that starts and ends with a
letter and does not end with a digit and "g"
'noise' -- 0 to 15 is a pitch; the result is subtracted from 15
because NES APU treats 15 as the longest period and thus
the lowest pitch
'absolute' -- Always guess the octave below C
'orelative' -- Guess the octave of the previous note.
'relative' -- Guess the octave of the note with the given scale degree
closest to the previous note, disregarding accidentals.
None: Wait for the first thing that looks like a pitch or drum.
Arpeggio-related:
last_arp -- last arpeggio value set with EN
arp_top -- if true, transpose notes down by the top of the chord
arp_mod -- if not None, the current note has a single-note arpeggio
modifier, and subsequent 'w' commands should get the same
last_chord -- last (pitch, arpeggio) used; note 'q' repeats this
arp_names
"""
def __init__(self, other=None, language='english'):
if other is None:
self.set_language(language)
self.reset_octave(octave_mode=None)
self.reset_arp()
self.simul_notes = False
self.arp_names = ChainMap({}, default_arp_names)
self.mml_octaves = True
else:
self.set_language(other.language)
self.last_octave = other.last_octave
self.octave_mode = other.octave_mode
self.last_arp = other.last_arp
self.arp_mod = other.arp_mod
self.arp_top = other.arp_top
self.last_chord = other.last_chord
self.simul_notes = other.simul_notes
self.arp_names = other.arp_names.new_child()
self.mml_octaves = other.mml_octaves
def set_language(self, language):
language = language.lower()
# English B is H; German and Scandinavian B is H flat
if language == 'english':
self.language, self.b_means = language, 11 # a, a#, b, c
elif language == 'deutsch':
self.language, self.b_means = language, 10 # a, a#, h, c
else:
raise ValueError("unknown notenames language %s; try english or deutsch"
% language)
def reset_octave(self, octave_mode="unchanged", octave=0):
"""Change octave mode and last note.
octave_mode -- the new octave mode, one of these:
"unchanged": Leave octave mode as it was
"absolute": Treat notes as relative to F below middle C
"orelative": Treat notes as relative to F nearest the last note
"relative": Treat notes as relative to the last note
"noise": Treat as noise period indices (0=lowest, 15=highest)
"drum": Treat as drum names
None: Wait for a drum or note, then go to "drum" or "absolute"
, which can be "absolute",
"relative", or "orelative", or a false value to leave it the same
octave -- the number of commas (negative) or primes (positive) in
the new octave. For example, octave 0 sets the last note to the
F below middle C, and octave 1 sets to the F above middle C.
"""
self.last_octave = (3, int(octave))
if octave_mode != 'unchanged':
self.octave_mode = octave_mode
def reset_arp(self):
self.last_arp = self.arp_mod = None
self.last_chord = None
self.arp_top = False
def set_pitched_mode(self):
"""Set the octave mode to absolute if None."""
if self.octave_mode is None: self.octave_mode = 'absolute'
@staticmethod
def calc_arp_inversion(arp):
if len(arp) != 2:
raise ValueError("internal error: %s not length 2" % repr(arp))
# Only an arpeggio within an octave can be inverted
nibbles = [int(c, 16) for c in arp]
if max(nibbles) >= 12:
raise ValueError("interval in %s too large to invert; must be smaller than an octave (C)"
% arp)
# 070 -> 050, preserving ratio of 50:50 arps
if nibbles[1] == 0:
return "%x0" % (12 - nibbles[0])
# Replace 0 with C and subtract the lowest nonzero
nibbles = [12] + [c or 12 for c in nibbles]
lowest = min(nibbles)
nibbles = [c - lowest for c in nibbles]
# Rotate to the left until 0 leads
while nibbles[0]:
nibbles.append(nibbles[0])
del nibbles[0]
return "%X%X" % (nibbles[1], nibbles[2])
def translate_arp_name(self, arp):
"""Normalize an arpeggio name to 2 hex digits or raise KeyError.
Return None (if arp is falsey), 2 hex digits, or '-' followed by
2 hex digits.
"""
if not arp: return None
# Chop off modifiers (downward, chord inversion)
arp_prefix = ''
if arp.startswith('-'):
arp_prefix, arp = '-', arp[1:]
arp = arp.split('/', 1)
inversion = int(arp[1] if len(arp) > 1 else 0)
arp = arp[0]
# If not a nibble pair, look it up
arpvalue = None
if len(arp) < 3:
try:
arpvalue = int(arp, 16)
except ValueError:
pass
else:
arpvalue = ("00" + arp)[-2:]
if arpvalue is None:
arp = self.arp_names[arp]
# Process inversion
for _ in range(inversion):
arp = self.calc_arp_inversion(arp)
return arp_prefix + arp
def add_arp_name(self, name, definition):
if definition.startswith('-'):
raise ValueError("%s: downward sign goes in pattern, not definition"
% definition)
definition = self.translate_arp_name(definition)
if not name[:1].isalpha():
raise ValueError("chord name %s must begin with a letter"
% name)
if name in ('P1', 'P2'):
raise ValueError("chord name %s is reserved for rate changes"
% name)
try:
olddefinition = self.translate_arp_name(name)
except KeyError:
pass
else:
raise ValueError("chord name %s already defined as %s"
% (name, definition))
self.arp_names[name] = definition
def set_arp(self, arp):
"""Set the arpeggio for subsequent notes to arp."""
self.set_pitched_mode()
self.last_arp = self.translate_arp_name(arp)
@staticmethod
def fixup_downward_arp(notenum, arp):
# - means transpose the note down by the larger nibble
# but it's ignored for waits
if arp and arp.startswith('-'):
arp = arp[1:]
if isinstance(notenum, int):
notenum -= max(int(c, 16) for c in arp)
return notenum, arp
def parse_pitch(self, preoctave, notename, accidental, postoctave, arp):
arp = self.translate_arp_name(arp)
if notename == 'p': notename = 'r'
nonpitchtypes = {
'r': 'rest', 'w': 'wait', 'l': 'length change',
'q': 'chord repeat'
}
if notename in nonpitchtypes:
bad_modifier = ("octave changes" if preoctave or postoctave
else "accidentals" if accidental
else "chords" if arp and notename in "qr"
else None)
if bad_modifier:
msg = ("%s: %s can't have %s"
% (notename, nonpitchtypes[notename], bad_modifier))
raise ValueError(msg)
if notename == 'q':
return self.last_chord
# Rests kill a single-note arpeggio.
# Waits and length changes preserve it.
if notename == 'r':
self.arp_mod = arp
arp = arp or self.arp_mod or self.last_arp
return self.fixup_downward_arp(notename, arp)
octave = 0
if preoctave and postoctave:
raise ValueError("%s: cannot specify octave both before and after note name"
% pitch)
elif preoctave:
octave = len(preoctave)
if preoctave.startswith('<'):
octave = -octave
elif postoctave:
octave = len(postoctave)
if postoctave.startswith(','):
octave = -octave
if self.octave_mode in ('orelative', 'relative'):
octave += self.last_octave[1]
scaledegree = scaledegrees[notename]
if self.octave_mode == 'relative':
# Process LilyPond style relative mode
degreediff = scaledegree - self.last_octave[0]
if degreediff > 3:
octave -= 1
elif degreediff < -3:
octave += 1
if notename == 'b':
semi = self.b_means
else:
semi = notenamesemis[notename]
self.last_octave = scaledegree, octave
notenum = semi + accidentalmeanings[accidental] + 12 * octave + 15
# Save the single-note arpeggio if any, and if there is one,
# have it return to 00 instead of unspecified
self.arp_mod = arp
if arp:
self.last_arp = self.last_arp or '00'
arp = arp or self.arp_mod or self.last_arp
notenum, arp = self.fixup_downward_arp(notenum, arp)
if arp and arp != '00':
self.last_chord = notenum, arp
return notenum, arp
pitchRE = re.compile(r"""
(>*|<*) # MML style octave
([a-h]) # note name (pitches only, no lengths, volumes, etc.)
(b|bb|-|--|es|eses|s|ss|is|isis|\#|\#\#|\+|\+\+|x|) # accidental
(,*|'*)$ # LilyPond style octave
""", re.VERBOSE)
def parse_absolute_pitch(self, pitch):
"""Parse an absolute pitch: a note or a noise frequency."""
if self.octave_mode == 'noise':
pitch = int(pitch)
if not 0 <= pitch <= 15:
raise ValueError("noise pitches must be 0 to 15")
return 15 - pitch
m = self.pitchRE.match(pitch)
if not m:
raise ValueError("%s doesn't look like a pitch in %s mode"
% (pitch, self.octave_mode))
g = list(m.groups())
if g[0] and not self.mml_octaves:
raise ValueError("%s: MML octave notation is off" % pitch)
g.append(None) # no arpeggio
notenum, arp = self.parse_pitch(*g)
return notenum
class PentlyRhythmContext(object):
def __init__(self, other=None):
if other is None:
self.durations_stick = False
self.set_scale(16)
self.set_time_signature(4, 4)
self.last_duration = None
self.cur_measure, self.row_in_measure = 1, 0
else:
self.durations_stick = other.durations_stick
self.set_scale(other.scale)
self.set_time_signature(other.timenum, other.timeden)
self.last_duration = other.last_duration
self.cur_measure = other.cur_measure
self.row_in_measure = other.row_in_measure
@staticmethod
def parse_duration(duration, duraugment):
if duration:
duration = int(duration)
if not 1 <= duration <= 64:
raise ValueError("only whole to 64th notes are valid, not %d"
% duration)
duraugment = duraugmentnums[duraugment]
if duraugment and (duration & (duration - 1)):
raise ValueError("only powers of 2 are valid, not %d"
% duration)
return duration, duraugment
elif duraugment:
raise ValueError("augment dots are valid only with numeric duration")
else:
return None, None
def set_time_signature(self, timenum, timeden):
if timenum < 2:
raise ValueError("beats per measure must be at least 2")
if not 2 <= timeden <= 64:
raise ValueError("beat duration must be a half (2) to 64th (64) note")
if timeden & (timeden - 1):
raise ValueError("beat duration must be a power of 2")
self.timenum, self.timeden = timenum, timeden
def set_scale(self, rowvalue):
if not 2 <= rowvalue <= 64:
raise ValueError("row duration must be a half (2) to 64th (64) note")
if rowvalue & (rowvalue - 1):
raise ValueError("beat duration must be a power of 2")
self.scale = rowvalue
def get_measure_length(self):
if self.scale % self.timeden != 0:
raise ValueError("scale must be a multiple of time signature denominator")
return self.scale * self.timenum // self.timeden
def get_beat_length(self):
if self.scale % self.timeden != 0:
raise ValueError("scale must be a multiple of time signature denominator")
rows_per_beat = self.scale // self.timeden
# correct for compound prolation convention
if self.timenum >= 6 and self.timenum % 3 == 0:
rows_per_beat *= 3
return rows_per_beat
def duration_to_rows(self, denom, augment):
wholerows = self.scale * augment // (denom * 4)
partrows = self.scale * augment % (denom * 4)
if partrows != 0:
augmentname = dotted_names[augment]
msg = ("%s1/%d note not multiple of 1/%d note scale (%.3f rows)"
% (augmentname, denom, self.scale,
wholerows + partrows / (denom * 4)))
raise ValueError(msg)
return wholerows
def fix_note_duration(self, notematch):
"""Convert duration to number of rows.
notematch -- (pitch, duration denominator, duration augment, slur)
Return (pitch, number of rows, slur) or None if it's not actually a note
(such as a length command 'l').
"""
pitcharp, denom, augment, slur = notematch[:4]
if isinstance(pitcharp, tuple) and pitcharp[0] == 'l':
if denom is None:
raise ValueError("length requires a duration argument")
self.last_duration = denom, augment
return None
if augment == 0: # 0: grace note
return pitcharp, -denom, slur
if denom is None:
# If this is the first note, set the default duration to
# one beat
if self.last_duration is None:
bl = self.get_beat_length()
if bl & (bl - 1): # Is it compound meter?
assert bl % 3 == 0
bl = bl * 2 // 3
assert self.scale % (2 * bl) == 0
augment = 6
else:
augment = 4
assert self.scale % bl == 0
self.last_duration = (self.scale // bl, augment)
denom, augment = self.last_duration
elif self.durations_stick:
self.last_duration = denom, augment
wholerows = self.duration_to_rows(denom, augment)
return pitcharp, wholerows, slur
def parse_measure(self, measure=1, beat=1, row=0):
if beat < 1:
raise ValueError("time %d:%d:%d has a beat less than 1"
% (measure, beat, row))
if row < 0:
raise ValueError("time %d:%d:%d has a row less than 0"
% (measure, beat, row))
measure_length = self.get_measure_length()
beat_length = self.get_beat_length()
actual_row = row + beat_length * (beat - 1)
if actual_row >= measure_length:
raise ValueError("time %d:%d:%d has beat %d but measure has only %d beats (%d rows)"
% (measure, beat, row,
actual_row // beat_length + 1,
measure_length // beat_length, measure_length))
return measure, actual_row, measure_length, beat_length
def set_measure(self, measure=1, beat=1, row=0):
"""Set the current musical time."""
measure, row, _, _ = self.parse_measure(measure, beat, row)
self.cur_measure, self.row_in_measure = measure, row
def add_rows(self, rows):
"""Add a duration in rows to the current musical time."""
measure_length = self.get_measure_length()
row = self.row_in_measure + rows
self.cur_measure += row // measure_length
self.row_in_measure = row % measure_length
def wait_for_measure(self, measure, beat=1, row=0):
"""Seek to a given musical time.
Return rows between old and new positions."""
measure, row, measure_length, beat_length = self.parse_measure(measure, beat, row)
if (measure < self.cur_measure
or (measure == self.cur_measure and row < self.row_in_measure)):
old_beat = self.row_in_measure // beat_length + 1
old_row = self.row_in_measure % beat_length
raise ValueError("wait for %d:%d:%d when song is already to %d:%d:%d"
% (measure, row // beat_length + 1, row % beat_length,
self.cur_measure, old_beat, old_row))
rows_to_wait = ((measure - self.cur_measure) * measure_length
+ (row - self.row_in_measure))
self.cur_measure, self.row_in_measure = measure, row
return rows_to_wait
# The parts of a score ##############################################
class PentlyRenderable(object):
nonalnumRE = re.compile("[^a-zA-Z0-9]")
def __init__(self, name=None, orderkey=0, fileline=None, warn=None):
self.name, self.orderkey, self.fileline = name, orderkey, fileline
self.warn = warn
self.asmdataname = self.asmdata = None
self.asmdataprefix = ''
self.bytesize = 0
@classmethod
def get_asmname(self, name):
return '_'.join(c for c in self.nonalnumRE.split(name) if c)
def resolve_scope(self, scoped_name, parent_scope, existing):
if scoped_name.startswith('::'):
return scoped_name.lstrip(':')
while parent_scope:
test = '::'.join((parent_scope, scoped_name))
if test in existing: return test
parent_scope = parent_scope.rsplit('::', 1)
if len(parent_scope) < 2: break
parent_scope = parent_scope[0]
return scoped_name
def render(self, scopes=None):
raise NotImplementedError
class PentlyEnvelopeContainer(PentlyRenderable):
def __init__(self, name=None, orderkey=0, fileline=None, warn=None):
super().__init__(name, orderkey, fileline, warn=warn)
self.timbre = self.volume = self.pitch = None
self.pitch_looplen = self.timbre_looplen = 1
def set_volume(self, volumes, fileline=None):
if self.volume is not None:
file, line = self.volume_fileline
raise ValueError("volume for %s was already set at %s line %d"
% (self.name, file, line))
volumes = list(volumes)
if not all(0 <= x <= 15 for x in volumes):
raise ValueError("volume steps must be 0 to 15")
self.volume, self.volume_fileline = volumes, fileline
@staticmethod
def expand_runs(words):
if isinstance(words, str):
words = words.split()
words = [word.rsplit(":", 1) for word in words]
# words is [[word], [word, "runlength"], [word], ...]
words = [(word[0], int(word[1]) if len(word) > 1 else 1)
for word in words]
# words is [(word, runlength), ...]
words = [word
for word, runlength in words
for i in range(runlength)]
return words
@staticmethod
def pipesplit(words):
pipesplit = ' '.join(words).split('|', 1)
pipesplit = [PentlyEnvelopeContainer.expand_runs(part)
for part in pipesplit]
out = pipesplit[0]
if len(pipesplit) > 1:
afterloop = pipesplit[1]
looplen = len(afterloop)
out.extend(afterloop)
else:
looplen = None
return out, looplen
def get_max_timbre(self):
return 3
def set_timbre(self, timbrewords, fileline=None):
if self.timbre is not None:
file, line = self.timbre_fileline
raise ValueError("timbre for %s %s was already set at %s line %d"
% (self.cur_obj[0], self.cur_obj[1].name,
file, line))
timbres, looplen = self.pipesplit(timbrewords)
timbres = [int(x) for x in timbres]
maxduty = self.get_max_timbre()
if not all(0 <= x <= maxduty for x in timbres):
raise ValueError("timbre steps must be 0 to %d" % maxduty)
self.timbre, self.timbre_looplen = timbres, looplen or 1
self.timbre_fileline = fileline
def parse_pitchenv(self, pitchword):
"""Parse an element of a pitch envelope.
The set_pitch() method calls this once per pitch word. Subclasses
may initialize any necessary state in their __init__() method or in
an overridden set_pitch().
If not overridden, this abstract method raises NotImplementedError.
"""
raise NotImplementedError
def set_pitch(self, pitchwords, fileline=None):
if self.pitch is not None:
fileline = self.pitch_fileline
raise ValueError("pitch for %s %s was already set at %s line %d"
% (self.cur_obj[0], self.cur_obj[1].name,
file, line))
pitches, looplen = self.pipesplit(pitchwords)
pitches = [self.parse_pitchenv(pitch) for pitch in pitches]
self.pitch, self.pitch_looplen = pitches, looplen or 1
self.pitch_fileline = fileline
@staticmethod
def expand_envelope_loop(envelope, looplen, length):
index = 0
for i in range(length):
yield envelope[index]
index += 1
if index >= len(envelope):
index -= looplen
def xform_timbre(self, t):
return t << 14
def get_default_timbre(self):
return 2
def render_tvp(self):
volume = self.volume or [8]
timbre = self.timbre or [self.get_default_timbre()]
timbre_looplen = self.timbre_looplen
timbre = list(self.expand_envelope_loop(timbre, timbre_looplen, len(volume)))
xtimbre = [self.xform_timbre(t) for t in timbre]
pitch = self.pitch or [0]
pitch_looplen = self.pitch_looplen
pitch = list(self.expand_envelope_loop(pitch, pitch_looplen, len(volume)))
attackdata = bytearray()
for t, v, p in zip(xtimbre, volume, pitch):
attackdata.append((t >> 8) | v)
attackdata.append((t | p) & 0xFF)
return timbre, volume, pitch, bytes(attackdata)
class PentlyInstrument(PentlyEnvelopeContainer):
def __init__(self, name=None, orderkey=0, fileline=None, warn=None):
"""Set up a new instrument.
name, fileline -- used in duplicate error messages
"""
super().__init__(name, orderkey, fileline, warn=warn)
self.detached = self.decay = None
def set_decay(self, rate, fileline=None):
if not 0 <= rate <= 127:
raise ValueError("decay must be 1 to 127 units per 16 frames, not %d"
% rate)
if self.decay is not None:
file, line = self.decay_fileline
raise ValueError("decay for %s was already set at %s line %d"
% (self.name, file, line))
self.decay, self.decay_fileline = rate, fileline
def parse_pitchenv(self, pitch):
"""Parse an element of the pitch envelope relative to the base note.
This is equivalent to an "absolute" arpeggio envelope in FamiTracker.
"""
pitch = int(pitch)
if not -60 <= pitch <= 60:
raise ValueError("noise pitches must be within five octaves")
return pitch
def set_detached(self, detached):
self.detached = detached
@staticmethod
def compress_zero_arps(attackdata):
"""Delete zero pitch byte and set bit 4 of timbre/volume byte."""
out = bytearray()
attackdata = iter(attackdata)
for timbre_volume in attackdata:
pitch = next(attackdata)
if pitch == 0:
out.append(timbre_volume | 0x10)
else:
out.append(timbre_volume)
out.append(pitch)
return bytes(out)
def render(self, scopes=None):
timbre, volume, pitch, attackdata = self.render_tvp()
# Drop the final (sustain) frame and compress the rest
# Sustain pitch is always 0
sustaintimbre = timbre[-1]
sustainvolume = volume[-1]
attackdata = self.compress_zero_arps(attackdata[:-2])
decay = self.decay or 0
detached = 1 if self.detached else 0
asmname = self.get_asmname(self.name)
self.asmname = 'PI_'+asmname
self.asmdef = ("instdef PI_%s, %d, %d, %d, %d, %s, %d"
% (asmname, sustaintimbre, sustainvolume, decay,
detached, 'PIDAT_'+asmname if attackdata else '0',
len(volume) - 1))
self.asmdataname = 'PIDAT_'+asmname
self.asmdataprefix = '.byte '
self.asmdata = attackdata
self.bytesize = len(attackdata) + 5
class PentlySfx(PentlyEnvelopeContainer):
def __init__(self, channel_type, pitchctx=None,
name=None, orderkey=0, fileline=None, warn=None):
"""Set up a new sound effect.
channel_type -- 0 for pulse, 2 for triangle, or 3 for noise
name, fileline -- used in duplicate error messages
"""
super().__init__(name, orderkey, fileline, warn=warn)
self.rate, self.channel_type = None, channel_type
self.pitchctx = PentlyPitchContext(pitchctx)
octave_mode = 'noise' if channel_type == 3 else 'absolute'
self.pitchctx.reset_octave(octave_mode=octave_mode)
def set_rate(self, rate, fileline=None):
"""Sets the playback rate of a sound effect."""
if not 1 <= rate <= 16:
raise ValueError("rate must be 1 to 16 frames per step, not %d"
% rate)
if self.rate is not None:
file, line = self.rate_fileline
raise ValueError("rate for %s was already set at %s line %d"
% (self.cur_obj[1].name, file, line))
self.rate, self.rate_fileline = rate, fileline
def get_max_timbre(self):
return 1 if self.channel_type == 3 else 3
def parse_pitchenv(self, pitch):
"""Parse an element of the absolute pitch envelope.
This is equivalent to a "fixed" arpeggio envelope in FamiTracker.
"""
return self.pitchctx.parse_absolute_pitch(pitch)
def get_default_timbre(self):
return 0 if self.channel_type == 3 else 2
def xform_timbre(self, t):
if self.channel_type == 2:
return 0x8000
if self.channel_type == 3:
return 0x80 if t else 0
return t << 14
def render(self, scopes=None):
timbre, volume, pitch, attackdata = self.render_tvp()
rate = self.rate or 1
# Trim trailing silence
trimmed_silence = 0
while len(volume) > 1 and volume[-1] == 0:
del volume[-1]
trimmed_silence += 1
if trimmed_silence:
attackdata = attackdata[:-2 * trimmed_silence]
asmname = self.get_asmname(self.name)
self.asmname = 'PE_'+asmname
self.asmdef = ("sfxdef PE_%s, PEDAT_%s, %d, %d, %d"
% (asmname, asmname,
len(volume), rate, self.channel_type))
self.asmdataname = 'PEDAT_'+asmname
self.asmdataprefix = '.byte '
self.asmdata = attackdata
self.bytesize = len(attackdata) + 4
class PentlyDrum(PentlyRenderable):
drumnameRE = re.compile('([a-zA-Z_][a-zA-Z0-9_]*[a-zA-Z_])$')
def __init__(self, sfxnames, name, orderkey=0, fileline=None, warn=None):
super().__init__(name, orderkey, fileline, warn=warn)
is_grace_note = name[-1] == 'g' and name[-2].isdigit()
if is_grace_note:
raise ValueError("drum name must not end with grace note command")
if not self.drumnameRE.match(name):
raise ValueError("drum name must begin and end with letter or '_'")
self.sfxnames = sfxnames
def render(self, scopes=None):
# TODO: For drums defined in a song, check for effects in same song
sfxnames = ', '.join('PE_'+self.get_asmname(sfxname)
for sfxname in self.sfxnames)
self.asmname = 'DR_'+PentlyRenderable.get_asmname(self.name)
self.asmdef = "drumdef %s, %s" % (self.asmname, sfxnames)
self.bytesize = 2
class PentlySong(PentlyRenderable):
def __init__(self, pitchctx=None, rhyctx=None,
name=None, orderkey=0, fileline=None, warn=None):
super().__init__(name, orderkey, fileline, warn=warn)
self.pitchctx = PentlyPitchContext(pitchctx)
self.rhyctx = PentlyRhythmContext(rhyctx)
self.rhyctx.tempo = 100.0
self.last_rowtempo = self.segno_fileline = self.last_beatlen = None
self.conductor = []
self.bytesize = 2
self.rehearsal_marks = {}
self.total_rows = self.last_mark_rows = 0
self.title = self.author = ""
self.wall_time = self.segno_wall_time = 0.0
def wait_rows(self, rows_to_wait):
"""Updates the tempo and beat duration if needed, then waits some rows."""
if rows_to_wait < 1: return
# Update tempo if needed
beat_length = self.rhyctx.get_beat_length()
rowtempo = int(round(self.rhyctx.tempo * beat_length))
if rowtempo > 1500:
raise ValueError("last tempo change exceeds 1500 rows per minute")
if rowtempo != self.last_rowtempo:
self.conductor.append('setTempo %d' % rowtempo)
self.bytesize += 2
self.last_rowtempo = rowtempo
if self.last_beatlen != beat_length:
try:
durcode = durcodes[beat_length]
except KeyError:
raise ValueError("no duration code for %d beats per row"
% beat_length)
self.conductor.append('setBeatDuration %s' % durcode)
self.bytesize += 1
self.last_beatlen = beat_length
self.total_rows += rows_to_wait
self.wall_time += rows_to_wait * 60.0 / rowtempo
endminutes, endseconds = self.wall_time // 60, self.wall_time % 60
while rows_to_wait > 256:
self.conductor.append('waitRows 256')
self.bytesize += 2
rows_to_wait -= 256
self.conductor.append('waitRows %d ; end at %d:%05.2f'
% (rows_to_wait, endminutes, endseconds))
self.bytesize += 2
def set_attack(self, chname):
chnum = pitched_tracks[chname]
if chnum >= 3:
raise ValueError("%s is not a pitched channel" % chname)
cmd = "attackOn%s" % track_suffixes[chnum]
self.conductor.append(cmd)
self.bytesize += 1
def play(self, patname, track=None, instrument=None, transpose=0):
if (track is not None and instrument is not None
and transpose == 0):
# Attempt a note-on rather than a pattern start
if track == 'noise':
ch = 3
self.pitchctx.octave_mode = "noise"
else:
ch = pitched_tracks[track]
self.pitchctx.octave_mode = 'absolute'
self.pitchctx.reset_octave()
if ch >= 3:
raise ValueError("cannot play conductor note on a track without its own channel")
try:
transpose = self.pitchctx.parse_absolute_pitch(patname)
except ValueError as e:
pass
else:
abstract_cmd = ('noteOn', ch, transpose, instrument)
self.conductor.append(abstract_cmd)
self.bytesize += 3
return
if track is not None:
try:
track = pitched_tracks[track]
except KeyError:
raise ValueError('unknown track ' + track)
abstract_cmd = ('playPat', track, patname, transpose, instrument)
self.bytesize += 4
self.conductor.append(abstract_cmd)
@staticmethod
def parse_trackset(tracks):
tracks_to_stop = set()
tracks_unknown = []
for trackname in tracks:
if trackname == 'drum':
tracks_to_stop.add(3)
continue
try:
track = pitched_tracks[trackname]
except KeyError:
tracks_unknown.append(trackname)
continue
else:
tracks_to_stop.add(track)
if tracks_unknown:
raise ValueError("unknown track names: "+" ".join(tracks_unknown))
return tracks_to_stop
def stop_tracks(self, tracks):
tracks_to_stop = self.parse_trackset(tracks)
abstract_cmds = [('stopPat', track) for track in tracks_to_stop]
self.conductor.extend(abstract_cmds)
self.bytesize += 4 * len(abstract_cmds)
def add_segno(self, fileline):
if self.segno_fileline is not None:
file, line = self.segno_fileline
raise ValueError("%s: loop point already set at %s line %d"
% (self.name, file, line))
self.conductor.append('segno')
self.bytesize += 1
self.segno_fileline = fileline
self.rehearsal_marks['%'] = (self.total_rows, fileline)
self.segno_wall_time = self.wall_time
def add_mark(self, markname, fileline):
if len(markname) > 24:
raise ValueError("name of mark %s exceeds 24 characters"
% markname)
try:
markname.encode('ascii', errors='strict')
except UnicodeError:
self.warn("mark %s contains non-ASCII characters" % markname)
markname = markname.encode('ascii', errors='replace')
markname = markname.decode('ascii')
if self.total_rows <= self.last_mark_rows:
raise ValueError("no time between mark %s and preceding mark"
% markname)
if markname.startswith('%'):
raise ValueError("mark names starting with % are reserved")
try:
_, fileline = self.rehearsal_marks[markname]
except KeyError:
pass
else:
file, line = fileline
raise ValueError("%s: mark %s already set at %s line %d"
% (self.name, markname, file, line))