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):
358 if len (self.finale) < 2:
360 fs = map (string.atoi, list (fs))
362 self.frames = [fs[0]]
364 fs = self.finale[0] + self.finale[1]
366 fs = map (string.atoi, list (fs))
373 def __init__ (self, finale):
376 (number, start, end ) = finale
382 def set_measure (self, m):
385 def calculate (self):
389 for c in self.chords:
390 if c.grace and (lastch == None or (not lastch.grace)):
391 c.chord_prefix = r'\grace {' + c.chord_prefix
392 elif not c.grace and lastch and lastch.grace:
393 lastch.chord_suffix = lastch.chord_suffix + ' } '
400 str = '%% FR(%d)\n' % self.number
401 left = self.measure.global_measure.length ()
405 for c in self.chords:
406 add = c.ly_string () + ' '
407 if len (ln) + len(add) > 72:
408 str = str + ln + '\n'
411 left = rat_subtract (left, c.length ())
416 sys.stderr.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self.number, self.start, self.end))
419 str = str + rat_to_lily_duration (left)
425 return chr ( i + ord ('A'))
428 def __init__ (self, number):
432 def get_measure (self, no):
433 if len (self.measures) <= no:
434 self.measures = self.measures + [None]* (1 + no - len (self.measures))
436 if self.measures[no] == None:
438 self.measures [no] =m
442 return self.measures[no]
444 return 'staff' + encodeint (self.number - 1)
445 def layerid (self, l):
446 return self.staffid() + 'layer%s' % chr (l -1 + ord ('A'))
448 def dump_time_key_sigs (self):
454 for m in self.measures[1:]:
455 if not m or not m.valid:
460 if last_key <> g.keysignature:
461 e = e + "\\key %s \\major; " % lily_notename (g.keysignature)
462 last_key = g.keysignature
463 if last_time <> g.timesig :
464 e = e + "\\time %d/%d; " % g.timesig
465 last_time = g.timesig
466 if last_clef <> m.clef :
467 e = e + '\\clef %s;' % lily_clef (m.clef)
471 k = k +' ' + rat_to_lily_duration (gap) + '\n'
475 gap = rat_add (gap, g.length ())
478 k = '%sglobal = \\notes { %s }\n\n ' % (self.staffid (), k)
486 for x in range (1,5): # 4 layers.
491 for m in self.measures[1:]:
492 if not m or not m.valid:
504 laystr = laystr +'} %s {\n ' % rat_to_lily_duration (gap)
506 laystr = laystr + fr.dump ()
508 gap = rat_add (gap, m.global_measure.length ())
512 laystr = '%s = \\notes { { %s } }\n\n' % (l, laystr)
516 str = str + self.dump_time_key_sigs ()
517 stafdef = '\\%sglobal' % self.staffid ()
519 stafdef = stafdef + ' \\' + i
522 str = str + '%s = \\context Staff = %s <\n %s\n >\n' % \
523 (self.staffid (), self.staffid (), stafdef)
530 def __init__ (self, finale_entry):
533 self.finale = finale_entry
538 self.note_suffix = ''
539 self.chord_suffix = ''
540 self.chord_prefix = ''
547 return self.frame.measure
553 l = (1, self.duration[0])
555 d = 1 << self.duration[1]
557 dotfact = rat_subtract ((2,1), (1,d))
558 mylen = rat_multiply (dotfact, l)
561 mylen = rat_multiply (mylen, self.tuplet.factor())
565 return self.finale[0][0]
567 def EDU_duration (self):
568 return self.finale[0][3]
569 def set_duration (self):
570 self.duration = EDU_to_duration(self.EDU_duration ())
571 def calculate (self):
572 self.find_realpitch ()
575 flag = self.finale[0][5]
576 if Chord.GRACE_MASK & flag:
580 def find_realpitch (self):
582 ((no, prev, next, dur, pos, entryflag, extended, follow), notelist) = self.finale
584 meas = self.measure ()
586 if not meas or not meas.global_measure :
587 print 'note %d not in measure' % self.number ()
588 elif not meas.global_measure.scale:
589 print 'note %d: no scale in this measure.' % self.number ()
599 scale = meas.global_measure.scale
600 (sn, sa) =scale[rest % 7]
601 sn = sn + (rest - (rest%7)) + 7
603 self.pitches.append ((sn, acc))
604 tiestart = tiestart or (flag & Chord.TIE_START_MASK)
606 self.chord_suffix = self.chord_suffix + ' ~ '
608 REST_MASK = 0x40000000L
609 TIE_START_MASK = 0x40000000L
610 GRACE_MASK = 0x00800000L
612 def ly_string (self):
617 if not (self.finale[0][5] & Chord.REST_MASK):
620 for p in self.pitches:
625 nn = lily_notename ((n,a))
638 s = s + '%s%d%s' % (nn, self.duration[0], '.'* self.duration[1])
641 s = 'r%d%s' % (self.duration[0] , '.'* self.duration[1])
642 s = self.note_prefix + s + self.note_suffix
643 if len (self.pitches) > 1:
646 s = self.chord_prefix + s + self.chord_suffix
649 GFre = re.compile(r"""^\^GF\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
650 BCre = re.compile (r"""^\^BC\(([0-9-]+)\) ([0-9-]+) .*$""")
651 eEre = re.compile(r"""^\^eE\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) \$([0-9A-Fa-f]+) ([0-9-]+) ([0-9-]+)""")
652 FRre = re.compile (r"""^\^FR\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
653 MSre = re.compile (r"""^\^MS\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
654 note_re = re.compile (r"""^ +([0-9-]+) \$([A-Fa-f0-9]+)""")
655 Sxre = re.compile (r"""^\^Sx\(([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
656 IMre = re.compile (r"""^\^IM\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
657 vere = re.compile(r"""^\^(ve|ch|se)\(([0-9-]+),([0-9-]+)\) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
658 versere = re.compile(r"""^\^verse\(([0-9]+)\)(.*)\^end""")
660 TPre = re.compile(r"""^\^TP\(([0-9]+),([0-9]+)\) *([0-9-]+) ([0-9-]+) ([0-9-]+) ([0-9-]+)""")
664 def __init__ (self, name):
665 self.measures = [None]
666 self.entries = [None]
669 self.tuplets = [None]
672 self.articulations = [None]
673 self.syllables = [None]
679 def get_global_measure (self, no):
680 if len (self.measures) <= no:
681 self.measures = self.measures + [None]* (1 + no - len (self.measures))
683 if self.measures[no] == None:
684 self.measures [no] = Global_measure (no)
686 return self.measures[no]
689 def get_staff(self,staffno):
690 if len (self.staffs) <= staffno:
691 self.staffs = self.staffs + [None] * (1 + staffno - len (self.staffs))
693 if self.staffs[staffno] == None:
694 self.staffs[staffno] = Staff (staffno)
696 return self.staffs[staffno]
699 def try_IS (self, l):
702 def try_BC (self, l):
705 bn = string.atoi (m.group (1))
706 where = string.atoi (m.group (2)) / 1024.0
711 (nil, num) = map (string.atoi, (m.groups ()[0:2]))
712 entries = map (string.atoi, (m.groups ()[2:]))
714 if self.tuplets[-1] == None or num <> self.tuplets[-1].start_note:
715 self.tuplets.append (Tuplet (num))
717 self.tuplets[-1].append_finale (entries)
719 def try_IM (self, l):
722 a = string.atoi (m.group (1))
723 b = string.atoi (m.group (2))
725 fin = map (string.atoi, m.groups ()[2:])
727 self.articulations.append (Articulation (a,b,fin))
729 def try_verse (self,l):
730 m = versere .match (l)
732 a = string.atoi (m.group (1))
735 body = re.sub (r"""\^[a-z]+\([^)]+\)""", "", body)
736 body = re.sub ("\^[a-z]+", "", body)
737 self.verses.append (Verse (a, body))
743 a = string.atoi (m.group (1))
744 b = string.atoi (m.group (2))
746 fin = map (string.atoi, m.groups ()[2:])
748 self.syllables.append (Syllable (a,b,fin))
750 def try_eE (self, l):
754 (no, prev, next, dur, pos, entryflag, extended, follow) = tup
755 (no, prev, next, dur, pos,extended, follow) \
756 = tuple (map (string.atoi, [no,prev,next,dur,pos,extended,follow]))
758 entryflag = string.atol (entryflag,16)
759 if no > len (self.entries):
760 sys.stderr.write ("\nHuh? Entry number to large,\nexpected %d got %d. Filling with void entries.\n" % (len(self.entries), no ))
761 while len (self.entries) <> no:
762 c = ((len (self.entries), 0, 0, 0, 0, 0L, 0, 0), [])
763 self.entries.append (c)
765 current_entry = ((no, prev, next, dur, pos, entryflag, extended, follow), [])
766 self.entries.append (current_entry)
772 slurno = string.atoi (m.group (1))
776 sl = self.slur_dict[slurno]
779 self.slur_dict[slurno] = sl
781 params = list (m.groups ()[1:])
782 params = map (string.atoi, params)
783 sl.append_entry (params)
789 (staffno,measno) = m.groups ()[0:2]
790 s = string.atoi (staffno)
791 me = string.atoi (measno)
793 entry = m.groups () [2:]
794 st = self.get_staff (s)
795 meas = st.get_measure (me)
796 meas.add_finale_entry (entry)
802 (frameno, startnote, endnote, foo, bar) = m.groups ()
803 (frameno, startnote, endnote) = tuple (map (string.atoi, [frameno, startnote, endnote]))
804 if frameno > len (self.frames):
805 sys.stderr.write ("Frame no %d missing, filling up to %d\n" % (len(self.frames), frameno))
806 while frameno <> len (self.frames):
807 self.frames.append (Frame ((len (self.frames), 0,0) ))
809 self.frames.append (Frame ((frameno, startnote, endnote)))
812 def try_MS (self, l):
815 measno = string.atoi (m.group (1))
816 keynum = string.atoi (m.group (3))
817 meas =self. get_global_measure (measno)
818 meas.set_keysig (keynum)
820 beats = string.atoi (m.group (4))
821 beatlen = string.atoi (m.group (5))
822 meas.set_timesig ((beats, beatlen))
826 def try_note (self, l):
827 m = note_re.match (l)
829 (pitch, flag) = m.groups ()
830 pitch = string.atoi (pitch)
831 flag = string.atol (flag,16)
832 self.entries[-1][1].append ((pitch,flag))
834 def parse (self, name):
835 sys.stderr.write ('parsing ...')
838 gulp = open (name).read ()
840 gulp = re.sub ('[\n\r]+', '\n', gulp)
841 ls = string.split (gulp, '\n')
852 m = self.try_note (l)
862 m = self.try_verse (l)
864 sys.stderr.write ('processing ...')
867 self.unthread_entries ()
869 for st in self.staffs[1:]:
873 for m in st.measures[1:]:
879 m.global_measure = self.measures[mno]
881 sys.stderr.write ("non-existent global measure %d" % mno)
884 frame_obj_list = [None]
885 for frno in m.frames:
886 fr = self.frames[frno]
887 frame_obj_list.append (fr)
889 m.frames = frame_obj_list
890 for fr in frame_obj_list[1:]:
896 fr.chords = self.get_thread (fr.start, fr.end)
901 for c in self.chords[1:]:
904 for f in self.frames[1:]:
907 for t in self.tuplets[1:]:
908 t.calculate (self.chords)
910 for s in self.slur_dict.values():
911 s.calculate (self.chords)
912 for s in self.articulations[1:]:
913 s.calculate (self.chords)
915 def get_thread (self, startno, endno):
921 c = self.chords[startno]
923 sys.stderr.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno, endno))
927 while c and c.number () <> endno:
939 for s in self.staffs[1:]:
941 str = str + '\n\n' + s.dump ()
942 staffs.append ('\\' + s.staffid ())
945 # should use \addlyrics ?
947 for v in self.verses[1:]:
950 if len (self.verses) > 1:
951 sys.stderr.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
954 str = str + '\\score { < %s > } ' % string.join (staffs)
960 return 'ETF FILE %s %s' % (self.measures, self.entries)
962 def unthread_entries (self):
964 for e in self.entries[1:]:
965 self.chords.append (Chord (e))
967 for e in self.chords[1:]:
968 e.prev = self.chords[e.finale[0][1]]
969 e.next = self.chords[e.finale[0][2]]
972 sys.stderr.write ("%s from LilyPond %s\n" % (program_name, version))
975 print """Usage: etf2ly [OPTION]... ETF-FILE
977 Convert ETF to LilyPond.
981 -o,--output=FILE set output filename to FILE
982 -v,--version version information
984 Enigma Transport Format is a format used by Coda Music Technology's
985 Finale product. This program will convert a subset of ETF to a
986 ready-to-use lilypond file.
988 Report bugs to bug-gnu-music@gnu.org
990 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>
993 def print_version ():
994 print r"""etf2ly (GNU lilypond) %s
996 This is free software. It is covered by the GNU General Public License,
997 and you are welcome to change it and/or distribute copies of it under
998 certain conditions. Invoke as `midi2ly --warranty' for more information.
1000 Copyright (c) 2000 by Han-Wen Nienhuys <hanwen@cs.uu.nl>
1005 (options, files) = getopt.getopt (sys.argv[1:], 'vo:h', ['help','version', 'output='])
1011 if o== '--help' or o == '-h':
1014 if o == '--version' or o == '-v':
1018 if o == '--output' or o == '-o':
1030 sys.stderr.write ('Processing `%s\'\n' % f)
1032 if not out_filename:
1033 out_filename = os.path.basename (re.sub ('(?i).etf$', '.ly', f))
1035 if out_filename == f:
1036 out_filename = os.path.basename (f + '.ly')
1038 sys.stderr.write ('Writing `%s\'' % out_filename)
1043 fo = open (out_filename, 'w')
1044 fo.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f)