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)
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 sys.stderr.write ("\nHuh? Beat duration has a dot? (EDU Duration = %d)" % fdur)
261 self.timesig = (beats, log)
266 def set_keysig (self, finale):
267 k = interpret_finale_key_sig (finale)
268 self.keysignature = k
269 self.scale = find_scale (k)
271 def set_flags (self,flag1, flag2):
273 # flag1 isn't all that interesting.
278 self.repeats.append ('start')
280 self.repeats.append ('stop')
284 self.repeats.append ('bracket')
297 class Articulation_def:
298 def __init__ (self, n, a, b):
299 self.finale_glyph = a & 0xff
304 return articulation_dict[self.finale_glyph]
306 sys.stderr.write ("\nUnknown articulation no. %d" % self.finale_glyph)
307 sys.stderr.write ("\nPlease add an entry to articulation_dict in the Python source")
311 def __init__ (self, a,b, finale):
312 self.definition = finale[0]
315 def calculate (self, chords, defs):
316 c = chords[self.notenumber]
318 adef = defs[self.definition]
322 sys.stderr.write ("\nThis happened on note %d" % self.notenumber)
324 c.note_suffix = '-' + lystr
327 def __init__ (self, a,b , finale):
329 self.syllable = finale[1]
330 self.verse = finale[0]
331 def calculate (self, chords, lyrics):
332 self.chord = chords[self.chordnum]
335 def __init__ (self, number, body):
338 self.split_syllables ()
339 def split_syllables (self):
340 ss = re.split ('(-| +)', self.body)
346 septor = re.sub (" +", "", s)
347 septor = re.sub ("-", " -- ", septor)
348 syls[-1] = syls[-1] + septor
354 self.syllables = syls
359 for s in self.syllables[1:]:
360 line = line + ' ' + s
362 str = str + ' ' * 4 + line + '\n'
365 str = """\nverse%s = \\lyrics {\n %s}\n""" % (encodeint (self.number - 1) ,str)
370 def __init__(self, no):
372 self.frames = [0] * 4
376 self.global_measure = None
383 def calculate (self):
386 if len (self.finale) < 2:
390 self.frames = [fs[0]]
399 def __init__ (self, finale):
402 (number, start, end ) = finale
408 def set_measure (self, m):
411 def calculate (self):
415 for c in self.chords:
416 if c.grace and (lastch == None or (not lastch.grace)):
417 c.chord_prefix = r'\grace {' + c.chord_prefix
418 elif not c.grace and lastch and lastch.grace:
419 lastch.chord_suffix = lastch.chord_suffix + ' } '
426 str = '%% FR(%d)\n' % self.number
427 left = self.measure.global_measure.length ()
431 for c in self.chords:
432 add = c.ly_string () + ' '
433 if len (ln) + len(add) > 72:
434 str = str + ln + '\n'
437 left = rat_subtract (left, c.length ())
442 sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
445 str = str + rat_to_lily_duration (left)
451 return chr ( i + ord ('A'))
454 def __init__ (self, number):
458 def get_measure (self, no):
459 fill_list_to (self.measures, no)
461 if self.measures[no] == None:
463 self.measures [no] =m
466 return self.measures[no]
468 return 'staff' + encodeint (self.number - 1)
469 def layerid (self, l):
470 return self.staffid() + 'layer%s' % chr (l -1 + ord ('A'))
472 def dump_time_key_sigs (self):
478 for m in self.measures[1:]:
479 if not m or not m.valid:
486 if last_key <> g.keysignature:
487 e = e + "\\key %s \\major " % lily_notename (g.keysignature)
488 last_key = g.keysignature
489 if last_time <> g.timesig :
490 e = e + "\\time %d/%d " % g.timesig
491 last_time = g.timesig
493 if 'start' in g.repeats:
494 e = e + ' \\bar "|:" '
497 # we don't attempt voltas since they fail easily.
498 if 0 : # and g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket:
500 if g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket == 'end':
504 if g.bracket == 'start':
507 str = string.join (map (lambda x: '(volta %s)' % x, strs))
509 e = e + ' \\property Score.repeatCommands = #\'(%s) ' % str
514 if last_clef <> m.clef :
515 e = e + '\\clef "%s"' % lily_clef (m.clef)
519 k = k +' ' + rat_to_lily_duration (gap) + '\n'
524 gap = rat_add (gap, g.length ())
525 if 'stop' in g.repeats:
526 k = k + ' \\bar ":|" '
528 k = '%sglobal = \\notes { %s }\n\n ' % (self.staffid (), k)
536 for x in range (1,5): # 4 layers.
541 for m in self.measures[1:]:
542 if not m or not m.valid:
543 sys.stderr.write ("Skipping non-existant or invalid measure\n")
550 sys.stderr.write ("Skipping nonexistent frame %d\n" % x)
551 laystr = laystr + "%% non existent frame %d (skipped) \n" % x
555 laystr = laystr +'} %s {\n ' % rat_to_lily_duration (gap)
557 laystr = laystr + fr.dump ()
559 if m.global_measure :
560 gap = rat_add (gap, m.global_measure.length ())
563 "No global measure for staff %d measure %d\n"
564 % (self.number, m.number))
567 laystr = '%s = \\notes { { %s } }\n\n' % (l, laystr)
571 str = str + self.dump_time_key_sigs ()
572 stafdef = '\\%sglobal' % self.staffid ()
574 stafdef = stafdef + ' \\' + i
577 str = str + '%s = \\context Staff = %s <\n %s\n >\n' % \
578 (self.staffid (), self.staffid (), stafdef)
587 return [(l[0], l[1])] + ziplist (l[2:])
591 def __init__ (self, number, contents):
594 self.finale = contents[:7]
596 self.notelist = ziplist (contents[7:])
602 self.note_suffix = ''
603 self.chord_suffix = ''
604 self.chord_prefix = ''
611 return self.frame.measure
617 l = (1, self.duration[0])
619 d = 1 << self.duration[1]
621 dotfact = rat_subtract ((2,1), (1,d))
622 mylen = rat_multiply (dotfact, l)
625 mylen = rat_multiply (mylen, self.tuplet.factor())
629 def EDU_duration (self):
630 return self.finale[2]
631 def set_duration (self):
632 self.duration = EDU_to_duration(self.EDU_duration ())
634 def calculate (self):
635 self.find_realpitch ()
638 flag = self.finale[4]
639 if Chord.GRACE_MASK & flag:
643 def find_realpitch (self):
645 meas = self.measure ()
647 if not meas or not meas.global_measure :
648 sys.stderr.write ('note %d not in measure\n' % self.number)
649 elif not meas.global_measure.scale:
650 sys.stderr.write ('note %d: no scale in this measure.' % self.number)
653 for p in self.notelist:
663 scale = meas.global_measure.scale
664 (sn, sa) =scale[rest % 7]
665 sn = sn + (rest - (rest%7)) + 7
667 self.pitches.append ((sn, acc))
668 tiestart = tiestart or (flag & Chord.TIE_START_MASK)
670 self.chord_suffix = self.chord_suffix + ' ~ '
672 REST_MASK = 0x40000000L
673 TIE_START_MASK = 0x40000000L
674 GRACE_MASK = 0x00800000L
676 def ly_string (self):
682 if not (self.finale[4] & Chord.REST_MASK):
685 for p in self.pitches:
690 nn = lily_notename ((n,a))
703 s = s + '%s%d%s' % (nn, self.duration[0], '.'* self.duration[1])
706 s = 'r%d%s' % (self.duration[0] , '.'* self.duration[1])
707 s = self.note_prefix + s + self.note_suffix
708 if len (self.pitches) > 1:
711 s = self.chord_prefix + s + self.chord_suffix
715 def fill_list_to (list, no):
717 Add None to LIST until it contains entry number NO.
719 while len (list) <= no:
720 list.extend ([None] * (no - len(list) + 1))
723 def read_finale_value (str):
725 Pry off one value from STR. The value may be $hex, decimal, or "string".
726 Return: (value, rest-of-STR)
728 while str and str[0] in ' \t\n':
738 while str and str[0] in '0123456789ABCDEF':
743 return (string.atol (hex, 16), str)
747 while str and str[0] <> '"':
752 elif str[0] in '-0123456789':
754 while str and str[0] in '-0123456789':
758 return (string.atoi (dec), str)
760 sys.stderr.write ("Can't convert `%s'\n" % str)
766 def parse_etf_file (fn, tag_dict):
768 """ Read FN, putting ETF info into
769 a giant dictionary. The keys of TAG_DICT indicate which tags
770 to put into the dict.
773 sys.stderr.write ('parsing ... ' )
776 gulp = re.sub ('[\n\r]+', '\n', f.read ())
777 ls = string.split (gulp, '\n^')
780 for k in tag_dict.keys ():
781 etf_file_dict[k] = {}
788 m = re.match ('^([a-zA-Z0-9&]+)\(([^)]+)\)', l)
789 if m and tag_dict.has_key (m.group (1)):
792 indices = tuple (map (string.atoi, string.split (m.group (2), ',')))
793 content = l[m.end (2)+1:]
796 tdict = etf_file_dict[tag]
797 if not tdict.has_key (indices):
803 if tag == 'verse' or tag == 'block':
804 m2 = re.match ('(.*)\^end', content)
806 parsed = [m2.group (1)]
809 (v, content) = read_finale_value (content)
813 tdict [indices].extend (parsed)
815 last_indices = indices
820 # let's not do this: this really confuses when eE happens to be before a ^text.
821 # if last_tag and last_indices:
822 # etf_file_dict[last_tag][last_indices].append (l)
824 sys.stderr.write ('\n')
832 def __init__ (self, name):
833 self.measures = [None]
836 self.tuplets = [None]
839 self.articulations = [None]
840 self.syllables = [None]
842 self.articulation_defs = [None]
847 def get_global_measure (self, no):
848 fill_list_to (self.measures, no)
849 if self.measures[no] == None:
850 self.measures [no] = Global_measure (no)
852 return self.measures[no]
855 def get_staff(self,staffno):
856 fill_list_to (self.staffs, staffno)
857 if self.staffs[staffno] == None:
858 self.staffs[staffno] = Staff (staffno)
860 return self.staffs[staffno]
863 def try_IS (self, indices, contents):
866 def try_BC (self, indices, contents):
868 where = contents[0] / 1024.0
869 def try_TP(self, indices, contents):
872 if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
873 self.tuplets.append (Tuplet (num))
875 self.tuplets[-1].append_finale (contents)
877 def try_IM (self, indices, contents):
880 self.articulations.append (Articulation (a,b,fin))
881 def try_verse (self, indices, contents):
885 body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
886 body = re.sub ("\^[a-z]+", "", body)
887 self.verses.append (Verse (a, body))
888 def try_ve (self,indices, contents):
890 self.syllables.append (Syllable (a,b,contents))
892 def try_eE (self,indices, contents):
894 (prev, next, dur, pos, entryflag, extended, follow) = contents[:7]
896 fill_list_to (self.chords, no)
897 self.chords[no] =Chord (no, contents)
899 def try_Sx(self,indices, contents):
901 fill_list_to (self.slurs, slurno)
902 self.slurs[slurno] = Slur(slurno, contents)
904 def try_IX (self, indices, contents):
911 ix = self.articulation_defs[n]
913 ix = Articulation_def (n,a,b)
914 self.articulation_defs.append (Articulation_def (n, a, b))
916 def try_GF(self, indices, contents):
917 (staffno,measno) = indices
919 st = self.get_staff (staffno)
920 meas = st.get_measure (measno)
921 meas.finale = contents
923 def try_FR(self, indices, contents):
924 frameno = indices [0]
926 startnote = contents[0]
927 endnote = contents[1]
929 fill_list_to (self.frames, frameno)
931 self.frames[frameno] = Frame ((frameno, startnote, endnote))
933 def try_MS (self, indices, contents):
936 meas =self. get_global_measure (measno)
937 meas.set_keysig (keynum)
940 beatlen = contents[3]
941 meas.set_timesig ((beats, beatlen))
943 meas_flag1 = contents[4]
944 meas_flag2 = contents[5]
946 meas.set_flags (meas_flag1, meas_flag2);
964 def parse (self, etf_dict):
965 sys.stderr.write ('reconstructing ...')
968 for (tag,routine) in Etf_file.routine_dict.items ():
969 ks = etf_dict[tag].keys ()
972 routine (self, k, etf_dict[tag][k])
974 sys.stderr.write ('processing ...')
977 self.unthread_entries ()
979 for st in self.staffs[1:]:
983 for m in st.measures[1:]:
989 m.global_measure = self.measures[mno]
991 sys.stderr.write ("Non-existent global measure %d" % mno)
994 frame_obj_list = [None]
995 for frno in m.frames:
997 fr = self.frames[frno]
998 frame_obj_list.append (fr)
1000 sys.stderr.write ("\nNon-existent frame %d" % frno)
1002 m.frames = frame_obj_list
1003 for fr in frame_obj_list[1:]:
1009 fr.chords = self.get_thread (fr.start, fr.end)
1014 for c in self.chords[1:]:
1018 for f in self.frames[1:]:
1022 for t in self.tuplets[1:]:
1023 t.calculate (self.chords)
1025 for s in self.slurs[1:]:
1027 s.calculate (self.chords)
1029 for s in self.articulations[1:]:
1030 s.calculate (self.chords, self.articulation_defs)
1032 def get_thread (self, startno, endno):
1038 c = self.chords[startno]
1040 sys.stderr.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno, endno))
1044 while c and c.number <> endno:
1056 for s in self.staffs[1:]:
1058 str = str + '\n\n' + s.dump ()
1059 staffs.append ('\\' + s.staffid ())
1062 # should use \addlyrics ?
1064 for v in self.verses[1:]:
1065 str = str + v.dump()
1067 if len (self.verses) > 1:
1068 sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
1071 str = str + '\\score { < %s > } ' % string.join (staffs)
1077 return 'ETF FILE %s %s' % (self.measures, self.entries)
1079 def unthread_entries (self):
1080 for e in self.chords[1:]:
1084 e.prev = self.chords[e.finale[0]]
1085 e.next = self.chords[e.finale[1]]
1088 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
1091 sys.stdout.write("""Usage: etf2ly [OPTION]... ETF-FILE
1093 Convert ETF to LilyPond.
1097 -o,--output=FILE set output filename to FILE
1098 -v,--version version information
1100 Enigma Transport Format is a format used by Coda Music Technology's
1101 Finale product. This program will convert a subset of ETF to a
1102 ready-to-use lilypond file.
1104 Report bugs to bug-gnu-music@gnu.org
1106 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>
1109 def print_version ():
1110 sys.stdout.write (r"""etf2ly (GNU lilypond) %s
1112 This is free software. It is covered by the GNU General Public License,
1113 and you are welcome to change it and/or distribute copies of it under
1114 certain conditions. Invoke as `midi2ly --warranty' for more information.
1116 Copyright (c) 2000 by Han-Wen Nienhuys <hanwen@cs.uu.nl>
1121 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
1127 if o== '--help' or o == '-h':
1130 if o == '--version' or o == '-v':
1134 if o == '--output' or o == '-o':
1147 sys.stderr.write ('Processing `%s\'\n' % f)
1149 dict = parse_etf_file (f, Etf_file.routine_dict)
1151 if not out_filename:
1152 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1154 if out_filename == f:
1155 out_filename = os.path.basename (f + '.ly')
1157 sys.stderr.write ('Writing `%s\'' % out_filename)
1162 fo = open (out_filename, 'w')
1163 fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)