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
46 ################################################################
51 finale_clefs= ['treble', 'alto', 'tenor', 'bass', 'percussion', 'treble_8', 'bass_8', 'baritone']
55 return finale_clefs[fin]
57 sys.stderr.write ( '\nHuh? Found clef number %d\n' % fin)
64 return open (f).read ()
66 # notename 0 == central C
67 distances = [0, 2, 4, 5, 7, 9, 11, 12]
68 def semitones (name, acc):
69 return (name / 7 ) * 12 + distances[name % 7] + acc
71 # represent pitches as (notename, alteration), relative to C-major scale
72 def transpose(orig, delta):
76 old_pitch =semitones (oname, oacc)
77 delta_pitch = semitones (dname, dacc)
78 nname = (oname + dname)
80 new_pitch = semitones (nname, nacc)
82 nacc = nacc - (new_pitch - old_pitch - delta_pitch)
88 def interpret_finale_key_sig (finale_id):
90 find the transposition of C-major scale that belongs here.
92 we are not going to insert the correct major/minor, we only want to
93 have the correct number of accidentals
99 bank_number = finale_id >> 8
100 accidental_bits = finale_id & 0xff
102 if 0 <= accidental_bits < 7:
103 while accidental_bits > 0:
104 p = transpose (p, (4,0)) # a fifth up
105 accidental_bits = accidental_bits - 1
106 elif 248 < accidental_bits <= 255:
107 while accidental_bits < 256:
108 p = transpose (p, (3,0))
109 accidental_bits = accidental_bits + 1
113 p = transpose (p, (5, 0))
116 return KeySignature (p, bank_number)
119 def find_scale (keysig):
120 cscale = map (lambda x: (x,0), range (0,7))
121 # print "cscale: ", cscale
122 ascale = map (lambda x: (x,0), range (-2,5))
123 # print "ascale: ", ascale
124 transposition = keysig.pitch
125 if keysig.sig_type == 1:
126 transposition = transpose(transposition, (2, -1))
127 transposition = (transposition[0] % 7, transposition[1])
128 trscale = map(lambda x, k=transposition: transpose(x, k), ascale)
130 trscale = map(lambda x, k=transposition: transpose(x, k), cscale)
131 # print "trscale: ", trscale
134 def EDU_to_duration (edu):
149 def rational_to_lily_skip (rat):
153 while d and d % 2 == 0:
154 basedur = basedur << 1
157 str = 's%d' % basedur
159 str = str + '*%d' % n
161 str = str + '/%d' % d
176 def rat_simplify (r):
187 def rat_multiply (a,b):
191 return rat_simplify ((x*p, y*q))
197 return rat_simplify ((x*q + p*y, y*q))
205 def rat_subtract (a,b ):
206 return rat_add (a, rat_neg (b))
208 def lily_notename (tuple2):
210 nn = chr ((n+ 2)%7 + ord ('a'))
212 return nn + {-2:'eses', -1:'es', 0:'', 1:'is', 2:'isis'}[a]
216 def __init__ (self, number):
217 self.start_note = number
220 def append_finale (self, fin):
221 self.finale.append (fin)
224 n = self.finale[0][2]*self.finale[0][3]
225 d = self.finale[0][0]*self.finale[0][1]
226 return rat_simplify( (n, d))
228 def dump_start (self):
229 return '\\times %d/%d { ' % self.factor ()
234 def calculate (self, chords):
235 edu_left = self.finale[0][0] * self.finale[0][1]
237 startch = chords[self.start_note]
239 while c and edu_left:
242 c.chord_prefix = self.dump_start () + c.chord_prefix
245 edu_left = edu_left - c.EDU_duration ()
247 c.chord_suffix = c.chord_suffix+ self.dump_end ()
251 sys.stderr.write ("\nHuh? Tuplet starting at entry %d was too short." % self.start_note)
254 def __init__ (self, number, params):
258 def append_entry (self, finale_e):
259 self.finale.append (finale_e)
261 def calculate (self, chords):
262 startnote = self.finale[5]
263 endnote = self.finale[3*6 + 2]
265 cs = chords[startnote]
271 cs.note_suffix = '-(' + cs.note_suffix
272 ce.note_suffix = ce.note_suffix + '-)'
275 sys.stderr.write ("""\nHuh? Slur no %d between (%d,%d), with %d notes""" % (self.number, startnote, endnote, len (chords)))
278 class Global_measure:
279 def __init__ (self, number):
282 self.key_signature = None
290 return `self.finale `
292 def set_timesig (self, finale):
293 (beats, fdur) = finale
294 (log, dots) = EDU_to_duration (fdur)
302 sys.stderr.write ("\nHuh? Beat duration has dots? (EDU Duration = %d)" % fdur)
303 self.timesig = (beats, log)
308 def set_key_sig (self, finale):
309 k = interpret_finale_key_sig (finale)
310 self.key_signature = k
311 self.scale = find_scale (k)
313 def set_flags (self,flag1, flag2):
315 # flag1 isn't all that interesting.
320 self.repeats.append ('start')
322 self.repeats.append ('stop')
326 self.repeats.append ('bracket')
339 class Articulation_def:
340 def __init__ (self, n, a, b):
341 self.finale_glyph = a & 0xff
346 return articulation_dict[self.finale_glyph]
348 sys.stderr.write ("\nUnknown articulation no. %d" % self.finale_glyph)
349 sys.stderr.write ("\nPlease add an entry to articulation_dict in the Python source")
353 def __init__ (self, a,b, finale):
354 self.definition = finale[0]
357 def calculate (self, chords, defs):
358 c = chords[self.notenumber]
360 adef = defs[self.definition]
364 sys.stderr.write ("\nThis happened on note %d" % self.notenumber)
366 c.note_suffix = '-' + lystr
369 def __init__ (self, a,b , finale):
371 self.syllable = finale[1]
372 self.verse = finale[0]
373 def calculate (self, chords, lyrics):
374 self.chord = chords[self.chordnum]
377 def __init__ (self, number, body):
380 self.split_syllables ()
381 def split_syllables (self):
382 ss = re.split ('(-| +)', self.body)
388 septor = re.sub (" +", "", s)
389 septor = re.sub ("-", " -- ", septor)
390 syls[-1] = syls[-1] + septor
396 self.syllables = syls
401 for s in self.syllables[1:]:
402 line = line + ' ' + s
404 str = str + ' ' * 4 + line + '\n'
407 str = """\nverse%s = \\lyricmode {\n %s }\n""" % (encodeint (self.number - 1) ,str)
411 def __init__(self, pitch, sig_type = 0):
413 self.sig_type = sig_type
415 def signature_type (self):
416 if self.sig_type == 1:
419 # really only for 0, but we only know about 0 and 1
422 def equal (self, other):
423 if other and other.pitch == self.pitch and other.sig_type == self.sig_type:
430 def __init__(self, no):
432 self.frames = [0] * 4
436 self.global_measure = None
443 def calculate (self):
446 if len (self.finale) < 2:
450 self.frames = [fs[0]]
459 def __init__ (self, finale):
462 (number, start, end ) = finale
468 def set_measure (self, m):
471 def calculate (self):
476 for c in self.chords:
477 if c.grace and (lastch == None or (not lastch.grace)):
478 c.chord_prefix = r'\grace {' + c.chord_prefix
480 elif not c.grace and lastch and lastch.grace:
481 lastch.chord_suffix = lastch.chord_suffix + ' } '
486 if lastch and in_grace:
487 lastch.chord_suffix += '}'
491 str = '%% FR(%d)\n' % self.number
492 left = self.measure.global_measure.length ()
496 for c in self.chords:
497 add = c.ly_string () + ' '
498 if len (ln) + len(add) > 72:
499 str = str + ln + '\n'
502 left = rat_subtract (left, c.length ())
507 sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
510 str = str + rational_to_lily_skip (left)
516 return chr ( i + ord ('A'))
519 def __init__ (self, number):
523 def get_measure (self, no):
524 fill_list_to (self.measures, no)
526 if self.measures[no] == None:
528 self.measures [no] =m
531 return self.measures[no]
533 return 'staff' + encodeint (self.number - 1)
534 def layerid (self, l):
535 return self.staffid() + 'layer%s' % chr (l -1 + ord ('A'))
537 def dump_time_key_sigs (self):
543 for m in self.measures[1:]:
544 if not m or not m.valid:
551 if g.key_signature and not g.key_signature.equal(last_key):
552 pitch= g.key_signature.pitch
553 e = e + "\\key %s %s " % (lily_notename (pitch),
554 g.key_signature.signature_type())
556 last_key = g.key_signature
557 if last_time <> g.timesig :
558 e = e + "\\time %d/%d " % g.timesig
559 last_time = g.timesig
561 if 'start' in g.repeats:
562 e = e + ' \\bar "|:" '
565 # we don't attempt voltas since they fail easily.
566 if 0 : # and g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket:
568 if g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket == 'end':
572 if g.bracket == 'start':
575 str = string.join (map (lambda x: '(volta %s)' % x, strs))
577 e = e + ' \\set Score.repeatCommands = #\'(%s) ' % str
582 if last_clef <> m.clef :
583 e = e + '\\clef "%s"' % lily_clef (m.clef)
587 k = k +' ' + rational_to_lily_skip (gap) + '\n'
592 gap = rat_add (gap, g.length ())
593 if 'stop' in g.repeats:
594 k = k + ' \\bar ":|" '
596 k = '%sglobal = { %s }\n\n ' % (self.staffid (), k)
604 for x in range (1,5): # 4 layers.
609 for m in self.measures[1:]:
610 if not m or not m.valid:
611 sys.stderr.write ("Skipping non-existant or invalid measure\n")
618 sys.stderr.write ("Skipping nonexistent frame %d\n" % x)
619 laystr = laystr + "%% non existent frame %d (skipped) \n" % x
623 laystr = laystr +'} %s {\n ' % rational_to_lily_skip (gap)
625 laystr = laystr + fr.dump ()
627 if m.global_measure :
628 gap = rat_add (gap, m.global_measure.length ())
631 "No global measure for staff %d measure %d\n"
632 % (self.number, m.number))
635 laystr = '%s = { { %s } }\n\n' % (l, laystr)
639 str = str + self.dump_time_key_sigs ()
640 stafdef = '\\%sglobal' % self.staffid ()
642 stafdef = stafdef + ' \\' + i
645 str = str + '%s = \\context Staff = %s <<\n %s\n >>\n' % \
646 (self.staffid (), self.staffid (), stafdef)
655 return [(l[0], l[1])] + ziplist (l[2:])
659 def __init__ (self, number, contents):
662 self.finale = contents[:7]
664 self.notelist = ziplist (contents[7:])
670 self.note_suffix = ''
671 self.chord_suffix = ''
672 self.chord_prefix = ''
679 return self.frame.measure
685 l = (1, self.duration[0])
687 d = 1 << self.duration[1]
689 dotfact = rat_subtract ((2,1), (1,d))
690 mylen = rat_multiply (dotfact, l)
693 mylen = rat_multiply (mylen, self.tuplet.factor())
697 def EDU_duration (self):
698 return self.finale[2]
699 def set_duration (self):
700 self.duration = EDU_to_duration(self.EDU_duration ())
702 def calculate (self):
703 self.find_realpitch ()
706 flag = self.finale[4]
707 if Chord.GRACE_MASK & flag:
711 def find_realpitch (self):
713 meas = self.measure ()
715 if not meas or not meas.global_measure :
716 sys.stderr.write ('note %d not in measure\n' % self.number)
717 elif not meas.global_measure.scale:
718 sys.stderr.write ('note %d: no scale in this measure.' % self.number)
721 for p in self.notelist:
731 scale = meas.global_measure.scale
732 (sn, sa) =scale[rest % 7]
733 sn = sn + (rest - (rest%7)) + 7
735 self.pitches.append ((sn, acc))
736 tiestart = tiestart or (flag & Chord.TIE_START_MASK)
738 self.chord_suffix = self.chord_suffix + ' ~ '
740 REST_MASK = 0x40000000L
741 TIE_START_MASK = 0x40000000L
742 GRACE_MASK = 0x00800000L
744 def ly_string (self):
750 if not (self.finale[4] & Chord.REST_MASK):
753 for p in self.pitches:
758 nn = lily_notename ((n,a))
775 if len (self.pitches) > 1:
778 s = s + '%d%s' % (self.duration[0], '.'* self.duration[1])
779 s = self.note_prefix + s + self.note_suffix
781 s = self.chord_prefix + s + self.chord_suffix
786 def fill_list_to (list, no):
788 Add None to LIST until it contains entry number NO.
790 while len (list) <= no:
791 list.extend ([None] * (no - len(list) + 1))
794 def read_finale_value (str):
796 Pry off one value from STR. The value may be $hex, decimal, or "string".
797 Return: (value, rest-of-STR)
799 while str and str[0] in ' \t\n':
809 while str and str[0] in '0123456789ABCDEF':
814 return (string.atol (hex, 16), str)
818 while str and str[0] <> '"':
823 elif str[0] in '-0123456789':
825 while str and str[0] in '-0123456789':
829 return (string.atoi (dec), str)
831 sys.stderr.write ("cannot convert `%s'\n" % str)
837 def parse_etf_file (fn, tag_dict):
839 """ Read FN, putting ETF info into
840 a giant dictionary. The keys of TAG_DICT indicate which tags
841 to put into the dict.
844 sys.stderr.write ('parsing ... ' )
847 gulp = re.sub ('[\n\r]+', '\n', f.read ())
848 ls = string.split (gulp, '\n^')
851 for k in tag_dict.keys ():
852 etf_file_dict[k] = {}
859 m = re.match ('^([a-zA-Z0-9&]+)\(([^)]+)\)', l)
860 if m and tag_dict.has_key (m.group (1)):
863 indices = tuple (map (string.atoi, string.split (m.group (2), ',')))
864 content = l[m.end (2)+1:]
867 tdict = etf_file_dict[tag]
868 if not tdict.has_key (indices):
874 if tag == 'verse' or tag == 'block':
875 m2 = re.match ('(.*)\^end', content)
877 parsed = [m2.group (1)]
880 (v, content) = read_finale_value (content)
884 tdict [indices].extend (parsed)
886 last_indices = indices
891 # let's not do this: this really confuses when eE happens to be before a ^text.
892 # if last_tag and last_indices:
893 # etf_file_dict[last_tag][last_indices].append (l)
895 sys.stderr.write ('\n')
903 def __init__ (self, name):
904 self.measures = [None]
907 self.tuplets = [None]
910 self.articulations = [None]
911 self.syllables = [None]
913 self.articulation_defs = [None]
918 def get_global_measure (self, no):
919 fill_list_to (self.measures, no)
920 if self.measures[no] == None:
921 self.measures [no] = Global_measure (no)
923 return self.measures[no]
926 def get_staff(self,staffno):
927 fill_list_to (self.staffs, staffno)
928 if self.staffs[staffno] == None:
929 self.staffs[staffno] = Staff (staffno)
931 return self.staffs[staffno]
934 def try_IS (self, indices, contents):
937 def try_BC (self, indices, contents):
939 where = contents[0] / 1024.0
940 def try_TP(self, indices, contents):
943 if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
944 self.tuplets.append (Tuplet (num))
946 self.tuplets[-1].append_finale (contents)
948 def try_IM (self, indices, contents):
951 self.articulations.append (Articulation (a,b,fin))
952 def try_verse (self, indices, contents):
956 body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
957 body = re.sub ("\^[a-z]+", "", body)
958 self.verses.append (Verse (a, body))
959 def try_ve (self,indices, contents):
961 self.syllables.append (Syllable (a,b,contents))
963 def try_eE (self,indices, contents):
965 (prev, next, dur, pos, entryflag, extended, follow) = contents[:7]
967 fill_list_to (self.chords, no)
968 self.chords[no] =Chord (no, contents)
970 def try_Sx(self,indices, contents):
972 fill_list_to (self.slurs, slurno)
973 self.slurs[slurno] = Slur(slurno, contents)
975 def try_IX (self, indices, contents):
982 ix = self.articulation_defs[n]
984 ix = Articulation_def (n,a,b)
985 self.articulation_defs.append (Articulation_def (n, a, b))
987 def try_GF(self, indices, contents):
988 (staffno,measno) = indices
990 st = self.get_staff (staffno)
991 meas = st.get_measure (measno)
992 meas.finale = contents
994 def try_FR(self, indices, contents):
995 frameno = indices [0]
997 startnote = contents[0]
998 endnote = contents[1]
1000 fill_list_to (self.frames, frameno)
1002 self.frames[frameno] = Frame ((frameno, startnote, endnote))
1004 def try_MS (self, indices, contents):
1006 keynum = contents[1]
1007 meas =self. get_global_measure (measno)
1009 meas.set_key_sig (keynum)
1012 beatlen = contents[3]
1013 meas.set_timesig ((beats, beatlen))
1015 meas_flag1 = contents[4]
1016 meas_flag2 = contents[5]
1018 meas.set_flags (meas_flag1, meas_flag2);
1028 'verse' : try_verse,
1036 def parse (self, etf_dict):
1037 sys.stderr.write ('reconstructing ...')
1040 for (tag,routine) in Etf_file.routine_dict.items ():
1041 ks = etf_dict[tag].keys ()
1044 routine (self, k, etf_dict[tag][k])
1046 sys.stderr.write ('processing ...')
1049 self.unthread_entries ()
1051 for st in self.staffs[1:]:
1055 for m in st.measures[1:]:
1061 m.global_measure = self.measures[mno]
1063 sys.stderr.write ("Non-existent global measure %d" % mno)
1066 frame_obj_list = [None]
1067 for frno in m.frames:
1069 fr = self.frames[frno]
1070 frame_obj_list.append (fr)
1072 sys.stderr.write ("\nNon-existent frame %d" % frno)
1074 m.frames = frame_obj_list
1075 for fr in frame_obj_list[1:]:
1081 fr.chords = self.get_thread (fr.start, fr.end)
1086 for c in self.chords[1:]:
1090 for f in self.frames[1:]:
1094 for t in self.tuplets[1:]:
1095 t.calculate (self.chords)
1097 for s in self.slurs[1:]:
1099 s.calculate (self.chords)
1101 for s in self.articulations[1:]:
1102 s.calculate (self.chords, self.articulation_defs)
1104 def get_thread (self, startno, endno):
1110 c = self.chords[startno]
1112 sys.stderr.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno, endno))
1116 while c and c.number <> endno:
1128 for s in self.staffs[1:]:
1130 str = str + '\n\n' + s.dump ()
1131 staffs.append ('\\' + s.staffid ())
1134 # should use \addlyrics ?
1136 for v in self.verses[1:]:
1137 str = str + v.dump()
1139 if len (self.verses) > 1:
1140 sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
1143 str += '\\version "2.3.25"\n'
1144 str = str + '<<\n %s\n>> } ' % string.join (staffs)
1150 return 'ETF FILE %s %s' % (self.measures, self.entries)
1152 def unthread_entries (self):
1153 for e in self.chords[1:]:
1157 e.prev = self.chords[e.finale[0]]
1158 e.next = self.chords[e.finale[1]]
1161 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1165 sys.stdout.write ('''
1173 ''' % ( '2001--2006',
1174 _('Distributed under terms of the GNU General Public License.'),
1175 _('It comes with NO WARRANTY.')))
1179 def get_option_parser ():
1180 p = ly.get_option_parser (usage=_ ("%s [OPTION]... ETF-FILE") % 'etf2ly',
1181 description=_ ("""Enigma Transport Format is a format used by Coda Music Technology's
1182 Finale product. etf2ly converts a subset of ETF to a ready-to-use LilyPond file."""),
1183 add_help_option=False)
1184 p.add_option("-h", "--help",
1186 help=_ ("show this help and exit"))
1187 p.version = "etf2ly (LilyPond) @TOPLEVEL_VERSION@"
1188 p.add_option("--version",
1190 help=_ ("show version number and exit"))
1191 p.add_option ('-o', '--output', help=_ ("write output to FILE"),
1194 p.add_option ('-w', '--warranty', help=_ ("show warranty and copyright"),
1195 action='store_true',
1198 p.add_option_group (ly.display_encode (_ ('Bugs')),
1199 description=(_ ('Report bugs via')
1200 + ''' http://post.gmane.org/post.php'''
1201 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
1205 opt_parser = get_option_parser()
1206 (options,args) = opt_parser.parse_args ()
1207 if options.warranty:
1211 return (options,args)
1213 (options, files) = do_options()
1216 out_filename = options.output
1223 sys.stderr.write ('Processing `%s\'\n' % f)
1225 dict = parse_etf_file (f, Etf_file.routine_dict)
1227 if not out_filename:
1228 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1230 if out_filename == f:
1231 out_filename = os.path.basename (f + '.ly')
1233 sys.stderr.write ('Writing `%s\'' % out_filename)
1236 fo = open (out_filename, 'w')
1237 fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)