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)
35 program_name = sys.argv[0]
37 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
38 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
40 version = '@TOPLEVEL_VERSION@'
41 if version == '@' + 'TOPLEVEL_VERSION' + '@':
42 version = '(unknown version)' # uGUHGUHGHGUGH
48 ################################################################
53 finale_clefs= ['treble', 'alto', 'tenor', 'bass', 'percussion', 'treble_8', 'bass_8', 'baritone']
57 return finale_clefs[fin]
59 sys.stderr.write ( '\nHuh? Found clef number %d\n' % fin)
66 return open (f).read ()
68 # notename 0 == central C
69 distances = [0, 2, 4, 5, 7, 9, 11, 12]
70 def semitones (name, acc):
71 return (name / 7 ) * 12 + distances[name % 7] + acc
73 # represent pitches as (notename, alteration), relative to C-major scale
74 def transpose(orig, delta):
78 old_pitch =semitones (oname, oacc)
79 delta_pitch = semitones (dname, dacc)
80 nname = (oname + dname)
82 new_pitch = semitones (nname, nacc)
84 nacc = nacc - (new_pitch - old_pitch - delta_pitch)
90 def interpret_finale_key_sig (finale_id):
92 find the transposition of C-major scale that belongs here.
94 we are not going to insert the correct major/minor, we only want to
95 have the correct number of accidentals
101 bank_number = finale_id >> 8
102 accidental_bits = finale_id & 0xff
104 if 0 <= accidental_bits < 7:
105 while accidental_bits > 0:
106 p = transpose (p, (4,0)) # a fifth up
107 accidental_bits = accidental_bits - 1
108 elif 248 < accidental_bits <= 255:
109 while accidental_bits < 256:
110 p = transpose (p, (3,0))
111 accidental_bits = accidental_bits + 1
115 p = transpose (p, (5, 0))
118 return KeySignature (p, bank_number)
121 def find_scale (keysig):
122 cscale = map (lambda x: (x,0), range (0,7))
123 # print "cscale: ", cscale
124 ascale = map (lambda x: (x,0), range (-2,5))
125 # print "ascale: ", ascale
126 transposition = keysig.pitch
127 if keysig.sig_type == 1:
128 transposition = transpose(transposition, (2, -1))
129 transposition = (transposition[0] % 7, transposition[1])
130 trscale = map(lambda x, k=transposition: transpose(x, k), ascale)
132 trscale = map(lambda x, k=transposition: transpose(x, k), cscale)
133 # print "trscale: ", trscale
136 def EDU_to_duration (edu):
151 def rational_to_lily_skip (rat):
155 while d and d % 2 == 0:
156 basedur = basedur << 1
159 str = 's%d' % basedur
161 str = str + '*%d' % n
163 str = str + '/%d' % d
178 def rat_simplify (r):
189 def rat_multiply (a,b):
193 return rat_simplify ((x*p, y*q))
199 return rat_simplify ((x*q + p*y, y*q))
207 def rat_subtract (a,b ):
208 return rat_add (a, rat_neg (b))
210 def lily_notename (tuple2):
212 nn = chr ((n+ 2)%7 + ord ('a'))
214 return nn + {-2:'eses', -1:'es', 0:'', 1:'is', 2:'isis'}[a]
218 def __init__ (self, number):
219 self.start_note = number
222 def append_finale (self, fin):
223 self.finale.append (fin)
226 n = self.finale[0][2]*self.finale[0][3]
227 d = self.finale[0][0]*self.finale[0][1]
228 return rat_simplify( (n, d))
230 def dump_start (self):
231 return '\\times %d/%d { ' % self.factor ()
236 def calculate (self, chords):
237 edu_left = self.finale[0][0] * self.finale[0][1]
239 startch = chords[self.start_note]
241 while c and edu_left:
244 c.chord_prefix = self.dump_start () + c.chord_prefix
247 edu_left = edu_left - c.EDU_duration ()
249 c.chord_suffix = c.chord_suffix+ self.dump_end ()
253 sys.stderr.write ("\nHuh? Tuplet starting at entry %d was too short." % self.start_note)
256 def __init__ (self, number, params):
260 def append_entry (self, finale_e):
261 self.finale.append (finale_e)
263 def calculate (self, chords):
264 startnote = self.finale[5]
265 endnote = self.finale[3*6 + 2]
267 cs = chords[startnote]
273 cs.note_suffix = '-(' + cs.note_suffix
274 ce.note_suffix = ce.note_suffix + '-)'
277 sys.stderr.write ("""\nHuh? Slur no %d between (%d,%d), with %d notes""" % (self.number, startnote, endnote, len (chords)))
280 class Global_measure:
281 def __init__ (self, number):
284 self.key_signature = None
292 return `self.finale `
294 def set_timesig (self, finale):
295 (beats, fdur) = finale
296 (log, dots) = EDU_to_duration (fdur)
304 sys.stderr.write ("\nHuh? Beat duration has dots? (EDU Duration = %d)" % fdur)
305 self.timesig = (beats, log)
310 def set_key_sig (self, finale):
311 k = interpret_finale_key_sig (finale)
312 self.key_signature = k
313 self.scale = find_scale (k)
315 def set_flags (self,flag1, flag2):
317 # flag1 isn't all that interesting.
322 self.repeats.append ('start')
324 self.repeats.append ('stop')
328 self.repeats.append ('bracket')
341 class Articulation_def:
342 def __init__ (self, n, a, b):
343 self.finale_glyph = a & 0xff
348 return articulation_dict[self.finale_glyph]
350 sys.stderr.write ("\nUnknown articulation no. %d" % self.finale_glyph)
351 sys.stderr.write ("\nPlease add an entry to articulation_dict in the Python source")
355 def __init__ (self, a,b, finale):
356 self.definition = finale[0]
359 def calculate (self, chords, defs):
360 c = chords[self.notenumber]
362 adef = defs[self.definition]
366 sys.stderr.write ("\nThis happened on note %d" % self.notenumber)
368 c.note_suffix = '-' + lystr
371 def __init__ (self, a,b , finale):
373 self.syllable = finale[1]
374 self.verse = finale[0]
375 def calculate (self, chords, lyrics):
376 self.chord = chords[self.chordnum]
379 def __init__ (self, number, body):
382 self.split_syllables ()
383 def split_syllables (self):
384 ss = re.split ('(-| +)', self.body)
390 septor = re.sub (" +", "", s)
391 septor = re.sub ("-", " -- ", septor)
392 syls[-1] = syls[-1] + septor
398 self.syllables = syls
403 for s in self.syllables[1:]:
404 line = line + ' ' + s
406 str = str + ' ' * 4 + line + '\n'
409 str = """\nverse%s = \\lyricmode {\n %s }\n""" % (encodeint (self.number - 1) ,str)
413 def __init__(self, pitch, sig_type = 0):
415 self.sig_type = sig_type
417 def signature_type (self):
418 if self.sig_type == 1:
421 # really only for 0, but we only know about 0 and 1
424 def equal (self, other):
425 if other and other.pitch == self.pitch and other.sig_type == self.sig_type:
432 def __init__(self, no):
434 self.frames = [0] * 4
438 self.global_measure = None
445 def calculate (self):
448 if len (self.finale) < 2:
452 self.frames = [fs[0]]
461 def __init__ (self, finale):
464 (number, start, end ) = finale
470 def set_measure (self, m):
473 def calculate (self):
478 for c in self.chords:
479 if c.grace and (lastch == None or (not lastch.grace)):
480 c.chord_prefix = r'\grace {' + c.chord_prefix
482 elif not c.grace and lastch and lastch.grace:
483 lastch.chord_suffix = lastch.chord_suffix + ' } '
488 if lastch and in_grace:
489 lastch.chord_suffix += '}'
493 str = '%% FR(%d)\n' % self.number
494 left = self.measure.global_measure.length ()
498 for c in self.chords:
499 add = c.ly_string () + ' '
500 if len (ln) + len(add) > 72:
501 str = str + ln + '\n'
504 left = rat_subtract (left, c.length ())
509 sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
512 str = str + rational_to_lily_skip (left)
518 return chr ( i + ord ('A'))
521 def __init__ (self, number):
525 def get_measure (self, no):
526 fill_list_to (self.measures, no)
528 if self.measures[no] == None:
530 self.measures [no] =m
533 return self.measures[no]
535 return 'staff' + encodeint (self.number - 1)
536 def layerid (self, l):
537 return self.staffid() + 'layer%s' % chr (l -1 + ord ('A'))
539 def dump_time_key_sigs (self):
545 for m in self.measures[1:]:
546 if not m or not m.valid:
553 if g.key_signature and not g.key_signature.equal(last_key):
554 pitch= g.key_signature.pitch
555 e = e + "\\key %s %s " % (lily_notename (pitch),
556 g.key_signature.signature_type())
558 last_key = g.key_signature
559 if last_time <> g.timesig :
560 e = e + "\\time %d/%d " % g.timesig
561 last_time = g.timesig
563 if 'start' in g.repeats:
564 e = e + ' \\bar "|:" '
567 # we don't attempt voltas since they fail easily.
568 if 0 : # and g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket:
570 if g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket == 'end':
574 if g.bracket == 'start':
577 str = ' '.join (['(volta %s)' % x for x in strs])
579 e = e + ' \\set Score.repeatCommands = #\'(%s) ' % str
584 if last_clef <> m.clef :
585 e = e + '\\clef "%s"' % lily_clef (m.clef)
589 k = k +' ' + rational_to_lily_skip (gap) + '\n'
594 gap = rat_add (gap, g.length ())
595 if 'stop' in g.repeats:
596 k = k + ' \\bar ":|" '
598 k = '%sglobal = { %s }\n\n ' % (self.staffid (), k)
606 for x in range (1,5): # 4 layers.
611 for m in self.measures[1:]:
612 if not m or not m.valid:
613 sys.stderr.write ("Skipping non-existant or invalid measure\n")
620 sys.stderr.write ("Skipping nonexistent frame %d\n" % x)
621 laystr = laystr + "%% non existent frame %d (skipped)\n" % x
625 laystr = laystr +'} %s {\n ' % rational_to_lily_skip (gap)
627 laystr = laystr + fr.dump ()
629 if m.global_measure :
630 gap = rat_add (gap, m.global_measure.length ())
633 "No global measure for staff %d measure %d\n"
634 % (self.number, m.number))
637 laystr = '%s = { { %s } }\n\n' % (l, laystr)
641 str = str + self.dump_time_key_sigs ()
642 stafdef = '\\%sglobal' % self.staffid ()
644 stafdef = stafdef + ' \\' + i
647 str = str + '%s = \\context Staff = %s <<\n %s\n >>\n' % \
648 (self.staffid (), self.staffid (), stafdef)
657 return [(l[0], l[1])] + ziplist (l[2:])
661 def __init__ (self, number, contents):
664 self.finale = contents[:7]
666 self.notelist = ziplist (contents[7:])
672 self.note_suffix = ''
673 self.chord_suffix = ''
674 self.chord_prefix = ''
681 return self.frame.measure
687 l = (1, self.duration[0])
689 d = 1 << self.duration[1]
691 dotfact = rat_subtract ((2,1), (1,d))
692 mylen = rat_multiply (dotfact, l)
695 mylen = rat_multiply (mylen, self.tuplet.factor())
699 def EDU_duration (self):
700 return self.finale[2]
701 def set_duration (self):
702 self.duration = EDU_to_duration(self.EDU_duration ())
704 def calculate (self):
705 self.find_realpitch ()
708 flag = self.finale[4]
709 if Chord.GRACE_MASK & flag:
713 def find_realpitch (self):
715 meas = self.measure ()
717 if not meas or not meas.global_measure :
718 sys.stderr.write ('note %d not in measure\n' % self.number)
719 elif not meas.global_measure.scale:
720 sys.stderr.write ('note %d: no scale in this measure.' % self.number)
723 for p in self.notelist:
733 scale = meas.global_measure.scale
734 (sn, sa) =scale[rest % 7]
735 sn = sn + (rest - (rest%7)) + 7
737 self.pitches.append ((sn, acc))
738 tiestart = tiestart or (flag & Chord.TIE_START_MASK)
740 self.chord_suffix = self.chord_suffix + ' ~ '
742 REST_MASK = 0x40000000L
743 TIE_START_MASK = 0x40000000L
744 GRACE_MASK = 0x00800000L
746 def ly_string (self):
752 if not (self.finale[4] & Chord.REST_MASK):
755 for p in self.pitches:
760 nn = lily_notename ((n,a))
777 if len (self.pitches) > 1:
780 s = s + '%d%s' % (self.duration[0], '.'* self.duration[1])
781 s = self.note_prefix + s + self.note_suffix
783 s = self.chord_prefix + s + self.chord_suffix
788 def fill_list_to (list, no):
790 Add None to LIST until it contains entry number NO.
792 while len (list) <= no:
793 list.extend ([None] * (no - len(list) + 1))
796 def read_finale_value (str):
798 Pry off one value from STR. The value may be $hex, decimal, or "string".
799 Return: (value, rest-of-STR)
801 while str and str[0] in ' \t\n':
811 while str and str[0] in '0123456789ABCDEF':
816 return (long (hex, 16), str)
820 while str and str[0] <> '"':
825 elif str[0] in '-0123456789':
827 while str and str[0] in '-0123456789':
831 return (int (dec), str)
833 sys.stderr.write ("cannot convert `%s'\n" % str)
839 def parse_etf_file (fn, tag_dict):
841 """ Read FN, putting ETF info into
842 a giant dictionary. The keys of TAG_DICT indicate which tags
843 to put into the dict.
846 sys.stderr.write ('parsing ... ' )
849 gulp = re.sub ('[\n\r]+', '\n', f.read ())
850 ls = gulp.split ('\n^')
854 etf_file_dict[k] = {}
861 m = re.match ('^([a-zA-Z0-9&]+)\(([^)]+)\)', l)
862 if m and tag_dict.has_key (m.group (1)):
865 indices = tuple ([int (s) for s in m.group (2).split (',')])
866 content = l[m.end (2)+1:]
869 tdict = etf_file_dict[tag]
870 if not tdict.has_key (indices):
876 if tag == 'verse' or tag == 'block':
877 m2 = re.match ('(.*)\^end', content)
879 parsed = [m2.group (1)]
882 (v, content) = read_finale_value (content)
886 tdict [indices].extend (parsed)
888 last_indices = indices
893 # let's not do this: this really confuses when eE happens to be before a ^text.
894 # if last_tag and last_indices:
895 # etf_file_dict[last_tag][last_indices].append (l)
897 sys.stderr.write ('\n')
905 def __init__ (self, name):
906 self.measures = [None]
909 self.tuplets = [None]
912 self.articulations = [None]
913 self.syllables = [None]
915 self.articulation_defs = [None]
920 def get_global_measure (self, no):
921 fill_list_to (self.measures, no)
922 if self.measures[no] == None:
923 self.measures [no] = Global_measure (no)
925 return self.measures[no]
928 def get_staff(self,staffno):
929 fill_list_to (self.staffs, staffno)
930 if self.staffs[staffno] == None:
931 self.staffs[staffno] = Staff (staffno)
933 return self.staffs[staffno]
936 def try_IS (self, indices, contents):
939 def try_BC (self, indices, contents):
941 where = contents[0] / 1024.0
942 def try_TP(self, indices, contents):
945 if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
946 self.tuplets.append (Tuplet (num))
948 self.tuplets[-1].append_finale (contents)
950 def try_IM (self, indices, contents):
953 self.articulations.append (Articulation (a,b,fin))
954 def try_verse (self, indices, contents):
958 body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
959 body = re.sub ("\^[a-z]+", "", body)
960 self.verses.append (Verse (a, body))
961 def try_ve (self,indices, contents):
963 self.syllables.append (Syllable (a,b,contents))
965 def try_eE (self,indices, contents):
967 (prev, next, dur, pos, entryflag, extended, follow) = contents[:7]
969 fill_list_to (self.chords, no)
970 self.chords[no] =Chord (no, contents)
972 def try_Sx(self,indices, contents):
974 fill_list_to (self.slurs, slurno)
975 self.slurs[slurno] = Slur(slurno, contents)
977 def try_IX (self, indices, contents):
984 ix = self.articulation_defs[n]
986 ix = Articulation_def (n,a,b)
987 self.articulation_defs.append (Articulation_def (n, a, b))
989 def try_GF(self, indices, contents):
990 (staffno,measno) = indices
992 st = self.get_staff (staffno)
993 meas = st.get_measure (measno)
994 meas.finale = contents
996 def try_FR(self, indices, contents):
997 frameno = indices [0]
999 startnote = contents[0]
1000 endnote = contents[1]
1002 fill_list_to (self.frames, frameno)
1004 self.frames[frameno] = Frame ((frameno, startnote, endnote))
1006 def try_MS (self, indices, contents):
1008 keynum = contents[1]
1009 meas =self. get_global_measure (measno)
1011 meas.set_key_sig (keynum)
1014 beatlen = contents[3]
1015 meas.set_timesig ((beats, beatlen))
1017 meas_flag1 = contents[4]
1018 meas_flag2 = contents[5]
1020 meas.set_flags (meas_flag1, meas_flag2);
1030 'verse' : try_verse,
1038 def parse (self, etf_dict):
1039 sys.stderr.write ('reconstructing ...')
1042 for (tag,routine) in Etf_file.routine_dict.items ():
1043 ks = etf_dict[tag].keys ()
1046 routine (self, k, etf_dict[tag][k])
1048 sys.stderr.write ('processing ...')
1051 self.unthread_entries ()
1053 for st in self.staffs[1:]:
1057 for m in st.measures[1:]:
1063 m.global_measure = self.measures[mno]
1065 sys.stderr.write ("Non-existent global measure %d" % mno)
1068 frame_obj_list = [None]
1069 for frno in m.frames:
1071 fr = self.frames[frno]
1072 frame_obj_list.append (fr)
1074 sys.stderr.write ("\nNon-existent frame %d" % frno)
1076 m.frames = frame_obj_list
1077 for fr in frame_obj_list[1:]:
1083 fr.chords = self.get_thread (fr.start, fr.end)
1088 for c in self.chords[1:]:
1092 for f in self.frames[1:]:
1096 for t in self.tuplets[1:]:
1097 t.calculate (self.chords)
1099 for s in self.slurs[1:]:
1101 s.calculate (self.chords)
1103 for s in self.articulations[1:]:
1104 s.calculate (self.chords, self.articulation_defs)
1106 def get_thread (self, startno, endno):
1112 c = self.chords[startno]
1114 sys.stderr.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno, endno))
1118 while c and c.number <> endno:
1130 for s in self.staffs[1:]:
1132 str = str + '\n\n' + s.dump ()
1133 staffs.append ('\\' + s.staffid ())
1136 # should use \addlyrics ?
1138 for v in self.verses[1:]:
1139 str = str + v.dump()
1141 if len (self.verses) > 1:
1142 sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
1145 str += '\\version "2.3.25"\n'
1146 str = str + '<<\n %s\n>> } ' % ' '.join (staffs)
1152 return 'ETF FILE %s %s' % (self.measures, self.entries)
1154 def unthread_entries (self):
1155 for e in self.chords[1:]:
1159 e.prev = self.chords[e.finale[0]]
1160 e.next = self.chords[e.finale[1]]
1163 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1167 sys.stdout.write ('''
1174 ''' % ( _ ('Copyright (c) %s by') % '2001--2009',
1175 '\n '.join (authors),
1176 _ ('Distributed under terms of the GNU General Public License.'),
1177 _ ('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.
1184 add_help_option=False)
1185 p.add_option("-h", "--help",
1187 help=_ ("show this help and exit"))
1188 p.version = "etf2ly (LilyPond) @TOPLEVEL_VERSION@"
1189 p.add_option("--version",
1191 help=_ ("show version number and exit"))
1192 p.add_option ('-o', '--output', help=_ ("write output to FILE"),
1195 p.add_option ('-w', '--warranty', help=_ ("show warranty and copyright"),
1196 action='store_true',
1199 p.add_option_group ('',
1201 _ ('Report bugs via %s')
1202 % 'http://post.gmane.org/post.php'
1203 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
1207 opt_parser = get_option_parser()
1208 (options,args) = opt_parser.parse_args ()
1209 if options.warranty:
1213 return (options,args)
1215 (options, files) = do_options()
1218 out_filename = options.output
1225 sys.stderr.write ('Processing `%s\'\n' % f)
1227 dict = parse_etf_file (f, Etf_file.routine_dict)
1229 if not out_filename:
1230 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1232 if out_filename == f:
1233 out_filename = os.path.basename (f + '.ly')
1235 sys.stderr.write ('Writing `%s\'' % out_filename)
1238 fo = open (out_filename, 'w')
1239 fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)