3 # This file is part of LilyPond, the GNU music typesetter.
5 # LilyPond is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # LilyPond is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with LilyPond. If not, see <http://www.gnu.org/licenses/>.
18 # info mostly taken from looking at files. See also
19 # http://lilypond.org/wiki/?EnigmaTransportFormat
34 # * slur/stem directions
35 # * voices (2nd half of frame?)
36 # * more intelligent lyrics
37 # * beams (better use autobeam?)
38 # * more robust: try entertainer.etf (freenote)
40 # * empty measures (eg. twopt03.etf from freenote)
50 program_name = sys.argv[0]
52 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
53 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
55 version = '@TOPLEVEL_VERSION@'
56 if version == '@' + 'TOPLEVEL_VERSION' + '@':
57 version = '(unknown version)' # uGUHGUHGHGUGH
63 ################################################################
68 finale_clefs= ['treble', 'alto', 'tenor', 'bass', 'percussion', 'treble_8', 'bass_8', 'baritone']
72 return finale_clefs[fin]
74 sys.stderr.write ( '\nHuh? Found clef number %d\n' % fin)
81 return open (f).read ()
83 # notename 0 == central C
84 distances = [0, 2, 4, 5, 7, 9, 11, 12]
85 def semitones (name, acc):
86 return (name / 7 ) * 12 + distances[name % 7] + acc
88 # represent pitches as (notename, alteration), relative to C-major scale
89 def transpose(orig, delta):
93 old_pitch =semitones (oname, oacc)
94 delta_pitch = semitones (dname, dacc)
95 nname = (oname + dname)
97 new_pitch = semitones (nname, nacc)
99 nacc = nacc - (new_pitch - old_pitch - delta_pitch)
105 def interpret_finale_key_sig (finale_id):
107 find the transposition of C-major scale that belongs here.
109 we are not going to insert the correct major/minor, we only want to
110 have the correct number of accidentals
116 bank_number = finale_id >> 8
117 accidental_bits = finale_id & 0xff
119 if 0 <= accidental_bits < 7:
120 while accidental_bits > 0:
121 p = transpose (p, (4,0)) # a fifth up
122 accidental_bits = accidental_bits - 1
123 elif 248 < accidental_bits <= 255:
124 while accidental_bits < 256:
125 p = transpose (p, (3,0))
126 accidental_bits = accidental_bits + 1
130 p = transpose (p, (5, 0))
133 return KeySignature (p, bank_number)
136 def find_scale (keysig):
137 cscale = map (lambda x: (x,0), range (0,7))
138 # print "cscale: ", cscale
139 ascale = map (lambda x: (x,0), range (-2,5))
140 # print "ascale: ", ascale
141 transposition = keysig.pitch
142 if keysig.sig_type == 1:
143 transposition = transpose(transposition, (2, -1))
144 transposition = (transposition[0] % 7, transposition[1])
145 trscale = map(lambda x, k=transposition: transpose(x, k), ascale)
147 trscale = map(lambda x, k=transposition: transpose(x, k), cscale)
148 # print "trscale: ", trscale
151 def EDU_to_duration (edu):
166 def rational_to_lily_skip (rat):
170 while d and d % 2 == 0:
171 basedur = basedur << 1
174 str = 's%d' % basedur
176 str = str + '*%d' % n
178 str = str + '/%d' % d
193 def rat_simplify (r):
204 def rat_multiply (a,b):
208 return rat_simplify ((x*p, y*q))
214 return rat_simplify ((x*q + p*y, y*q))
222 def rat_subtract (a,b ):
223 return rat_add (a, rat_neg (b))
225 def lily_notename (tuple2):
227 nn = chr ((n+ 2)%7 + ord ('a'))
229 return nn + {-2:'eses', -1:'es', 0:'', 1:'is', 2:'isis'}[a]
233 def __init__ (self, number):
234 self.start_note = number
237 def append_finale (self, fin):
238 self.finale.append (fin)
241 n = self.finale[0][2]*self.finale[0][3]
242 d = self.finale[0][0]*self.finale[0][1]
243 return rat_simplify( (n, d))
245 def dump_start (self):
246 return '\\times %d/%d { ' % self.factor ()
251 def calculate (self, chords):
252 edu_left = self.finale[0][0] * self.finale[0][1]
254 startch = chords[self.start_note]
256 while c and edu_left:
259 c.chord_prefix = self.dump_start () + c.chord_prefix
262 edu_left = edu_left - c.EDU_duration ()
264 c.chord_suffix = c.chord_suffix+ self.dump_end ()
268 sys.stderr.write ("\nHuh? Tuplet starting at entry %d was too short." % self.start_note)
271 def __init__ (self, number, params):
275 def append_entry (self, finale_e):
276 self.finale.append (finale_e)
278 def calculate (self, chords):
279 startnote = self.finale[5]
280 endnote = self.finale[3*6 + 2]
282 cs = chords[startnote]
288 cs.note_suffix = '-(' + cs.note_suffix
289 ce.note_suffix = ce.note_suffix + '-)'
292 sys.stderr.write ("""\nHuh? Slur no %d between (%d,%d), with %d notes""" % (self.number, startnote, endnote, len (chords)))
295 class Global_measure:
296 def __init__ (self, number):
299 self.key_signature = None
307 return `self.finale `
309 def set_timesig (self, finale):
310 (beats, fdur) = finale
311 (log, dots) = EDU_to_duration (fdur)
319 sys.stderr.write ("\nHuh? Beat duration has dots? (EDU Duration = %d)" % fdur)
320 self.timesig = (beats, log)
325 def set_key_sig (self, finale):
326 k = interpret_finale_key_sig (finale)
327 self.key_signature = k
328 self.scale = find_scale (k)
330 def set_flags (self,flag1, flag2):
332 # flag1 isn't all that interesting.
337 self.repeats.append ('start')
339 self.repeats.append ('stop')
343 self.repeats.append ('bracket')
356 class Articulation_def:
357 def __init__ (self, n, a, b):
358 self.finale_glyph = a & 0xff
363 return articulation_dict[self.finale_glyph]
365 sys.stderr.write ("\nUnknown articulation no. %d" % self.finale_glyph)
366 sys.stderr.write ("\nPlease add an entry to articulation_dict in the Python source")
370 def __init__ (self, a,b, finale):
371 self.definition = finale[0]
374 def calculate (self, chords, defs):
375 c = chords[self.notenumber]
377 adef = defs[self.definition]
381 sys.stderr.write ("\nThis happened on note %d" % self.notenumber)
383 c.note_suffix = '-' + lystr
386 def __init__ (self, a,b , finale):
388 self.syllable = finale[1]
389 self.verse = finale[0]
390 def calculate (self, chords, lyrics):
391 self.chord = chords[self.chordnum]
394 def __init__ (self, number, body):
397 self.split_syllables ()
398 def split_syllables (self):
399 ss = re.split ('(-| +)', self.body)
405 septor = re.sub (" +", "", s)
406 septor = re.sub ("-", " -- ", septor)
407 syls[-1] = syls[-1] + septor
413 self.syllables = syls
418 for s in self.syllables[1:]:
419 line = line + ' ' + s
421 str = str + ' ' * 4 + line + '\n'
424 str = """\nverse%s = \\lyricmode {\n %s }\n""" % (encodeint (self.number - 1) ,str)
428 def __init__(self, pitch, sig_type = 0):
430 self.sig_type = sig_type
432 def signature_type (self):
433 if self.sig_type == 1:
436 # really only for 0, but we only know about 0 and 1
439 def equal (self, other):
440 if other and other.pitch == self.pitch and other.sig_type == self.sig_type:
447 def __init__(self, no):
449 self.frames = [0] * 4
453 self.global_measure = None
460 def calculate (self):
463 if len (self.finale) < 2:
467 self.frames = [fs[0]]
476 def __init__ (self, finale):
479 (number, start, end ) = finale
485 def set_measure (self, m):
488 def calculate (self):
493 for c in self.chords:
494 if c.grace and (lastch == None or (not lastch.grace)):
495 c.chord_prefix = r'\grace {' + c.chord_prefix
497 elif not c.grace and lastch and lastch.grace:
498 lastch.chord_suffix = lastch.chord_suffix + ' } '
503 if lastch and in_grace:
504 lastch.chord_suffix += '}'
508 str = '%% FR(%d)\n' % self.number
509 left = self.measure.global_measure.length ()
513 for c in self.chords:
514 add = c.ly_string () + ' '
515 if len (ln) + len(add) > 72:
516 str = str + ln + '\n'
519 left = rat_subtract (left, c.length ())
524 sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
527 str = str + rational_to_lily_skip (left)
533 return chr ( i + ord ('A'))
536 def __init__ (self, number):
540 def get_measure (self, no):
541 fill_list_to (self.measures, no)
543 if self.measures[no] == None:
545 self.measures [no] =m
548 return self.measures[no]
550 return 'staff' + encodeint (self.number - 1)
551 def layerid (self, l):
552 return self.staffid() + 'layer%s' % chr (l -1 + ord ('A'))
554 def dump_time_key_sigs (self):
560 for m in self.measures[1:]:
561 if not m or not m.valid:
568 if g.key_signature and not g.key_signature.equal(last_key):
569 pitch= g.key_signature.pitch
570 e = e + "\\key %s %s " % (lily_notename (pitch),
571 g.key_signature.signature_type())
573 last_key = g.key_signature
574 if last_time <> g.timesig :
575 e = e + "\\time %d/%d " % g.timesig
576 last_time = g.timesig
578 if 'start' in g.repeats:
579 e = e + ' \\bar ".|:" '
582 # we don't attempt voltas since they fail easily.
583 if 0 : # and g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket:
585 if g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket == 'end':
589 if g.bracket == 'start':
592 str = ' '.join (['(volta %s)' % x for x in strs])
594 e = e + ' \\set Score.repeatCommands = #\'(%s) ' % str
599 if last_clef <> m.clef :
600 e = e + '\\clef "%s"' % lily_clef (m.clef)
604 k = k +' ' + rational_to_lily_skip (gap) + '\n'
609 gap = rat_add (gap, g.length ())
610 if 'stop' in g.repeats:
611 k = k + ' \\bar ":|." '
613 k = '%sglobal = { %s }\n\n ' % (self.staffid (), k)
621 for x in range (1,5): # 4 layers.
626 for m in self.measures[1:]:
627 if not m or not m.valid:
628 sys.stderr.write ("Skipping non-existant or invalid measure\n")
635 sys.stderr.write ("Skipping nonexistent frame %d\n" % x)
636 laystr = laystr + "%% non existent frame %d (skipped)\n" % x
640 laystr = laystr +'} %s {\n ' % rational_to_lily_skip (gap)
642 laystr = laystr + fr.dump ()
644 if m.global_measure :
645 gap = rat_add (gap, m.global_measure.length ())
648 "No global measure for staff %d measure %d\n"
649 % (self.number, m.number))
652 laystr = '%s = { { %s } }\n\n' % (l, laystr)
656 str = str + self.dump_time_key_sigs ()
657 stafdef = '\\%sglobal' % self.staffid ()
659 stafdef = stafdef + ' \\' + i
662 str = str + '%s = \\context Staff = %s <<\n %s\n >>\n' % \
663 (self.staffid (), self.staffid (), stafdef)
672 return [(l[0], l[1])] + ziplist (l[2:])
676 def __init__ (self, number, contents):
679 self.finale = contents[:7]
681 self.notelist = ziplist (contents[7:])
687 self.note_suffix = ''
688 self.chord_suffix = ''
689 self.chord_prefix = ''
696 return self.frame.measure
702 l = (1, self.duration[0])
704 d = 1 << self.duration[1]
706 dotfact = rat_subtract ((2,1), (1,d))
707 mylen = rat_multiply (dotfact, l)
710 mylen = rat_multiply (mylen, self.tuplet.factor())
714 def EDU_duration (self):
715 return self.finale[2]
716 def set_duration (self):
717 self.duration = EDU_to_duration(self.EDU_duration ())
719 def calculate (self):
720 self.find_realpitch ()
723 flag = self.finale[4]
724 if Chord.GRACE_MASK & flag:
728 def find_realpitch (self):
730 meas = self.measure ()
732 if not meas or not meas.global_measure :
733 sys.stderr.write ('note %d not in measure\n' % self.number)
734 elif not meas.global_measure.scale:
735 sys.stderr.write ('note %d: no scale in this measure.' % self.number)
738 for p in self.notelist:
748 scale = meas.global_measure.scale
749 (sn, sa) =scale[rest % 7]
750 sn = sn + (rest - (rest%7)) + 7
752 self.pitches.append ((sn, acc))
753 tiestart = tiestart or (flag & Chord.TIE_START_MASK)
755 self.chord_suffix = self.chord_suffix + ' ~ '
757 REST_MASK = 0x40000000L
758 TIE_START_MASK = 0x40000000L
759 GRACE_MASK = 0x00800000L
761 def ly_string (self):
767 if not (self.finale[4] & Chord.REST_MASK):
770 for p in self.pitches:
775 nn = lily_notename ((n,a))
792 if len (self.pitches) > 1:
795 s = s + '%d%s' % (self.duration[0], '.'* self.duration[1])
796 s = self.note_prefix + s + self.note_suffix
798 s = self.chord_prefix + s + self.chord_suffix
803 def fill_list_to (list, no):
805 Add None to LIST until it contains entry number NO.
807 while len (list) <= no:
808 list.extend ([None] * (no - len(list) + 1))
811 def read_finale_value (str):
813 Pry off one value from STR. The value may be $hex, decimal, or "string".
814 Return: (value, rest-of-STR)
816 while str and str[0] in ' \t\n':
826 while str and str[0] in '0123456789ABCDEF':
831 return (long (hex, 16), str)
835 while str and str[0] <> '"':
840 elif str[0] in '-0123456789':
842 while str and str[0] in '-0123456789':
846 return (int (dec), str)
848 sys.stderr.write ("cannot convert `%s'\n" % str)
854 def parse_etf_file (fn, tag_dict):
856 """ Read FN, putting ETF info into
857 a giant dictionary. The keys of TAG_DICT indicate which tags
858 to put into the dict.
861 sys.stderr.write ('parsing ... ' )
864 gulp = re.sub ('[\n\r]+', '\n', f.read ())
865 ls = gulp.split ('\n^')
869 etf_file_dict[k] = {}
876 m = re.match ('^([a-zA-Z0-9&]+)\(([^)]+)\)', l)
877 if m and tag_dict.has_key (m.group (1)):
880 indices = tuple ([int (s) for s in m.group (2).split (',')])
881 content = l[m.end (2)+1:]
884 tdict = etf_file_dict[tag]
885 if not tdict.has_key (indices):
891 if tag == 'verse' or tag == 'block':
892 m2 = re.match ('(.*)\^end', content)
894 parsed = [m2.group (1)]
897 (v, content) = read_finale_value (content)
901 tdict [indices].extend (parsed)
903 last_indices = indices
908 # let's not do this: this really confuses when eE happens to be before a ^text.
909 # if last_tag and last_indices:
910 # etf_file_dict[last_tag][last_indices].append (l)
912 sys.stderr.write ('\n')
920 def __init__ (self, name):
921 self.measures = [None]
924 self.tuplets = [None]
927 self.articulations = [None]
928 self.syllables = [None]
930 self.articulation_defs = [None]
935 def get_global_measure (self, no):
936 fill_list_to (self.measures, no)
937 if self.measures[no] == None:
938 self.measures [no] = Global_measure (no)
940 return self.measures[no]
943 def get_staff(self,staffno):
944 fill_list_to (self.staffs, staffno)
945 if self.staffs[staffno] == None:
946 self.staffs[staffno] = Staff (staffno)
948 return self.staffs[staffno]
951 def try_IS (self, indices, contents):
954 def try_BC (self, indices, contents):
956 where = contents[0] / 1024.0
957 def try_TP(self, indices, contents):
960 if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
961 self.tuplets.append (Tuplet (num))
963 self.tuplets[-1].append_finale (contents)
965 def try_IM (self, indices, contents):
968 self.articulations.append (Articulation (a,b,fin))
969 def try_verse (self, indices, contents):
973 body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
974 body = re.sub ("\^[a-z]+", "", body)
975 self.verses.append (Verse (a, body))
976 def try_ve (self,indices, contents):
978 self.syllables.append (Syllable (a,b,contents))
980 def try_eE (self,indices, contents):
982 (prev, next, dur, pos, entryflag, extended, follow) = contents[:7]
984 fill_list_to (self.chords, no)
985 self.chords[no] =Chord (no, contents)
987 def try_Sx(self,indices, contents):
989 fill_list_to (self.slurs, slurno)
990 self.slurs[slurno] = Slur(slurno, contents)
992 def try_IX (self, indices, contents):
999 ix = self.articulation_defs[n]
1001 ix = Articulation_def (n,a,b)
1002 self.articulation_defs.append (Articulation_def (n, a, b))
1004 def try_GF(self, indices, contents):
1005 (staffno,measno) = indices
1007 st = self.get_staff (staffno)
1008 meas = st.get_measure (measno)
1009 meas.finale = contents
1011 def try_FR(self, indices, contents):
1012 frameno = indices [0]
1014 startnote = contents[0]
1015 endnote = contents[1]
1017 fill_list_to (self.frames, frameno)
1019 self.frames[frameno] = Frame ((frameno, startnote, endnote))
1021 def try_MS (self, indices, contents):
1023 keynum = contents[1]
1024 meas =self. get_global_measure (measno)
1026 meas.set_key_sig (keynum)
1029 beatlen = contents[3]
1030 meas.set_timesig ((beats, beatlen))
1032 meas_flag1 = contents[4]
1033 meas_flag2 = contents[5]
1035 meas.set_flags (meas_flag1, meas_flag2);
1045 'verse' : try_verse,
1053 def parse (self, etf_dict):
1054 sys.stderr.write ('reconstructing ...')
1057 for (tag,routine) in Etf_file.routine_dict.items ():
1058 ks = etf_dict[tag].keys ()
1061 routine (self, k, etf_dict[tag][k])
1063 sys.stderr.write ('processing ...')
1066 self.unthread_entries ()
1068 for st in self.staffs[1:]:
1072 for m in st.measures[1:]:
1078 m.global_measure = self.measures[mno]
1080 sys.stderr.write ("Non-existent global measure %d" % mno)
1083 frame_obj_list = [None]
1084 for frno in m.frames:
1086 fr = self.frames[frno]
1087 frame_obj_list.append (fr)
1089 sys.stderr.write ("\nNon-existent frame %d" % frno)
1091 m.frames = frame_obj_list
1092 for fr in frame_obj_list[1:]:
1098 fr.chords = self.get_thread (fr.start, fr.end)
1103 for c in self.chords[1:]:
1107 for f in self.frames[1:]:
1111 for t in self.tuplets[1:]:
1112 t.calculate (self.chords)
1114 for s in self.slurs[1:]:
1116 s.calculate (self.chords)
1118 for s in self.articulations[1:]:
1119 s.calculate (self.chords, self.articulation_defs)
1121 def get_thread (self, startno, endno):
1127 c = self.chords[startno]
1129 sys.stderr.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno, endno))
1133 while c and c.number <> endno:
1134 d = c # hack to avoid problem with build/scripts/grand-replace.py
1139 d = c # hack to avoid problem with build/scripts/grand-replace.py
1147 for s in self.staffs[1:]:
1149 str = str + '\n\n' + s.dump ()
1150 staffs.append ('\\' + s.staffid ())
1153 # should use \addlyrics ?
1155 for v in self.verses[1:]:
1156 str = str + v.dump()
1158 if len (self.verses) > 1:
1159 sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
1162 str += '\\version "2.3.25"\n'
1163 str = str + '<<\n %s\n>> } ' % ' '.join (staffs)
1169 return 'ETF FILE %s %s' % (self.measures, self.entries)
1171 def unthread_entries (self):
1172 for e in self.chords[1:]:
1176 e.prev = self.chords[e.finale[0]]
1177 e.next = self.chords[e.finale[1]]
1180 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1184 sys.stdout.write ('''
1191 ''' % ( _ ('Copyright (c) %s by') % '2001--2014',
1192 '\n '.join (authors),
1193 _ ('Distributed under terms of the GNU General Public License.'),
1194 _ ('It comes with NO WARRANTY.')))
1196 def get_option_parser ():
1197 p = ly.get_option_parser (usage=_ ("%s [OPTION]... ETF-FILE") % 'etf2ly',
1198 description=_ ("""Enigma Transport Format is a format used by Coda Music Technology's
1199 Finale product. etf2ly converts a subset of ETF to a ready-to-use LilyPond file.
1201 add_help_option=False)
1202 p.add_option("-h", "--help",
1204 help=_ ("show this help and exit"))
1205 p.version = "etf2ly (LilyPond) @TOPLEVEL_VERSION@"
1206 p.add_option("--version",
1208 help=_ ("show version number and exit"))
1209 p.add_option ('-o', '--output', help=_ ("write output to FILE"),
1212 p.add_option ('-w', '--warranty', help=_ ("show warranty and copyright"),
1213 action='store_true',
1216 p.add_option_group ('',
1218 _ ('Report bugs via %s')
1219 % 'http://post.gmane.org/post.php'
1220 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
1224 opt_parser = get_option_parser()
1225 (options,args) = opt_parser.parse_args ()
1226 if options.warranty:
1230 return (options,args)
1232 (options, files) = do_options()
1235 out_filename = options.output
1242 sys.stderr.write ('Processing `%s\'\n' % f)
1244 dict = parse_etf_file (f, Etf_file.routine_dict)
1246 if not out_filename:
1247 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1249 if out_filename == f:
1250 out_filename = os.path.basename (f + '.ly')
1252 sys.stderr.write ('Writing `%s\'' % out_filename)
1255 fo = open (out_filename, 'w')
1256 fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)