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)
27 program_name = 'etf2ly'
28 version = '@TOPLEVEL_VERSION@'
29 if version == '@' + 'TOPLEVEL_VERSION' + '@':
30 version = '(unknown version)' # uGUHGUHGHGUGH
39 finale_clefs= ['treble', 'alto', 'tenor', 'bass', 'percussion', 'treble8vb', 'bass8vb', 'baritone']
42 return finale_clefs[fin]
45 return open (f).read ()
47 # notename 0 == central C
48 distances = [0, 2, 4, 5, 7, 9, 11, 12]
49 def semitones (name, acc):
50 return (name / 7 ) * 12 + distances[name % 7] + acc
52 # represent pitches as (notename, alteration), relative to C-major scale
53 def transpose(orig, delta):
57 old_pitch =semitones (oname, oacc)
58 delta_pitch = semitones (dname, dacc)
59 nname = (oname + dname)
61 new_pitch = semitones (nname, nacc)
63 nacc = nacc - (new_pitch - old_pitch - delta_pitch)
69 # find transposition of C-major scale that belongs here.
70 def interpret_finale_key_sig (finale_id):
72 if 0 <= finale_id < 7:
74 p = transpose (p, (4,0)) # a fifth up
75 finale_id = finale_id - 1
76 elif 248 < finale_id <= 255:
77 while finale_id < 256:
78 p = transpose (p, (3,0))
79 finale_id = finale_id + 1
85 def find_scale (transposition):
86 cscale = map (lambda x: (x,0), range (0,7))
87 trscale = map(lambda x, k=transposition: transpose(x, k), cscale)
90 def EDU_to_duration (edu):
105 def rat_to_lily_duration (rat):
109 while d and d % 2 == 0:
110 basedur = basedur << 1
113 str = 's%d' % basedur
115 str = str + '*%d' % n
117 str = str + '/%d' % d
132 def rat_simplify (r):
143 def rat_multiply (a,b):
147 return rat_simplify ((x*p, y*q))
153 return rat_simplify ((x*q + p*y, y*q))
161 def rat_subtract (a,b ):
162 return rat_add (a, rat_neg (b))
164 def lily_notename (tuple2):
166 nn = chr ((n+ 2)%7 + ord ('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):
223 def append_entry (self, finale_e):
224 self.finale.append (finale_e)
226 def calculate (self, chords):
227 startnote = self.finale[0][5]
228 endnote = self.finale[3][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
252 return `self.finale `
254 def set_timesig (self, finale):
255 (beats, fdur) = finale
256 (log, dots) = EDU_to_duration (fdur)
258 self.timesig = (beats, log)
263 def set_keysig (self, finale):
264 k = interpret_finale_key_sig (finale)
265 self.keysignature = k
266 self.scale = find_scale (k)
276 18: '"arp"' , # arpeggio
280 def __init__ (self, a,b, finale):
281 self.type = finale[0]
283 def calculate (self, chords):
284 c = chords[self.notenumber]
287 a = articulation_dict[self.type]
289 sys.stderr.write ("\nUnknown articulation no. %d on note no. %d" % (self.type, self.notenumber))
292 c.note_suffix = '-' + a + c.note_suffix
295 def __init__ (self, a,b , finale):
297 self.syllable = finale[1]
298 self.verse = finale[0]
299 def calculate (self, chords, lyrics):
300 self.chord = chords[self.chordnum]
303 def __init__ (self, number, body):
306 self.split_syllables ()
307 def split_syllables (self):
308 ss = re.split ('(-| +)', self.body)
314 septor = re.sub (" +", "", s)
315 septor = re.sub ("-", " -- ", septor)
316 syls[-1] = syls[-1] + septor
322 self.syllables = syls
327 for s in self.syllables[1:]:
328 line = line + ' ' + s
330 str = str + ' ' * 4 + line + '\n'
333 str = """\nverse%s = \\lyrics {\n %s}\n""" % (encodeint (self.number - 1) ,str)
338 def __init__(self, no):
340 self.frames = [0] * 4
344 self.global_measure = None
347 def add_finale_entry (self, entry):
348 self.finale.append (entry)
350 def calculate (self):
351 if len (self.finale) < 2:
352 sys.stderr.write ("Measure %d in staff %d has incomplete information.\n" % (self.number, self.staff.number))
359 self.clef = string.atoi (f0[0])
360 self.flags = string.atoi (f0[1])
361 fs = map (string.atoi, list (f0[2:]) + [f1[0]])
366 def __init__ (self, finale):
369 (number, start, end ) = finale
375 def set_measure (self, m):
378 def calculate (self):
382 for c in self.chords:
383 if c.grace and (lastch == None or (not lastch.grace)):
384 c.chord_prefix = r'\grace {' + c.chord_prefix
385 elif not c.grace and lastch and lastch.grace:
386 lastch.chord_suffix = lastch.chord_suffix + ' } '
393 str = '%% FR(%d)\n' % self.number
394 left = self.measure.global_measure.length ()
398 for c in self.chords:
399 add = c.ly_string () + ' '
400 if len (ln) + len(add) > 72:
401 str = str + ln + '\n'
404 left = rat_subtract (left, c.length ())
409 sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
412 str = str + rat_to_lily_duration (left)
418 return chr ( i + ord ('A'))
421 def __init__ (self, number):
425 def get_measure (self, no):
426 if len (self.measures) <= no:
427 self.measures = self.measures + [None]* (1 + no - len (self.measures))
429 if self.measures[no] == None:
431 self.measures [no] =m
435 return self.measures[no]
437 return 'staff' + encodeint (self.number - 1)
438 def layerid (self, l):
439 return self.staffid() + 'layer%s' % chr (l -1 + ord ('A'))
441 def dump_time_key_sigs (self):
447 for m in self.measures[1:]:
453 if last_key <> g.keysignature:
454 e = e + "\\key %s \\major; " % lily_notename (g.keysignature)
455 last_key = g.keysignature
456 if last_time <> g.timesig :
457 e = e + "\\time %d/%d; " % g.timesig
458 last_time = g.timesig
459 if last_clef <> m.clef :
460 e = e + '\\clef %s;' % lily_clef (m.clef)
464 k = k +' ' + rat_to_lily_duration (gap) + '\n'
468 gap = rat_add (gap, g.length ())
471 k = '%sglobal = \\notes { %s }\n\n ' % (self.staffid (), k)
479 for x in range (1,5): # 4 layers.
484 for m in self.measures[1:]:
493 laystr = laystr +'} %s {\n ' % rat_to_lily_duration (gap)
495 laystr = laystr + fr.dump ()
497 gap = rat_add (gap, m.global_measure.length ())
501 laystr = '%s = \\notes { { %s } }\n\n' % (l, laystr)
505 str = str + self.dump_time_key_sigs ()
506 stafdef = '\\%sglobal' % self.staffid ()
508 stafdef = stafdef + ' \\' + i
511 str = str + '%s = \\context Staff = %s <\n %s\n >\n' % \
512 (self.staffid (), self.staffid (), stafdef)
519 def __init__ (self, finale_entry):
522 self.finale = finale_entry
527 self.note_suffix = ''
528 self.chord_suffix = ''
529 self.chord_prefix = ''
536 return self.frame.measure
542 l = (1, self.duration[0])
544 d = 1 << self.duration[1]
546 dotfact = rat_subtract ((2,1), (1,d))
547 mylen = rat_multiply (dotfact, l)
550 mylen = rat_multiply (mylen, self.tuplet.factor())
554 return self.finale[0][0]
556 def EDU_duration (self):
557 return self.finale[0][3]
558 def set_duration (self):
559 self.duration = EDU_to_duration(self.EDU_duration ())
560 def calculate (self):
561 self.find_realpitch ()
564 flag = self.finale[0][5]
565 if Chord.GRACE_MASK & flag:
569 def find_realpitch (self):
571 ((no, prev, next, dur, pos, entryflag, extended, follow), notelist) = self.finale
573 meas = self.measure ()
575 if not meas or not meas.global_measure :
576 print 'note %d not in measure' % self.number ()
577 elif not meas.global_measure.scale:
578 print 'note %d: no scale in this measure.' % self.number ()
588 scale = meas.global_measure.scale
589 (sn, sa) =scale[rest % 7]
590 sn = sn + (rest - (rest%7)) + 7
592 self.pitches.append ((sn, acc))
593 tiestart = tiestart or (flag & Chord.TIE_START_MASK)
595 self.chord_suffix = self.chord_suffix + ' ~ '
597 REST_MASK = 0x40000000L
598 TIE_START_MASK = 0x40000000L
599 GRACE_MASK = 0x00800000L
601 def ly_string (self):
606 if not (self.finale[0][5] & Chord.REST_MASK):
609 for p in self.pitches:
614 nn = lily_notename ((n,a))
627 s = s + '%s%d%s' % (nn, self.duration[0], '.'* self.duration[1])
630 s = 'r%d%s' % (self.duration[0] , '.'* self.duration[1])
631 s = self.note_prefix + s + self.note_suffix
632 if len (self.pitches) > 1:
635 s = self.chord_prefix + s + self.chord_suffix
638 GFre = re.compile(r"""^\^GF\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
639 BCre = re.compile (r"""^\^BC\(([0-9-]+)\) ([0-9-]+) .*$""")
640 eEre = re.compile(r"""^\^eE\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) \$([0-9A-Fa-f]+) ([0-9-]+) ([0-9-]+)""")
641 FRre = re.compile (r"""^\^FR\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
642 MSre = re.compile (r"""^\^MS\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
643 note_re = re.compile (r"""^ +([0-9-]+) \$([A-Fa-f0-9]+)""")
644 Sxre = re.compile (r"""^\^Sx\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
645 IMre = re.compile (r"""^\^IM\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
646 vere = re.compile(r"""^\^(ve|ch|se)\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
647 versere = re.compile(r"""^\^verse\(([0-9]+)\)(.*)\^end""")
649 TPre = re.compile(r"""^\^TP\(([0-9]+),([0-9]+)\) *([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
653 def __init__ (self, name):
654 self.measures = [None]
655 self.entries = [None]
658 self.tuplets = [None]
661 self.articulations = [None]
662 self.syllables = [None]
668 def get_global_measure (self, no):
669 if len (self.measures) <= no:
670 self.measures = self.measures + [None]* (1 + no - len (self.measures))
672 if self.measures[no] == None:
673 self.measures [no] = Global_measure (no)
675 return self.measures[no]
678 def get_staff(self,staffno):
679 if len (self.staffs) <= staffno:
680 self.staffs = self.staffs + [None] * (1 + staffno - len (self.staffs))
682 if self.staffs[staffno] == None:
683 self.staffs[staffno] = Staff (staffno)
685 return self.staffs[staffno]
688 def try_IS (self, l):
691 def try_BC (self, l):
694 bn = string.atoi (m.group (1))
695 where = string.atoi (m.group (2)) / 1024.0
700 (nil, num) = map (string.atoi, (m.groups ()[0:2]))
701 entries = map (string.atoi, (m.groups ()[2:]))
703 if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
704 self.tuplets.append (Tuplet (num))
706 self.tuplets[-1].append_finale (entries)
708 def try_IM (self, l):
711 a = string.atoi (m.group (1))
712 b = string.atoi (m.group (2))
714 fin = map (string.atoi, m.groups ()[2:])
716 self.articulations.append (Articulation (a,b,fin))
718 def try_verse (self,l):
719 m = versere .match (l)
721 a = string.atoi (m.group (1))
724 body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
725 body = re.sub ("\^[a-z]+", "", body)
726 self.verses.append (Verse (a, body))
732 a = string.atoi (m.group (1))
733 b = string.atoi (m.group (2))
735 fin = map (string.atoi, m.groups ()[2:])
737 self.syllables.append (Syllable (a,b,fin))
739 def try_eE (self, l):
743 (no, prev, next, dur, pos, entryflag, extended, follow) = tup
744 (no, prev, next, dur, pos,extended, follow) \
745 = tuple (map (string.atoi, [no,prev,next,dur,pos,extended,follow]))
747 entryflag = string.atol (entryflag,16)
748 if no > len (self.entries):
749 sys.stderr.write ("\nHuh? Entry number to large,\nexpected %d got %d. Filling with void entries.\n" % (len(self.entries), no ))
750 while len (self.entries) <> no:
751 c = ((len (self.entries), 0, 0, 0, 0, 0L, 0, 0), [])
752 self.entries.append (c)
754 current_entry = ((no, prev, next, dur, pos, entryflag, extended, follow), [])
755 self.entries.append (current_entry)
761 slurno = string.atoi (m.group (1))
763 if len (self.slurs) == slurno:
764 self.slurs.append (Slur (slurno))
766 params = list (m.groups ()[1:])
767 params = map (string.atoi, params)
768 self.slurs[-1].append_entry (params)
774 (staffno,measno) = m.groups ()[0:2]
775 s = string.atoi (staffno)
776 me = string.atoi (measno)
778 entry = m.groups () [2:]
779 st = self.get_staff (s)
780 meas = st.get_measure (me)
781 meas.add_finale_entry (entry)
787 (frameno, startnote, endnote, foo, bar) = m.groups ()
788 (frameno, startnote, endnote) = tuple (map (string.atoi, [frameno, startnote, endnote]))
789 if frameno > len (self.frames):
790 sys.stderr.write ("Frame no %d missing, filling up to %d\n" % (len(self.frames), frameno))
791 while frameno <> len (self.frames):
792 self.frames.append (Frame ((len (self.frames), 0,0) ))
794 self.frames.append (Frame ((frameno, startnote, endnote)))
797 def try_MS (self, l):
800 measno = string.atoi (m.group (1))
801 keynum = string.atoi (m.group (3))
802 meas =self. get_global_measure (measno)
803 meas.set_keysig (keynum)
805 beats = string.atoi (m.group (4))
806 beatlen = string.atoi (m.group (5))
807 meas.set_timesig ((beats, beatlen))
811 def try_note (self, l):
812 m = note_re.match (l)
814 (pitch, flag) = m.groups ()
815 pitch = string.atoi (pitch)
816 flag = string.atol (flag,16)
817 self.entries[-1][1].append ((pitch,flag))
819 def parse (self, name):
820 sys.stderr.write ('parsing ...')
823 gulp = open (name).read ()
825 gulp = re.sub ('[\n\r]+', '\n', gulp)
826 ls = string.split (gulp, '\n')
837 m = self.try_note (l)
847 m = self.try_verse (l)
849 sys.stderr.write ('processing ...')
852 self.unthread_entries ()
854 for st in self.staffs[1:]:
858 for m in st.measures[1:]:
862 m.global_measure = self.measures[mno]
865 frame_obj_list = [None]
866 for frno in m.frames:
867 fr = self.frames[frno]
868 frame_obj_list.append (fr)
870 m.frames = frame_obj_list
871 for fr in frame_obj_list[1:]:
877 fr.chords = self.get_thread (fr.start, fr.end)
882 for c in self.chords[1:]:
885 for f in self.frames[1:]:
888 for t in self.tuplets[1:]:
889 t.calculate (self.chords)
891 for s in self.slurs [1:]:
892 s.calculate (self.chords)
893 for s in self.articulations[1:]:
894 s.calculate (self.chords)
896 def get_thread (self, startno, endno):
899 c = self.chords[startno]
900 while c and c.number () <> endno:
912 for s in self.staffs[1:]:
914 str = str + '\n\n' + s.dump ()
915 staffs.append ('\\' + s.staffid ())
918 # should use \addlyrics ?
920 for v in self.verses[1:]:
923 if len (self.verses) > 1:
924 sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
927 str = str + '\\score { < %s > } ' % string.join (staffs)
933 return 'ETF FILE %s %s' % (self.measures, self.entries)
935 def unthread_entries (self):
937 for e in self.entries[1:]:
938 self.chords.append (Chord (e))
940 for e in self.chords[1:]:
941 e.prev = self.chords[e.finale[0][1]]
942 e.next = self.chords[e.finale[0][2]]
945 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
948 print """Usage: etf2ly [OPTION]... ETF-FILE
950 Convert ETF to LilyPond.
954 -o,--output=FILE set output filename to FILE
955 -v,--version version information
957 Enigma Transport Format is a format used by Coda Music Technology's
958 Finale product. This program will convert a subset of ETF to a
959 ready-to-use lilypond file.
961 Report bugs to bug-gnu-music@gnu.org
963 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>
966 def print_version ():
967 print r"""etf2ly (GNU lilypond) %s
969 This is free software. It is covered by the GNU General Public License,
970 and you are welcome to change it and/or distribute copies of it under
971 certain conditions. Invoke as `midi2ly --warranty' for more information.
973 Copyright (c) 2000 by Han-Wen Nienhuys <hanwen@cs.uu.nl>
978 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
984 if o== '--help' or o == '-h':
987 if o == '--version' or o == '-v':
991 if o == '--output' or o == '-o':
999 # header['tagline'] = 'Lily was here %s -- automatically converted from ABC' % version
1004 sys.stderr.write ('Processing `%s\'\n' % f)
1006 if not out_filename:
1007 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1009 if out_filename == f:
1010 out_filename = os.path.basename (f + '.ly')
1012 sys.stderr.write ('Writing `%s\'' % out_filename)
1017 fo = open (out_filename, 'w')
1018 fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)