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_suffix
= ce
.note_suffix
+ '-)'
240 sys
.stderr
.write ("""\nHuh? Slur no %d between (%d,%d), with %d notes""" % (self
.number
, startnote
, endnote
, len (chords
)))
243 class Global_measure
:
244 def __init__ (self
, number
):
247 self
.keysignature
= None
255 return `self
.finale `
257 def set_timesig (self
, finale
):
258 (beats
, fdur
) = finale
259 (log
, dots
) = EDU_to_duration (fdur
)
261 sys
.stderr
.write ("\nHuh? Beat duration has a dot? (EDU Duration = %d)" % fdur
)
262 self
.timesig
= (beats
, log
)
267 def set_keysig (self
, finale
):
268 k
= interpret_finale_key_sig (finale
)
269 self
.keysignature
= k
270 self
.scale
= find_scale (k
)
272 def set_flags (self
,flag1
, flag2
):
274 # flag1 isn't all that interesting.
279 self
.repeats
.append ('start')
281 self
.repeats
.append ('stop')
285 self
.repeats
.append ('bracket')
298 class Articulation_def
:
299 def __init__ (self
, n
, a
, b
):
300 self
.finale_glyph
= a
& 0xff
305 return articulation_dict
[self
.finale_glyph
]
307 sys
.stderr
.write ("\nUnknown articulation no. %d" % self
.finale_glyph
)
308 sys
.stderr
.write ("\nPlease add an entry to articulation_dict in the Python source")
312 def __init__ (self
, a
,b
, finale
):
313 self
.definition
= finale
[0]
316 def calculate (self
, chords
, defs
):
317 c
= chords
[self
.notenumber
]
319 adef
= defs
[self
.definition
]
323 sys
.stderr
.write ("\nThis happened on note %d" % self
.notenumber
)
325 c
.note_suffix
= '-' + lystr
328 def __init__ (self
, a
,b
, finale
):
330 self
.syllable
= finale
[1]
331 self
.verse
= finale
[0]
332 def calculate (self
, chords
, lyrics
):
333 self
.chord
= chords
[self
.chordnum
]
336 def __init__ (self
, number
, body
):
339 self
.split_syllables ()
340 def split_syllables (self
):
341 ss
= re
.split ('(-| +)', self
.body
)
347 septor
= re
.sub (" +", "", s
)
348 septor
= re
.sub ("-", " -- ", septor
)
349 syls
[-1] = syls
[-1] + septor
355 self
.syllables
= syls
360 for s
in self
.syllables
[1:]:
361 line
= line
+ ' ' + s
363 str = str + ' ' * 4 + line
+ '\n'
366 str = """\nverse%s = \\lyrics {\n %s}\n""" % (encodeint (self
.number
- 1) ,str)
371 def __init__(self
, no
):
373 self
.frames
= [0] * 4
377 self
.global_measure
= None
384 def calculate (self
):
387 if len (self
.finale
) < 2:
391 self
.frames
= [fs
[0]]
400 def __init__ (self
, finale
):
403 (number
, start
, end
) = finale
409 def set_measure (self
, m
):
412 def calculate (self
):
416 for c
in self
.chords
:
417 if c
.grace
and (lastch
== None or (not lastch
.grace
)):
418 c
.chord_prefix
= r
'\grace {' + c
.chord_prefix
419 elif not c
.grace
and lastch
and lastch
.grace
:
420 lastch
.chord_suffix
= lastch
.chord_suffix
+ ' } '
427 str = '%% FR(%d)\n' % self
.number
428 left
= self
.measure
.global_measure
.length ()
432 for c
in self
.chords
:
433 add
= c
.ly_string () + ' '
434 if len (ln
) + len(add
) > 72:
435 str = str + ln
+ '\n'
438 left
= rat_subtract (left
, c
.length ())
443 sys
.stderr
.write ("""\nHuh? Going backwards in frame no %d, start/end (%d,%d)""" % (self
.number
, self
.start
, self
.end
))
446 str = str + rat_to_lily_duration (left
)
452 return chr ( i
+ ord ('A'))
455 def __init__ (self
, number
):
459 def get_measure (self
, no
):
460 fill_list_to (self
.measures
, no
)
462 if self
.measures
[no
] == None:
464 self
.measures
[no
] =m
467 return self
.measures
[no
]
469 return 'staff' + encodeint (self
.number
- 1)
470 def layerid (self
, l
):
471 return self
.staffid() + 'layer%s' % chr (l
-1 + ord ('A'))
473 def dump_time_key_sigs (self
):
479 for m
in self
.measures
[1:]:
480 if not m
or not m
.valid
:
487 if last_key
<> g
.keysignature
:
488 e
= e
+ "\\key %s \\major " % lily_notename (g
.keysignature
)
489 last_key
= g
.keysignature
490 if last_time
<> g
.timesig
:
491 e
= e
+ "\\time %d/%d " % g
.timesig
492 last_time
= g
.timesig
494 if 'start' in g
.repeats
:
495 e
= e
+ ' \\bar "|:" '
498 # we don't attempt voltas since they fail easily.
499 if 0 : # and g.repeat_bar == '|:' or g.repeat_bar == ':|:' or g.bracket:
501 if g
.repeat_bar
== '|:' or g
.repeat_bar
== ':|:' or g
.bracket
== 'end':
505 if g
.bracket
== 'start':
508 str = string
.join (map (lambda x
: '(volta %s)' % x
, strs
))
510 e
= e
+ ' \\property Score.repeatCommands = #\'(%s) ' % str
515 if last_clef
<> m
.clef
:
516 e
= e
+ '\\clef "%s"' % lily_clef (m
.clef
)
520 k
= k
+' ' + rat_to_lily_duration (gap
) + '\n'
525 gap
= rat_add (gap
, g
.length ())
526 if 'stop' in g
.repeats
:
527 k
= k
+ ' \\bar ":|" '
529 k
= '%sglobal = \\notes { %s }\n\n ' % (self
.staffid (), k
)
537 for x
in range (1,5): # 4 layers.
542 for m
in self
.measures
[1:]:
543 if not m
or not m
.valid
:
544 sys
.stderr
.write ("Skipping non-existant or invalid measure\n")
551 sys
.stderr
.write ("Skipping nonexistent frame %d\n" % x
)
552 laystr
= laystr
+ "%% non existent frame %d (skipped) \n" % x
556 laystr
= laystr
+'} %s {\n ' % rat_to_lily_duration (gap
)
558 laystr
= laystr
+ fr
.dump ()
560 if m
.global_measure
:
561 gap
= rat_add (gap
, m
.global_measure
.length ())
564 "No global measure for staff %d measure %d\n"
565 % (self
.number
, m
.number
))
568 laystr
= '%s = \\notes { { %s } }\n\n' % (l
, laystr
)
572 str = str + self
.dump_time_key_sigs ()
573 stafdef
= '\\%sglobal' % self
.staffid ()
575 stafdef
= stafdef
+ ' \\' + i
578 str = str + '%s = \\context Staff = %s <\n %s\n >\n' % \
579 (self
.staffid (), self
.staffid (), stafdef
)
588 return [(l
[0], l
[1])] + ziplist (l
[2:])
592 def __init__ (self
, number
, contents
):
595 self
.finale
= contents
[:7]
597 self
.notelist
= ziplist (contents
[7:])
603 self
.note_suffix
= ''
604 self
.chord_suffix
= ''
605 self
.chord_prefix
= ''
612 return self
.frame
.measure
618 l
= (1, self
.duration
[0])
620 d
= 1 << self
.duration
[1]
622 dotfact
= rat_subtract ((2,1), (1,d
))
623 mylen
= rat_multiply (dotfact
, l
)
626 mylen
= rat_multiply (mylen
, self
.tuplet
.factor())
630 def EDU_duration (self
):
631 return self
.finale
[2]
632 def set_duration (self
):
633 self
.duration
= EDU_to_duration(self
.EDU_duration ())
635 def calculate (self
):
636 self
.find_realpitch ()
639 flag
= self
.finale
[4]
640 if Chord
.GRACE_MASK
& flag
:
644 def find_realpitch (self
):
646 meas
= self
.measure ()
648 if not meas
or not meas
.global_measure
:
649 sys
.stderr
.write ('note %d not in measure\n' % self
.number
)
650 elif not meas
.global_measure
.scale
:
651 sys
.stderr
.write ('note %d: no scale in this measure.' % self
.number
)
654 for p
in self
.notelist
:
664 scale
= meas
.global_measure
.scale
665 (sn
, sa
) =scale
[rest
% 7]
666 sn
= sn
+ (rest
- (rest
%7)) + 7
668 self
.pitches
.append ((sn
, acc
))
669 tiestart
= tiestart
or (flag
& Chord
.TIE_START_MASK
)
671 self
.chord_suffix
= self
.chord_suffix
+ ' ~ '
673 REST_MASK
= 0x40000000L
674 TIE_START_MASK
= 0x40000000L
675 GRACE_MASK
= 0x00800000L
677 def ly_string (self
):
683 if not (self
.finale
[4] & Chord
.REST_MASK
):
686 for p
in self
.pitches
:
691 nn
= lily_notename ((n
,a
))
708 if len (self
.pitches
) > 1:
711 s
= s
+ '%d%s' % (self
.duration
[0], '.'* self
.duration
[1])
712 s
= self
.note_prefix
+ s
+ self
.note_suffix
714 s
= self
.chord_prefix
+ s
+ self
.chord_suffix
719 def fill_list_to (list, no
):
721 Add None to LIST until it contains entry number NO.
723 while len (list) <= no
:
724 list.extend ([None] * (no
- len(list) + 1))
727 def read_finale_value (str):
729 Pry off one value from STR. The value may be $hex, decimal, or "string".
730 Return: (value, rest-of-STR)
732 while str and str[0] in ' \t\n':
742 while str and str[0] in '0123456789ABCDEF':
747 return (string
.atol (hex, 16), str)
751 while str and str[0] <> '"':
756 elif str[0] in '-0123456789':
758 while str and str[0] in '-0123456789':
762 return (string
.atoi (dec
), str)
764 sys
.stderr
.write ("Can't convert `%s'\n" % str)
770 def parse_etf_file (fn
, tag_dict
):
772 """ Read FN, putting ETF info into
773 a giant dictionary. The keys of TAG_DICT indicate which tags
774 to put into the dict.
777 sys
.stderr
.write ('parsing ... ' )
780 gulp
= re
.sub ('[\n\r]+', '\n', f
.read ())
781 ls
= string
.split (gulp
, '\n^')
784 for k
in tag_dict
.keys ():
785 etf_file_dict
[k
] = {}
792 m
= re
.match ('^([a-zA-Z0-9&]+)\(([^)]+)\)', l
)
793 if m
and tag_dict
.has_key (m
.group (1)):
796 indices
= tuple (map (string
.atoi
, string
.split (m
.group (2), ',')))
797 content
= l
[m
.end (2)+1:]
800 tdict
= etf_file_dict
[tag
]
801 if not tdict
.has_key (indices
):
807 if tag
== 'verse' or tag
== 'block':
808 m2
= re
.match ('(.*)\^end', content
)
810 parsed
= [m2
.group (1)]
813 (v
, content
) = read_finale_value (content
)
817 tdict
[indices
].extend (parsed
)
819 last_indices
= indices
824 # let's not do this: this really confuses when eE happens to be before a ^text.
825 # if last_tag and last_indices:
826 # etf_file_dict[last_tag][last_indices].append (l)
828 sys
.stderr
.write ('\n')
836 def __init__ (self
, name
):
837 self
.measures
= [None]
840 self
.tuplets
= [None]
843 self
.articulations
= [None]
844 self
.syllables
= [None]
846 self
.articulation_defs
= [None]
851 def get_global_measure (self
, no
):
852 fill_list_to (self
.measures
, no
)
853 if self
.measures
[no
] == None:
854 self
.measures
[no
] = Global_measure (no
)
856 return self
.measures
[no
]
859 def get_staff(self
,staffno
):
860 fill_list_to (self
.staffs
, staffno
)
861 if self
.staffs
[staffno
] == None:
862 self
.staffs
[staffno
] = Staff (staffno
)
864 return self
.staffs
[staffno
]
867 def try_IS (self
, indices
, contents
):
870 def try_BC (self
, indices
, contents
):
872 where
= contents
[0] / 1024.0
873 def try_TP(self
, indices
, contents
):
876 if self
.tuplets
[-1] == None or num
<> self
.tuplets
[-1].start_note
:
877 self
.tuplets
.append (Tuplet (num
))
879 self
.tuplets
[-1].append_finale (contents
)
881 def try_IM (self
, indices
, contents
):
884 self
.articulations
.append (Articulation (a
,b
,fin
))
885 def try_verse (self
, indices
, contents
):
889 body
= re
.sub (r
"""\^[a-z]+\([^)]+\)""", "", body
)
890 body
= re
.sub ("\^[a-z]+", "", body
)
891 self
.verses
.append (Verse (a
, body
))
892 def try_ve (self
,indices
, contents
):
894 self
.syllables
.append (Syllable (a
,b
,contents
))
896 def try_eE (self
,indices
, contents
):
898 (prev
, next
, dur
, pos
, entryflag
, extended
, follow
) = contents
[:7]
900 fill_list_to (self
.chords
, no
)
901 self
.chords
[no
] =Chord (no
, contents
)
903 def try_Sx(self
,indices
, contents
):
905 fill_list_to (self
.slurs
, slurno
)
906 self
.slurs
[slurno
] = Slur(slurno
, contents
)
908 def try_IX (self
, indices
, contents
):
915 ix
= self
.articulation_defs
[n
]
917 ix
= Articulation_def (n
,a
,b
)
918 self
.articulation_defs
.append (Articulation_def (n
, a
, b
))
920 def try_GF(self
, indices
, contents
):
921 (staffno
,measno
) = indices
923 st
= self
.get_staff (staffno
)
924 meas
= st
.get_measure (measno
)
925 meas
.finale
= contents
927 def try_FR(self
, indices
, contents
):
928 frameno
= indices
[0]
930 startnote
= contents
[0]
931 endnote
= contents
[1]
933 fill_list_to (self
.frames
, frameno
)
935 self
.frames
[frameno
] = Frame ((frameno
, startnote
, endnote
))
937 def try_MS (self
, indices
, contents
):
940 meas
=self
. get_global_measure (measno
)
941 meas
.set_keysig (keynum
)
944 beatlen
= contents
[3]
945 meas
.set_timesig ((beats
, beatlen
))
947 meas_flag1
= contents
[4]
948 meas_flag2
= contents
[5]
950 meas
.set_flags (meas_flag1
, meas_flag2
);
968 def parse (self
, etf_dict
):
969 sys
.stderr
.write ('reconstructing ...')
972 for (tag
,routine
) in Etf_file
.routine_dict
.items ():
973 ks
= etf_dict
[tag
].keys ()
976 routine (self
, k
, etf_dict
[tag
][k
])
978 sys
.stderr
.write ('processing ...')
981 self
.unthread_entries ()
983 for st
in self
.staffs
[1:]:
987 for m
in st
.measures
[1:]:
993 m
.global_measure
= self
.measures
[mno
]
995 sys
.stderr
.write ("Non-existent global measure %d" % mno
)
998 frame_obj_list
= [None]
999 for frno
in m
.frames
:
1001 fr
= self
.frames
[frno
]
1002 frame_obj_list
.append (fr
)
1004 sys
.stderr
.write ("\nNon-existent frame %d" % frno
)
1006 m
.frames
= frame_obj_list
1007 for fr
in frame_obj_list
[1:]:
1013 fr
.chords
= self
.get_thread (fr
.start
, fr
.end
)
1018 for c
in self
.chords
[1:]:
1022 for f
in self
.frames
[1:]:
1026 for t
in self
.tuplets
[1:]:
1027 t
.calculate (self
.chords
)
1029 for s
in self
.slurs
[1:]:
1031 s
.calculate (self
.chords
)
1033 for s
in self
.articulations
[1:]:
1034 s
.calculate (self
.chords
, self
.articulation_defs
)
1036 def get_thread (self
, startno
, endno
):
1042 c
= self
.chords
[startno
]
1044 sys
.stderr
.write ("Huh? Frame has invalid bounds (%d,%d)\n" % (startno
, endno
))
1048 while c
and c
.number
<> endno
:
1060 for s
in self
.staffs
[1:]:
1062 str = str + '\n\n' + s
.dump ()
1063 staffs
.append ('\\' + s
.staffid ())
1066 # should use \addlyrics ?
1068 for v
in self
.verses
[1:]:
1069 str = str + v
.dump()
1071 if len (self
.verses
) > 1:
1072 sys
.stderr
.write ("\nLyrics found; edit to use \\addlyrics to couple to a staff\n")
1075 str = str + '\\score { < %s > } ' % string
.join (staffs
)
1081 return 'ETF FILE %s %s' % (self
.measures
, self
.entries
)
1083 def unthread_entries (self
):
1084 for e
in self
.chords
[1:]:
1088 e
.prev
= self
.chords
[e
.finale
[0]]
1089 e
.next
= self
.chords
[e
.finale
[1]]
1092 sys
.stderr
.write ("%s from LilyPond %s\n" % (program_name
, version
))
1095 sys
.stdout
.write("""Usage: etf2ly [OPTION]... ETF-FILE
1097 Convert ETF to LilyPond.
1101 -o,--output=FILE set output filename to FILE
1102 -v,--version version information
1104 Enigma Transport Format is a format used by Coda Music Technology's
1105 Finale product. This program will convert a subset of ETF to a
1106 ready-to-use lilypond file.
1108 Report bugs to bug-lilypond@gnu.org
1110 Written by Han-Wen Nienhuys <hanwen@cs.uu.nl>
1113 def print_version ():
1114 sys
.stdout
.write (r
"""etf2ly (GNU lilypond) %s
1116 This is free software. It is covered by the GNU General Public License,
1117 and you are welcome to change it and/or distribute copies of it under
1118 certain conditions. Invoke as `midi2ly --warranty' for more information.
1120 Copyright (c) 2000 by Han-Wen Nienhuys <hanwen@cs.uu.nl>
1125 (options
, files
) = getopt
.getopt (sys
.argv
[1:], 'vo:h', ['help','version', 'output='])
1131 if o
== '--help' or o
== '-h':
1134 if o
== '--version' or o
== '-v':
1138 if o
== '--output' or o
== '-o':
1151 sys
.stderr
.write ('Processing `%s\'\n' % f
)
1153 dict = parse_etf_file (f
, Etf_file
.routine_dict
)
1155 if not out_filename
:
1156 out_filename
= os
.path
.basename (re
.sub ('(?i).etf$', '.ly', f
))
1158 if out_filename
== f
:
1159 out_filename
= os
.path
.basename (f
+ '.ly')
1161 sys
.stderr
.write ('Writing `%s\'' % out_filename
)
1166 fo
= open (out_filename
, 'w')
1167 fo
.write ('%% lily was here -- automatically converted by etf2ly from %s\n' % f
)