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'))
177 return nn + {-2:'eses', -1:'es', 0:'', 1:'is', 2:'isis'}[a]
181 def __init__ (self, number):
182 self.start_note = number
185 def append_finale (self, fin):
186 self.finale.append (fin)
189 n = self.finale[0][2]*self.finale[0][3]
190 d = self.finale[0][0]*self.finale[0][1]
191 return rat_simplify( (n, d))
193 def dump_start (self):
194 return '\\times %d/%d { ' % self.factor ()
199 def calculate (self, chords):
200 edu_left = self.finale[0][0] * self.finale[0][1]
202 startch = chords[self.start_note]
204 while c and edu_left:
207 c.chord_prefix = self.dump_start () + c.chord_prefix
210 edu_left = edu_left - c.EDU_duration ()
212 c.chord_suffix = c.chord_suffix+ self.dump_end ()
216 sys.stderr.write ("\nHuh? Tuplet starting at entry %d was too short." % self.start_note)
219 def __init__ (self, number, params):
223 def append_entry (self, finale_e):
224 self.finale.append (finale_e)
226 def calculate (self, chords):
227 startnote = self.finale[5]
228 endnote = self.finale[3*6 + 2]
230 cs = chords[startnote]
236 cs.note_suffix = '(' + cs.note_suffix
237 ce.note_prefix = ce.note_prefix + ')'
239 sys.stderr.write ("""\nHuh? Slur no %d between (%d,%d), with %d notes""" % (self.number, startnote, endnote, len (chords)))
242 class Global_measure:
243 def __init__ (self, number):
246 self.keysignature = None
254 return `self.finale `
256 def set_timesig (self, finale):
257 (beats, fdur) = finale
258 (log, dots) = EDU_to_duration (fdur)
260 self.timesig = (beats, log)
265 def set_keysig (self, finale):
266 k = interpret_finale_key_sig (finale)
267 self.keysignature = k
268 self.scale = find_scale (k)
270 def set_flags (self,flag1, flag2):
272 # flag1 isn't all that interesting.
277 self.repeats.append ('start')
279 self.repeats.append ('stop')
283 self.repeats.append ('bracket')
296 class Articulation_def:
297 def __init__ (self, n, a, b):
298 self.finale_glyph = a & 0xff
303 return articulation_dict[self.finale_glyph]
305 sys.stderr.write ("\nUnknown articulation no. %d" % self.finale_glyph)
306 sys.stderr.write ("\nPlease add an entry to articulation_dict in the Python source")
310 def __init__ (self, a,b, finale):
311 self.definition = finale[0]
314 def calculate (self, chords, defs):
315 c = chords[self.notenumber]
317 adef = defs[self.definition]
321 sys.stderr.write ("\nThis happened on note %d" % self.notenumber)
323 c.note_suffix = '-' + lystr
326 def __init__ (self, a,b , finale):
328 self.syllable = finale[1]
329 self.verse = finale[0]
330 def calculate (self, chords, lyrics):
331 self.chord = chords[self.chordnum]
334 def __init__ (self, number, body):
337 self.split_syllables ()
338 def split_syllables (self):
339 ss = re.split ('(-| +)', self.body)
345 septor = re.sub (" +", "", s)
346 septor = re.sub ("-", " -- ", septor)
347 syls[-1] = syls[-1] + septor
353 self.syllables = syls
358 for s in self.syllables[1:]:
359 line = line + ' ' + s
361 str = str + ' ' * 4 + line + '\n'
364 str = """\nverse%s = \\lyrics {\n %s}\n""" % (encodeint (self.number - 1) ,str)
369 def __init__(self, no):
371 self.frames = [0] * 4
375 self.global_measure = None
382 def calculate (self):
385 if len (self.finale) < 2:
389 self.frames = [fs[0]]
398 def __init__ (self, finale):
401 (number, start, end ) = finale
407 def set_measure (self, m):
410 def calculate (self):
414 for c in self.chords:
415 if c.grace and (lastch == None or (not lastch.grace)):
416 c.chord_prefix = r'\grace {' + c.chord_prefix
417 elif not c.grace and lastch and lastch.grace:
418 lastch.chord_suffix = lastch.chord_suffix + ' } '
425 str = '%% FR(%d)\n' % self.number
426 left = self.measure.global_measure.length ()
430 for c in self.chords:
431 add = c.ly_string () + ' '
432 if len (ln) + len(add) > 72:
433 str = str + ln + '\n'
436 left = rat_subtract (left, c.length ())
441 sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
444 str = str + rat_to_lily_duration (left)
450 return chr ( i + ord ('A'))
453 def __init__ (self, number):
457 def get_measure (self, no):
458 fill_list_to (self.measures, no)
460 if self.measures[no] == None:
462 self.measures [no] =m
465 return self.measures[no]
467 return 'staff' + encodeint (self.number - 1)
468 def layerid (self, l):
469 return self.staffid() + 'layer%s' % chr (l -1 + ord ('A'))
471 def dump_time_key_sigs (self):
477 for m in self.measures[1:]:
478 if not m or not m.valid:
485 if last_key <> g.keysignature:
486 e = e + "\\key %s \\major " % lily_notename (g.keysignature)
487 last_key = g.keysignature
488 if last_time <> g.timesig :
489 e = e + "\\time %d/%d " % g.timesig
490 last_time = g.timesig
492 if 'start' in g.repeats:
493 e = e + ' \\bar "|:" '
496 # we don't attempt voltas since they fail easily.
497 if 0 : # and g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket:
499 if g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket == 'end':
503 if g.bracket == 'start':
506 str = string.join (map (lambda x: '(volta %s)' % x, strs))
508 e = e + ' \\property Score.repeatCommands = #\'(%s) ' % str
513 if last_clef <> m.clef :
514 e = e + '\\clef "%s"' % lily_clef (m.clef)
518 k = k +' ' + rat_to_lily_duration (gap) + '\n'
523 gap = rat_add (gap, g.length ())
524 if 'stop' in g.repeats:
525 k = k + ' \\bar ":|" '
527 k = '%sglobal = \\notes { %s }\n\n ' % (self.staffid (), k)
535 for x in range (1,5): # 4 layers.
540 for m in self.measures[1:]:
541 if not m or not m.valid:
542 sys.stderr.write ("Skipping non-existant or invalid measure\n")
549 sys.stderr.write ("Skipping nonexistent frame %d\n" % x)
550 laystr = laystr + "%% non existent frame %d (skipped) \n" % x
554 laystr = laystr +'} %s {\n ' % rat_to_lily_duration (gap)
556 laystr = laystr + fr.dump ()
558 if m.global_measure :
559 gap = rat_add (gap, m.global_measure.length ())
562 "No global measure for staff %d measure %d\n"
563 % (self.number, m.number))
566 laystr = '%s = \\notes { { %s } }\n\n' % (l, laystr)
570 str = str + self.dump_time_key_sigs ()
571 stafdef = '\\%sglobal' % self.staffid ()
573 stafdef = stafdef + ' \\' + i
576 str = str + '%s = \\context Staff = %s <\n %s\n >\n' % \
577 (self.staffid (), self.staffid (), stafdef)
586 return [(l[0], l[1])] + ziplist (l[2:])
590 def __init__ (self, number, contents):
593 self.finale = contents[:7]
595 self.notelist = ziplist (contents[7:])
601 self.note_suffix = ''
602 self.chord_suffix = ''
603 self.chord_prefix = ''
610 return self.frame.measure
616 l = (1, self.duration[0])
618 d = 1 << self.duration[1]
620 dotfact = rat_subtract ((2,1), (1,d))
621 mylen = rat_multiply (dotfact, l)
624 mylen = rat_multiply (mylen, self.tuplet.factor())
628 def EDU_duration (self):
629 return self.finale[2]
630 def set_duration (self):
631 self.duration = EDU_to_duration(self.EDU_duration ())
633 def calculate (self):
634 self.find_realpitch ()
637 flag = self.finale[4]
638 if Chord.GRACE_MASK & flag:
642 def find_realpitch (self):
644 meas = self.measure ()
646 if not meas or not meas.global_measure :
647 sys.stderr.write ('note %d not in measure\n' % self.number)
648 elif not meas.global_measure.scale:
649 sys.stderr.write ('note %d: no scale in this measure.' % self.number)
652 for p in self.notelist:
662 scale = meas.global_measure.scale
663 (sn, sa) =scale[rest % 7]
664 sn = sn + (rest - (rest%7)) + 7
666 self.pitches.append ((sn, acc))
667 tiestart = tiestart or (flag & Chord.TIE_START_MASK)
669 self.chord_suffix = self.chord_suffix + ' ~ '
671 REST_MASK = 0x40000000L
672 TIE_START_MASK = 0x40000000L
673 GRACE_MASK = 0x00800000L
675 def ly_string (self):
681 if not (self.finale[4] & Chord.REST_MASK):
684 for p in self.pitches:
689 nn = lily_notename ((n,a))
702 s = s + '%s%d%s' % (nn, self.duration[0], '.'* self.duration[1])
705 s = 'r%d%s' % (self.duration[0] , '.'* self.duration[1])
706 s = self.note_prefix + s + self.note_suffix
707 if len (self.pitches) > 1:
710 s = self.chord_prefix + s + self.chord_suffix
714 def fill_list_to (list, no):
716 Add None to LIST until it contains entry number NO.
718 while len (list) <= no:
719 list.extend ([None] * (no - len(list) + 1))
722 def read_finale_value (str):
724 Pry off one value from STR. The value may be $hex, decimal, or "string".
725 Return: (value, rest-of-STR)
727 while str and str[0] in ' \t\n':
737 while str and str[0] in '0123456789ABCDEF':
742 return (string.atol (hex, 16), str)
746 while str and str[0] <> '"':
751 elif str[0] in '-0123456789':
753 while str and str[0] in '-0123456789':
757 return (string.atoi (dec), str)
759 sys.stderr.write ("Can't convert `%s'\n" % str)
765 def parse_etf_file (fn, tag_dict):
767 """ Read FN, putting ETF info into
768 a giant dictionary. The keys of TAG_DICT indicate which tags
769 to put into the dict.
772 sys.stderr.write ('parsing ... ' )
775 gulp = re.sub ('[\n\r]+', '\n', f.read ())
776 ls = string.split (gulp, '\n^')
779 for k in tag_dict.keys ():
780 etf_file_dict[k] = {}
787 m = re.match ('^([a-zA-Z0-9&]+)\(([^)]+)\)', l)
788 if m and tag_dict.has_key (m.group (1)):
791 indices = tuple (map (string.atoi, string.split (m.group (2), ',')))
792 content = l[m.end (2)+1:]
795 tdict = etf_file_dict[tag]
796 if not tdict.has_key (indices):
802 if tag == 'verse' or tag == 'block':
803 m2 = re.match ('(.*)\^end', content)
805 parsed = [m2.group (1)]
808 (v, content) = read_finale_value (content)
812 tdict [indices].extend (parsed)
814 last_indices = indices
819 # let's not do this: this really confuses when eE happens to be before a ^text.
820 # if last_tag and last_indices:
821 # etf_file_dict[last_tag][last_indices].append (l)
823 sys.stderr.write ('\n')
831 def __init__ (self, name):
832 self.measures = [None]
835 self.tuplets = [None]
838 self.articulations = [None]
839 self.syllables = [None]
841 self.articulation_defs = [None]
846 def get_global_measure (self, no):
847 fill_list_to (self.measures, no)
848 if self.measures[no] == None:
849 self.measures [no] = Global_measure (no)
851 return self.measures[no]
854 def get_staff(self,staffno):
855 fill_list_to (self.staffs, staffno)
856 if self.staffs[staffno] == None:
857 self.staffs[staffno] = Staff (staffno)
859 return self.staffs[staffno]
862 def try_IS (self, indices, contents):
865 def try_BC (self, indices, contents):
867 where = contents[0] / 1024.0
868 def try_TP(self, indices, contents):
871 if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
872 self.tuplets.append (Tuplet (num))
874 self.tuplets[-1].append_finale (contents)
876 def try_IM (self, indices, contents):
879 self.articulations.append (Articulation (a,b,fin))
880 def try_verse (self, indices, contents):
884 body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
885 body = re.sub ("\^[a-z]+", "", body)
886 self.verses.append (Verse (a, body))
887 def try_ve (self,indices, contents):
889 self.syllables.append (Syllable (a,b,contents))
891 def try_eE (self,indices, contents):
893 (prev, next, dur, pos, entryflag, extended, follow) = contents[:7]
895 fill_list_to (self.chords, no)
896 self.chords[no] =Chord (no, contents)
898 def try_Sx(self,indices, contents):
900 fill_list_to (self.slurs, slurno)
901 self.slurs[slurno] = Slur(slurno, contents)
903 def try_IX (self, indices, contents):
910 ix = self.articulation_defs[n]
912 ix = Articulation_def (n,a,b)
913 self.articulation_defs.append (Articulation_def (n, a, b))
915 def try_GF(self, indices, contents):
916 (staffno,measno) = indices
918 st = self.get_staff (staffno)
919 meas = st.get_measure (measno)
920 meas.finale = contents
922 def try_FR(self, indices, contents):
923 frameno = indices [0]
925 startnote = contents[0]
926 endnote = contents[1]
928 fill_list_to (self.frames, frameno)
930 self.frames[frameno] = Frame ((frameno, startnote, endnote))
932 def try_MS (self, indices, contents):
935 meas =self. get_global_measure (measno)
936 meas.set_keysig (keynum)
939 beatlen = contents[3]
940 meas.set_timesig ((beats, beatlen))
942 meas_flag1 = contents[4]
943 meas_flag2 = contents[5]
945 meas.set_flags (meas_flag1, meas_flag2);
963 def parse (self, etf_dict):
964 sys.stderr.write ('reconstructing ...')
967 for (tag,routine) in Etf_file.routine_dict.items ():
968 ks = etf_dict[tag].keys ()
971 routine (self, k, etf_dict[tag][k])
973 sys.stderr.write ('processing ...')
976 self.unthread_entries ()
978 for st in self.staffs[1:]:
982 for m in st.measures[1:]:
988 m.global_measure = self.measures[mno]
990 sys.stderr.write ("Non-existent global measure %d" % mno)
993 frame_obj_list = [None]
994 for frno in m.frames:
995 fr = self.frames[frno]
996 frame_obj_list.append (fr)
998 m.frames = frame_obj_list
999 for fr in frame_obj_list[1:]:
1005 fr.chords = self.get_thread (fr.start, fr.end)
1010 for c in self.chords[1:]:
1014 for f in self.frames[1:]:
1018 for t in self.tuplets[1:]:
1019 t.calculate (self.chords)
1021 for s in self.slurs[1:]:
1023 s.calculate (self.chords)
1025 for s in self.articulations[1:]:
1026 s.calculate (self.chords, self.articulation_defs)
1028 def get_thread (self, startno, endno):
1034 c = self.chords[startno]
1036 sys.stderr.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno, endno))
1040 while c and c.number <> endno:
1052 for s in self.staffs[1:]:
1054 str = str + '\n\n' + s.dump ()
1055 staffs.append ('\\' + s.staffid ())
1058 # should use \addlyrics ?
1060 for v in self.verses[1:]:
1061 str = str + v.dump()
1063 if len (self.verses) > 1:
1064 sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
1067 str = str + '\\score { < %s > } ' % string.join (staffs)
1073 return 'ETF FILE %s %s' % (self.measures, self.entries)
1075 def unthread_entries (self):
1076 for e in self.chords[1:]:
1080 e.prev = self.chords[e.finale[0]]
1081 e.next = self.chords[e.finale[1]]
1084 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1087 sys.stdout.write("""Usage: etf2ly [OPTION]... ETF-FILE
1089 Convert ETF to LilyPond.
1093 -o,--output=FILE set output filename to FILE
1094 -v,--version version information
1096 Enigma Transport Format is a format used by Coda Music Technology's
1097 Finale product. This program will convert a subset of ETF to a
1098 ready-to-use lilypond file.
1100 Report bugs to bug-gnu-music@gnu.org
1102 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>
1105 def print_version ():
1106 sys.stdout.write (r"""etf2ly (GNU lilypond) %s
1108 This is free software. It is covered by the GNU General Public License,
1109 and you are welcome to change it and/or distribute copies of it under
1110 certain conditions. Invoke as `midi2ly --warranty' for more information.
1112 Copyright (c) 2000 by Han-Wen Nienhuys <hanwen@cs.uu.nl>
1117 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
1123 if o== '--help' or o == '-h':
1126 if o == '--version' or o == '-v':
1130 if o == '--output' or o == '-o':
1143 sys.stderr.write ('Processing `%s\'\n' % f)
1145 dict = parse_etf_file (f, Etf_file.routine_dict)
1147 if not out_filename:
1148 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1150 if out_filename == f:
1151 out_filename = os.path.basename (f + '.ly')
1153 sys.stderr.write ('Writing `%s\'' % out_filename)
1158 fo = open (out_filename, 'w')
1159 fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)