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', '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):
232 def append_entry (self, finale_e):
233 self.finale.append (finale_e)
235 def calculate (self, chords):
236 startnote = self.finale[0][5]
237 endnote = self.finale[3][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
261 return `self.finale `
263 def set_timesig (self, finale):
264 (beats, fdur) = finale
265 (log, dots) = EDU_to_duration (fdur)
267 self.timesig = (beats, log)
272 def set_keysig (self, finale):
273 k = interpret_finale_key_sig (finale)
274 self.keysignature = k
275 self.scale = find_scale (k)
285 18: '"arp"' , # arpeggio
289 def __init__ (self, a,b, finale):
290 self.type = finale[0]
292 def calculate (self, chords):
293 c = chords[self.notenumber]
296 a = articulation_dict[self.type]
298 sys.stderr.write ("\nUnknown articulation no. %d on note no. %d" % (self.type, self.notenumber))
299 sys.stderr.write ("\nPlease add an entry to articulation_dict in the Python source")
302 c.note_suffix = '-' + a + c.note_suffix
305 def __init__ (self, a,b , finale):
307 self.syllable = finale[1]
308 self.verse = finale[0]
309 def calculate (self, chords, lyrics):
310 self.chord = chords[self.chordnum]
313 def __init__ (self, number, body):
316 self.split_syllables ()
317 def split_syllables (self):
318 ss = re.split ('(-| +)', self.body)
324 septor = re.sub (" +", "", s)
325 septor = re.sub ("-", " -- ", septor)
326 syls[-1] = syls[-1] + septor
332 self.syllables = syls
337 for s in self.syllables[1:]:
338 line = line + ' ' + s
340 str = str + ' ' * 4 + line + '\n'
343 str = """\nverse%s = \\lyrics {\n %s}\n""" % (encodeint (self.number - 1) ,str)
348 def __init__(self, no):
350 self.frames = [0] * 4
354 self.global_measure = None
358 def add_finale_entry (self, entry):
359 self.finale.append (entry)
363 def calculate (self):
366 if len (self.finale) < 2:
368 fs = map (string.atoi, list (fs))
370 self.frames = [fs[0]]
372 fs = self.finale[0] + self.finale[1]
374 fs = map (string.atoi, list (fs))
381 def __init__ (self, finale):
384 (number, start, end ) = finale
390 def set_measure (self, m):
393 def calculate (self):
397 for c in self.chords:
398 if c.grace and (lastch == None or (not lastch.grace)):
399 c.chord_prefix = r'\grace {' + c.chord_prefix
400 elif not c.grace and lastch and lastch.grace:
401 lastch.chord_suffix = lastch.chord_suffix + ' } '
408 str = '%% FR(%d)\n' % self.number
409 left = self.measure.global_measure.length ()
413 for c in self.chords:
414 add = c.ly_string () + ' '
415 if len (ln) + len(add) > 72:
416 str = str + ln + '\n'
419 left = rat_subtract (left, c.length ())
424 sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
427 str = str + rat_to_lily_duration (left)
433 return chr ( i + ord ('A'))
436 def __init__ (self, number):
440 def get_measure (self, no):
441 if len (self.measures) <= no:
442 self.measures = self.measures + [None]* (1 + no - len (self.measures))
444 if self.measures[no] == None:
446 self.measures [no] =m
450 return self.measures[no]
452 return 'staff' + encodeint (self.number - 1)
453 def layerid (self, l):
454 return self.staffid() + 'layer%s' % chr (l -1 + ord ('A'))
456 def dump_time_key_sigs (self):
462 for m in self.measures[1:]:
463 if not m or not m.valid:
468 if g and last_key <> g.keysignature:
469 e = e + "\\key %s \\major; " % lily_notename (g.keysignature)
470 last_key = g.keysignature
471 if g and last_time <> g.timesig :
472 e = e + "\\time %d/%d; " % g.timesig
473 last_time = g.timesig
476 if last_clef <> m.clef :
477 e = e + '\\clef "%s";' % lily_clef (m.clef)
481 k = k +' ' + rat_to_lily_duration (gap) + '\n'
486 gap = rat_add (gap, g.length ())
489 k = '%sglobal = \\notes { %s }\n\n ' % (self.staffid (), k)
497 for x in range (1,5): # 4 layers.
502 for m in self.measures[1:]:
503 if not m or not m.valid:
515 laystr = laystr +'} %s {\n ' % rat_to_lily_duration (gap)
517 laystr = laystr + fr.dump ()
519 if m.global_measure :
520 gap = rat_add (gap, m.global_measure.length ())
523 "No global measure for staff %d measure %d\n"
524 % (self.number, m.number))
527 laystr = '%s = \\notes { { %s } }\n\n' % (l, laystr)
531 str = str + self.dump_time_key_sigs ()
532 stafdef = '\\%sglobal' % self.staffid ()
534 stafdef = stafdef + ' \\' + i
537 str = str + '%s = \\context Staff = %s <\n %s\n >\n' % \
538 (self.staffid (), self.staffid (), stafdef)
545 def __init__ (self, finale_entry):
548 self.finale = finale_entry
553 self.note_suffix = ''
554 self.chord_suffix = ''
555 self.chord_prefix = ''
562 return self.frame.measure
568 l = (1, self.duration[0])
570 d = 1 << self.duration[1]
572 dotfact = rat_subtract ((2,1), (1,d))
573 mylen = rat_multiply (dotfact, l)
576 mylen = rat_multiply (mylen, self.tuplet.factor())
580 return self.finale[0][0]
582 def EDU_duration (self):
583 return self.finale[0][3]
584 def set_duration (self):
585 self.duration = EDU_to_duration(self.EDU_duration ())
586 def calculate (self):
587 self.find_realpitch ()
590 flag = self.finale[0][5]
591 if Chord.GRACE_MASK & flag:
595 def find_realpitch (self):
597 ((no, prev, next, dur, pos, entryflag, extended, follow), notelist) = self.finale
599 meas = self.measure ()
601 if not meas or not meas.global_measure :
602 print 'note %d not in measure' % self.number ()
603 elif not meas.global_measure.scale:
604 print 'note %d: no scale in this measure.' % self.number ()
614 scale = meas.global_measure.scale
615 (sn, sa) =scale[rest % 7]
616 sn = sn + (rest - (rest%7)) + 7
618 self.pitches.append ((sn, acc))
619 tiestart = tiestart or (flag & Chord.TIE_START_MASK)
621 self.chord_suffix = self.chord_suffix + ' ~ '
623 REST_MASK = 0x40000000L
624 TIE_START_MASK = 0x40000000L
625 GRACE_MASK = 0x00800000L
627 def ly_string (self):
632 if not (self.finale[0][5] & Chord.REST_MASK):
635 for p in self.pitches:
640 nn = lily_notename ((n,a))
653 s = s + '%s%d%s' % (nn, self.duration[0], '.'* self.duration[1])
656 s = 'r%d%s' % (self.duration[0] , '.'* self.duration[1])
657 s = self.note_prefix + s + self.note_suffix
658 if len (self.pitches) > 1:
661 s = self.chord_prefix + s + self.chord_suffix
664 GFre = re.compile(r"""^\^GF\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
665 BCre = re.compile (r"""^\^BC\(([0-9-]+)\) ([0-9-]+) .*$""")
666 eEre = re.compile(r"""^\^eE\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) \$([0-9A-Fa-f]+) ([0-9-]+) ([0-9-]+)""")
667 FRre = re.compile (r"""^\^FR\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
668 MSre = re.compile (r"""^\^MS\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
669 note_re = re.compile (r"""^ +([0-9-]+) \$([A-Fa-f0-9]+)""")
670 Sxre = re.compile (r"""^\^Sx\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
671 IMre = re.compile (r"""^\^IM\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
672 vere = re.compile(r"""^\^(ve|ch|se)\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
673 versere = re.compile(r"""^\^verse\(([0-9]+)\)(.*)\^end""")
675 TPre = re.compile(r"""^\^TP\(([0-9]+),([0-9]+)\) *([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
679 def __init__ (self, name):
680 self.measures = [None]
681 self.entries = [None]
684 self.tuplets = [None]
687 self.articulations = [None]
688 self.syllables = [None]
694 def get_global_measure (self, no):
695 if len (self.measures) <= no:
696 self.measures = self.measures + [None]* (1 + no - len (self.measures))
698 if self.measures[no] == None:
699 self.measures [no] = Global_measure (no)
701 return self.measures[no]
704 def get_staff(self,staffno):
705 if len (self.staffs) <= staffno:
706 self.staffs = self.staffs + [None] * (1 + staffno - len (self.staffs))
708 if self.staffs[staffno] == None:
709 self.staffs[staffno] = Staff (staffno)
711 return self.staffs[staffno]
714 def try_IS (self, l):
717 def try_BC (self, l):
720 bn = string.atoi (m.group (1))
721 where = string.atoi (m.group (2)) / 1024.0
726 (nil, num) = map (string.atoi, (m.groups ()[0:2]))
727 entries = map (string.atoi, (m.groups ()[2:]))
729 if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
730 self.tuplets.append (Tuplet (num))
732 self.tuplets[-1].append_finale (entries)
734 def try_IM (self, l):
737 a = string.atoi (m.group (1))
738 b = string.atoi (m.group (2))
740 fin = map (string.atoi, m.groups ()[2:])
742 self.articulations.append (Articulation (a,b,fin))
744 def try_verse (self,l):
745 m = versere .match (l)
747 a = string.atoi (m.group (1))
750 body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
751 body = re.sub ("\^[a-z]+", "", body)
752 self.verses.append (Verse (a, body))
758 a = string.atoi (m.group (1))
759 b = string.atoi (m.group (2))
761 fin = map (string.atoi, m.groups ()[2:])
763 self.syllables.append (Syllable (a,b,fin))
765 def try_eE (self, l):
769 (no, prev, next, dur, pos, entryflag, extended, follow) = tup
770 (no, prev, next, dur, pos,extended, follow) \
771 = tuple (map (string.atoi, [no,prev,next,dur,pos,extended,follow]))
773 entryflag = string.atol (entryflag,16)
774 if len (self.entries) <= no:
775 # missing entries seem to be quite common.
776 # we fill'em up with None.
777 self.entries = self.entries + [None] * (no - len (self.entries) + 1)
779 current_entry = ((no, prev, next, dur, pos, entryflag, extended, follow), [])
780 self.entries[no] = current_entry
786 slurno = string.atoi (m.group (1))
790 sl = self.slur_dict[slurno]
793 self.slur_dict[slurno] = sl
795 params = list (m.groups ()[1:])
796 params = map (string.atoi, params)
797 sl.append_entry (params)
803 (staffno,measno) = m.groups ()[0:2]
804 s = string.atoi (staffno)
805 me = string.atoi (measno)
807 entry = m.groups () [2:]
808 st = self.get_staff (s)
809 meas = st.get_measure (me)
810 meas.add_finale_entry (entry)
816 (frameno, startnote, endnote, foo, bar) = m.groups ()
817 (frameno, startnote, endnote) = tuple (map (string.atoi, [frameno, startnote, endnote]))
818 if len (self.frames) <= frameno:
819 self.frames = self.frames + [None] * (frameno - len(self.frames) + 1)
821 self.frames[frameno] = Frame ((frameno, startnote, endnote))
825 def try_MS (self, l):
828 measno = string.atoi (m.group (1))
829 keynum = string.atoi (m.group (3))
830 meas =self. get_global_measure (measno)
831 meas.set_keysig (keynum)
833 beats = string.atoi (m.group (4))
834 beatlen = string.atoi (m.group (5))
835 meas.set_timesig ((beats, beatlen))
839 def try_note (self, l):
840 m = note_re.match (l)
842 (pitch, flag) = m.groups ()
843 pitch = string.atoi (pitch)
844 flag = string.atol (flag,16)
845 self.entries[-1][1].append ((pitch,flag))
847 def parse (self, name):
848 sys.stderr.write ('parsing ...')
851 gulp = open (name).read ()
853 gulp = re.sub ('[\n\r]+', '\n', gulp)
854 ls = string.split (gulp, '\n')
865 m = self.try_note (l)
875 m = self.try_verse (l)
877 sys.stderr.write ('processing ...')
880 self.unthread_entries ()
882 for st in self.staffs[1:]:
886 for m in st.measures[1:]:
892 m.global_measure = self.measures[mno]
894 sys.stderr.write ("Non-existent global measure %d" % mno)
897 frame_obj_list = [None]
898 for frno in m.frames:
899 fr = self.frames[frno]
900 frame_obj_list.append (fr)
902 m.frames = frame_obj_list
903 for fr in frame_obj_list[1:]:
909 fr.chords = self.get_thread (fr.start, fr.end)
914 for c in self.chords[1:]:
918 for f in self.frames[1:]:
922 for t in self.tuplets[1:]:
923 t.calculate (self.chords)
925 for s in self.slur_dict.values():
926 s.calculate (self.chords)
927 for s in self.articulations[1:]:
928 s.calculate (self.chords)
930 def get_thread (self, startno, endno):
936 c = self.chords[startno]
938 sys.stderr.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno, endno))
942 while c and c.number () <> endno:
954 for s in self.staffs[1:]:
956 str = str + '\n\n' + s.dump ()
957 staffs.append ('\\' + s.staffid ())
960 # should use \addlyrics ?
962 for v in self.verses[1:]:
965 if len (self.verses) > 1:
966 sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
969 str = str + '\\score { < %s > } ' % string.join (staffs)
975 return 'ETF FILE %s %s' % (self.measures, self.entries)
977 def unthread_entries (self):
979 for e in self.entries[1:]:
983 self.chords.append (ch)
985 for e in self.chords[1:]:
988 e.prev = self.chords[e.finale[0][1]]
989 e.next = self.chords[e.finale[0][2]]
992 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
995 print """Usage: etf2ly [OPTION]... ETF-FILE
997 Convert ETF to LilyPond.
1001 -o,--output=FILE set output filename to FILE
1002 -v,--version version information
1004 Enigma Transport Format is a format used by Coda Music Technology's
1005 Finale product. This program will convert a subset of ETF to a
1006 ready-to-use lilypond file.
1008 Report bugs to bug-gnu-music@gnu.org
1010 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>
1013 def print_version ():
1014 print r"""etf2ly (GNU lilypond) %s
1016 This is free software. It is covered by the GNU General Public License,
1017 and you are welcome to change it and/or distribute copies of it under
1018 certain conditions. Invoke as `midi2ly --warranty' for more information.
1020 Copyright (c) 2000 by Han-Wen Nienhuys <hanwen@cs.uu.nl>
1025 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
1031 if o== '--help' or o == '-h':
1034 if o == '--version' or o == '-v':
1038 if o == '--output' or o == '-o':
1050 sys.stderr.write ('Processing `%s\'\n' % f)
1052 if not out_filename:
1053 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1055 if out_filename == f:
1056 out_filename = os.path.basename (f + '.ly')
1058 sys.stderr.write ('Writing `%s\'' % out_filename)
1063 fo = open (out_filename, 'w')
1064 fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)