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
43 ################################################################
44 # Users of python modules should include this snippet.
50 for d in ['@lilypond_datadir@',
52 sys.path.insert (0, os.path.join (d, 'python'))
55 # dynamic relocation, for GUB binaries.
56 bindir = os.path.abspath (os.path.split (sys.argv[0])[0])
57 for p in ['share', 'lib']:
58 datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % p)
59 sys.path.insert (0, datadir)
62 ################################################################
67 finale_clefs= ['treble', 'alto', 'tenor', 'bass', 'percussion', 'treble_8', 'bass_8', 'baritone']
71 return finale_clefs[fin]
73 sys.stderr.write ( '\nHuh? Found clef number %d\n' % fin)
80 return open (f).read ()
82 # notename 0 == central C
83 distances = [0, 2, 4, 5, 7, 9, 11, 12]
84 def semitones (name, acc):
85 return (name / 7 ) * 12 + distances[name % 7] + acc
87 # represent pitches as (notename, alteration), relative to C-major scale
88 def transpose(orig, delta):
92 old_pitch =semitones (oname, oacc)
93 delta_pitch = semitones (dname, dacc)
94 nname = (oname + dname)
96 new_pitch = semitones (nname, nacc)
98 nacc = nacc - (new_pitch - old_pitch - delta_pitch)
104 def interpret_finale_key_sig (finale_id):
106 find the transposition of C-major scale that belongs here.
108 we are not going to insert the correct major/minor, we only want to
109 have the correct number of accidentals
115 bank_number = finale_id >> 8
116 accidental_bits = finale_id & 0xff
118 if 0 <= accidental_bits < 7:
119 while accidental_bits > 0:
120 p = transpose (p, (4,0)) # a fifth up
121 accidental_bits = accidental_bits - 1
122 elif 248 < accidental_bits <= 255:
123 while accidental_bits < 256:
124 p = transpose (p, (3,0))
125 accidental_bits = accidental_bits + 1
129 p = transpose (p, (5, 0))
132 return KeySignature (p, bank_number)
135 def find_scale (keysig):
136 cscale = map (lambda x: (x,0), range (0,7))
137 # print "cscale: ", cscale
138 ascale = map (lambda x: (x,0), range (-2,5))
139 # print "ascale: ", ascale
140 transposition = keysig.pitch
141 if keysig.sig_type == 1:
142 transposition = transpose(transposition, (2, -1))
143 transposition = (transposition[0] % 7, transposition[1])
144 trscale = map(lambda x, k=transposition: transpose(x, k), ascale)
146 trscale = map(lambda x, k=transposition: transpose(x, k), cscale)
147 # print "trscale: ", trscale
150 def EDU_to_duration (edu):
165 def rational_to_lily_skip (rat):
169 while d and d % 2 == 0:
170 basedur = basedur << 1
173 str = 's%d' % basedur
175 str = str + '*%d' % n
177 str = str + '/%d' % d
192 def rat_simplify (r):
203 def rat_multiply (a,b):
207 return rat_simplify ((x*p, y*q))
213 return rat_simplify ((x*q + p*y, y*q))
221 def rat_subtract (a,b ):
222 return rat_add (a, rat_neg (b))
224 def lily_notename (tuple2):
226 nn = chr ((n+ 2)%7 + ord ('a'))
228 return nn + {-2:'eses', -1:'es', 0:'', 1:'is', 2:'isis'}[a]
232 def __init__ (self, number):
233 self.start_note = number
236 def append_finale (self, fin):
237 self.finale.append (fin)
240 n = self.finale[0][2]*self.finale[0][3]
241 d = self.finale[0][0]*self.finale[0][1]
242 return rat_simplify( (n, d))
244 def dump_start (self):
245 return '\\times %d/%d { ' % self.factor ()
250 def calculate (self, chords):
251 edu_left = self.finale[0][0] * self.finale[0][1]
253 startch = chords[self.start_note]
255 while c and edu_left:
258 c.chord_prefix = self.dump_start () + c.chord_prefix
261 edu_left = edu_left - c.EDU_duration ()
263 c.chord_suffix = c.chord_suffix+ self.dump_end ()
267 sys.stderr.write ("\nHuh? Tuplet starting at entry %d was too short." % self.start_note)
270 def __init__ (self, number, params):
274 def append_entry (self, finale_e):
275 self.finale.append (finale_e)
277 def calculate (self, chords):
278 startnote = self.finale[5]
279 endnote = self.finale[3*6 + 2]
281 cs = chords[startnote]
287 cs.note_suffix = '-(' + cs.note_suffix
288 ce.note_suffix = ce.note_suffix + '-)'
291 sys.stderr.write ("""\nHuh? Slur no %d between (%d,%d), with %d notes""" % (self.number, startnote, endnote, len (chords)))
294 class Global_measure:
295 def __init__ (self, number):
298 self.key_signature = None
306 return `self.finale `
308 def set_timesig (self, finale):
309 (beats, fdur) = finale
310 (log, dots) = EDU_to_duration (fdur)
318 sys.stderr.write ("\nHuh? Beat duration has dots? (EDU Duration = %d)" % fdur)
319 self.timesig = (beats, log)
324 def set_key_sig (self, finale):
325 k = interpret_finale_key_sig (finale)
326 self.key_signature = k
327 self.scale = find_scale (k)
329 def set_flags (self,flag1, flag2):
331 # flag1 isn't all that interesting.
336 self.repeats.append ('start')
338 self.repeats.append ('stop')
342 self.repeats.append ('bracket')
355 class Articulation_def:
356 def __init__ (self, n, a, b):
357 self.finale_glyph = a & 0xff
362 return articulation_dict[self.finale_glyph]
364 sys.stderr.write ("\nUnknown articulation no. %d" % self.finale_glyph)
365 sys.stderr.write ("\nPlease add an entry to articulation_dict in the Python source")
369 def __init__ (self, a,b, finale):
370 self.definition = finale[0]
373 def calculate (self, chords, defs):
374 c = chords[self.notenumber]
376 adef = defs[self.definition]
380 sys.stderr.write ("\nThis happened on note %d" % self.notenumber)
382 c.note_suffix = '-' + lystr
385 def __init__ (self, a,b , finale):
387 self.syllable = finale[1]
388 self.verse = finale[0]
389 def calculate (self, chords, lyrics):
390 self.chord = chords[self.chordnum]
393 def __init__ (self, number, body):
396 self.split_syllables ()
397 def split_syllables (self):
398 ss = re.split ('(-| +)', self.body)
404 septor = re.sub (" +", "", s)
405 septor = re.sub ("-", " -- ", septor)
406 syls[-1] = syls[-1] + septor
412 self.syllables = syls
417 for s in self.syllables[1:]:
418 line = line + ' ' + s
420 str = str + ' ' * 4 + line + '\n'
423 str = """\nverse%s = \\lyricmode {\n %s }\n""" % (encodeint (self.number - 1) ,str)
427 def __init__(self, pitch, sig_type = 0):
429 self.sig_type = sig_type
431 def signature_type (self):
432 if self.sig_type == 1:
435 # really only for 0, but we only know about 0 and 1
438 def equal (self, other):
439 if other and other.pitch == self.pitch and other.sig_type == self.sig_type:
446 def __init__(self, no):
448 self.frames = [0] * 4
452 self.global_measure = None
459 def calculate (self):
462 if len (self.finale) < 2:
466 self.frames = [fs[0]]
475 def __init__ (self, finale):
478 (number, start, end ) = finale
484 def set_measure (self, m):
487 def calculate (self):
492 for c in self.chords:
493 if c.grace and (lastch == None or (not lastch.grace)):
494 c.chord_prefix = r'\grace {' + c.chord_prefix
496 elif not c.grace and lastch and lastch.grace:
497 lastch.chord_suffix = lastch.chord_suffix + ' } '
502 if lastch and in_grace:
503 lastch.chord_suffix += '}'
507 str = '%% FR(%d)\n' % self.number
508 left = self.measure.global_measure.length ()
512 for c in self.chords:
513 add = c.ly_string () + ' '
514 if len (ln) + len(add) > 72:
515 str = str + ln + '\n'
518 left = rat_subtract (left, c.length ())
523 sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
526 str = str + rational_to_lily_skip (left)
532 return chr ( i + ord ('A'))
535 def __init__ (self, number):
539 def get_measure (self, no):
540 fill_list_to (self.measures, no)
542 if self.measures[no] == None:
544 self.measures [no] =m
547 return self.measures[no]
549 return 'staff' + encodeint (self.number - 1)
550 def layerid (self, l):
551 return self.staffid() + 'layer%s' % chr (l -1 + ord ('A'))
553 def dump_time_key_sigs (self):
559 for m in self.measures[1:]:
560 if not m or not m.valid:
567 if g.key_signature and not g.key_signature.equal(last_key):
568 pitch= g.key_signature.pitch
569 e = e + "\\key %s %s " % (lily_notename (pitch),
570 g.key_signature.signature_type())
572 last_key = g.key_signature
573 if last_time <> g.timesig :
574 e = e + "\\time %d/%d " % g.timesig
575 last_time = g.timesig
577 if 'start' in g.repeats:
578 e = e + ' \\bar "|:" '
581 # we don't attempt voltas since they fail easily.
582 if 0 : # and g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket:
584 if g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket == 'end':
588 if g.bracket == 'start':
591 str = string.join (map (lambda x: '(volta %s)' % x, strs))
593 e = e + ' \\set Score.repeatCommands = #\'(%s) ' % str
598 if last_clef <> m.clef :
599 e = e + '\\clef "%s"' % lily_clef (m.clef)
603 k = k +' ' + rational_to_lily_skip (gap) + '\n'
608 gap = rat_add (gap, g.length ())
609 if 'stop' in g.repeats:
610 k = k + ' \\bar ":|" '
612 k = '%sglobal = { %s }\n\n ' % (self.staffid (), k)
620 for x in range (1,5): # 4 layers.
625 for m in self.measures[1:]:
626 if not m or not m.valid:
627 sys.stderr.write ("Skipping non-existant or invalid measure\n")
634 sys.stderr.write ("Skipping nonexistent frame %d\n" % x)
635 laystr = laystr + "%% non existent frame %d (skipped) \n" % x
639 laystr = laystr +'} %s {\n ' % rational_to_lily_skip (gap)
641 laystr = laystr + fr.dump ()
643 if m.global_measure :
644 gap = rat_add (gap, m.global_measure.length ())
647 "No global measure for staff %d measure %d\n"
648 % (self.number, m.number))
651 laystr = '%s = { { %s } }\n\n' % (l, laystr)
655 str = str + self.dump_time_key_sigs ()
656 stafdef = '\\%sglobal' % self.staffid ()
658 stafdef = stafdef + ' \\' + i
661 str = str + '%s = \\context Staff = %s <<\n %s\n >>\n' % \
662 (self.staffid (), self.staffid (), stafdef)
671 return [(l[0], l[1])] + ziplist (l[2:])
675 def __init__ (self, number, contents):
678 self.finale = contents[:7]
680 self.notelist = ziplist (contents[7:])
686 self.note_suffix = ''
687 self.chord_suffix = ''
688 self.chord_prefix = ''
695 return self.frame.measure
701 l = (1, self.duration[0])
703 d = 1 << self.duration[1]
705 dotfact = rat_subtract ((2,1), (1,d))
706 mylen = rat_multiply (dotfact, l)
709 mylen = rat_multiply (mylen, self.tuplet.factor())
713 def EDU_duration (self):
714 return self.finale[2]
715 def set_duration (self):
716 self.duration = EDU_to_duration(self.EDU_duration ())
718 def calculate (self):
719 self.find_realpitch ()
722 flag = self.finale[4]
723 if Chord.GRACE_MASK & flag:
727 def find_realpitch (self):
729 meas = self.measure ()
731 if not meas or not meas.global_measure :
732 sys.stderr.write ('note %d not in measure\n' % self.number)
733 elif not meas.global_measure.scale:
734 sys.stderr.write ('note %d: no scale in this measure.' % self.number)
737 for p in self.notelist:
747 scale = meas.global_measure.scale
748 (sn, sa) =scale[rest % 7]
749 sn = sn + (rest - (rest%7)) + 7
751 self.pitches.append ((sn, acc))
752 tiestart = tiestart or (flag & Chord.TIE_START_MASK)
754 self.chord_suffix = self.chord_suffix + ' ~ '
756 REST_MASK = 0x40000000L
757 TIE_START_MASK = 0x40000000L
758 GRACE_MASK = 0x00800000L
760 def ly_string (self):
766 if not (self.finale[4] & Chord.REST_MASK):
769 for p in self.pitches:
774 nn = lily_notename ((n,a))
791 if len (self.pitches) > 1:
794 s = s + '%d%s' % (self.duration[0], '.'* self.duration[1])
795 s = self.note_prefix + s + self.note_suffix
797 s = self.chord_prefix + s + self.chord_suffix
802 def fill_list_to (list, no):
804 Add None to LIST until it contains entry number NO.
806 while len (list) <= no:
807 list.extend ([None] * (no - len(list) + 1))
810 def read_finale_value (str):
812 Pry off one value from STR. The value may be $hex, decimal, or "string".
813 Return: (value, rest-of-STR)
815 while str and str[0] in ' \t\n':
825 while str and str[0] in '0123456789ABCDEF':
830 return (string.atol (hex, 16), str)
834 while str and str[0] <> '"':
839 elif str[0] in '-0123456789':
841 while str and str[0] in '-0123456789':
845 return (string.atoi (dec), str)
847 sys.stderr.write ("can't convert `%s'\n" % str)
853 def parse_etf_file (fn, tag_dict):
855 """ Read FN, putting ETF info into
856 a giant dictionary. The keys of TAG_DICT indicate which tags
857 to put into the dict.
860 sys.stderr.write ('parsing ... ' )
863 gulp = re.sub ('[\n\r]+', '\n', f.read ())
864 ls = string.split (gulp, '\n^')
867 for k in tag_dict.keys ():
868 etf_file_dict[k] = {}
875 m = re.match ('^([a-zA-Z0-9&]+)\(([^)]+)\)', l)
876 if m and tag_dict.has_key (m.group (1)):
879 indices = tuple (map (string.atoi, string.split (m.group (2), ',')))
880 content = l[m.end (2)+1:]
883 tdict = etf_file_dict[tag]
884 if not tdict.has_key (indices):
890 if tag == 'verse' or tag == 'block':
891 m2 = re.match ('(.*)\^end', content)
893 parsed = [m2.group (1)]
896 (v, content) = read_finale_value (content)
900 tdict [indices].extend (parsed)
902 last_indices = indices
907 # let's not do this: this really confuses when eE happens to be before a ^text.
908 # if last_tag and last_indices:
909 # etf_file_dict[last_tag][last_indices].append (l)
911 sys.stderr.write ('\n')
919 def __init__ (self, name):
920 self.measures = [None]
923 self.tuplets = [None]
926 self.articulations = [None]
927 self.syllables = [None]
929 self.articulation_defs = [None]
934 def get_global_measure (self, no):
935 fill_list_to (self.measures, no)
936 if self.measures[no] == None:
937 self.measures [no] = Global_measure (no)
939 return self.measures[no]
942 def get_staff(self,staffno):
943 fill_list_to (self.staffs, staffno)
944 if self.staffs[staffno] == None:
945 self.staffs[staffno] = Staff (staffno)
947 return self.staffs[staffno]
950 def try_IS (self, indices, contents):
953 def try_BC (self, indices, contents):
955 where = contents[0] / 1024.0
956 def try_TP(self, indices, contents):
959 if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
960 self.tuplets.append (Tuplet (num))
962 self.tuplets[-1].append_finale (contents)
964 def try_IM (self, indices, contents):
967 self.articulations.append (Articulation (a,b,fin))
968 def try_verse (self, indices, contents):
972 body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
973 body = re.sub ("\^[a-z]+", "", body)
974 self.verses.append (Verse (a, body))
975 def try_ve (self,indices, contents):
977 self.syllables.append (Syllable (a,b,contents))
979 def try_eE (self,indices, contents):
981 (prev, next, dur, pos, entryflag, extended, follow) = contents[:7]
983 fill_list_to (self.chords, no)
984 self.chords[no] =Chord (no, contents)
986 def try_Sx(self,indices, contents):
988 fill_list_to (self.slurs, slurno)
989 self.slurs[slurno] = Slur(slurno, contents)
991 def try_IX (self, indices, contents):
998 ix = self.articulation_defs[n]
1000 ix = Articulation_def (n,a,b)
1001 self.articulation_defs.append (Articulation_def (n, a, b))
1003 def try_GF(self, indices, contents):
1004 (staffno,measno) = indices
1006 st = self.get_staff (staffno)
1007 meas = st.get_measure (measno)
1008 meas.finale = contents
1010 def try_FR(self, indices, contents):
1011 frameno = indices [0]
1013 startnote = contents[0]
1014 endnote = contents[1]
1016 fill_list_to (self.frames, frameno)
1018 self.frames[frameno] = Frame ((frameno, startnote, endnote))
1020 def try_MS (self, indices, contents):
1022 keynum = contents[1]
1023 meas =self. get_global_measure (measno)
1025 meas.set_key_sig (keynum)
1028 beatlen = contents[3]
1029 meas.set_timesig ((beats, beatlen))
1031 meas_flag1 = contents[4]
1032 meas_flag2 = contents[5]
1034 meas.set_flags (meas_flag1, meas_flag2);
1044 'verse' : try_verse,
1052 def parse (self, etf_dict):
1053 sys.stderr.write ('reconstructing ...')
1056 for (tag,routine) in Etf_file.routine_dict.items ():
1057 ks = etf_dict[tag].keys ()
1060 routine (self, k, etf_dict[tag][k])
1062 sys.stderr.write ('processing ...')
1065 self.unthread_entries ()
1067 for st in self.staffs[1:]:
1071 for m in st.measures[1:]:
1077 m.global_measure = self.measures[mno]
1079 sys.stderr.write ("Non-existent global measure %d" % mno)
1082 frame_obj_list = [None]
1083 for frno in m.frames:
1085 fr = self.frames[frno]
1086 frame_obj_list.append (fr)
1088 sys.stderr.write ("\nNon-existent frame %d" % frno)
1090 m.frames = frame_obj_list
1091 for fr in frame_obj_list[1:]:
1097 fr.chords = self.get_thread (fr.start, fr.end)
1102 for c in self.chords[1:]:
1106 for f in self.frames[1:]:
1110 for t in self.tuplets[1:]:
1111 t.calculate (self.chords)
1113 for s in self.slurs[1:]:
1115 s.calculate (self.chords)
1117 for s in self.articulations[1:]:
1118 s.calculate (self.chords, self.articulation_defs)
1120 def get_thread (self, startno, endno):
1126 c = self.chords[startno]
1128 sys.stderr.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno, endno))
1132 while c and c.number <> endno:
1144 for s in self.staffs[1:]:
1146 str = str + '\n\n' + s.dump ()
1147 staffs.append ('\\' + s.staffid ())
1150 # should use \addlyrics ?
1152 for v in self.verses[1:]:
1153 str = str + v.dump()
1155 if len (self.verses) > 1:
1156 sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
1159 str += '\\version "2.3.25"\n'
1160 str = str + '<<\n %s\n>> } ' % string.join (staffs)
1166 return 'ETF FILE %s %s' % (self.measures, self.entries)
1168 def unthread_entries (self):
1169 for e in self.chords[1:]:
1173 e.prev = self.chords[e.finale[0]]
1174 e.next = self.chords[e.finale[1]]
1177 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1181 sys.stdout.write ('''
1189 ''' % ( '2001--2006',
1190 _('Distributed under terms of the GNU General Public License.'),
1191 _('It comes with NO WARRANTY.')))
1195 def get_option_parser ():
1196 p = ly.get_option_parser (usage='etf2ly [OPTIONS]... ETF-FILE',
1197 version="etf2ly (LilyPond) @TOPLEVEL_VERSION@",
1198 description=_("""Enigma Transport Format is a format used by Coda Music Technology's
1199 Finale product. This program will convert a subset of ETF to a
1200 ready-to-use lilypond file."""))
1201 p.add_option ('-o', '--output', help=_("write output to FILE"),
1204 p.add_option ('-w', '--warranty', help=_ ("show warranty"),
1205 action='store_true',
1208 p.add_option_group ('bugs',
1209 description='''Report bugs via http://post.gmane.org/post.php'''
1210 '''?group=gmane.comp.gnu.lilypond.bugs\n''')
1214 opt_parser = get_option_parser()
1215 (options,args) = opt_parser.parse_args ()
1216 if options.warranty:
1220 return (options,args)
1222 (options, files) = do_options()
1225 out_filename = options.output
1232 sys.stderr.write ('Processing `%s\'\n' % f)
1234 dict = parse_etf_file (f, Etf_file.routine_dict)
1236 if not out_filename:
1237 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1239 if out_filename == f:
1240 out_filename = os.path.basename (f + '.ly')
1242 sys.stderr.write ('Writing `%s\'' % out_filename)
1247 fo = open (out_filename, 'w')
1248 fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)