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 version = '@TOPLEVEL_VERSION@'
38 if version == '@' + 'TOPLEVEL_VERSION' + '@':
39 version = '(unknown version)' # uGUHGUHGHGUGH
45 ################################################################
50 finale_clefs= ['treble', 'alto', 'tenor', 'bass', 'percussion', 'treble_8', 'bass_8', 'baritone']
54 return finale_clefs[fin]
56 sys.stderr.write ( '\nHuh? Found clef number %d\n' % fin)
63 return open (f).read ()
65 # notename 0 == central C
66 distances = [0, 2, 4, 5, 7, 9, 11, 12]
67 def semitones (name, acc):
68 return (name / 7 ) * 12 + distances[name % 7] + acc
70 # represent pitches as (notename, alteration), relative to C-major scale
71 def transpose(orig, delta):
75 old_pitch =semitones (oname, oacc)
76 delta_pitch = semitones (dname, dacc)
77 nname = (oname + dname)
79 new_pitch = semitones (nname, nacc)
81 nacc = nacc - (new_pitch - old_pitch - delta_pitch)
87 def interpret_finale_key_sig (finale_id):
89 find the transposition of C-major scale that belongs here.
91 we are not going to insert the correct major/minor, we only want to
92 have the correct number of accidentals
98 bank_number = finale_id >> 8
99 accidental_bits = finale_id & 0xff
101 if 0 <= accidental_bits < 7:
102 while accidental_bits > 0:
103 p = transpose (p, (4,0)) # a fifth up
104 accidental_bits = accidental_bits - 1
105 elif 248 < accidental_bits <= 255:
106 while accidental_bits < 256:
107 p = transpose (p, (3,0))
108 accidental_bits = accidental_bits + 1
112 p = transpose (p, (5, 0))
115 return KeySignature (p, bank_number)
118 def find_scale (keysig):
119 cscale = map (lambda x: (x,0), range (0,7))
120 # print "cscale: ", cscale
121 ascale = map (lambda x: (x,0), range (-2,5))
122 # print "ascale: ", ascale
123 transposition = keysig.pitch
124 if keysig.sig_type == 1:
125 transposition = transpose(transposition, (2, -1))
126 transposition = (transposition[0] % 7, transposition[1])
127 trscale = map(lambda x, k=transposition: transpose(x, k), ascale)
129 trscale = map(lambda x, k=transposition: transpose(x, k), cscale)
130 # print "trscale: ", trscale
133 def EDU_to_duration (edu):
148 def rational_to_lily_skip (rat):
152 while d and d % 2 == 0:
153 basedur = basedur << 1
156 str = 's%d' % basedur
158 str = str + '*%d' % n
160 str = str + '/%d' % d
175 def rat_simplify (r):
186 def rat_multiply (a,b):
190 return rat_simplify ((x*p, y*q))
196 return rat_simplify ((x*q + p*y, y*q))
204 def rat_subtract (a,b ):
205 return rat_add (a, rat_neg (b))
207 def lily_notename (tuple2):
209 nn = chr ((n+ 2)%7 + ord ('a'))
211 return nn + {-2:'eses', -1:'es', 0:'', 1:'is', 2:'isis'}[a]
215 def __init__ (self, number):
216 self.start_note = number
219 def append_finale (self, fin):
220 self.finale.append (fin)
223 n = self.finale[0][2]*self.finale[0][3]
224 d = self.finale[0][0]*self.finale[0][1]
225 return rat_simplify( (n, d))
227 def dump_start (self):
228 return '\\times %d/%d { ' % self.factor ()
233 def calculate (self, chords):
234 edu_left = self.finale[0][0] * self.finale[0][1]
236 startch = chords[self.start_note]
238 while c and edu_left:
241 c.chord_prefix = self.dump_start () + c.chord_prefix
244 edu_left = edu_left - c.EDU_duration ()
246 c.chord_suffix = c.chord_suffix+ self.dump_end ()
250 sys.stderr.write ("\nHuh? Tuplet starting at entry %d was too short." % self.start_note)
253 def __init__ (self, number, params):
257 def append_entry (self, finale_e):
258 self.finale.append (finale_e)
260 def calculate (self, chords):
261 startnote = self.finale[5]
262 endnote = self.finale[3*6 + 2]
264 cs = chords[startnote]
270 cs.note_suffix = '-(' + cs.note_suffix
271 ce.note_suffix = ce.note_suffix + '-)'
274 sys.stderr.write ("""\nHuh? Slur no %d between (%d,%d), with %d notes""" % (self.number, startnote, endnote, len (chords)))
277 class Global_measure:
278 def __init__ (self, number):
281 self.key_signature = None
289 return `self.finale `
291 def set_timesig (self, finale):
292 (beats, fdur) = finale
293 (log, dots) = EDU_to_duration (fdur)
301 sys.stderr.write ("\nHuh? Beat duration has dots? (EDU Duration = %d)" % fdur)
302 self.timesig = (beats, log)
307 def set_key_sig (self, finale):
308 k = interpret_finale_key_sig (finale)
309 self.key_signature = k
310 self.scale = find_scale (k)
312 def set_flags (self,flag1, flag2):
314 # flag1 isn't all that interesting.
319 self.repeats.append ('start')
321 self.repeats.append ('stop')
325 self.repeats.append ('bracket')
338 class Articulation_def:
339 def __init__ (self, n, a, b):
340 self.finale_glyph = a & 0xff
345 return articulation_dict[self.finale_glyph]
347 sys.stderr.write ("\nUnknown articulation no. %d" % self.finale_glyph)
348 sys.stderr.write ("\nPlease add an entry to articulation_dict in the Python source")
352 def __init__ (self, a,b, finale):
353 self.definition = finale[0]
356 def calculate (self, chords, defs):
357 c = chords[self.notenumber]
359 adef = defs[self.definition]
363 sys.stderr.write ("\nThis happened on note %d" % self.notenumber)
365 c.note_suffix = '-' + lystr
368 def __init__ (self, a,b , finale):
370 self.syllable = finale[1]
371 self.verse = finale[0]
372 def calculate (self, chords, lyrics):
373 self.chord = chords[self.chordnum]
376 def __init__ (self, number, body):
379 self.split_syllables ()
380 def split_syllables (self):
381 ss = re.split ('(-| +)', self.body)
387 septor = re.sub (" +", "", s)
388 septor = re.sub ("-", " -- ", septor)
389 syls[-1] = syls[-1] + septor
395 self.syllables = syls
400 for s in self.syllables[1:]:
401 line = line + ' ' + s
403 str = str + ' ' * 4 + line + '\n'
406 str = """\nverse%s = \\lyricmode {\n %s }\n""" % (encodeint (self.number - 1) ,str)
410 def __init__(self, pitch, sig_type = 0):
412 self.sig_type = sig_type
414 def signature_type (self):
415 if self.sig_type == 1:
418 # really only for 0, but we only know about 0 and 1
421 def equal (self, other):
422 if other and other.pitch == self.pitch and other.sig_type == self.sig_type:
429 def __init__(self, no):
431 self.frames = [0] * 4
435 self.global_measure = None
442 def calculate (self):
445 if len (self.finale) < 2:
449 self.frames = [fs[0]]
458 def __init__ (self, finale):
461 (number, start, end ) = finale
467 def set_measure (self, m):
470 def calculate (self):
475 for c in self.chords:
476 if c.grace and (lastch == None or (not lastch.grace)):
477 c.chord_prefix = r'\grace {' + c.chord_prefix
479 elif not c.grace and lastch and lastch.grace:
480 lastch.chord_suffix = lastch.chord_suffix + ' } '
485 if lastch and in_grace:
486 lastch.chord_suffix += '}'
490 str = '%% FR(%d)\n' % self.number
491 left = self.measure.global_measure.length ()
495 for c in self.chords:
496 add = c.ly_string () + ' '
497 if len (ln) + len(add) > 72:
498 str = str + ln + '\n'
501 left = rat_subtract (left, c.length ())
506 sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
509 str = str + rational_to_lily_skip (left)
515 return chr ( i + ord ('A'))
518 def __init__ (self, number):
522 def get_measure (self, no):
523 fill_list_to (self.measures, no)
525 if self.measures[no] == None:
527 self.measures [no] =m
530 return self.measures[no]
532 return 'staff' + encodeint (self.number - 1)
533 def layerid (self, l):
534 return self.staffid() + 'layer%s' % chr (l -1 + ord ('A'))
536 def dump_time_key_sigs (self):
542 for m in self.measures[1:]:
543 if not m or not m.valid:
550 if g.key_signature and not g.key_signature.equal(last_key):
551 pitch= g.key_signature.pitch
552 e = e + "\\key %s %s " % (lily_notename (pitch),
553 g.key_signature.signature_type())
555 last_key = g.key_signature
556 if last_time <> g.timesig :
557 e = e + "\\time %d/%d " % g.timesig
558 last_time = g.timesig
560 if 'start' in g.repeats:
561 e = e + ' \\bar "|:" '
564 # we don't attempt voltas since they fail easily.
565 if 0 : # and g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket:
567 if g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket == 'end':
571 if g.bracket == 'start':
574 str = ' '.join (['(volta %s)' % x for x in strs])
576 e = e + ' \\set Score.repeatCommands = #\'(%s) ' % str
581 if last_clef <> m.clef :
582 e = e + '\\clef "%s"' % lily_clef (m.clef)
586 k = k +' ' + rational_to_lily_skip (gap) + '\n'
591 gap = rat_add (gap, g.length ())
592 if 'stop' in g.repeats:
593 k = k + ' \\bar ":|" '
595 k = '%sglobal = { %s }\n\n ' % (self.staffid (), k)
603 for x in range (1,5): # 4 layers.
608 for m in self.measures[1:]:
609 if not m or not m.valid:
610 sys.stderr.write ("Skipping non-existant or invalid measure\n")
617 sys.stderr.write ("Skipping nonexistent frame %d\n" % x)
618 laystr = laystr + "%% non existent frame %d (skipped) \n" % x
622 laystr = laystr +'} %s {\n ' % rational_to_lily_skip (gap)
624 laystr = laystr + fr.dump ()
626 if m.global_measure :
627 gap = rat_add (gap, m.global_measure.length ())
630 "No global measure for staff %d measure %d\n"
631 % (self.number, m.number))
634 laystr = '%s = { { %s } }\n\n' % (l, laystr)
638 str = str + self.dump_time_key_sigs ()
639 stafdef = '\\%sglobal' % self.staffid ()
641 stafdef = stafdef + ' \\' + i
644 str = str + '%s = \\context Staff = %s <<\n %s\n >>\n' % \
645 (self.staffid (), self.staffid (), stafdef)
654 return [(l[0], l[1])] + ziplist (l[2:])
658 def __init__ (self, number, contents):
661 self.finale = contents[:7]
663 self.notelist = ziplist (contents[7:])
669 self.note_suffix = ''
670 self.chord_suffix = ''
671 self.chord_prefix = ''
678 return self.frame.measure
684 l = (1, self.duration[0])
686 d = 1 << self.duration[1]
688 dotfact = rat_subtract ((2,1), (1,d))
689 mylen = rat_multiply (dotfact, l)
692 mylen = rat_multiply (mylen, self.tuplet.factor())
696 def EDU_duration (self):
697 return self.finale[2]
698 def set_duration (self):
699 self.duration = EDU_to_duration(self.EDU_duration ())
701 def calculate (self):
702 self.find_realpitch ()
705 flag = self.finale[4]
706 if Chord.GRACE_MASK & flag:
710 def find_realpitch (self):
712 meas = self.measure ()
714 if not meas or not meas.global_measure :
715 sys.stderr.write ('note %d not in measure\n' % self.number)
716 elif not meas.global_measure.scale:
717 sys.stderr.write ('note %d: no scale in this measure.' % self.number)
720 for p in self.notelist:
730 scale = meas.global_measure.scale
731 (sn, sa) =scale[rest % 7]
732 sn = sn + (rest - (rest%7)) + 7
734 self.pitches.append ((sn, acc))
735 tiestart = tiestart or (flag & Chord.TIE_START_MASK)
737 self.chord_suffix = self.chord_suffix + ' ~ '
739 REST_MASK = 0x40000000L
740 TIE_START_MASK = 0x40000000L
741 GRACE_MASK = 0x00800000L
743 def ly_string (self):
749 if not (self.finale[4] & Chord.REST_MASK):
752 for p in self.pitches:
757 nn = lily_notename ((n,a))
774 if len (self.pitches) > 1:
777 s = s + '%d%s' % (self.duration[0], '.'* self.duration[1])
778 s = self.note_prefix + s + self.note_suffix
780 s = self.chord_prefix + s + self.chord_suffix
785 def fill_list_to (list, no):
787 Add None to LIST until it contains entry number NO.
789 while len (list) <= no:
790 list.extend ([None] * (no - len(list) + 1))
793 def read_finale_value (str):
795 Pry off one value from STR. The value may be $hex, decimal, or "string".
796 Return: (value, rest-of-STR)
798 while str and str[0] in ' \t\n':
808 while str and str[0] in '0123456789ABCDEF':
813 return (long (hex, 16), str)
817 while str and str[0] <> '"':
822 elif str[0] in '-0123456789':
824 while str and str[0] in '-0123456789':
828 return (int (dec), str)
830 sys.stderr.write ("cannot convert `%s'\n" % str)
836 def parse_etf_file (fn, tag_dict):
838 """ Read FN, putting ETF info into
839 a giant dictionary. The keys of TAG_DICT indicate which tags
840 to put into the dict.
843 sys.stderr.write ('parsing ... ' )
846 gulp = re.sub ('[\n\r]+', '\n', f.read ())
847 ls = gulp.split ('\n^')
851 etf_file_dict[k] = {}
858 m = re.match ('^([a-zA-Z0-9&]+)\(([^)]+)\)', l)
859 if m and tag_dict.has_key (m.group (1)):
862 indices = tuple ([int (s) for s in m.group (2).split (',')])
863 content = l[m.end (2)+1:]
866 tdict = etf_file_dict[tag]
867 if not tdict.has_key (indices):
873 if tag == 'verse' or tag == 'block':
874 m2 = re.match ('(.*)\^end', content)
876 parsed = [m2.group (1)]
879 (v, content) = read_finale_value (content)
883 tdict [indices].extend (parsed)
885 last_indices = indices
890 # let's not do this: this really confuses when eE happens to be before a ^text.
891 # if last_tag and last_indices:
892 # etf_file_dict[last_tag][last_indices].append (l)
894 sys.stderr.write ('\n')
902 def __init__ (self, name):
903 self.measures = [None]
906 self.tuplets = [None]
909 self.articulations = [None]
910 self.syllables = [None]
912 self.articulation_defs = [None]
917 def get_global_measure (self, no):
918 fill_list_to (self.measures, no)
919 if self.measures[no] == None:
920 self.measures [no] = Global_measure (no)
922 return self.measures[no]
925 def get_staff(self,staffno):
926 fill_list_to (self.staffs, staffno)
927 if self.staffs[staffno] == None:
928 self.staffs[staffno] = Staff (staffno)
930 return self.staffs[staffno]
933 def try_IS (self, indices, contents):
936 def try_BC (self, indices, contents):
938 where = contents[0] / 1024.0
939 def try_TP(self, indices, contents):
942 if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
943 self.tuplets.append (Tuplet (num))
945 self.tuplets[-1].append_finale (contents)
947 def try_IM (self, indices, contents):
950 self.articulations.append (Articulation (a,b,fin))
951 def try_verse (self, indices, contents):
955 body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
956 body = re.sub ("\^[a-z]+", "", body)
957 self.verses.append (Verse (a, body))
958 def try_ve (self,indices, contents):
960 self.syllables.append (Syllable (a,b,contents))
962 def try_eE (self,indices, contents):
964 (prev, next, dur, pos, entryflag, extended, follow) = contents[:7]
966 fill_list_to (self.chords, no)
967 self.chords[no] =Chord (no, contents)
969 def try_Sx(self,indices, contents):
971 fill_list_to (self.slurs, slurno)
972 self.slurs[slurno] = Slur(slurno, contents)
974 def try_IX (self, indices, contents):
981 ix = self.articulation_defs[n]
983 ix = Articulation_def (n,a,b)
984 self.articulation_defs.append (Articulation_def (n, a, b))
986 def try_GF(self, indices, contents):
987 (staffno,measno) = indices
989 st = self.get_staff (staffno)
990 meas = st.get_measure (measno)
991 meas.finale = contents
993 def try_FR(self, indices, contents):
994 frameno = indices [0]
996 startnote = contents[0]
997 endnote = contents[1]
999 fill_list_to (self.frames, frameno)
1001 self.frames[frameno] = Frame ((frameno, startnote, endnote))
1003 def try_MS (self, indices, contents):
1005 keynum = contents[1]
1006 meas =self. get_global_measure (measno)
1008 meas.set_key_sig (keynum)
1011 beatlen = contents[3]
1012 meas.set_timesig ((beats, beatlen))
1014 meas_flag1 = contents[4]
1015 meas_flag2 = contents[5]
1017 meas.set_flags (meas_flag1, meas_flag2);
1027 'verse' : try_verse,
1035 def parse (self, etf_dict):
1036 sys.stderr.write ('reconstructing ...')
1039 for (tag,routine) in Etf_file.routine_dict.items ():
1040 ks = etf_dict[tag].keys ()
1043 routine (self, k, etf_dict[tag][k])
1045 sys.stderr.write ('processing ...')
1048 self.unthread_entries ()
1050 for st in self.staffs[1:]:
1054 for m in st.measures[1:]:
1060 m.global_measure = self.measures[mno]
1062 sys.stderr.write ("Non-existent global measure %d" % mno)
1065 frame_obj_list = [None]
1066 for frno in m.frames:
1068 fr = self.frames[frno]
1069 frame_obj_list.append (fr)
1071 sys.stderr.write ("\nNon-existent frame %d" % frno)
1073 m.frames = frame_obj_list
1074 for fr in frame_obj_list[1:]:
1080 fr.chords = self.get_thread (fr.start, fr.end)
1085 for c in self.chords[1:]:
1089 for f in self.frames[1:]:
1093 for t in self.tuplets[1:]:
1094 t.calculate (self.chords)
1096 for s in self.slurs[1:]:
1098 s.calculate (self.chords)
1100 for s in self.articulations[1:]:
1101 s.calculate (self.chords, self.articulation_defs)
1103 def get_thread (self, startno, endno):
1109 c = self.chords[startno]
1111 sys.stderr.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno, endno))
1115 while c and c.number <> endno:
1127 for s in self.staffs[1:]:
1129 str = str + '\n\n' + s.dump ()
1130 staffs.append ('\\' + s.staffid ())
1133 # should use \addlyrics ?
1135 for v in self.verses[1:]:
1136 str = str + v.dump()
1138 if len (self.verses) > 1:
1139 sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
1142 str += '\\version "2.3.25"\n'
1143 str = str + '<<\n %s\n>> } ' % ' '.join (staffs)
1149 return 'ETF FILE %s %s' % (self.measures, self.entries)
1151 def unthread_entries (self):
1152 for e in self.chords[1:]:
1156 e.prev = self.chords[e.finale[0]]
1157 e.next = self.chords[e.finale[1]]
1160 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1164 sys.stdout.write ('''
1172 ''' % ( '2001--2006',
1173 _('Distributed under terms of the GNU General Public License.'),
1174 _('It comes with NO WARRANTY.')))
1178 def get_option_parser ():
1179 p = ly.get_option_parser (usage=_ ("%s [OPTION]... ETF-FILE") % 'etf2ly',
1180 description=_ ("""Enigma Transport Format is a format used by Coda Music Technology's
1181 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 ('',
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)