3 # info mostly taken from looking at files. See also
4 # http://lilypond.org/wiki/?EnigmaTransportFormat
19 # * slur/stem directions
20 # * voices (2nd half of frame?)
21 # * more intelligent lyrics
22 # * beams (better use autobeam?)
23 # * more robust: try entertainer.etf (freenote)
25 # * empty measures (eg. twopt03.etf from freenote)
36 program_name = sys.argv[0]
38 version = '@TOPLEVEL_VERSION@'
39 if version == '@' + 'TOPLEVEL_VERSION' + '@':
40 version = '(unknown version)' # uGUHGUHGHGUGH
42 finale_clefs= ['treble', 'alto', 'tenor', 'bass', 'percussion', 'treble_8', 'bass_8', 'baritone']
46 return finale_clefs[fin]
48 sys.stderr.write ( '\nHuh? Found clef number %d\n' % fin)
55 return open (f).read ()
57 # notename 0 == central C
58 distances = [0, 2, 4, 5, 7, 9, 11, 12]
59 def semitones (name, acc):
60 return (name / 7 ) * 12 + distances[name % 7] + acc
62 # represent pitches as (notename, alteration), relative to C-major scale
63 def transpose(orig, delta):
67 old_pitch =semitones (oname, oacc)
68 delta_pitch = semitones (dname, dacc)
69 nname = (oname + dname)
71 new_pitch = semitones (nname, nacc)
73 nacc = nacc - (new_pitch - old_pitch - delta_pitch)
79 def interpret_finale_key_sig (finale_id):
81 find the transposition of C-major scale that belongs here.
83 we are not going to insert the correct major/minor, we only want to
84 have the correct number of accidentals
90 bank_number = finale_id >> 8
91 accidental_bits = finale_id & 0xff
93 if 0 <= accidental_bits < 7:
94 while accidental_bits > 0:
95 p = transpose (p, (4,0)) # a fifth up
96 accidental_bits = accidental_bits - 1
97 elif 248 < accidental_bits <= 255:
98 while accidental_bits < 256:
99 p = transpose (p, (3,0))
100 accidental_bits = accidental_bits + 1
104 p = transpose (p, (5, 0))
107 return KeySignature (p, bank_number)
110 def find_scale (keysig):
111 cscale = map (lambda x: (x,0), range (0,7))
112 # print "cscale: ", cscale
113 ascale = map (lambda x: (x,0), range (-2,5))
114 # print "ascale: ", ascale
115 transposition = keysig.pitch
116 if keysig.sig_type == 1:
117 transposition = transpose(transposition, (2, -1))
118 transposition = (transposition[0] % 7, transposition[1])
119 trscale = map(lambda x, k=transposition: transpose(x, k), ascale)
121 trscale = map(lambda x, k=transposition: transpose(x, k), cscale)
122 # print "trscale: ", trscale
125 def EDU_to_duration (edu):
140 def rational_to_lily_skip (rat):
144 while d and d % 2 == 0:
145 basedur = basedur << 1
148 str = 's%d' % basedur
150 str = str + '*%d' % n
152 str = str + '/%d' % d
167 def rat_simplify (r):
178 def rat_multiply (a,b):
182 return rat_simplify ((x*p, y*q))
188 return rat_simplify ((x*q + p*y, y*q))
196 def rat_subtract (a,b ):
197 return rat_add (a, rat_neg (b))
199 def lily_notename (tuple2):
201 nn = chr ((n+ 2)%7 + ord ('a'))
203 return nn + {-2:'eses', -1:'es', 0:'', 1:'is', 2:'isis'}[a]
207 def __init__ (self, number):
208 self.start_note = number
211 def append_finale (self, fin):
212 self.finale.append (fin)
215 n = self.finale[0][2]*self.finale[0][3]
216 d = self.finale[0][0]*self.finale[0][1]
217 return rat_simplify( (n, d))
219 def dump_start (self):
220 return '\\times %d/%d { ' % self.factor ()
225 def calculate (self, chords):
226 edu_left = self.finale[0][0] * self.finale[0][1]
228 startch = chords[self.start_note]
230 while c and edu_left:
233 c.chord_prefix = self.dump_start () + c.chord_prefix
236 edu_left = edu_left - c.EDU_duration ()
238 c.chord_suffix = c.chord_suffix+ self.dump_end ()
242 sys.stderr.write ("\nHuh? Tuplet starting at entry %d was too short." % self.start_note)
245 def __init__ (self, number, params):
249 def append_entry (self, finale_e):
250 self.finale.append (finale_e)
252 def calculate (self, chords):
253 startnote = self.finale[5]
254 endnote = self.finale[3*6 + 2]
256 cs = chords[startnote]
262 cs.note_suffix = '-(' + cs.note_suffix
263 ce.note_suffix = ce.note_suffix + '-)'
266 sys.stderr.write ("""\nHuh? Slur no %d between (%d,%d), with %d notes""" % (self.number, startnote, endnote, len (chords)))
269 class Global_measure:
270 def __init__ (self, number):
273 self.key_signature = None
281 return `self.finale `
283 def set_timesig (self, finale):
284 (beats, fdur) = finale
285 (log, dots) = EDU_to_duration (fdur)
293 sys.stderr.write ("\nHuh? Beat duration has dots? (EDU Duration = %d)" % fdur)
294 self.timesig = (beats, log)
299 def set_key_sig (self, finale):
300 k = interpret_finale_key_sig (finale)
301 self.key_signature = k
302 self.scale = find_scale (k)
304 def set_flags (self,flag1, flag2):
306 # flag1 isn't all that interesting.
311 self.repeats.append ('start')
313 self.repeats.append ('stop')
317 self.repeats.append ('bracket')
330 class Articulation_def:
331 def __init__ (self, n, a, b):
332 self.finale_glyph = a & 0xff
337 return articulation_dict[self.finale_glyph]
339 sys.stderr.write ("\nUnknown articulation no. %d" % self.finale_glyph)
340 sys.stderr.write ("\nPlease add an entry to articulation_dict in the Python source")
344 def __init__ (self, a,b, finale):
345 self.definition = finale[0]
348 def calculate (self, chords, defs):
349 c = chords[self.notenumber]
351 adef = defs[self.definition]
355 sys.stderr.write ("\nThis happened on note %d" % self.notenumber)
357 c.note_suffix = '-' + lystr
360 def __init__ (self, a,b , finale):
362 self.syllable = finale[1]
363 self.verse = finale[0]
364 def calculate (self, chords, lyrics):
365 self.chord = chords[self.chordnum]
368 def __init__ (self, number, body):
371 self.split_syllables ()
372 def split_syllables (self):
373 ss = re.split ('(-| +)', self.body)
379 septor = re.sub (" +", "", s)
380 septor = re.sub ("-", " -- ", septor)
381 syls[-1] = syls[-1] + septor
387 self.syllables = syls
392 for s in self.syllables[1:]:
393 line = line + ' ' + s
395 str = str + ' ' * 4 + line + '\n'
398 str = """\nverse%s = \\lyricmode {\n %s }\n""" % (encodeint (self.number - 1) ,str)
402 def __init__(self, pitch, sig_type = 0):
404 self.sig_type = sig_type
406 def signature_type (self):
407 if self.sig_type == 1:
410 # really only for 0, but we only know about 0 and 1
413 def equal (self, other):
414 if other and other.pitch == self.pitch and other.sig_type == self.sig_type:
421 def __init__(self, no):
423 self.frames = [0] * 4
427 self.global_measure = None
434 def calculate (self):
437 if len (self.finale) < 2:
441 self.frames = [fs[0]]
450 def __init__ (self, finale):
453 (number, start, end ) = finale
459 def set_measure (self, m):
462 def calculate (self):
467 for c in self.chords:
468 if c.grace and (lastch == None or (not lastch.grace)):
469 c.chord_prefix = r'\grace {' + c.chord_prefix
471 elif not c.grace and lastch and lastch.grace:
472 lastch.chord_suffix = lastch.chord_suffix + ' } '
477 if lastch and in_grace:
478 lastch.chord_suffix += '}'
482 str = '%% FR(%d)\n' % self.number
483 left = self.measure.global_measure.length ()
487 for c in self.chords:
488 add = c.ly_string () + ' '
489 if len (ln) + len(add) > 72:
490 str = str + ln + '\n'
493 left = rat_subtract (left, c.length ())
498 sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
501 str = str + rational_to_lily_skip (left)
507 return chr ( i + ord ('A'))
510 def __init__ (self, number):
514 def get_measure (self, no):
515 fill_list_to (self.measures, no)
517 if self.measures[no] == None:
519 self.measures [no] =m
522 return self.measures[no]
524 return 'staff' + encodeint (self.number - 1)
525 def layerid (self, l):
526 return self.staffid() + 'layer%s' % chr (l -1 + ord ('A'))
528 def dump_time_key_sigs (self):
534 for m in self.measures[1:]:
535 if not m or not m.valid:
542 if g.key_signature and not g.key_signature.equal(last_key):
543 pitch= g.key_signature.pitch
544 e = e + "\\key %s %s " % (lily_notename (pitch),
545 g.key_signature.signature_type())
547 last_key = g.key_signature
548 if last_time <> g.timesig :
549 e = e + "\\time %d/%d " % g.timesig
550 last_time = g.timesig
552 if 'start' in g.repeats:
553 e = e + ' \\bar "|:" '
556 # we don't attempt voltas since they fail easily.
557 if 0 : # and g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket:
559 if g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket == 'end':
563 if g.bracket == 'start':
566 str = string.join (map (lambda x: '(volta %s)' % x, strs))
568 e = e + ' \\set Score.repeatCommands = #\'(%s) ' % str
573 if last_clef <> m.clef :
574 e = e + '\\clef "%s"' % lily_clef (m.clef)
578 k = k +' ' + rational_to_lily_skip (gap) + '\n'
583 gap = rat_add (gap, g.length ())
584 if 'stop' in g.repeats:
585 k = k + ' \\bar ":|" '
587 k = '%sglobal = { %s }\n\n ' % (self.staffid (), k)
595 for x in range (1,5): # 4 layers.
600 for m in self.measures[1:]:
601 if not m or not m.valid:
602 sys.stderr.write ("Skipping non-existant or invalid measure\n")
609 sys.stderr.write ("Skipping nonexistent frame %d\n" % x)
610 laystr = laystr + "%% non existent frame %d (skipped) \n" % x
614 laystr = laystr +'} %s {\n ' % rational_to_lily_skip (gap)
616 laystr = laystr + fr.dump ()
618 if m.global_measure :
619 gap = rat_add (gap, m.global_measure.length ())
622 "No global measure for staff %d measure %d\n"
623 % (self.number, m.number))
626 laystr = '%s = { { %s } }\n\n' % (l, laystr)
630 str = str + self.dump_time_key_sigs ()
631 stafdef = '\\%sglobal' % self.staffid ()
633 stafdef = stafdef + ' \\' + i
636 str = str + '%s = \\context Staff = %s <<\n %s\n >>\n' % \
637 (self.staffid (), self.staffid (), stafdef)
646 return [(l[0], l[1])] + ziplist (l[2:])
650 def __init__ (self, number, contents):
653 self.finale = contents[:7]
655 self.notelist = ziplist (contents[7:])
661 self.note_suffix = ''
662 self.chord_suffix = ''
663 self.chord_prefix = ''
670 return self.frame.measure
676 l = (1, self.duration[0])
678 d = 1 << self.duration[1]
680 dotfact = rat_subtract ((2,1), (1,d))
681 mylen = rat_multiply (dotfact, l)
684 mylen = rat_multiply (mylen, self.tuplet.factor())
688 def EDU_duration (self):
689 return self.finale[2]
690 def set_duration (self):
691 self.duration = EDU_to_duration(self.EDU_duration ())
693 def calculate (self):
694 self.find_realpitch ()
697 flag = self.finale[4]
698 if Chord.GRACE_MASK & flag:
702 def find_realpitch (self):
704 meas = self.measure ()
706 if not meas or not meas.global_measure :
707 sys.stderr.write ('note %d not in measure\n' % self.number)
708 elif not meas.global_measure.scale:
709 sys.stderr.write ('note %d: no scale in this measure.' % self.number)
712 for p in self.notelist:
722 scale = meas.global_measure.scale
723 (sn, sa) =scale[rest % 7]
724 sn = sn + (rest - (rest%7)) + 7
726 self.pitches.append ((sn, acc))
727 tiestart = tiestart or (flag & Chord.TIE_START_MASK)
729 self.chord_suffix = self.chord_suffix + ' ~ '
731 REST_MASK = 0x40000000L
732 TIE_START_MASK = 0x40000000L
733 GRACE_MASK = 0x00800000L
735 def ly_string (self):
741 if not (self.finale[4] & Chord.REST_MASK):
744 for p in self.pitches:
749 nn = lily_notename ((n,a))
766 if len (self.pitches) > 1:
769 s = s + '%d%s' % (self.duration[0], '.'* self.duration[1])
770 s = self.note_prefix + s + self.note_suffix
772 s = self.chord_prefix + s + self.chord_suffix
777 def fill_list_to (list, no):
779 Add None to LIST until it contains entry number NO.
781 while len (list) <= no:
782 list.extend ([None] * (no - len(list) + 1))
785 def read_finale_value (str):
787 Pry off one value from STR. The value may be $hex, decimal, or "string".
788 Return: (value, rest-of-STR)
790 while str and str[0] in ' \t\n':
800 while str and str[0] in '0123456789ABCDEF':
805 return (string.atol (hex, 16), str)
809 while str and str[0] <> '"':
814 elif str[0] in '-0123456789':
816 while str and str[0] in '-0123456789':
820 return (string.atoi (dec), str)
822 sys.stderr.write ("can't convert `%s'\n" % str)
828 def parse_etf_file (fn, tag_dict):
830 """ Read FN, putting ETF info into
831 a giant dictionary. The keys of TAG_DICT indicate which tags
832 to put into the dict.
835 sys.stderr.write ('parsing ... ' )
838 gulp = re.sub ('[\n\r]+', '\n', f.read ())
839 ls = string.split (gulp, '\n^')
842 for k in tag_dict.keys ():
843 etf_file_dict[k] = {}
850 m = re.match ('^([a-zA-Z0-9&]+)\(([^)]+)\)', l)
851 if m and tag_dict.has_key (m.group (1)):
854 indices = tuple (map (string.atoi, string.split (m.group (2), ',')))
855 content = l[m.end (2)+1:]
858 tdict = etf_file_dict[tag]
859 if not tdict.has_key (indices):
865 if tag == 'verse' or tag == 'block':
866 m2 = re.match ('(.*)\^end', content)
868 parsed = [m2.group (1)]
871 (v, content) = read_finale_value (content)
875 tdict [indices].extend (parsed)
877 last_indices = indices
882 # let's not do this: this really confuses when eE happens to be before a ^text.
883 # if last_tag and last_indices:
884 # etf_file_dict[last_tag][last_indices].append (l)
886 sys.stderr.write ('\n')
894 def __init__ (self, name):
895 self.measures = [None]
898 self.tuplets = [None]
901 self.articulations = [None]
902 self.syllables = [None]
904 self.articulation_defs = [None]
909 def get_global_measure (self, no):
910 fill_list_to (self.measures, no)
911 if self.measures[no] == None:
912 self.measures [no] = Global_measure (no)
914 return self.measures[no]
917 def get_staff(self,staffno):
918 fill_list_to (self.staffs, staffno)
919 if self.staffs[staffno] == None:
920 self.staffs[staffno] = Staff (staffno)
922 return self.staffs[staffno]
925 def try_IS (self, indices, contents):
928 def try_BC (self, indices, contents):
930 where = contents[0] / 1024.0
931 def try_TP(self, indices, contents):
934 if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
935 self.tuplets.append (Tuplet (num))
937 self.tuplets[-1].append_finale (contents)
939 def try_IM (self, indices, contents):
942 self.articulations.append (Articulation (a,b,fin))
943 def try_verse (self, indices, contents):
947 body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
948 body = re.sub ("\^[a-z]+", "", body)
949 self.verses.append (Verse (a, body))
950 def try_ve (self,indices, contents):
952 self.syllables.append (Syllable (a,b,contents))
954 def try_eE (self,indices, contents):
956 (prev, next, dur, pos, entryflag, extended, follow) = contents[:7]
958 fill_list_to (self.chords, no)
959 self.chords[no] =Chord (no, contents)
961 def try_Sx(self,indices, contents):
963 fill_list_to (self.slurs, slurno)
964 self.slurs[slurno] = Slur(slurno, contents)
966 def try_IX (self, indices, contents):
973 ix = self.articulation_defs[n]
975 ix = Articulation_def (n,a,b)
976 self.articulation_defs.append (Articulation_def (n, a, b))
978 def try_GF(self, indices, contents):
979 (staffno,measno) = indices
981 st = self.get_staff (staffno)
982 meas = st.get_measure (measno)
983 meas.finale = contents
985 def try_FR(self, indices, contents):
986 frameno = indices [0]
988 startnote = contents[0]
989 endnote = contents[1]
991 fill_list_to (self.frames, frameno)
993 self.frames[frameno] = Frame ((frameno, startnote, endnote))
995 def try_MS (self, indices, contents):
998 meas =self. get_global_measure (measno)
1000 meas.set_key_sig (keynum)
1003 beatlen = contents[3]
1004 meas.set_timesig ((beats, beatlen))
1006 meas_flag1 = contents[4]
1007 meas_flag2 = contents[5]
1009 meas.set_flags (meas_flag1, meas_flag2);
1019 'verse' : try_verse,
1027 def parse (self, etf_dict):
1028 sys.stderr.write ('reconstructing ...')
1031 for (tag,routine) in Etf_file.routine_dict.items ():
1032 ks = etf_dict[tag].keys ()
1035 routine (self, k, etf_dict[tag][k])
1037 sys.stderr.write ('processing ...')
1040 self.unthread_entries ()
1042 for st in self.staffs[1:]:
1046 for m in st.measures[1:]:
1052 m.global_measure = self.measures[mno]
1054 sys.stderr.write ("Non-existent global measure %d" % mno)
1057 frame_obj_list = [None]
1058 for frno in m.frames:
1060 fr = self.frames[frno]
1061 frame_obj_list.append (fr)
1063 sys.stderr.write ("\nNon-existent frame %d" % frno)
1065 m.frames = frame_obj_list
1066 for fr in frame_obj_list[1:]:
1072 fr.chords = self.get_thread (fr.start, fr.end)
1077 for c in self.chords[1:]:
1081 for f in self.frames[1:]:
1085 for t in self.tuplets[1:]:
1086 t.calculate (self.chords)
1088 for s in self.slurs[1:]:
1090 s.calculate (self.chords)
1092 for s in self.articulations[1:]:
1093 s.calculate (self.chords, self.articulation_defs)
1095 def get_thread (self, startno, endno):
1101 c = self.chords[startno]
1103 sys.stderr.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno, endno))
1107 while c and c.number <> endno:
1119 for s in self.staffs[1:]:
1121 str = str + '\n\n' + s.dump ()
1122 staffs.append ('\\' + s.staffid ())
1125 # should use \addlyrics ?
1127 for v in self.verses[1:]:
1128 str = str + v.dump()
1130 if len (self.verses) > 1:
1131 sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
1134 str += '\\version "2.3.25"\n'
1135 str = str + '<<\n %s\n>> } ' % string.join (staffs)
1141 return 'ETF FILE %s %s' % (self.measures, self.entries)
1143 def unthread_entries (self):
1144 for e in self.chords[1:]:
1148 e.prev = self.chords[e.finale[0]]
1149 e.next = self.chords[e.finale[1]]
1152 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1155 sys.stdout.write("""Usage: etf2ly [OPTIONS]... ETF-FILE
1157 Convert ETF to LilyPond.
1160 -h, --help print this help
1161 -o, --output=FILE set output filename to FILE
1162 -v, --version show version information
1164 Enigma Transport Format is a format used by Coda Music Technology's
1165 Finale product. This program will convert a subset of ETF to a
1166 ready-to-use lilypond file.
1168 Report bugs to bug-lilypond@gnu.org.
1170 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>.
1174 def print_version ():
1175 sys.stdout.write (r"""etf2ly (GNU lilypond) %s
1177 This is free software. It is covered by the GNU General Public License,
1178 and you are welcome to change it and/or distribute copies of it under
1179 certain conditions. Invoke as `midi2ly --warranty' for more information.
1181 Copyright (c) 2000--2005 by Han-Wen Nienhuys <hanwen@cs.uu.nl>
1186 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
1192 if o== '--help' or o == '-h':
1195 if o == '--version' or o == '-v':
1199 if o == '--output' or o == '-o':
1212 sys.stderr.write ('Processing `%s\'\n' % f)
1214 dict = parse_etf_file (f, Etf_file.routine_dict)
1216 if not out_filename:
1217 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1219 if out_filename == f:
1220 out_filename = os.path.basename (f + '.ly')
1222 sys.stderr.write ('Writing `%s\'' % out_filename)
1227 fo = open (out_filename, 'w')
1228 fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)