3 # info mostly taken from looking at files. See also
4 # http://www.cs.uu.nl/~hanwen/lily-devel/etf.html
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)
29 program_name = 'etf2ly'
30 version = '@TOPLEVEL_VERSION@'
31 if version == '@' + 'TOPLEVEL_VERSION' + '@':
32 version = '(unknown version)' # uGUHGUHGHGUGH
41 finale_clefs= ['treble', 'alto', 'tenor', 'bass', 'percussion', 'treble_8', 'bass_8', 'baritone']
45 return finale_clefs[fin]
47 sys.stderr.write ( '\nHuh? Found clef number %d\n' % fin)
54 return open (f).read ()
56 # notename 0 == central C
57 distances = [0, 2, 4, 5, 7, 9, 11, 12]
58 def semitones (name, acc):
59 return (name / 7 ) * 12 + distances[name % 7] + acc
61 # represent pitches as (notename, alteration), relative to C-major scale
62 def transpose(orig, delta):
66 old_pitch =semitones (oname, oacc)
67 delta_pitch = semitones (dname, dacc)
68 nname = (oname + dname)
70 new_pitch = semitones (nname, nacc)
72 nacc = nacc - (new_pitch - old_pitch - delta_pitch)
78 # find transposition of C-major scale that belongs here.
79 def interpret_finale_key_sig (finale_id):
81 if 0 <= finale_id < 7:
83 p = transpose (p, (4,0)) # a fifth up
84 finale_id = finale_id - 1
85 elif 248 < finale_id <= 255:
86 while finale_id < 256:
87 p = transpose (p, (3,0))
88 finale_id = finale_id + 1
94 def find_scale (transposition):
95 cscale = map (lambda x: (x,0), range (0,7))
96 trscale = map(lambda x, k=transposition: transpose(x, k), cscale)
99 def EDU_to_duration (edu):
114 def rat_to_lily_duration (rat):
118 while d and d % 2 == 0:
119 basedur = basedur << 1
122 str = 's%d' % basedur
124 str = str + '*%d' % n
126 str = str + '/%d' % d
141 def rat_simplify (r):
152 def rat_multiply (a,b):
156 return rat_simplify ((x*p, y*q))
162 return rat_simplify ((x*q + p*y, y*q))
170 def rat_subtract (a,b ):
171 return rat_add (a, rat_neg (b))
173 def lily_notename (tuple2):
175 nn = chr ((n+ 2)%7 + ord ('a'))
190 def __init__ (self, number):
191 self.start_note = number
194 def append_finale (self, fin):
195 self.finale.append (fin)
198 n = self.finale[0][2]*self.finale[0][3]
199 d = self.finale[0][0]*self.finale[0][1]
200 return rat_simplify( (n, d))
202 def dump_start (self):
203 return '\\times %d/%d { ' % self.factor ()
208 def calculate (self, chords):
209 edu_left = self.finale[0][0] * self.finale[0][1]
211 startch = chords[self.start_note]
213 while c and edu_left:
216 c.chord_prefix = self.dump_start () + c.chord_prefix
219 edu_left = edu_left - c.EDU_duration ()
221 c.chord_suffix = c.chord_suffix+ self.dump_end ()
225 sys.stderr.write ("\nHuh? Tuplet starting at entry %d was too short." % self.start_note)
228 def __init__ (self, number, params):
232 def append_entry (self, finale_e):
233 self.finale.append (finale_e)
235 def calculate (self, chords):
236 startnote = self.finale[5]
237 endnote = self.finale[3*6 + 2]
239 cs = chords[startnote]
245 cs.note_suffix = '(' + cs.note_suffix
246 ce.note_prefix = ce.note_prefix + ')'
248 sys.stderr.write ("""\nHuh? Slur no %d between (%d,%d), with %d notes""" % (self.number, startnote, endnote, len (chords)))
251 class Global_measure:
252 def __init__ (self, number):
255 self.keysignature = None
263 return `self.finale `
265 def set_timesig (self, finale):
266 (beats, fdur) = finale
267 (log, dots) = EDU_to_duration (fdur)
269 self.timesig = (beats, log)
274 def set_keysig (self, finale):
275 k = interpret_finale_key_sig (finale)
276 self.keysignature = k
277 self.scale = find_scale (k)
279 def set_flags (self,flag1, flag2):
281 # flag1 isn't all that interesting.
286 self.repeats.append ('start')
288 self.repeats.append ('stop')
292 self.repeats.append ('bracket')
305 class Articulation_def:
306 def __init__ (self, n, a, b):
307 self.finale_glyph = a & 0xff
312 return articulation_dict[self.finale_glyph]
314 sys.stderr.write ("\nUnknown articulation no. %d" % self.finale_glyph)
315 sys.stderr.write ("\nPlease add an entry to articulation_dict in the Python source")
319 def __init__ (self, a,b, finale):
320 self.definition = finale[0]
323 def calculate (self, chords, defs):
324 c = chords[self.notenumber]
326 adef = defs[self.definition]
330 sys.stderr.write ("\nThis happened on note %d" % self.notenumber)
332 c.note_suffix = '-' + lystr
335 def __init__ (self, a,b , finale):
337 self.syllable = finale[1]
338 self.verse = finale[0]
339 def calculate (self, chords, lyrics):
340 self.chord = chords[self.chordnum]
343 def __init__ (self, number, body):
346 self.split_syllables ()
347 def split_syllables (self):
348 ss = re.split ('(-| +)', self.body)
354 septor = re.sub (" +", "", s)
355 septor = re.sub ("-", " -- ", septor)
356 syls[-1] = syls[-1] + septor
362 self.syllables = syls
367 for s in self.syllables[1:]:
368 line = line + ' ' + s
370 str = str + ' ' * 4 + line + '\n'
373 str = """\nverse%s = \\lyrics {\n %s}\n""" % (encodeint (self.number - 1) ,str)
378 def __init__(self, no):
380 self.frames = [0] * 4
384 self.global_measure = None
391 def calculate (self):
394 if len (self.finale) < 2:
398 self.frames = [fs[0]]
407 def __init__ (self, finale):
410 (number, start, end ) = finale
416 def set_measure (self, m):
419 def calculate (self):
423 for c in self.chords:
424 if c.grace and (lastch == None or (not lastch.grace)):
425 c.chord_prefix = r'\grace {' + c.chord_prefix
426 elif not c.grace and lastch and lastch.grace:
427 lastch.chord_suffix = lastch.chord_suffix + ' } '
434 str = '%% FR(%d)\n' % self.number
435 left = self.measure.global_measure.length ()
439 for c in self.chords:
440 add = c.ly_string () + ' '
441 if len (ln) + len(add) > 72:
442 str = str + ln + '\n'
445 left = rat_subtract (left, c.length ())
450 sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
453 str = str + rat_to_lily_duration (left)
459 return chr ( i + ord ('A'))
462 def __init__ (self, number):
466 def get_measure (self, no):
467 fill_list_to (self.measures, no)
469 if self.measures[no] == None:
471 self.measures [no] =m
474 return self.measures[no]
476 return 'staff' + encodeint (self.number - 1)
477 def layerid (self, l):
478 return self.staffid() + 'layer%s' % chr (l -1 + ord ('A'))
480 def dump_time_key_sigs (self):
486 for m in self.measures[1:]:
487 if not m or not m.valid:
494 if last_key <> g.keysignature:
495 e = e + "\\key %s \\major " % lily_notename (g.keysignature)
496 last_key = g.keysignature
497 if last_time <> g.timesig :
498 e = e + "\\time %d/%d " % g.timesig
499 last_time = g.timesig
501 if 'start' in g.repeats:
502 e = e + ' \\bar "|:" '
505 # we don't attempt voltas since they fail easily.
506 if 0 : # and g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket:
508 if g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket == 'end':
512 if g.bracket == 'start':
515 str = string.join (map (lambda x: '(volta %s)' % x, strs))
517 e = e + ' \\property Score.repeatCommands = #\'(%s) ' % str
522 if last_clef <> m.clef :
523 e = e + '\\clef "%s"' % lily_clef (m.clef)
527 k = k +' ' + rat_to_lily_duration (gap) + '\n'
532 gap = rat_add (gap, g.length ())
533 if 'stop' in g.repeats:
534 k = k + ' \\bar ":|" '
536 k = '%sglobal = \\notes { %s }\n\n ' % (self.staffid (), k)
544 for x in range (1,5): # 4 layers.
549 for m in self.measures[1:]:
550 if not m or not m.valid:
551 sys.stderr.write ("Skipping non-existant or invalid measure\n")
558 sys.stderr.write ("Skipping nonexistent frame %d\n" % x)
559 laystr = laystr + "%% non existent frame %d (skipped) \n" % x
563 laystr = laystr +'} %s {\n ' % rat_to_lily_duration (gap)
565 laystr = laystr + fr.dump ()
567 if m.global_measure :
568 gap = rat_add (gap, m.global_measure.length ())
571 "No global measure for staff %d measure %d\n"
572 % (self.number, m.number))
575 laystr = '%s = \\notes { { %s } }\n\n' % (l, laystr)
579 str = str + self.dump_time_key_sigs ()
580 stafdef = '\\%sglobal' % self.staffid ()
582 stafdef = stafdef + ' \\' + i
585 str = str + '%s = \\context Staff = %s <\n %s\n >\n' % \
586 (self.staffid (), self.staffid (), stafdef)
595 return [(l[0], l[1])] + ziplist (l[2:])
599 def __init__ (self, number, contents):
602 self.finale = contents[:7]
604 self.notelist = ziplist (contents[7:])
610 self.note_suffix = ''
611 self.chord_suffix = ''
612 self.chord_prefix = ''
619 return self.frame.measure
625 l = (1, self.duration[0])
627 d = 1 << self.duration[1]
629 dotfact = rat_subtract ((2,1), (1,d))
630 mylen = rat_multiply (dotfact, l)
633 mylen = rat_multiply (mylen, self.tuplet.factor())
637 def EDU_duration (self):
638 return self.finale[2]
639 def set_duration (self):
640 self.duration = EDU_to_duration(self.EDU_duration ())
642 def calculate (self):
643 self.find_realpitch ()
646 flag = self.finale[4]
647 if Chord.GRACE_MASK & flag:
651 def find_realpitch (self):
653 meas = self.measure ()
655 if not meas or not meas.global_measure :
656 sys.stderr.write ('note %d not in measure\n' % self.number)
657 elif not meas.global_measure.scale:
658 sys.stderr.write ('note %d: no scale in this measure.' % self.number)
661 for p in self.notelist:
671 scale = meas.global_measure.scale
672 (sn, sa) =scale[rest % 7]
673 sn = sn + (rest - (rest%7)) + 7
675 self.pitches.append ((sn, acc))
676 tiestart = tiestart or (flag & Chord.TIE_START_MASK)
678 self.chord_suffix = self.chord_suffix + ' ~ '
680 REST_MASK = 0x40000000L
681 TIE_START_MASK = 0x40000000L
682 GRACE_MASK = 0x00800000L
684 def ly_string (self):
690 if not (self.finale[4] & Chord.REST_MASK):
693 for p in self.pitches:
698 nn = lily_notename ((n,a))
711 s = s + '%s%d%s' % (nn, self.duration[0], '.'* self.duration[1])
714 s = 'r%d%s' % (self.duration[0] , '.'* self.duration[1])
715 s = self.note_prefix + s + self.note_suffix
716 if len (self.pitches) > 1:
719 s = self.chord_prefix + s + self.chord_suffix
723 def fill_list_to (list, no):
725 Add None to LIST until it contains entry number NO.
727 while len (list) <= no:
728 list.extend ([None] * (no - len(list) + 1))
731 def read_finale_value (str):
732 while str and str[0] in ' \t\n':
742 while str and str[0] in '0123456789ABCDEF':
747 return (string.atol (hex, 16), str)
751 while str and str[0] <> '"':
756 elif str[0] in '-0123456789':
758 while str and str[0] in '-0123456789':
762 return (string.atoi (dec), str)
764 sys.stderr.write ("Can't convert `%s'\n" % str)
770 def parse_etf_file (fn, tag_dict):
772 """ Read FN, putting ETF info into
773 a giant dictionary. The keys of TAG_DICT indicate which tags
774 to put into the dict.
777 sys.stderr.write ('parsing ... ' )
780 gulp = re.sub ('[\n\r]+', '\n', f.read ())
781 ls = string.split (gulp, '\n^')
784 for k in tag_dict.keys ():
785 etf_file_dict[k] = {}
792 m = re.match ('^([a-zA-Z0-9&]+)\(([^)]+)\)', l)
793 if m and tag_dict.has_key (m.group (1)):
796 indices = tuple (map (string.atoi, string.split (m.group (2), ',')))
797 content = l[m.end (2)+1:]
800 tdict = etf_file_dict[tag]
801 if not tdict.has_key (indices):
807 if tag == 'verse' or tag == 'block':
808 m2 = re.match ('(.*)\^end', content)
810 parsed = [m2.group (1)]
813 (v, content) = read_finale_value (content)
817 tdict [indices].extend (parsed)
819 last_indices = indices
824 # let's not do this: this really confuses when eE happens to be before a ^text.
825 # if last_tag and last_indices:
826 # etf_file_dict[last_tag][last_indices].append (l)
828 sys.stderr.write ('\n')
836 def __init__ (self, name):
837 self.measures = [None]
840 self.tuplets = [None]
843 self.articulations = [None]
844 self.syllables = [None]
846 self.articulation_defs = [None]
851 def get_global_measure (self, no):
852 fill_list_to (self.measures, no)
853 if self.measures[no] == None:
854 self.measures [no] = Global_measure (no)
856 return self.measures[no]
859 def get_staff(self,staffno):
860 fill_list_to (self.staffs, staffno)
861 if self.staffs[staffno] == None:
862 self.staffs[staffno] = Staff (staffno)
864 return self.staffs[staffno]
867 def try_IS (self, indices, contents):
870 def try_BC (self, indices, contents):
872 where = contents[0] / 1024.0
873 def try_TP(self, indices, contents):
876 if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
877 self.tuplets.append (Tuplet (num))
879 self.tuplets[-1].append_finale (contents)
881 def try_IM (self, indices, contents):
884 self.articulations.append (Articulation (a,b,fin))
885 def try_verse (self, indices, contents):
889 body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
890 body = re.sub ("\^[a-z]+", "", body)
891 self.verses.append (Verse (a, body))
892 def try_ve (self,indices, contents):
894 self.syllables.append (Syllable (a,b,contents))
896 def try_eE (self,indices, contents):
898 (prev, next, dur, pos, entryflag, extended, follow) = contents[:7]
900 fill_list_to (self.chords, no)
901 self.chords[no] =Chord (no, contents)
903 def try_Sx(self,indices, contents):
905 fill_list_to (self.slurs, slurno)
906 self.slurs[slurno] = Slur(slurno, contents)
908 def try_IX (self, indices, contents):
915 ix = self.articulation_defs[n]
917 ix = Articulation_def (n,a,b)
918 self.articulation_defs.append (Articulation_def (n, a, b))
920 def try_GF(self, indices, contents):
921 (staffno,measno) = indices
923 st = self.get_staff (staffno)
924 meas = st.get_measure (measno)
925 meas.finale = contents
927 def try_FR(self, indices, contents):
928 frameno = indices [0]
930 startnote = contents[0]
931 endnote = contents[1]
933 fill_list_to (self.frames, frameno)
935 self.frames[frameno] = Frame ((frameno, startnote, endnote))
937 def try_MS (self, indices, contents):
940 meas =self. get_global_measure (measno)
941 meas.set_keysig (keynum)
944 beatlen = contents[3]
945 meas.set_timesig ((beats, beatlen))
947 meas_flag1 = contents[4]
948 meas_flag2 = contents[5]
950 meas.set_flags (meas_flag1, meas_flag2);
968 def parse (self, etf_dict):
969 sys.stderr.write ('reconstructing ...')
972 for (tag,routine) in Etf_file.routine_dict.items ():
973 ks = etf_dict[tag].keys ()
976 routine (self, k, etf_dict[tag][k])
978 sys.stderr.write ('processing ...')
981 self.unthread_entries ()
983 for st in self.staffs[1:]:
987 for m in st.measures[1:]:
993 m.global_measure = self.measures[mno]
995 sys.stderr.write ("Non-existent global measure %d" % mno)
998 frame_obj_list = [None]
999 for frno in m.frames:
1000 fr = self.frames[frno]
1001 frame_obj_list.append (fr)
1003 m.frames = frame_obj_list
1004 for fr in frame_obj_list[1:]:
1010 fr.chords = self.get_thread (fr.start, fr.end)
1015 for c in self.chords[1:]:
1019 for f in self.frames[1:]:
1023 for t in self.tuplets[1:]:
1024 t.calculate (self.chords)
1026 for s in self.slurs[1:]:
1028 s.calculate (self.chords)
1030 for s in self.articulations[1:]:
1031 s.calculate (self.chords, self.articulation_defs)
1033 def get_thread (self, startno, endno):
1039 c = self.chords[startno]
1041 sys.stderr.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno, endno))
1045 while c and c.number <> endno:
1057 for s in self.staffs[1:]:
1059 str = str + '\n\n' + s.dump ()
1060 staffs.append ('\\' + s.staffid ())
1063 # should use \addlyrics ?
1065 for v in self.verses[1:]:
1066 str = str + v.dump()
1068 if len (self.verses) > 1:
1069 sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
1072 str = str + '\\score { < %s > } ' % string.join (staffs)
1078 return 'ETF FILE %s %s' % (self.measures, self.entries)
1080 def unthread_entries (self):
1081 for e in self.chords[1:]:
1085 e.prev = self.chords[e.finale[0]]
1086 e.next = self.chords[e.finale[1]]
1089 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1092 sys.stdout.write("""Usage: etf2ly [OPTION]... ETF-FILE
1094 Convert ETF to LilyPond.
1098 -o,--output=FILE set output filename to FILE
1099 -v,--version version information
1101 Enigma Transport Format is a format used by Coda Music Technology's
1102 Finale product. This program will convert a subset of ETF to a
1103 ready-to-use lilypond file.
1105 Report bugs to bug-gnu-music@gnu.org
1107 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>
1110 def print_version ():
1111 sys.stdout.write (r"""etf2ly (GNU lilypond) %s
1113 This is free software. It is covered by the GNU General Public License,
1114 and you are welcome to change it and/or distribute copies of it under
1115 certain conditions. Invoke as `midi2ly --warranty' for more information.
1117 Copyright (c) 2000 by Han-Wen Nienhuys <hanwen@cs.uu.nl>
1122 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
1128 if o== '--help' or o == '-h':
1131 if o == '--version' or o == '-v':
1135 if o == '--output' or o == '-o':
1148 sys.stderr.write ('Processing `%s\'\n' % f)
1150 dict = parse_etf_file (f, Etf_file.routine_dict)
1152 if not out_filename:
1153 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1155 if out_filename == f:
1156 out_filename = os.path.basename (f + '.ly')
1158 sys.stderr.write ('Writing `%s\'' % out_filename)
1163 fo = open (out_filename, 'w')
1164 fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)