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 # * automatic `deletion' of invalid items
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', 'treble8vb', 'bass8vb', 'baritone']
44 return finale_clefs[fin]
47 return open (f).read ()
49 # notename 0 == central C
50 distances = [0, 2, 4, 5, 7, 9, 11, 12]
51 def semitones (name, acc):
52 return (name / 7 ) * 12 + distances[name % 7] + acc
54 # represent pitches as (notename, alteration), relative to C-major scale
55 def transpose(orig, delta):
59 old_pitch =semitones (oname, oacc)
60 delta_pitch = semitones (dname, dacc)
61 nname = (oname + dname)
63 new_pitch = semitones (nname, nacc)
65 nacc = nacc - (new_pitch - old_pitch - delta_pitch)
71 # find transposition of C-major scale that belongs here.
72 def interpret_finale_key_sig (finale_id):
74 if 0 <= finale_id < 7:
76 p = transpose (p, (4,0)) # a fifth up
77 finale_id = finale_id - 1
78 elif 248 < finale_id <= 255:
79 while finale_id < 256:
80 p = transpose (p, (3,0))
81 finale_id = finale_id + 1
87 def find_scale (transposition):
88 cscale = map (lambda x: (x,0), range (0,7))
89 trscale = map(lambda x, k=transposition: transpose(x, k), cscale)
92 def EDU_to_duration (edu):
107 def rat_to_lily_duration (rat):
111 while d and d % 2 == 0:
112 basedur = basedur << 1
115 str = 's%d' % basedur
117 str = str + '*%d' % n
119 str = str + '/%d' % d
134 def rat_simplify (r):
145 def rat_multiply (a,b):
149 return rat_simplify ((x*p, y*q))
155 return rat_simplify ((x*q + p*y, y*q))
163 def rat_subtract (a,b ):
164 return rat_add (a, rat_neg (b))
166 def lily_notename (tuple2):
168 nn = chr ((n+ 2)%7 + ord ('a'))
183 def __init__ (self, number):
184 self.start_note = number
187 def append_finale (self, fin):
188 self.finale.append (fin)
191 n = self.finale[0][2]*self.finale[0][3]
192 d = self.finale[0][0]*self.finale[0][1]
193 return rat_simplify( (n, d))
195 def dump_start (self):
196 return '\\times %d/%d { ' % self.factor ()
201 def calculate (self, chords):
202 edu_left = self.finale[0][0] * self.finale[0][1]
204 startch = chords[self.start_note]
206 while c and edu_left:
209 c.chord_prefix = self.dump_start () + c.chord_prefix
212 edu_left = edu_left - c.EDU_duration ()
214 c.chord_suffix = c.chord_suffix+ self.dump_end ()
218 sys.stderr.write ("\nHuh? Tuplet starting at entry %d was too short." % self.start_note)
221 def __init__ (self, number):
225 def append_entry (self, finale_e):
226 self.finale.append (finale_e)
228 def calculate (self, chords):
229 startnote = self.finale[0][5]
230 endnote = self.finale[3][2]
232 cs = chords[startnote]
238 cs.note_suffix = '(' + cs.note_suffix
239 ce.note_prefix = ce.note_prefix + ')'
241 sys.stderr.write ("""\nHuh? Slur no %d between (%d,%d), with %d notes""" % (self.number, startnote, endnote, len (chords)))
244 class Global_measure:
245 def __init__ (self, number):
248 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)
278 18: '"arp"' , # arpeggio
282 def __init__ (self, a,b, finale):
283 self.type = finale[0]
285 def calculate (self, chords):
286 c = chords[self.notenumber]
289 a = articulation_dict[self.type]
291 sys.stderr.write ("\nUnknown articulation no. %d on note no. %d" % (self.type, self.notenumber))
294 c.note_suffix = '-' + a + c.note_suffix
297 def __init__ (self, a,b , finale):
299 self.syllable = finale[1]
300 self.verse = finale[0]
301 def calculate (self, chords, lyrics):
302 self.chord = chords[self.chordnum]
305 def __init__ (self, number, body):
308 self.split_syllables ()
309 def split_syllables (self):
310 ss = re.split ('(-| +)', self.body)
316 septor = re.sub (" +", "", s)
317 septor = re.sub ("-", " -- ", septor)
318 syls[-1] = syls[-1] + septor
324 self.syllables = syls
329 for s in self.syllables[1:]:
330 line = line + ' ' + s
332 str = str + ' ' * 4 + line + '\n'
335 str = """\nverse%s = \\lyrics {\n %s}\n""" % (encodeint (self.number - 1) ,str)
340 def __init__(self, no):
342 self.frames = [0] * 4
346 self.global_measure = None
350 def add_finale_entry (self, entry):
351 self.finale.append (entry)
355 def calculate (self):
359 if len (self.finale) < 2:
361 fs = map (string.atoi, list (fs))
363 self.frames = [fs[0]]
365 fs = self.finale[0:2]
367 fs = map (string.atoi, list (fs))
374 def __init__ (self, finale):
377 (number, start, end ) = finale
383 def set_measure (self, m):
386 def calculate (self):
390 for c in self.chords:
391 if c.grace and (lastch == None or (not lastch.grace)):
392 c.chord_prefix = r'\grace {' + c.chord_prefix
393 elif not c.grace and lastch and lastch.grace:
394 lastch.chord_suffix = lastch.chord_suffix + ' } '
401 str = '%% FR(%d)\n' % self.number
402 left = self.measure.global_measure.length ()
406 for c in self.chords:
407 add = c.ly_string () + ' '
408 if len (ln) + len(add) > 72:
409 str = str + ln + '\n'
412 left = rat_subtract (left, c.length ())
417 sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
420 str = str + rat_to_lily_duration (left)
426 return chr ( i + ord ('A'))
429 def __init__ (self, number):
433 def get_measure (self, no):
434 if len (self.measures) <= no:
435 self.measures = self.measures + [None]* (1 + no - len (self.measures))
437 if self.measures[no] == None:
439 self.measures [no] =m
443 return self.measures[no]
445 return 'staff' + encodeint (self.number - 1)
446 def layerid (self, l):
447 return self.staffid() + 'layer%s' % chr (l -1 + ord ('A'))
449 def dump_time_key_sigs (self):
455 for m in self.measures[1:]:
456 if not m or not m.valid:
461 if last_key <> g.keysignature:
462 e = e + "\\key %s \\major; " % lily_notename (g.keysignature)
463 last_key = g.keysignature
464 if last_time <> g.timesig :
465 e = e + "\\time %d/%d; " % g.timesig
466 last_time = g.timesig
467 if last_clef <> m.clef :
468 e = e + '\\clef %s;' % lily_clef (m.clef)
472 k = k +' ' + rat_to_lily_duration (gap) + '\n'
476 gap = rat_add (gap, g.length ())
479 k = '%sglobal = \\notes { %s }\n\n ' % (self.staffid (), k)
487 for x in range (1,5): # 4 layers.
492 for m in self.measures[1:]:
493 if not m or not m.valid:
505 laystr = laystr +'} %s {\n ' % rat_to_lily_duration (gap)
507 laystr = laystr + fr.dump ()
509 gap = rat_add (gap, m.global_measure.length ())
513 laystr = '%s = \\notes { { %s } }\n\n' % (l, laystr)
517 str = str + self.dump_time_key_sigs ()
518 stafdef = '\\%sglobal' % self.staffid ()
520 stafdef = stafdef + ' \\' + i
523 str = str + '%s = \\context Staff = %s <\n %s\n >\n' % \
524 (self.staffid (), self.staffid (), stafdef)
531 def __init__ (self, finale_entry):
534 self.finale = finale_entry
539 self.note_suffix = ''
540 self.chord_suffix = ''
541 self.chord_prefix = ''
548 return self.frame.measure
554 l = (1, self.duration[0])
556 d = 1 << self.duration[1]
558 dotfact = rat_subtract ((2,1), (1,d))
559 mylen = rat_multiply (dotfact, l)
562 mylen = rat_multiply (mylen, self.tuplet.factor())
566 return self.finale[0][0]
568 def EDU_duration (self):
569 return self.finale[0][3]
570 def set_duration (self):
571 self.duration = EDU_to_duration(self.EDU_duration ())
572 def calculate (self):
573 self.find_realpitch ()
576 flag = self.finale[0][5]
577 if Chord.GRACE_MASK & flag:
581 def find_realpitch (self):
583 ((no, prev, next, dur, pos, entryflag, extended, follow), notelist) = self.finale
585 meas = self.measure ()
587 if not meas or not meas.global_measure :
588 print 'note %d not in measure' % self.number ()
589 elif not meas.global_measure.scale:
590 print 'note %d: no scale in this measure.' % self.number ()
600 scale = meas.global_measure.scale
601 (sn, sa) =scale[rest % 7]
602 sn = sn + (rest - (rest%7)) + 7
604 self.pitches.append ((sn, acc))
605 tiestart = tiestart or (flag & Chord.TIE_START_MASK)
607 self.chord_suffix = self.chord_suffix + ' ~ '
609 REST_MASK = 0x40000000L
610 TIE_START_MASK = 0x40000000L
611 GRACE_MASK = 0x00800000L
613 def ly_string (self):
618 if not (self.finale[0][5] & Chord.REST_MASK):
621 for p in self.pitches:
626 nn = lily_notename ((n,a))
639 s = s + '%s%d%s' % (nn, self.duration[0], '.'* self.duration[1])
642 s = 'r%d%s' % (self.duration[0] , '.'* self.duration[1])
643 s = self.note_prefix + s + self.note_suffix
644 if len (self.pitches) > 1:
647 s = self.chord_prefix + s + self.chord_suffix
650 GFre = re.compile(r"""^\^GF\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
651 BCre = re.compile (r"""^\^BC\(([0-9-]+)\) ([0-9-]+) .*$""")
652 eEre = re.compile(r"""^\^eE\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) \$([0-9A-Fa-f]+) ([0-9-]+) ([0-9-]+)""")
653 FRre = re.compile (r"""^\^FR\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
654 MSre = re.compile (r"""^\^MS\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
655 note_re = re.compile (r"""^ +([0-9-]+) \$([A-Fa-f0-9]+)""")
656 Sxre = re.compile (r"""^\^Sx\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
657 IMre = re.compile (r"""^\^IM\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
658 vere = re.compile(r"""^\^(ve|ch|se)\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
659 versere = re.compile(r"""^\^verse\(([0-9]+)\)(.*)\^end""")
661 TPre = re.compile(r"""^\^TP\(([0-9]+),([0-9]+)\) *([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
665 def __init__ (self, name):
666 self.measures = [None]
667 self.entries = [None]
670 self.tuplets = [None]
673 self.articulations = [None]
674 self.syllables = [None]
680 def get_global_measure (self, no):
681 if len (self.measures) <= no:
682 self.measures = self.measures + [None]* (1 + no - len (self.measures))
684 if self.measures[no] == None:
685 self.measures [no] = Global_measure (no)
687 return self.measures[no]
690 def get_staff(self,staffno):
691 if len (self.staffs) <= staffno:
692 self.staffs = self.staffs + [None] * (1 + staffno - len (self.staffs))
694 if self.staffs[staffno] == None:
695 self.staffs[staffno] = Staff (staffno)
697 return self.staffs[staffno]
700 def try_IS (self, l):
703 def try_BC (self, l):
706 bn = string.atoi (m.group (1))
707 where = string.atoi (m.group (2)) / 1024.0
712 (nil, num) = map (string.atoi, (m.groups ()[0:2]))
713 entries = map (string.atoi, (m.groups ()[2:]))
715 if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
716 self.tuplets.append (Tuplet (num))
718 self.tuplets[-1].append_finale (entries)
720 def try_IM (self, l):
723 a = string.atoi (m.group (1))
724 b = string.atoi (m.group (2))
726 fin = map (string.atoi, m.groups ()[2:])
728 self.articulations.append (Articulation (a,b,fin))
730 def try_verse (self,l):
731 m = versere .match (l)
733 a = string.atoi (m.group (1))
736 body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
737 body = re.sub ("\^[a-z]+", "", body)
738 self.verses.append (Verse (a, body))
744 a = string.atoi (m.group (1))
745 b = string.atoi (m.group (2))
747 fin = map (string.atoi, m.groups ()[2:])
749 self.syllables.append (Syllable (a,b,fin))
751 def try_eE (self, l):
755 (no, prev, next, dur, pos, entryflag, extended, follow) = tup
756 (no, prev, next, dur, pos,extended, follow) \
757 = tuple (map (string.atoi, [no,prev,next,dur,pos,extended,follow]))
759 entryflag = string.atol (entryflag,16)
760 if no > len (self.entries):
761 sys.stderr.write ("\nHuh? Entry number to large,\nexpected %d got %d. Filling with void entries.\n" % (len(self.entries), no ))
762 while len (self.entries) <> no:
763 c = ((len (self.entries), 0, 0, 0, 0, 0L, 0, 0), [])
764 self.entries.append (c)
766 current_entry = ((no, prev, next, dur, pos, entryflag, extended, follow), [])
767 self.entries.append (current_entry)
773 slurno = string.atoi (m.group (1))
777 sl = self.slur_dict[slurno]
780 self.slur_dict[slurno] = sl
782 params = list (m.groups ()[1:])
783 params = map (string.atoi, params)
784 sl.append_entry (params)
790 (staffno,measno) = m.groups ()[0:2]
791 s = string.atoi (staffno)
792 me = string.atoi (measno)
794 entry = m.groups () [2:]
795 st = self.get_staff (s)
796 meas = st.get_measure (me)
797 meas.add_finale_entry (entry)
803 (frameno, startnote, endnote, foo, bar) = m.groups ()
804 (frameno, startnote, endnote) = tuple (map (string.atoi, [frameno, startnote, endnote]))
805 if frameno > len (self.frames):
806 sys.stderr.write ("Frame no %d missing, filling up to %d\n" % (len(self.frames), frameno))
807 while frameno <> len (self.frames):
808 self.frames.append (Frame ((len (self.frames), 0,0) ))
810 self.frames.append (Frame ((frameno, startnote, endnote)))
813 def try_MS (self, l):
816 measno = string.atoi (m.group (1))
817 keynum = string.atoi (m.group (3))
818 meas =self. get_global_measure (measno)
819 meas.set_keysig (keynum)
821 beats = string.atoi (m.group (4))
822 beatlen = string.atoi (m.group (5))
823 meas.set_timesig ((beats, beatlen))
827 def try_note (self, l):
828 m = note_re.match (l)
830 (pitch, flag) = m.groups ()
831 pitch = string.atoi (pitch)
832 flag = string.atol (flag,16)
833 self.entries[-1][1].append ((pitch,flag))
835 def parse (self, name):
836 sys.stderr.write ('parsing ...')
839 gulp = open (name).read ()
841 gulp = re.sub ('[\n\r]+', '\n', gulp)
842 ls = string.split (gulp, '\n')
853 m = self.try_note (l)
863 m = self.try_verse (l)
865 sys.stderr.write ('processing ...')
868 self.unthread_entries ()
870 for st in self.staffs[1:]:
874 for m in st.measures[1:]:
880 m.global_measure = self.measures[mno]
882 sys.stderr.write ("non-existent global measure %d" % mno)
885 frame_obj_list = [None]
886 for frno in m.frames:
887 fr = self.frames[frno]
888 frame_obj_list.append (fr)
890 m.frames = frame_obj_list
891 for fr in frame_obj_list[1:]:
897 fr.chords = self.get_thread (fr.start, fr.end)
902 for c in self.chords[1:]:
905 for f in self.frames[1:]:
908 for t in self.tuplets[1:]:
909 t.calculate (self.chords)
911 for s in self.slur_dict.values():
912 s.calculate (self.chords)
913 for s in self.articulations[1:]:
914 s.calculate (self.chords)
916 def get_thread (self, startno, endno):
922 c = self.chords[startno]
924 sys.stderr.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno, endno))
928 while c and c.number () <> endno:
940 for s in self.staffs[1:]:
942 str = str + '\n\n' + s.dump ()
943 staffs.append ('\\' + s.staffid ())
946 # should use \addlyrics ?
948 for v in self.verses[1:]:
951 if len (self.verses) > 1:
952 sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
955 str = str + '\\score { < %s > } ' % string.join (staffs)
961 return 'ETF FILE %s %s' % (self.measures, self.entries)
963 def unthread_entries (self):
965 for e in self.entries[1:]:
966 self.chords.append (Chord (e))
968 for e in self.chords[1:]:
969 e.prev = self.chords[e.finale[0][1]]
970 e.next = self.chords[e.finale[0][2]]
973 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
976 print """Usage: etf2ly [OPTION]... ETF-FILE
978 Convert ETF to LilyPond.
982 -o,--output=FILE set output filename to FILE
983 -v,--version version information
985 Enigma Transport Format is a format used by Coda Music Technology's
986 Finale product. This program will convert a subset of ETF to a
987 ready-to-use lilypond file.
989 Report bugs to bug-gnu-music@gnu.org
991 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>
994 def print_version ():
995 print r"""etf2ly (GNU lilypond) %s
997 This is free software. It is covered by the GNU General Public License,
998 and you are welcome to change it and/or distribute copies of it under
999 certain conditions. Invoke as `midi2ly --warranty' for more information.
1001 Copyright (c) 2000 by Han-Wen Nienhuys <hanwen@cs.uu.nl>
1006 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
1012 if o== '--help' or o == '-h':
1015 if o == '--version' or o == '-v':
1019 if o == '--output' or o == '-o':
1031 sys.stderr.write ('Processing `%s\'\n' % f)
1033 if not out_filename:
1034 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1036 if out_filename == f:
1037 out_filename = os.path.basename (f + '.ly')
1039 sys.stderr.write ('Writing `%s\'' % out_filename)
1044 fo = open (out_filename, 'w')
1045 fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)