2 # -*- coding: utf-8 -*-
22 from rational import Rational
24 # Store command-line options in a global variable, so we can access them everythwere
27 class Conversion_Settings:
29 self.ignore_beaming = False
31 conversion_settings = Conversion_Settings ()
32 # Use a global variable to store the setting needed inside a \layout block.
33 # whenever we need to change a setting or add/remove an engraver, we can access
34 # this layout and add the corresponding settings
35 layout_information = musicexp.Layout ()
38 ly.stderr_write (str + '\n')
41 def error_message (str):
42 ly.stderr_write (str + '\n')
45 needed_additional_definitions = []
46 additional_definitions = {
48 "tuplet-note-wrapper": """ % a formatter function, which is simply a wrapper around an existing
49 % tuplet formatter function. It takes the value returned by the given
50 % function and appends a note of given length.
51 #(define-public ((tuplet-number::append-note-wrapper function note) grob)
52 (let* ((txt (if function (function grob) #f)))
54 (markup txt #:fontsize -5 #:note note UP)
55 (markup #:fontsize -5 #:note note UP)
60 "tuplet-non-default-denominator": """#(define ((tuplet-number::non-default-tuplet-denominator-text denominator) grob)
61 (number->string (if denominator
63 (ly:event-property (event-cause grob) 'denominator))))
66 "tuplet-non-default-fraction": """#(define ((tuplet-number::non-default-tuplet-fraction-text denominator numerator) grob)
67 (let* ((ev (event-cause grob))
68 (den (if denominator denominator (ly:event-property ev 'denominator)))
69 (num (if numerator numerator (ly:event-property ev 'numerator))))
70 (format "~a:~a" den num)))
73 "compound-time-signature": """%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
74 % Formatting of (possibly complex) compound time signatures
75 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
77 #(define-public (insert-markups l m)
78 (let* ((ll (reverse l)))
79 (let join-markups ((markups (list (car ll)))
82 (join-markups (cons (car remaining) (cons m markups)) (cdr remaining))
85 % Use a centered-column inside a left-column, because the centered column
86 % moves its reference point to the center, which the left-column undoes.
87 % The center-column also aligns its contented centered, which is not undone...
88 #(define-public (format-time-fraction time-sig-fraction)
89 (let* ((revargs (reverse (map number->string time-sig-fraction)))
91 (nums (reverse (cdr revargs))))
92 (make-override-markup '(baseline-skip . 0)
94 (make-left-column-markup (list
95 (make-center-column-markup (list
96 (make-line-markup (insert-markups nums "+"))
99 #(define-public (format-complex-compound-time time-sig)
100 (let* ((sigs (map format-time-fraction time-sig)))
101 (make-override-markup '(baseline-skip . 0)
104 (insert-markups sigs (make-vcenter-markup "+")))))))
106 #(define-public (format-compound-time time-sig)
108 ((not (pair? time-sig)) (null-markup))
109 ((pair? (car time-sig)) (format-complex-compound-time time-sig))
110 (else (format-time-fraction time-sig))))
113 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
114 % Measure length calculation of (possibly complex) compound time signatures
115 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
117 #(define-public (calculate-time-fraction time-sig-fraction)
118 (let* ((revargs (reverse time-sig-fraction))
120 (nums (cdr revargs)))
121 (ly:make-moment (apply + nums) den)))
123 #(define-public (calculate-complex-compound-time time-sig)
124 (let* ((sigs (map calculate-time-fraction time-sig)))
125 (let add-moment ((moment ZERO-MOMENT)
127 (if (pair? remaining)
128 (add-moment (ly:moment-add moment (car remaining)) (cdr remaining))
131 #(define-public (calculate-compound-measure-length time-sig)
133 ((not (pair? time-sig)) (ly:make-moment 4 4))
134 ((pair? (car time-sig)) (calculate-complex-compound-time time-sig))
135 (else (calculate-time-fraction time-sig))))
138 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
140 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
142 #(define-public (calculate-compound-base-beat-full time-sig)
143 (let* ((den (map last time-sig)))
146 #(define-public (calculate-compound-base-beat time-sig)
147 (ly:make-moment 1 (cond
148 ((not (pair? time-sig)) 4)
149 ((pair? (car time-sig)) (calculate-compound-base-beat-full time-sig))
150 (else (calculate-compound-base-beat-full (list time-sig))))))
153 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
154 % The music function to set the complex time signature
155 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
158 #(define-music-function (parser location args) (pair?)
159 (let ((mlen (calculate-compound-measure-length args))
160 (beat (calculate-compound-base-beat args)))
162 \once \override Staff.TimeSignature #'stencil = #ly:text-interface::print
163 \once \override Staff.TimeSignature #'text = #(format-compound-time $args)
164 % \set Staff.beatGrouping = #(reverse (cdr (reverse $args)))
165 \set Timing.measureLength = $mlen
166 \set Timing.timeSignatureFraction = #(cons (ly:moment-main-numerator $mlen)
167 (ly:moment-main-denominator $mlen))
168 \set Timing.beatLength = $beat
170 % TODO: Implement beatGrouping and auto-beam-settings!!!
175 def round_to_two_digits (val):
176 return round (val * 100) / 100
178 def extract_paper_information (tree):
179 paper = musicexp.Paper ()
180 defaults = tree.get_maybe_exist_named_child ('defaults')
184 scaling = defaults.get_maybe_exist_named_child ('scaling')
186 mm = scaling.get_named_child ('millimeters')
187 mm = string.atof (mm.get_text ())
188 tn = scaling.get_maybe_exist_named_child ('tenths')
189 tn = string.atof (tn.get_text ())
191 paper.global_staff_size = mm * 72.27 / 25.4
192 # We need the scaling (i.e. the size of staff tenths for everything!
196 def from_tenths (txt):
197 return round_to_two_digits (string.atof (txt) * tenths / 10)
198 def set_paper_variable (varname, parent, element_name):
199 el = parent.get_maybe_exist_named_child (element_name)
200 if el: # Convert to cm from tenths
201 setattr (paper, varname, from_tenths (el.get_text ()))
203 pagelayout = defaults.get_maybe_exist_named_child ('page-layout')
205 # TODO: How can one have different margins for even and odd pages???
206 set_paper_variable ("page_height", pagelayout, 'page-height')
207 set_paper_variable ("page_width", pagelayout, 'page-width')
209 pmargins = pagelayout.get_named_children ('page-margins')
211 set_paper_variable ("left_margin", pm, 'left-margin')
212 set_paper_variable ("right_margin", pm, 'right-margin')
213 set_paper_variable ("bottom_margin", pm, 'bottom-margin')
214 set_paper_variable ("top_margin", pm, 'top-margin')
216 systemlayout = defaults.get_maybe_exist_named_child ('system-layout')
218 sl = systemlayout.get_maybe_exist_named_child ('system-margins')
220 set_paper_variable ("system_left_margin", sl, 'left-margin')
221 set_paper_variable ("system_right_margin", sl, 'right-margin')
222 set_paper_variable ("system_distance", systemlayout, 'system-distance')
223 set_paper_variable ("top_system_distance", systemlayout, 'top-system-distance')
225 stafflayout = defaults.get_named_children ('staff-layout')
226 for sl in stafflayout:
227 nr = getattr (sl, 'number', 1)
228 dist = sl.get_named_child ('staff-distance')
229 #TODO: the staff distance needs to be set in the Staff context!!!
231 # TODO: Finish appearance?, music-font?, word-font?, lyric-font*, lyric-language*
232 appearance = defaults.get_named_child ('appearance')
234 lws = appearance.get_named_children ('line-width')
236 # Possible types are: beam, bracket, dashes,
237 # enclosure, ending, extend, heavy barline, leger,
238 # light barline, octave shift, pedal, slur middle, slur tip,
239 # staff, stem, tie middle, tie tip, tuplet bracket, and wedge
241 w = from_tenths (lw.get_text ())
242 # TODO: Do something with these values!
243 nss = appearance.get_named_children ('note-size')
245 # Possible types are: cue, grace and large
247 sz = from_tenths (ns.get_text ())
248 # TODO: Do something with these values!
249 # <other-appearance> elements have no specified meaning
251 rawmusicfont = defaults.get_named_child ('music-font')
253 # TODO: Convert the font
255 rawwordfont = defaults.get_named_child ('word-font')
257 # TODO: Convert the font
259 rawlyricsfonts = defaults.get_named_children ('lyric-font')
260 for lyricsfont in rawlyricsfonts:
261 # TODO: Convert the font
268 # score information is contained in the <work>, <identification> or <movement-title> tags
269 # extract those into a hash, indexed by proper lilypond header attributes
270 def extract_score_information (tree):
271 header = musicexp.Header ()
272 def set_if_exists (field, value):
274 header.set_field (field, musicxml.escape_ly_output_string (value))
276 movement_title = tree.get_maybe_exist_named_child ('movement-title')
278 set_if_exists ('title', movement_title.get_text ())
279 work = tree.get_maybe_exist_named_child ('work')
281 # Overwrite the title from movement-title with work->title
282 set_if_exists ('title', work.get_work_title ())
283 set_if_exists ('worknumber', work.get_work_number ())
284 set_if_exists ('opus', work.get_opus ())
286 identifications = tree.get_named_children ('identification')
287 for ids in identifications:
288 set_if_exists ('copyright', ids.get_rights ())
289 set_if_exists ('composer', ids.get_composer ())
290 set_if_exists ('arranger', ids.get_arranger ())
291 set_if_exists ('editor', ids.get_editor ())
292 set_if_exists ('poet', ids.get_poet ())
294 set_if_exists ('tagline', ids.get_encoding_software ())
295 set_if_exists ('encodingsoftware', ids.get_encoding_software ())
296 set_if_exists ('encodingdate', ids.get_encoding_date ())
297 set_if_exists ('encoder', ids.get_encoding_person ())
298 set_if_exists ('encodingdescription', ids.get_encoding_description ())
300 set_if_exists ('texidoc', ids.get_file_description ());
302 # Finally, apply the required compatibility modes
303 # Some applications created wrong MusicXML files, so we need to
304 # apply some compatibility mode, e.g. ignoring some features/tags
306 software = ids.get_encoding_software_list ()
308 # Case 1: "Sibelius 5.1" with the "Dolet 3.4 for Sibelius" plugin
309 # is missing all beam ends => ignore all beaming information
310 ignore_beaming_software = {
311 "Dolet 4 for Sibelius, Beta 2": "Dolet 4 for Sibelius, Beta 2",
312 "Dolet 3.5 for Sibelius": "Dolet 3.5 for Sibelius",
313 "Dolet 3.4 for Sibelius": "Dolet 3.4 for Sibelius",
314 "Dolet 3.3 for Sibelius": "Dolet 3.3 for Sibelius",
315 "Dolet 3.2 for Sibelius": "Dolet 3.2 for Sibelius",
316 "Dolet 3.1 for Sibelius": "Dolet 3.1 for Sibelius",
317 "Dolet for Sibelius 1.3": "Dolet for Sibelius 1.3",
318 "Noteworthy Composer": "Noteworthy Composer's nwc2xm[",
321 app_description = ignore_beaming_software.get (s, False);
323 conversion_settings.ignore_beaming = True
324 progress (_ ("Encountered file created by %s, containing wrong beaming information. All beaming information in the MusicXML file will be ignored") % app_description)
326 # TODO: Check for other unsupported features
334 return len (self.start) + len (self.end) == 0
335 def add_start (self, g):
336 self.start[getattr (g, 'number', "1")] = g
337 def add_end (self, g):
338 self.end[getattr (g, 'number', "1")] = g
339 def print_ly (self, printer):
340 error_message (_ ("Unprocessed PartGroupInfo %s encountered") % self)
341 def ly_expression (self):
342 error_message (_ ("Unprocessed PartGroupInfo %s encountered") % self)
345 def staff_attributes_to_string_tunings (mxl_attr):
346 details = mxl_attr.get_maybe_exist_named_child ('staff-details')
350 staff_lines = details.get_maybe_exist_named_child ('staff-lines')
352 lines = string.atoi (staff_lines.get_text ())
355 staff_tunings = details.get_named_children ('staff-tuning')
356 for i in staff_tunings:
360 line = string.atoi (i.line) - 1
365 step = i.get_named_child (u'tuning-step')
366 step = step.get_text ().strip ()
367 p.step = musicxml_step_to_lily (step)
369 octave = i.get_named_child (u'tuning-octave')
370 octave = octave.get_text ().strip ()
371 p.octave = int (octave) - 4
373 alter = i.get_named_child (u'tuning-alter')
375 p.alteration = int (alter.get_text ().strip ())
376 # lilypond seems to use the opposite ordering than MusicXML...
382 def staff_attributes_to_lily_staff (mxl_attr):
384 return musicexp.Staff ()
386 (staff_id, attributes) = mxl_attr.items ()[0]
388 # distinguish by clef:
389 # percussion (percussion and rhythmic), tab, and everything else
391 clef = attributes.get_maybe_exist_named_child ('clef')
393 sign = clef.get_maybe_exist_named_child ('sign')
395 clef_sign = {"percussion": "percussion", "TAB": "tab"}.get (sign.get_text (), None)
398 details = attributes.get_named_children ('staff-details')
400 staff_lines = d.get_maybe_exist_named_child ('staff-lines')
402 lines = string.atoi (staff_lines.get_text ())
405 if clef_sign == "percussion" and lines == 1:
406 staff = musicexp.RhythmicStaff ()
407 elif clef_sign == "percussion":
408 staff = musicexp.DrumStaff ()
409 # staff.drum_style_table = ???
410 elif clef_sign == "tab":
411 staff = musicexp.TabStaff ()
412 staff.string_tunings = staff_attributes_to_string_tunings (attributes)
413 # staff.tablature_format = ???
415 # TODO: Handle case with lines <> 5!
416 staff = musicexp.Staff ()
421 def extract_score_structure (part_list, staffinfo):
422 score = musicexp.Score ()
423 structure = musicexp.StaffGroup (None)
424 score.set_contents (structure)
429 def read_score_part (el):
430 if not isinstance (el, musicxml.Score_part):
432 # Depending on the attributes of the first measure, we create different
433 # types of staves (Staff, RhythmicStaff, DrumStaff, TabStaff, etc.)
434 staff = staff_attributes_to_lily_staff (staffinfo.get (el.id, None))
438 partname = el.get_maybe_exist_named_child ('part-name')
439 # Finale gives unnamed parts the name "MusicXML Part" automatically!
440 if partname and partname.get_text() != "MusicXML Part":
441 staff.instrument_name = partname.get_text ()
442 # part-name-display overrides part-name!
443 partname = el.get_maybe_exist_named_child ("part-name-display")
445 staff.instrument_name = extract_display_text (partname)
447 partdisplay = el.get_maybe_exist_named_child ('part-abbreviation')
449 staff.short_instrument_name = partdisplay.get_text ()
450 # part-abbreviation-display overrides part-abbreviation!
451 partdisplay = el.get_maybe_exist_named_child ("part-abbreviation-display")
453 staff.short_instrument_name = extract_display_text (partdisplay)
454 # TODO: Read in the MIDI device / instrument
458 def read_score_group (el):
459 if not isinstance (el, musicxml.Part_group):
461 group = musicexp.StaffGroup ()
462 if hasattr (el, 'number'):
465 #currentgroups_dict[id] = group
466 #currentgroups.append (id)
467 if el.get_maybe_exist_named_child ('group-name'):
468 group.instrument_name = el.get_maybe_exist_named_child ('group-name').get_text ()
469 if el.get_maybe_exist_named_child ('group-abbreviation'):
470 group.short_instrument_name = el.get_maybe_exist_named_child ('group-abbreviation').get_text ()
471 if el.get_maybe_exist_named_child ('group-symbol'):
472 group.symbol = el.get_maybe_exist_named_child ('group-symbol').get_text ()
473 if el.get_maybe_exist_named_child ('group-barline'):
474 group.spanbar = el.get_maybe_exist_named_child ('group-barline').get_text ()
478 parts_groups = part_list.get_all_children ()
480 # the start/end group tags are not necessarily ordered correctly and groups
481 # might even overlap, so we can't go through the children sequentially!
483 # 1) Replace all Score_part objects by their corresponding Staff objects,
484 # also collect all group start/stop points into one PartGroupInfo object
486 group_info = PartGroupInfo ()
487 for el in parts_groups:
488 if isinstance (el, musicxml.Score_part):
489 if not group_info.is_empty ():
490 staves.append (group_info)
491 group_info = PartGroupInfo ()
492 staff = read_score_part (el)
494 staves.append (staff)
495 elif isinstance (el, musicxml.Part_group):
496 if el.type == "start":
497 group_info.add_start (el)
498 elif el.type == "stop":
499 group_info.add_end (el)
500 if not group_info.is_empty ():
501 staves.append (group_info)
503 # 2) Now, detect the groups:
506 while pos < len (staves):
508 if isinstance (el, PartGroupInfo):
510 if len (group_starts) > 0:
511 prev_start = group_starts[-1]
512 elif len (el.end) > 0: # no group to end here
514 if len (el.end) > 0: # closes an existing group
515 ends = el.end.keys ()
516 prev_started = staves[prev_start].start.keys ()
518 intersection = filter(lambda x:x in ends, prev_started)
519 if len (intersection) > 0:
520 grpid = intersection[0]
522 # Close the last started group
523 grpid = staves[prev_start].start.keys () [0]
524 # Find the corresponding closing tag and remove it!
527 while j < len (staves) and not foundclosing:
528 if isinstance (staves[j], PartGroupInfo) and staves[j].end.has_key (grpid):
530 del staves[j].end[grpid]
531 if staves[j].is_empty ():
534 grpobj = staves[prev_start].start[grpid]
535 group = read_score_group (grpobj)
536 # remove the id from both the start and end
537 if el.end.has_key (grpid):
539 del staves[prev_start].start[grpid]
542 # replace the staves with the whole group
543 for j in staves[(prev_start + 1):pos]:
544 group.append_staff (j)
545 del staves[(prev_start + 1):pos]
546 staves.insert (prev_start + 1, group)
547 # reset pos so that we continue at the correct position
549 # remove an empty start group
550 if staves[prev_start].is_empty ():
551 del staves[prev_start]
552 group_starts.remove (prev_start)
554 elif len (el.start) > 0: # starts new part groups
555 group_starts.append (pos)
558 if len (staves) == 1:
561 structure.append_staff (i)
565 def musicxml_duration_to_lily (mxl_note):
566 # if the note has no Type child, then that method returns None. In that case,
567 # use the <duration> tag instead. If that doesn't exist, either -> Error
568 dur = mxl_note.get_duration_info ()
570 d = musicexp.Duration ()
571 d.duration_log = dur[0]
573 # Grace notes by specification have duration 0, so no time modification
574 # factor is possible. It even messes up the output with *0/1
575 if not mxl_note.get_maybe_exist_typed_child (musicxml.Grace):
576 d.factor = mxl_note._duration / d.get_length ()
580 if mxl_note._duration > 0:
581 return rational_to_lily_duration (mxl_note._duration)
583 mxl_note.message (_ ("Encountered note at %s without type and duration (=%s)") % (mxl_note.start, mxl_note._duration) )
587 def rational_to_lily_duration (rational_len):
588 d = musicexp.Duration ()
590 rational_len.normalize_self ()
591 d_log = {1: 0, 2: 1, 4:2, 8:3, 16:4, 32:5, 64:6, 128:7, 256:8, 512:9}.get (rational_len.denominator (), -1)
593 # Duration of the form 1/2^n or 3/2^n can be converted to a simple lilypond duration
594 dots = {1: 0, 3: 1, 7: 2, 15: 3, 31: 4, 63: 5, 127: 6}.get (rational_len.numerator(), -1)
595 if ( d_log >= dots >= 0 ):
596 # account for the dots!
597 d.duration_log = d_log - dots
600 d.duration_log = d_log
601 d.factor = Rational (rational_len.numerator ())
603 error_message (_ ("Encountered rational duration with denominator %s, "
604 "unable to convert to lilypond duration") %
605 rational_len.denominator ())
606 # TODO: Test the above error message
611 def musicxml_partial_to_lily (partial_len):
613 p = musicexp.Partial ()
614 p.partial = rational_to_lily_duration (partial_len)
619 # Detect repeats and alternative endings in the chord event list (music_list)
620 # and convert them to the corresponding musicexp objects, containing nested
622 def group_repeats (music_list):
623 repeat_replaced = True
626 # Walk through the list of expressions, looking for repeat structure
627 # (repeat start/end, corresponding endings). If we find one, try to find the
628 # last event of the repeat, replace the whole structure and start over again.
629 # For nested repeats, as soon as we encounter another starting repeat bar,
630 # treat that one first, and start over for the outer repeat.
631 while repeat_replaced and i < 100:
633 repeat_start = -1 # position of repeat start / end
634 repeat_end = -1 # position of repeat start / end
636 ending_start = -1 # position of current ending start
637 endings = [] # list of already finished endings
639 last = len (music_list) - 1
640 repeat_replaced = False
642 while pos < len (music_list) and not repeat_replaced:
644 repeat_finished = False
645 if isinstance (e, RepeatMarker):
646 if not repeat_times and e.times:
647 repeat_times = e.times
648 if e.direction == -1:
650 repeat_finished = True
656 elif e.direction == 1:
662 elif isinstance (e, EndingMarker):
663 if e.direction == -1:
669 elif e.direction == 1:
672 endings.append ([ending_start, pos])
675 elif not isinstance (e, musicexp.BarLine):
676 # As soon as we encounter an element when repeat start and end
677 # is set and we are not inside an alternative ending,
678 # this whole repeat structure is finished => replace it
679 if repeat_start >= 0 and repeat_end > 0 and ending_start < 0:
680 repeat_finished = True
682 # Finish off all repeats without explicit ending bar (e.g. when
683 # we convert only one page of a multi-page score with repeats)
684 if pos == last and repeat_start >= 0:
685 repeat_finished = True
689 if ending_start >= 0:
690 endings.append ([ending_start, pos])
694 # We found the whole structure replace it!
695 r = musicexp.RepeatedMusic ()
696 if repeat_times <= 0:
698 r.repeat_count = repeat_times
699 # don't erase the first element for "implicit" repeats (i.e. no
700 # starting repeat bars at the very beginning)
701 start = repeat_start+1
702 if repeat_start == music_start:
704 r.set_music (music_list[start:repeat_end])
705 for (start, end) in endings:
706 s = musicexp.SequentialMusic ()
707 s.elements = music_list[start+1:end]
709 del music_list[repeat_start:final_marker+1]
710 music_list.insert (repeat_start, r)
711 repeat_replaced = True
713 # TODO: Implement repeats until the end without explicit ending bar
717 # Extract the settings for tuplets from the <notations><tuplet> and the
718 # <time-modification> elements of the note:
719 def musicxml_tuplet_to_lily (tuplet_elt, time_modification):
720 tsm = musicexp.TimeScaledMusic ()
722 if time_modification:
723 fraction = time_modification.get_fraction ()
724 tsm.numerator = fraction[0]
725 tsm.denominator = fraction[1]
728 normal_type = tuplet_elt.get_normal_type ()
729 if not normal_type and time_modification:
730 normal_type = time_modification.get_normal_type ()
731 if not normal_type and time_modification:
732 note = time_modification.get_parent ()
734 normal_type = note.get_duration_info ()
736 normal_note = musicexp.Duration ()
737 (normal_note.duration_log, normal_note.dots) = normal_type
738 tsm.normal_type = normal_note
740 actual_type = tuplet_elt.get_actual_type ()
742 actual_note = musicexp.Duration ()
743 (actual_note.duration_log, actual_note.dots) = actual_type
744 tsm.actual_type = actual_note
746 # Obtain non-default nrs of notes from the tuplet object!
747 tsm.display_numerator = tuplet_elt.get_normal_nr ()
748 tsm.display_denominator = tuplet_elt.get_actual_nr ()
751 if hasattr (tuplet_elt, 'bracket') and tuplet_elt.bracket == "no":
752 tsm.display_bracket = None
753 elif hasattr (tuplet_elt, 'line-shape') and getattr (tuplet_elt, 'line-shape') == "curved":
754 tsm.display_bracket = "curved"
756 tsm.display_bracket = "bracket"
758 display_values = {"none": None, "actual": "actual", "both": "both"}
759 if hasattr (tuplet_elt, "show-number"):
760 tsm.display_number = display_values.get (getattr (tuplet_elt, "show-number"), "actual")
762 if hasattr (tuplet_elt, "show-type"):
763 tsm.display_type = display_values.get (getattr (tuplet_elt, "show-type"), None)
768 def group_tuplets (music_list, events):
771 """Collect Musics from
772 MUSIC_LIST demarcated by EVENTS_LIST in TimeScaledMusic objects.
780 for (ev_chord, tuplet_elt, time_modification) in events:
781 while (j < len (music_list)):
782 if music_list[j] == ev_chord:
786 if hasattr (tuplet_elt, 'number'):
787 nr = getattr (tuplet_elt, 'number')
788 if tuplet_elt.type == 'start':
789 tuplet_object = musicxml_tuplet_to_lily (tuplet_elt, time_modification)
790 tuplet_info = [j, None, tuplet_object]
791 indices.append (tuplet_info)
792 brackets[nr] = tuplet_info
793 elif tuplet_elt.type == 'stop':
794 bracket_info = brackets.get (nr, None)
796 bracket_info[1] = j # Set the ending position to j
801 for (i1, i2, tsm) in indices:
805 new_list.extend (music_list[last:i1])
806 seq = musicexp.SequentialMusic ()
808 seq.elements = music_list[i1:last]
812 new_list.append (tsm)
813 #TODO: Handle nested tuplets!!!!
815 new_list.extend (music_list[last:])
819 def musicxml_clef_to_lily (attributes):
820 change = musicexp.ClefChange ()
821 (change.type, change.position, change.octave) = attributes.get_clef_information ()
824 def musicxml_time_to_lily (attributes):
825 sig = attributes.get_time_signature ()
828 change = musicexp.TimeSignatureChange()
829 change.fractions = sig
830 if (len(sig) != 2) or isinstance (sig[0], list):
831 needed_additional_definitions.append ("compound-time-signature")
833 time_elm = attributes.get_maybe_exist_named_child ('time')
834 if time_elm and hasattr (time_elm, 'symbol'):
835 change.style = { 'single-number': "'single-digit",
838 'normal': "'()"}.get (time_elm.symbol, "'()")
842 # TODO: Handle senza-misura measures
843 # TODO: Handle hidden time signatures (print-object="no")
844 # TODO: What shall we do if the symbol clashes with the sig? e.g. "cut"
845 # with 3/8 or "single-number" with (2+3)/8 or 3/8+2/4?
849 def musicxml_key_to_lily (attributes):
850 key_sig = attributes.get_key_signature ()
851 if not key_sig or not (isinstance (key_sig, list) or isinstance (key_sig, tuple)):
852 error_message (_ ("Unable to extract key signature!"))
855 change = musicexp.KeySignatureChange()
857 if len (key_sig) == 2 and not isinstance (key_sig[0], list):
858 # standard key signature, (fifths, mode)
859 (fifths, mode) = key_sig
862 start_pitch = musicexp.Pitch ()
863 start_pitch.octave = 0
877 start_pitch.alteration = a
879 error_message (_ ("unknown mode %s, expecting 'major' or 'minor' "
880 "or a church mode!") % mode)
882 fifth = musicexp.Pitch()
888 for x in range (fifths):
889 start_pitch = start_pitch.transposed (fifth)
890 change.tonic = start_pitch
893 # Non-standard key signature of the form [[step,alter<,octave>],...]
894 change.non_standard_alterations = key_sig
897 def musicxml_transpose_to_lily (attributes):
898 transpose = attributes.get_transposition ()
902 shift = musicexp.Pitch ()
903 octave_change = transpose.get_maybe_exist_named_child ('octave-change')
905 shift.octave = string.atoi (octave_change.get_text ())
906 chromatic_shift = string.atoi (transpose.get_named_child ('chromatic').get_text ())
907 chromatic_shift_normalized = chromatic_shift % 12;
908 (shift.step, shift.alteration) = [
909 (0,0), (0,1), (1,0), (2,-1), (2,0),
910 (3,0), (3,1), (4,0), (5,-1), (5,0),
911 (6,-1), (6,0)][chromatic_shift_normalized];
913 shift.octave += (chromatic_shift - chromatic_shift_normalized) / 12
915 diatonic = transpose.get_maybe_exist_named_child ('diatonic')
917 diatonic_step = string.atoi (diatonic.get_text ()) % 7
918 if diatonic_step != shift.step:
919 # We got the alter incorrect!
920 old_semitones = shift.semitones ()
921 shift.step = diatonic_step
922 new_semitones = shift.semitones ()
923 shift.alteration += old_semitones - new_semitones
925 transposition = musicexp.Transposition ()
926 transposition.pitch = musicexp.Pitch ().transposed (shift)
930 def musicxml_attributes_to_lily (attrs):
933 'clef': musicxml_clef_to_lily,
934 'time': musicxml_time_to_lily,
935 'key': musicxml_key_to_lily,
936 'transpose': musicxml_transpose_to_lily,
938 for (k, func) in attr_dispatch.items ():
939 children = attrs.get_named_children (k)
947 def extract_display_text (el):
948 child = el.get_maybe_exist_named_child ("display-text")
950 return child.get_text ()
955 def musicxml_print_to_lily (el):
956 # TODO: Implement other print attributes
957 # <!ELEMENT print (page-layout?, system-layout?, staff-layout*,
958 # measure-layout?, measure-numbering?, part-name-display?,
959 # part-abbreviation-display?)>
961 # staff-spacing %tenths; #IMPLIED
962 # new-system %yes-no; #IMPLIED
963 # new-page %yes-no-number; #IMPLIED
964 # blank-page NMTOKEN #IMPLIED
965 # page-number CDATA #IMPLIED
968 if (hasattr (el, "new-system") and conversion_settings.convert_page_layout):
969 val = getattr (el, "new-system")
971 elts.append (musicexp.Break ("break"))
972 if (hasattr (el, "new-page") and conversion_settings.convert_page_layout):
973 val = getattr (el, "new-page")
975 elts.append (musicexp.Break ("pageBreak"))
979 class Marker (musicexp.Music):
983 def print_ly (self, printer):
984 ly.stderr_write (_ ("Encountered unprocessed marker %s\n") % self)
986 def ly_expression (self):
988 class RepeatMarker (Marker):
990 Marker.__init__ (self)
992 class EndingMarker (Marker):
995 # Convert the <barline> element to musicxml.BarLine (for non-standard barlines)
996 # and to RepeatMarker and EndingMarker objects for repeat and
997 # alternatives start/stops
998 def musicxml_barline_to_lily (barline):
999 # retval contains all possible markers in the order:
1000 # 0..bw_ending, 1..bw_repeat, 2..barline, 3..fw_repeat, 4..fw_ending
1002 bartype_element = barline.get_maybe_exist_named_child ("bar-style")
1003 repeat_element = barline.get_maybe_exist_named_child ("repeat")
1004 ending_element = barline.get_maybe_exist_named_child ("ending")
1008 bartype = bartype_element.get_text ()
1010 if repeat_element and hasattr (repeat_element, 'direction'):
1011 repeat = RepeatMarker ()
1012 repeat.direction = {"forward": -1, "backward": 1}.get (repeat_element.direction, 0)
1014 if ( (repeat_element.direction == "forward" and bartype == "heavy-light") or
1015 (repeat_element.direction == "backward" and bartype == "light-heavy") ):
1017 if hasattr (repeat_element, 'times'):
1019 repeat.times = int (repeat_element.times)
1022 repeat.event = barline
1023 if repeat.direction == -1:
1028 if ending_element and hasattr (ending_element, 'type'):
1029 ending = EndingMarker ()
1030 ending.direction = {"start": -1, "stop": 1, "discontinue": 1}.get (ending_element.type, 0)
1031 ending.event = barline
1032 if ending.direction == -1:
1038 b = musicexp.BarLine ()
1042 return retval.values ()
1044 spanner_event_dict = {
1045 'beam' : musicexp.BeamEvent,
1046 'dashes' : musicexp.TextSpannerEvent,
1047 'bracket' : musicexp.BracketSpannerEvent,
1048 'glissando' : musicexp.GlissandoEvent,
1049 'octave-shift' : musicexp.OctaveShiftEvent,
1050 'pedal' : musicexp.PedalEvent,
1051 'slide' : musicexp.GlissandoEvent,
1052 'slur' : musicexp.SlurEvent,
1053 'wavy-line' : musicexp.TrillSpanEvent,
1054 'wedge' : musicexp.HairpinEvent
1056 spanner_type_dict = {
1070 def musicxml_spanner_to_lily_event (mxl_event):
1073 name = mxl_event.get_name()
1074 func = spanner_event_dict.get (name)
1078 error_message (_ ('unknown span event %s') % mxl_event)
1081 type = mxl_event.get_type ()
1082 span_direction = spanner_type_dict.get (type)
1083 # really check for None, because some types will be translated to 0, which
1084 # would otherwise also lead to the unknown span warning
1085 if span_direction != None:
1086 ev.span_direction = span_direction
1088 error_message (_ ('unknown span type %s for %s') % (type, name))
1090 ev.set_span_type (type)
1091 ev.line_type = getattr (mxl_event, 'line-type', 'solid')
1093 # assign the size, which is used for octave-shift, etc.
1094 ev.size = mxl_event.get_size ()
1098 def musicxml_direction_to_indicator (direction):
1099 return { "above": 1, "upright": 1, "up": 1, "below": -1, "downright": -1, "down": -1, "inverted": -1 }.get (direction, 0)
1101 def musicxml_fermata_to_lily_event (mxl_event):
1102 ev = musicexp.ArticulationEvent ()
1103 txt = mxl_event.get_text ()
1104 # The contents of the element defined the shape, possible are normal, angled and square
1105 ev.type = { "angled": "shortfermata", "square": "longfermata" }.get (txt, "fermata")
1106 if hasattr (mxl_event, 'type'):
1107 dir = musicxml_direction_to_indicator (mxl_event.type)
1108 if dir and options.convert_directions:
1109 ev.force_direction = dir
1112 def musicxml_arpeggiate_to_lily_event (mxl_event):
1113 ev = musicexp.ArpeggioEvent ()
1114 ev.direction = musicxml_direction_to_indicator (getattr (mxl_event, 'direction', None))
1117 def musicxml_nonarpeggiate_to_lily_event (mxl_event):
1118 ev = musicexp.ArpeggioEvent ()
1119 ev.non_arpeggiate = True
1120 ev.direction = musicxml_direction_to_indicator (getattr (mxl_event, 'direction', None))
1123 def musicxml_tremolo_to_lily_event (mxl_event):
1124 ev = musicexp.TremoloEvent ()
1125 txt = mxl_event.get_text ()
1132 def musicxml_falloff_to_lily_event (mxl_event):
1133 ev = musicexp.BendEvent ()
1137 def musicxml_doit_to_lily_event (mxl_event):
1138 ev = musicexp.BendEvent ()
1142 def musicxml_bend_to_lily_event (mxl_event):
1143 ev = musicexp.BendEvent ()
1144 ev.alter = mxl_event.bend_alter ()
1147 def musicxml_caesura_to_lily_event (mxl_event):
1148 ev = musicexp.MarkupEvent ()
1149 # FIXME: default to straight or curved caesura?
1150 ev.contents = "\\musicglyph #\"scripts.caesura.straight\""
1151 ev.force_direction = 1
1154 def musicxml_fingering_event (mxl_event):
1155 ev = musicexp.ShortArticulationEvent ()
1156 ev.type = mxl_event.get_text ()
1159 def musicxml_string_event (mxl_event):
1160 ev = musicexp.NoDirectionArticulationEvent ()
1161 ev.type = mxl_event.get_text ()
1164 def musicxml_accidental_mark (mxl_event):
1165 ev = musicexp.MarkupEvent ()
1166 contents = { "sharp": "\\sharp",
1167 "natural": "\\natural",
1169 "double-sharp": "\\doublesharp",
1170 "sharp-sharp": "\\sharp\\sharp",
1171 "flat-flat": "\\flat\\flat",
1172 "flat-flat": "\\doubleflat",
1173 "natural-sharp": "\\natural\\sharp",
1174 "natural-flat": "\\natural\\flat",
1175 "quarter-flat": "\\semiflat",
1176 "quarter-sharp": "\\semisharp",
1177 "three-quarters-flat": "\\sesquiflat",
1178 "three-quarters-sharp": "\\sesquisharp",
1179 }.get (mxl_event.get_text ())
1181 ev.contents = contents
1186 # translate articulations, ornaments and other notations into ArticulationEvents
1188 # -) string (ArticulationEvent with that name)
1189 # -) function (function(mxl_event) needs to return a full ArticulationEvent-derived object
1190 # -) (class, name) (like string, only that a different class than ArticulationEvent is used)
1191 # TODO: Some translations are missing!
1192 articulations_dict = {
1193 "accent": (musicexp.ShortArticulationEvent, ">"), # or "accent"
1194 "accidental-mark": musicxml_accidental_mark,
1195 "bend": musicxml_bend_to_lily_event,
1196 "breath-mark": (musicexp.NoDirectionArticulationEvent, "breathe"),
1197 "caesura": musicxml_caesura_to_lily_event,
1198 #"delayed-turn": "?",
1199 "detached-legato": (musicexp.ShortArticulationEvent, "_"), # or "portato"
1200 "doit": musicxml_doit_to_lily_event,
1201 #"double-tongue": "?",
1202 "down-bow": "downbow",
1203 "falloff": musicxml_falloff_to_lily_event,
1204 "fingering": musicxml_fingering_event,
1205 #"fingernails": "?",
1208 "harmonic": "flageolet",
1210 "inverted-mordent": "prall",
1211 "inverted-turn": "reverseturn",
1212 "mordent": "mordent",
1213 "open-string": "open",
1220 "snap-pizzicato": "snappizzicato",
1222 "staccatissimo": (musicexp.ShortArticulationEvent, "|"), # or "staccatissimo"
1223 "staccato": (musicexp.ShortArticulationEvent, "."), # or "staccato"
1224 "stopped": (musicexp.ShortArticulationEvent, "+"), # or "stopped"
1226 "string": musicxml_string_event,
1227 "strong-accent": (musicexp.ShortArticulationEvent, "^"), # or "marcato"
1229 "tenuto": (musicexp.ShortArticulationEvent, "-"), # or "tenuto"
1230 "thumb-position": "thumb",
1233 "tremolo": musicxml_tremolo_to_lily_event,
1234 "trill-mark": "trill",
1235 #"triple-tongue": "?",
1240 articulation_spanners = [ "wavy-line" ]
1242 def musicxml_articulation_to_lily_event (mxl_event):
1243 # wavy-line elements are treated as trill spanners, not as articulation ornaments
1244 if mxl_event.get_name () in articulation_spanners:
1245 return musicxml_spanner_to_lily_event (mxl_event)
1247 tmp_tp = articulations_dict.get (mxl_event.get_name ())
1251 if isinstance (tmp_tp, str):
1252 ev = musicexp.ArticulationEvent ()
1254 elif isinstance (tmp_tp, tuple):
1258 ev = tmp_tp (mxl_event)
1260 # Some articulations use the type attribute, other the placement...
1262 if hasattr (mxl_event, 'type') and options.convert_directions:
1263 dir = musicxml_direction_to_indicator (mxl_event.type)
1264 if hasattr (mxl_event, 'placement') and options.convert_directions:
1265 dir = musicxml_direction_to_indicator (mxl_event.placement)
1267 ev.force_direction = dir
1272 def musicxml_dynamics_to_lily_event (dynentry):
1273 dynamics_available = (
1274 "ppppp", "pppp", "ppp", "pp", "p", "mp", "mf",
1275 "f", "ff", "fff", "ffff", "fp", "sf", "sff", "sp", "spp", "sfz", "rfz" )
1276 dynamicsname = dynentry.get_name ()
1277 if dynamicsname == "other-dynamics":
1278 dynamicsname = dynentry.get_text ()
1279 if not dynamicsname or dynamicsname=="#text":
1282 if not dynamicsname in dynamics_available:
1283 # Get rid of - in tag names (illegal in ly tags!)
1284 dynamicstext = dynamicsname
1285 dynamicsname = string.replace (dynamicsname, "-", "")
1286 additional_definitions[dynamicsname] = dynamicsname + \
1287 " = #(make-dynamic-script \"" + dynamicstext + "\")"
1288 needed_additional_definitions.append (dynamicsname)
1289 event = musicexp.DynamicsEvent ()
1290 event.type = dynamicsname
1293 # Convert single-color two-byte strings to numbers 0.0 - 1.0
1294 def hexcolorval_to_nr (hex_val):
1296 v = int (hex_val, 16)
1303 def hex_to_color (hex_val):
1304 res = re.match (r'#([0-9a-f][0-9a-f]|)([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])$', hex_val, re.IGNORECASE)
1306 return map (lambda x: hexcolorval_to_nr (x), res.group (2,3,4))
1310 def musicxml_words_to_lily_event (words):
1311 event = musicexp.TextEvent ()
1312 text = words.get_text ()
1313 text = re.sub ('^ *\n? *', '', text)
1314 text = re.sub (' *\n? *$', '', text)
1317 if hasattr (words, 'default-y') and options.convert_directions:
1318 offset = getattr (words, 'default-y')
1320 off = string.atoi (offset)
1322 event.force_direction = 1
1324 event.force_direction = -1
1326 event.force_direction = 0
1328 if hasattr (words, 'font-weight'):
1329 font_weight = { "normal": '', "bold": '\\bold' }.get (getattr (words, 'font-weight'), '')
1331 event.markup += font_weight
1333 if hasattr (words, 'font-size'):
1334 size = getattr (words, 'font-size')
1336 "xx-small": '\\teeny',
1337 "x-small": '\\tiny',
1341 "x-large": '\\huge',
1342 "xx-large": '\\larger\\huge'
1345 event.markup += font_size
1347 if hasattr (words, 'color'):
1348 color = getattr (words, 'color')
1349 rgb = hex_to_color (color)
1351 event.markup += "\\with-color #(rgb-color %s %s %s)" % (rgb[0], rgb[1], rgb[2])
1353 if hasattr (words, 'font-style'):
1354 font_style = { "italic": '\\italic' }.get (getattr (words, 'font-style'), '')
1356 event.markup += font_style
1358 # TODO: How should I best convert the font-family attribute?
1360 # TODO: How can I represent the underline, overline and line-through
1361 # attributes in LilyPond? Values of these attributes indicate
1362 # the number of lines
1367 # convert accordion-registration to lilypond.
1368 # Since lilypond does not have any built-in commands, we need to create
1369 # the markup commands manually and define our own variables.
1370 # Idea was taken from: http://lsr.dsi.unimi.it/LSR/Item?id=194
1371 def musicxml_accordion_to_markup (mxl_event):
1372 commandname = "accReg"
1375 high = mxl_event.get_maybe_exist_named_child ('accordion-high')
1378 command += """\\combine
1379 \\raise #2.5 \\musicglyph #\"accordion.accDot\"
1381 middle = mxl_event.get_maybe_exist_named_child ('accordion-middle')
1383 # By default, use one dot (when no or invalid content is given). The
1384 # MusicXML spec is quiet about this case...
1387 txt = string.atoi (middle.get_text ())
1391 commandname += "MMM"
1392 command += """\\combine
1393 \\raise #1.5 \\musicglyph #\"accordion.accDot\"
1395 \\raise #1.5 \\translate #(cons 1 0) \\musicglyph #\"accordion.accDot\"
1397 \\raise #1.5 \\translate #(cons -1 0) \\musicglyph #\"accordion.accDot\"
1401 command += """\\combine
1402 \\raise #1.5 \\translate #(cons 0.5 0) \\musicglyph #\"accordion.accDot\"
1404 \\raise #1.5 \\translate #(cons -0.5 0) \\musicglyph #\"accordion.accDot\"
1408 command += """\\combine
1409 \\raise #1.5 \\musicglyph #\"accordion.accDot\"
1411 low = mxl_event.get_maybe_exist_named_child ('accordion-low')
1414 command += """\\combine
1415 \\raise #0.5 \musicglyph #\"accordion.accDot\"
1418 command += "\musicglyph #\"accordion.accDiscant\""
1419 command = "\\markup { \\normalsize %s }" % command
1420 # Define the newly built command \accReg[H][MMM][L]
1421 additional_definitions[commandname] = "%s = %s" % (commandname, command)
1422 needed_additional_definitions.append (commandname)
1423 return "\\%s" % commandname
1425 def musicxml_accordion_to_ly (mxl_event):
1426 txt = musicxml_accordion_to_markup (mxl_event)
1428 ev = musicexp.MarkEvent (txt)
1433 def musicxml_rehearsal_to_ly_mark (mxl_event):
1434 text = mxl_event.get_text ()
1437 # default is boxed rehearsal marks!
1439 if hasattr (mxl_event, 'enclosure'):
1440 encl = {"none": None, "square": "box", "circle": "circle" }.get (mxl_event.enclosure, None)
1442 text = "\\%s { %s }" % (encl, text)
1443 ev = musicexp.MarkEvent ("\\markup { %s }" % text)
1446 def musicxml_harp_pedals_to_ly (mxl_event):
1448 result = "\\harp-pedal #\""
1449 for t in mxl_event.get_named_children ('pedal-tuning'):
1450 alter = t.get_named_child ('pedal-alter')
1452 val = int (alter.get_text ().strip ())
1453 result += {1: "v", 0: "-", -1: "^"}.get (val, "")
1457 ev = musicexp.MarkupEvent ()
1458 ev.contents = result + "\""
1461 def musicxml_eyeglasses_to_ly (mxl_event):
1462 needed_additional_definitions.append ("eyeglasses")
1463 return musicexp.MarkEvent ("\\markup { \\eyeglasses }")
1465 def next_non_hash_index (lst, pos):
1467 while pos < len (lst) and isinstance (lst[pos], musicxml.Hash_text):
1471 def musicxml_metronome_to_ly (mxl_event):
1472 children = mxl_event.get_all_children ()
1477 index = next_non_hash_index (children, index)
1478 if isinstance (children[index], musicxml.BeatUnit):
1479 # first form of metronome-mark, using unit and beats/min or other unit
1480 ev = musicexp.TempoMark ()
1481 if hasattr (mxl_event, 'parentheses'):
1482 ev.set_parentheses (mxl_event.parentheses == "yes")
1484 d = musicexp.Duration ()
1485 d.duration_log = musicxml.musicxml_duration_to_log (children[index].get_text ())
1486 index = next_non_hash_index (children, index)
1487 if isinstance (children[index], musicxml.BeatUnitDot):
1489 index = next_non_hash_index (children, index)
1490 ev.set_base_duration (d)
1491 if isinstance (children[index], musicxml.BeatUnit):
1492 # Form "note = newnote"
1493 newd = musicexp.Duration ()
1494 newd.duration_log = musicxml.musicxml_duration_to_log (children[index].get_text ())
1495 index = next_non_hash_index (children, index)
1496 if isinstance (children[index], musicxml.BeatUnitDot):
1498 index = next_non_hash_index (children, index)
1499 ev.set_new_duration (newd)
1500 elif isinstance (children[index], musicxml.PerMinute):
1503 beats = int (children[index].get_text ())
1504 ev.set_beats_per_minute (beats)
1508 error_message (_ ("Unknown metronome mark, ignoring"))
1512 #TODO: Implement the other (more complex) way for tempo marks!
1513 error_message (_ ("Metronome marks with complex relations (<metronome-note> in MusicXML) are not yet implemented."))
1516 # translate directions into Events, possible values:
1517 # -) string (MarkEvent with that command)
1518 # -) function (function(mxl_event) needs to return a full Event-derived object
1519 # -) (class, name) (like string, only that a different class than MarkEvent is used)
1521 'accordion-registration' : musicxml_accordion_to_ly,
1522 'coda' : (musicexp.MusicGlyphMarkEvent, "coda"),
1525 'eyeglasses': musicxml_eyeglasses_to_ly,
1526 'harp-pedals' : musicxml_harp_pedals_to_ly,
1528 'metronome' : musicxml_metronome_to_ly,
1529 'rehearsal' : musicxml_rehearsal_to_ly_mark,
1530 # 'scordatura' : ???
1531 'segno' : (musicexp.MusicGlyphMarkEvent, "segno"),
1532 'words' : musicxml_words_to_lily_event,
1534 directions_spanners = [ 'octave-shift', 'pedal', 'wedge', 'dashes', 'bracket' ]
1536 def musicxml_direction_to_lily (n):
1537 # TODO: Handle the <staff> element!
1539 # placement applies to all children!
1541 if hasattr (n, 'placement') and options.convert_directions:
1542 dir = musicxml_direction_to_indicator (n.placement)
1543 dirtype_children = []
1544 # TODO: The direction-type is used for grouping (e.g. dynamics with text),
1545 # so we can't simply flatten them out!
1546 for dt in n.get_typed_children (musicxml.DirType):
1547 dirtype_children += dt.get_all_children ()
1549 for entry in dirtype_children:
1550 # backets, dashes, octave shifts. pedal marks, hairpins etc. are spanners:
1551 if entry.get_name() in directions_spanners:
1552 event = musicxml_spanner_to_lily_event (entry)
1557 # now treat all the "simple" ones, that can be translated using the dict
1559 tmp_tp = directions_dict.get (entry.get_name (), None)
1560 if isinstance (tmp_tp, str): # string means MarkEvent
1561 ev = musicexp.MarkEvent (tmp_tp)
1562 elif isinstance (tmp_tp, tuple): # tuple means (EventClass, "text")
1563 ev = tmp_tp[0] (tmp_tp[1])
1567 # TODO: set the correct direction! Unfortunately, \mark in ly does
1568 # not seem to support directions!
1572 if entry.get_name () == "dynamics":
1573 for dynentry in entry.get_all_children ():
1574 ev = musicxml_dynamics_to_lily_event (dynentry)
1580 def musicxml_frame_to_lily_event (frame):
1581 ev = musicexp.FretEvent ()
1582 ev.strings = frame.get_strings ()
1583 ev.frets = frame.get_frets ()
1584 #offset = frame.get_first_fret () - 1
1586 for fn in frame.get_named_children ('frame-note'):
1587 fret = fn.get_fret ()
1590 el = [ fn.get_string (), fret ]
1591 fingering = fn.get_fingering ()
1593 el.append (fingering)
1594 ev.elements.append (el)
1597 barre[0] = el[0] # start string
1598 barre[2] = el[1] # fret
1600 barre[1] = el[0] # end string
1605 def musicxml_harmony_to_lily (n):
1607 for f in n.get_named_children ('frame'):
1608 ev = musicxml_frame_to_lily_event (f)
1614 notehead_styles_dict = {
1616 'triangle': '\'triangle',
1617 'diamond': '\'diamond',
1618 'square': '\'la', # TODO: Proper squared note head
1619 'cross': None, # TODO: + shaped note head
1621 'circle-x': '\'xcircle',
1622 'inverted triangle': None, # TODO: Implement
1623 'arrow down': None, # TODO: Implement
1624 'arrow up': None, # TODO: Implement
1625 'slashed': None, # TODO: Implement
1626 'back slashed': None, # TODO: Implement
1628 'cluster': None, # TODO: Implement
1639 def musicxml_notehead_to_lily (nh):
1643 style = notehead_styles_dict.get (nh.get_text ().strip (), None)
1644 style_elm = musicexp.NotestyleEvent ()
1646 style_elm.style = style
1647 if hasattr (nh, 'filled'):
1648 style_elm.filled = (getattr (nh, 'filled') == "yes")
1649 if style_elm.style or (style_elm.filled != None):
1650 styles.append (style_elm)
1653 if hasattr (nh, 'parentheses') and (nh.parentheses == "yes"):
1654 styles.append (musicexp.ParenthesizeEvent ())
1658 def musicxml_chordpitch_to_lily (mxl_cpitch):
1659 r = musicexp.ChordPitch ()
1660 r.alteration = mxl_cpitch.get_alteration ()
1661 r.step = musicxml_step_to_lily (mxl_cpitch.get_step ())
1667 'augmented': 'aug5',
1668 'diminished': 'dim5',
1671 'dominant-seventh': '7',
1672 'major-seventh': 'maj7',
1673 'minor-seventh': 'm7',
1674 'diminished-seventh': 'dim7',
1675 'augmented-seventh': 'aug7',
1676 'half-diminished': 'dim5m7',
1677 'major-minor': 'maj7m5',
1680 'minor-sixth': 'm6',
1682 'dominant-ninth': '9',
1683 'major-ninth': 'maj9',
1684 'minor-ninth': 'm9',
1685 # 11ths (usually as the basis for alteration):
1686 'dominant-11th': '11',
1687 'major-11th': 'maj11',
1688 'minor-11th': 'm11',
1689 # 13ths (usually as the basis for alteration):
1690 'dominant-13th': '13.11',
1691 'major-13th': 'maj13.11',
1692 'minor-13th': 'm13',
1694 'suspended-second': 'sus2',
1695 'suspended-fourth': 'sus4',
1696 # Functional sixths:
1698 #'Neapolitan': '???',
1703 #'pedal': '???',(pedal-point bass)
1710 def musicxml_chordkind_to_lily (kind):
1711 res = chordkind_dict.get (kind, None)
1712 # Check for None, since a major chord is converted to ''
1714 error_message (_ ("Unable to convert chord type %s to lilypond.") % kind)
1717 def musicxml_harmony_to_lily_chordname (n):
1719 root = n.get_maybe_exist_named_child ('root')
1721 ev = musicexp.ChordNameEvent ()
1722 ev.root = musicxml_chordpitch_to_lily (root)
1723 kind = n.get_maybe_exist_named_child ('kind')
1725 ev.kind = musicxml_chordkind_to_lily (kind.get_text ())
1728 bass = n.get_maybe_exist_named_child ('bass')
1730 ev.bass = musicxml_chordpitch_to_lily (bass)
1731 inversion = n.get_maybe_exist_named_child ('inversion')
1733 # TODO: LilyPond does not support inversions, does it?
1735 # Mail from Carl Sorensen on lilypond-devel, June 11, 2008:
1736 # 4. LilyPond supports the first inversion in the form of added
1737 # bass notes. So the first inversion of C major would be c:/g.
1738 # To get the second inversion of C major, you would need to do
1739 # e:6-3-^5 or e:m6-^5. However, both of these techniques
1740 # require you to know the chord and calculate either the fifth
1741 # pitch (for the first inversion) or the third pitch (for the
1742 # second inversion) so they may not be helpful for musicxml2ly.
1743 inversion_count = string.atoi (inversion.get_text ())
1744 if inversion_count == 1:
1745 # TODO: Calculate the bass note for the inversion...
1748 for deg in n.get_named_children ('degree'):
1749 d = musicexp.ChordModification ()
1750 d.type = deg.get_type ()
1751 d.step = deg.get_value ()
1752 d.alteration = deg.get_alter ()
1753 ev.add_modification (d)
1754 #TODO: convert the user-symbols attribute:
1755 #major: a triangle, like Unicode 25B3
1756 #minor: -, like Unicode 002D
1757 #augmented: +, like Unicode 002B
1758 #diminished: (degree), like Unicode 00B0
1759 #half-diminished: (o with slash), like Unicode 00F8
1765 def musicxml_figured_bass_note_to_lily (n):
1766 res = musicexp.FiguredBassNote ()
1767 suffix_dict = { 'sharp' : "+",
1770 'double-sharp' : "++",
1772 'sharp-sharp' : "++",
1774 prefix = n.get_maybe_exist_named_child ('prefix')
1776 res.set_prefix (suffix_dict.get (prefix.get_text (), ""))
1777 fnumber = n.get_maybe_exist_named_child ('figure-number')
1779 res.set_number (fnumber.get_text ())
1780 suffix = n.get_maybe_exist_named_child ('suffix')
1782 res.set_suffix (suffix_dict.get (suffix.get_text (), ""))
1783 if n.get_maybe_exist_named_child ('extend'):
1784 # TODO: Implement extender lines (unfortunately, in lilypond you have
1785 # to use \set useBassFigureExtenders = ##t, which turns them on
1786 # globally, while MusicXML has a property for each note...
1787 # I'm not sure there is a proper way to implement this cleanly
1794 def musicxml_figured_bass_to_lily (n):
1795 if not isinstance (n, musicxml.FiguredBass):
1797 res = musicexp.FiguredBassEvent ()
1798 for i in n.get_named_children ('figure'):
1799 note = musicxml_figured_bass_note_to_lily (i)
1802 dur = n.get_maybe_exist_named_child ('duration')
1804 # apply the duration to res
1805 length = Rational(int(dur.get_text()), n._divisions)*Rational(1,4)
1806 res.set_real_duration (length)
1807 duration = rational_to_lily_duration (length)
1809 res.set_duration (duration)
1810 if hasattr (n, 'parentheses') and n.parentheses == "yes":
1811 res.set_parentheses (True)
1814 instrument_drumtype_dict = {
1815 'Acoustic Snare Drum': 'acousticsnare',
1816 'Side Stick': 'sidestick',
1817 'Open Triangle': 'opentriangle',
1818 'Mute Triangle': 'mutetriangle',
1819 'Tambourine': 'tambourine',
1820 'Bass Drum': 'bassdrum',
1823 def musicxml_note_to_lily_main_event (n):
1828 mxl_pitch = n.get_maybe_exist_typed_child (musicxml.Pitch)
1830 pitch = musicxml_pitch_to_lily (mxl_pitch)
1831 event = musicexp.NoteEvent ()
1834 acc = n.get_maybe_exist_named_child ('accidental')
1836 # let's not force accs everywhere.
1837 event.cautionary = acc.editorial
1839 elif n.get_maybe_exist_typed_child (musicxml.Unpitched):
1840 # Unpitched elements have display-step and can also have
1842 unpitched = n.get_maybe_exist_typed_child (musicxml.Unpitched)
1843 event = musicexp.NoteEvent ()
1844 event.pitch = musicxml_unpitched_to_lily (unpitched)
1846 elif n.get_maybe_exist_typed_child (musicxml.Rest):
1847 # rests can have display-octave and display-step, which are
1848 # treated like an ordinary note pitch
1849 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
1850 event = musicexp.RestEvent ()
1851 if options.convert_rest_positions:
1852 pitch = musicxml_restdisplay_to_lily (rest)
1855 elif n.instrument_name:
1856 event = musicexp.NoteEvent ()
1857 drum_type = instrument_drumtype_dict.get (n.instrument_name)
1859 event.drum_type = drum_type
1861 n.message (_ ("drum %s type unknown, please add to instrument_drumtype_dict") % n.instrument_name)
1862 event.drum_type = 'acousticsnare'
1865 n.message (_ ("cannot find suitable event"))
1868 event.duration = musicxml_duration_to_lily (n)
1870 noteheads = n.get_named_children ('notehead')
1871 for nh in noteheads:
1872 styles = musicxml_notehead_to_lily (nh)
1874 event.add_associated_event (s)
1878 def musicxml_lyrics_to_text (lyrics):
1879 # TODO: Implement text styles for lyrics syllables
1883 for e in lyrics.get_all_children ():
1884 if isinstance (e, musicxml.Syllabic):
1885 continued = e.continued ()
1886 elif isinstance (e, musicxml.Text):
1887 # We need to convert soft hyphens to -, otherwise the ascii codec as well
1888 # as lilypond will barf on that character
1889 text += string.replace( e.get_text(), u'\xad', '-' )
1890 elif isinstance (e, musicxml.Elision):
1895 elif isinstance (e, musicxml.Extend):
1900 if text == "-" and continued:
1902 elif text == "_" and extended:
1904 elif continued and text:
1905 return musicxml.escape_ly_output_string (text) + " --"
1908 elif extended and text:
1909 return musicxml.escape_ly_output_string (text) + " __"
1913 return musicxml.escape_ly_output_string (text)
1919 def __init__ (self, here, dest):
1923 class LilyPondVoiceBuilder:
1924 def __init__ (self):
1926 self.pending_dynamics = []
1927 self.end_moment = Rational (0)
1928 self.begin_moment = Rational (0)
1929 self.pending_multibar = Rational (0)
1930 self.ignore_skips = False
1931 self.has_relevant_elements = False
1932 self.measure_length = Rational (4, 4)
1934 def _insert_multibar (self):
1935 layout_information.set_context_item ('Score', 'skipBars = ##t')
1936 r = musicexp.MultiMeasureRest ()
1937 lenfrac = self.measure_length
1938 r.duration = rational_to_lily_duration (lenfrac)
1939 r.duration.factor *= self.pending_multibar / lenfrac
1940 self.elements.append (r)
1941 self.begin_moment = self.end_moment
1942 self.end_moment = self.begin_moment + self.pending_multibar
1943 self.pending_multibar = Rational (0)
1945 def set_measure_length (self, mlen):
1946 if (mlen != self.measure_length) and self.pending_multibar:
1947 self._insert_multibar ()
1948 self.measure_length = mlen
1950 def add_multibar_rest (self, duration):
1951 self.pending_multibar += duration
1953 def set_duration (self, duration):
1954 self.end_moment = self.begin_moment + duration
1955 def current_duration (self):
1956 return self.end_moment - self.begin_moment
1958 def add_music (self, music, duration, relevant = True):
1959 assert isinstance (music, musicexp.Music)
1960 if self.pending_multibar > Rational (0):
1961 self._insert_multibar ()
1963 self.has_relevant_elements = self.has_relevant_elements or relevant
1964 self.elements.append (music)
1965 self.begin_moment = self.end_moment
1966 self.set_duration (duration)
1968 # Insert all pending dynamics right after the note/rest:
1969 if isinstance (music, musicexp.ChordEvent) and self.pending_dynamics:
1970 for d in self.pending_dynamics:
1972 self.pending_dynamics = []
1974 # Insert some music command that does not affect the position in the measure
1975 def add_command (self, command, relevant = True):
1976 assert isinstance (command, musicexp.Music)
1977 if self.pending_multibar > Rational (0):
1978 self._insert_multibar ()
1979 self.has_relevant_elements = self.has_relevant_elements or relevant
1980 self.elements.append (command)
1981 def add_barline (self, barline, relevant = False):
1982 # Insert only if we don't have a barline already
1983 # TODO: Implement proper merging of default barline and custom bar line
1984 has_relevant = self.has_relevant_elements
1985 if (not (self.elements) or
1986 not (isinstance (self.elements[-1], musicexp.BarLine)) or
1987 (self.pending_multibar > Rational (0))):
1988 self.add_music (barline, Rational (0))
1989 self.has_relevant_elements = has_relevant or relevant
1990 def add_partial (self, command):
1991 self.ignore_skips = True
1992 # insert the partial, but restore relevant_elements (partial is not relevant)
1993 relevant = self.has_relevant_elements
1994 self.add_command (command)
1995 self.has_relevant_elements = relevant
1997 def add_dynamics (self, dynamic):
1998 # store the dynamic item(s) until we encounter the next note/rest:
1999 self.pending_dynamics.append (dynamic)
2001 def add_bar_check (self, number):
2002 # re/store has_relevant_elements, so that a barline alone does not
2003 # trigger output for figured bass, chord names
2004 b = musicexp.BarLine ()
2005 b.bar_number = number
2006 self.add_barline (b)
2008 def jumpto (self, moment):
2009 current_end = self.end_moment + self.pending_multibar
2010 diff = moment - current_end
2012 if diff < Rational (0):
2013 error_message (_ ('Negative skip %s (from position %s to %s)') %
2014 (diff, current_end, moment))
2017 if diff > Rational (0) and not (self.ignore_skips and moment == 0):
2018 skip = musicexp.SkipEvent()
2020 duration_log = {1: 0, 2: 1, 4:2, 8:3, 16:4, 32:5, 64:6, 128:7, 256:8, 512:9}.get (diff.denominator (), -1)
2022 # TODO: Use the time signature for skips, too. Problem: The skip
2023 # might not start at a measure boundary!
2024 if duration_log > 0: # denominator is a power of 2...
2025 if diff.numerator () == 3:
2029 duration_factor = Rational (diff.numerator ())
2031 # for skips of a whole or more, simply use s1*factor
2033 duration_factor = diff
2034 skip.duration.duration_log = duration_log
2035 skip.duration.factor = duration_factor
2036 skip.duration.dots = duration_dots
2038 evc = musicexp.ChordEvent ()
2039 evc.elements.append (skip)
2040 self.add_music (evc, diff, False)
2042 if diff > Rational (0) and moment == 0:
2043 self.ignore_skips = False
2045 def last_event_chord (self, starting_at):
2049 # if the position matches, find the last ChordEvent, do not cross a bar line!
2050 at = len( self.elements ) - 1
2052 not isinstance (self.elements[at], musicexp.ChordEvent) and
2053 not isinstance (self.elements[at], musicexp.BarLine)):
2058 and isinstance (self.elements[at], musicexp.ChordEvent)
2059 and self.begin_moment == starting_at):
2060 value = self.elements[at]
2062 self.jumpto (starting_at)
2066 def correct_negative_skip (self, goto):
2067 self.end_moment = goto
2068 self.begin_moment = goto
2069 evc = musicexp.ChordEvent ()
2070 self.elements.append (evc)
2074 def __init__ (self):
2075 self.voicename = None
2076 self.voicedata = None
2077 self.ly_voice = None
2078 self.figured_bass = None
2079 self.chordnames = None
2080 self.lyrics_dict = {}
2081 self.lyrics_order = []
2083 def musicxml_step_to_lily (step):
2085 return (ord (step) - ord ('A') + 7 - 2) % 7
2089 def measure_length_from_attributes (attr, current_measure_length):
2090 len = attr.get_measure_length ()
2092 len = current_measure_length
2095 def musicxml_voice_to_lily_voice (voice):
2099 return_value = VoiceData ()
2100 return_value.voicedata = voice
2102 # First pitch needed for relative mode (if selected in command-line options)
2105 # Needed for melismata detection (ignore lyrics on those notes!):
2110 ignore_lyrics = False
2112 current_staff = None
2114 pending_figured_bass = []
2115 pending_chordnames = []
2117 # Make sure that the keys in the dict don't get reordered, since
2118 # we need the correct ordering of the lyrics stanzas! By default,
2119 # a dict will reorder its keys
2120 return_value.lyrics_order = voice.get_lyrics_numbers ()
2121 for k in return_value.lyrics_order:
2124 voice_builder = LilyPondVoiceBuilder ()
2125 figured_bass_builder = LilyPondVoiceBuilder ()
2126 chordnames_builder = LilyPondVoiceBuilder ()
2127 current_measure_length = Rational (4, 4)
2128 voice_builder.set_measure_length (current_measure_length)
2130 for n in voice._elements:
2132 if n.get_name () == 'forward':
2134 staff = n.get_maybe_exist_named_child ('staff')
2136 staff = staff.get_text ()
2137 if current_staff and staff <> current_staff and not n.get_maybe_exist_named_child ('chord'):
2138 voice_builder.add_command (musicexp.StaffChange (staff))
2139 current_staff = staff
2141 if isinstance (n, musicxml.Partial) and n.partial > 0:
2142 a = musicxml_partial_to_lily (n.partial)
2144 voice_builder.add_partial (a)
2145 figured_bass_builder.add_partial (a)
2146 chordnames_builder.add_partial (a)
2149 is_chord = n.get_maybe_exist_named_child ('chord')
2150 is_after_grace = (isinstance (n, musicxml.Note) and n.is_after_grace ());
2151 if not is_chord and not is_after_grace:
2153 voice_builder.jumpto (n._when)
2154 figured_bass_builder.jumpto (n._when)
2155 chordnames_builder.jumpto (n._when)
2156 except NegativeSkip, neg:
2157 voice_builder.correct_negative_skip (n._when)
2158 figured_bass_builder.correct_negative_skip (n._when)
2159 chordnames_builder.correct_negative_skip (n._when)
2160 n.message (_ ("Negative skip found: from %s to %s, difference is %s") % (neg.here, neg.dest, neg.dest - neg.here))
2162 if isinstance (n, musicxml.Barline):
2163 barlines = musicxml_barline_to_lily (n)
2165 if isinstance (a, musicexp.BarLine):
2166 voice_builder.add_barline (a)
2167 figured_bass_builder.add_barline (a, False)
2168 chordnames_builder.add_barline (a, False)
2169 elif isinstance (a, RepeatMarker) or isinstance (a, EndingMarker):
2170 voice_builder.add_command (a)
2171 figured_bass_builder.add_barline (a, False)
2172 chordnames_builder.add_barline (a, False)
2176 if isinstance (n, musicxml.Print):
2177 for a in musicxml_print_to_lily (n):
2178 voice_builder.add_command (a, False)
2181 # Continue any multimeasure-rests before trying to add bar checks!
2182 # Don't handle new MM rests yet, because for them we want bar checks!
2183 rest = n.get_maybe_exist_typed_child (musicxml.Rest)
2184 if (rest and rest.is_whole_measure ()
2185 and voice_builder.pending_multibar > Rational (0)):
2186 voice_builder.add_multibar_rest (n._duration)
2190 # print a bar check at the beginning of each measure!
2191 if n.is_first () and n._measure_position == Rational (0) and n != voice._elements[0]:
2193 num = int (n.get_parent ().number)
2197 voice_builder.add_bar_check (num)
2198 figured_bass_builder.add_bar_check (num)
2199 chordnames_builder.add_bar_check (num)
2201 # Start any new multimeasure rests
2202 if (rest and rest.is_whole_measure ()):
2203 voice_builder.add_multibar_rest (n._duration)
2207 if isinstance (n, musicxml.Direction):
2208 for a in musicxml_direction_to_lily (n):
2209 if a.wait_for_note ():
2210 voice_builder.add_dynamics (a)
2212 voice_builder.add_command (a)
2215 if isinstance (n, musicxml.Harmony):
2216 for a in musicxml_harmony_to_lily (n):
2217 if a.wait_for_note ():
2218 voice_builder.add_dynamics (a)
2220 voice_builder.add_command (a)
2221 for a in musicxml_harmony_to_lily_chordname (n):
2222 pending_chordnames.append (a)
2225 if isinstance (n, musicxml.FiguredBass):
2226 a = musicxml_figured_bass_to_lily (n)
2228 pending_figured_bass.append (a)
2231 if isinstance (n, musicxml.Attributes):
2232 for a in musicxml_attributes_to_lily (n):
2233 voice_builder.add_command (a)
2234 measure_length = measure_length_from_attributes (n, current_measure_length)
2235 if current_measure_length != measure_length:
2236 current_measure_length = measure_length
2237 voice_builder.set_measure_length (current_measure_length)
2240 if not n.__class__.__name__ == 'Note':
2241 n.message (_ ('unexpected %s; expected %s or %s or %s') % (n, 'Note', 'Attributes', 'Barline'))
2244 main_event = musicxml_note_to_lily_main_event (n)
2245 if main_event and not first_pitch:
2246 first_pitch = main_event.pitch
2247 # ignore lyrics for notes inside a slur, tie, chord or beam
2248 ignore_lyrics = inside_slur or is_tied or is_chord or is_beamed
2250 if main_event and hasattr (main_event, 'drum_type') and main_event.drum_type:
2251 modes_found['drummode'] = True
2253 ev_chord = voice_builder.last_event_chord (n._when)
2255 ev_chord = musicexp.ChordEvent()
2256 voice_builder.add_music (ev_chord, n._duration)
2259 grace = n.get_maybe_exist_typed_child (musicxml.Grace)
2261 is_after_grace = ev_chord.has_elements () or n.is_after_grace ();
2262 is_chord = n.get_maybe_exist_typed_child (musicxml.Chord)
2266 # after-graces and other graces use different lists; Depending on
2267 # whether we have a chord or not, obtain either a new ChordEvent or
2268 # the previous one to create a chord
2270 if ev_chord.after_grace_elements and n.get_maybe_exist_typed_child (musicxml.Chord):
2271 grace_chord = ev_chord.after_grace_elements.get_last_event_chord ()
2273 grace_chord = musicexp.ChordEvent ()
2274 ev_chord.append_after_grace (grace_chord)
2276 if ev_chord.grace_elements and n.get_maybe_exist_typed_child (musicxml.Chord):
2277 grace_chord = ev_chord.grace_elements.get_last_event_chord ()
2279 grace_chord = musicexp.ChordEvent ()
2280 ev_chord.append_grace (grace_chord)
2282 if hasattr (grace, 'slash') and not is_after_grace:
2283 # TODO: use grace_type = "appoggiatura" for slurred grace notes
2284 if grace.slash == "yes":
2285 ev_chord.grace_type = "acciaccatura"
2286 # now that we have inserted the chord into the grace music, insert
2287 # everything into that chord instead of the ev_chord
2288 ev_chord = grace_chord
2289 ev_chord.append (main_event)
2290 ignore_lyrics = True
2292 ev_chord.append (main_event)
2293 # When a note/chord has grace notes (duration==0), the duration of the
2294 # event chord is not yet known, but the event chord was already added
2295 # with duration 0. The following correct this when we hit the real note!
2296 if voice_builder.current_duration () == 0 and n._duration > 0:
2297 voice_builder.set_duration (n._duration)
2299 # if we have a figured bass, set its voice builder to the correct position
2300 # and insert the pending figures
2301 if pending_figured_bass:
2303 figured_bass_builder.jumpto (n._when)
2304 except NegativeSkip, neg:
2306 for fb in pending_figured_bass:
2307 # if a duration is given, use that, otherwise the one of the note
2308 dur = fb.real_duration
2310 dur = ev_chord.get_length ()
2312 fb.duration = ev_chord.get_duration ()
2313 figured_bass_builder.add_music (fb, dur)
2314 pending_figured_bass = []
2316 if pending_chordnames:
2318 chordnames_builder.jumpto (n._when)
2319 except NegativeSkip, neg:
2321 for cn in pending_chordnames:
2322 # Assign the duration of the EventChord
2323 cn.duration = ev_chord.get_duration ()
2324 chordnames_builder.add_music (cn, ev_chord.get_length ())
2325 pending_chordnames = []
2327 notations_children = n.get_typed_children (musicxml.Notations)
2331 # The <notation> element can have the following children (+ means implemented, ~ partially, - not):
2332 # +tied | +slur | +tuplet | glissando | slide |
2333 # ornaments | technical | articulations | dynamics |
2334 # +fermata | arpeggiate | non-arpeggiate |
2335 # accidental-mark | other-notation
2336 for notations in notations_children:
2337 for tuplet_event in notations.get_tuplets():
2338 time_mod = n.get_maybe_exist_typed_child (musicxml.Time_modification)
2339 tuplet_events.append ((ev_chord, tuplet_event, time_mod))
2341 # First, close all open slurs, only then start any new slur
2342 # TODO: Record the number of the open slur to dtermine the correct
2344 endslurs = [s for s in notations.get_named_children ('slur')
2345 if s.get_type () in ('stop')]
2346 if endslurs and not inside_slur:
2347 endslurs[0].message (_ ('Encountered closing slur, but no slur is open'))
2349 if len (endslurs) > 1:
2350 endslurs[0].message (_ ('Cannot have two simultaneous (closing) slurs'))
2351 # record the slur status for the next note in the loop
2353 lily_ev = musicxml_spanner_to_lily_event (endslurs[0])
2354 ev_chord.append (lily_ev)
2356 startslurs = [s for s in notations.get_named_children ('slur')
2357 if s.get_type () in ('start')]
2358 if startslurs and inside_slur:
2359 startslurs[0].message (_ ('Cannot have a slur inside another slur'))
2361 if len (startslurs) > 1:
2362 startslurs[0].message (_ ('Cannot have two simultaneous slurs'))
2363 # record the slur status for the next note in the loop
2365 lily_ev = musicxml_spanner_to_lily_event (startslurs[0])
2366 ev_chord.append (lily_ev)
2370 mxl_tie = notations.get_tie ()
2371 if mxl_tie and mxl_tie.type == 'start':
2372 ev_chord.append (musicexp.TieEvent ())
2378 fermatas = notations.get_named_children ('fermata')
2380 ev = musicxml_fermata_to_lily_event (a)
2382 ev_chord.append (ev)
2384 arpeggiate = notations.get_named_children ('arpeggiate')
2385 for a in arpeggiate:
2386 ev = musicxml_arpeggiate_to_lily_event (a)
2388 ev_chord.append (ev)
2390 arpeggiate = notations.get_named_children ('non-arpeggiate')
2391 for a in arpeggiate:
2392 ev = musicxml_nonarpeggiate_to_lily_event (a)
2394 ev_chord.append (ev)
2396 glissandos = notations.get_named_children ('glissando')
2397 glissandos += notations.get_named_children ('slide')
2398 for a in glissandos:
2399 ev = musicxml_spanner_to_lily_event (a)
2401 ev_chord.append (ev)
2403 # accidental-marks are direct children of <notation>!
2404 for a in notations.get_named_children ('accidental-mark'):
2405 ev = musicxml_articulation_to_lily_event (a)
2407 ev_chord.append (ev)
2409 # Articulations can contain the following child elements:
2410 # accent | strong-accent | staccato | tenuto |
2411 # detached-legato | staccatissimo | spiccato |
2412 # scoop | plop | doit | falloff | breath-mark |
2413 # caesura | stress | unstress
2414 # Technical can contain the following child elements:
2415 # up-bow | down-bow | harmonic | open-string |
2416 # thumb-position | fingering | pluck | double-tongue |
2417 # triple-tongue | stopped | snap-pizzicato | fret |
2418 # string | hammer-on | pull-off | bend | tap | heel |
2419 # toe | fingernails | other-technical
2420 # Ornaments can contain the following child elements:
2421 # trill-mark | turn | delayed-turn | inverted-turn |
2422 # shake | wavy-line | mordent | inverted-mordent |
2423 # schleifer | tremolo | other-ornament, accidental-mark
2424 ornaments = notations.get_named_children ('ornaments')
2425 ornaments += notations.get_named_children ('articulations')
2426 ornaments += notations.get_named_children ('technical')
2429 for ch in a.get_all_children ():
2430 ev = musicxml_articulation_to_lily_event (ch)
2432 ev_chord.append (ev)
2434 dynamics = notations.get_named_children ('dynamics')
2436 for ch in a.get_all_children ():
2437 ev = musicxml_dynamics_to_lily_event (ch)
2439 ev_chord.append (ev)
2442 mxl_beams = [b for b in n.get_named_children ('beam')
2443 if (b.get_type () in ('begin', 'end')
2444 and b.is_primary ())]
2445 if mxl_beams and not conversion_settings.ignore_beaming:
2446 beam_ev = musicxml_spanner_to_lily_event (mxl_beams[0])
2448 ev_chord.append (beam_ev)
2449 if beam_ev.span_direction == -1: # beam and thus melisma starts here
2451 elif beam_ev.span_direction == 1: # beam and thus melisma ends here
2454 # Extract the lyrics
2455 if not rest and not ignore_lyrics:
2456 note_lyrics_processed = []
2457 note_lyrics_elements = n.get_typed_children (musicxml.Lyric)
2458 for l in note_lyrics_elements:
2459 if l.get_number () < 0:
2460 for k in lyrics.keys ():
2461 lyrics[k].append (musicxml_lyrics_to_text (l))
2462 note_lyrics_processed.append (k)
2464 lyrics[l.number].append(musicxml_lyrics_to_text (l))
2465 note_lyrics_processed.append (l.number)
2466 for lnr in lyrics.keys ():
2467 if not lnr in note_lyrics_processed:
2468 lyrics[lnr].append ("\skip4")
2470 # Assume that a <tie> element only lasts for one note.
2471 # This might not be correct MusicXML interpretation, but works for
2472 # most cases and fixes broken files, which have the end tag missing
2473 if is_tied and not tie_started:
2476 ## force trailing mm rests to be written out.
2477 voice_builder.add_music (musicexp.ChordEvent (), Rational (0))
2479 ly_voice = group_tuplets (voice_builder.elements, tuplet_events)
2480 ly_voice = group_repeats (ly_voice)
2482 seq_music = musicexp.SequentialMusic ()
2484 if 'drummode' in modes_found.keys ():
2485 ## \key <pitch> barfs in drummode.
2486 ly_voice = [e for e in ly_voice
2487 if not isinstance(e, musicexp.KeySignatureChange)]
2489 seq_music.elements = ly_voice
2490 for k in lyrics.keys ():
2491 return_value.lyrics_dict[k] = musicexp.Lyrics ()
2492 return_value.lyrics_dict[k].lyrics_syllables = lyrics[k]
2495 if len (modes_found) > 1:
2496 error_message (_ ('cannot simultaneously have more than one mode: %s') % modes_found.keys ())
2498 if options.relative:
2499 v = musicexp.RelativeMusic ()
2500 v.element = seq_music
2501 v.basepitch = first_pitch
2504 return_value.ly_voice = seq_music
2505 for mode in modes_found.keys ():
2506 v = musicexp.ModeChangingMusicWrapper()
2507 v.element = seq_music
2509 return_value.ly_voice = v
2511 # create \figuremode { figured bass elements }
2512 if figured_bass_builder.has_relevant_elements:
2513 fbass_music = musicexp.SequentialMusic ()
2514 fbass_music.elements = group_repeats (figured_bass_builder.elements)
2515 v = musicexp.ModeChangingMusicWrapper()
2516 v.mode = 'figuremode'
2517 v.element = fbass_music
2518 return_value.figured_bass = v
2520 # create \chordmode { chords }
2521 if chordnames_builder.has_relevant_elements:
2522 cname_music = musicexp.SequentialMusic ()
2523 cname_music.elements = group_repeats (chordnames_builder.elements)
2524 v = musicexp.ModeChangingMusicWrapper()
2525 v.mode = 'chordmode'
2526 v.element = cname_music
2527 return_value.chordnames = v
2531 def musicxml_id_to_lily (id):
2532 digits = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five',
2533 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
2535 for digit in digits:
2536 d = digits.index (digit)
2537 id = re.sub ('%d' % d, digit, id)
2539 id = re.sub ('[^a-zA-Z]', 'X', id)
2542 def musicxml_pitch_to_lily (mxl_pitch):
2543 p = musicexp.Pitch ()
2544 p.alteration = mxl_pitch.get_alteration ()
2545 p.step = musicxml_step_to_lily (mxl_pitch.get_step ())
2546 p.octave = mxl_pitch.get_octave () - 4
2549 def musicxml_unpitched_to_lily (mxl_unpitched):
2551 step = mxl_unpitched.get_step ()
2553 p = musicexp.Pitch ()
2554 p.step = musicxml_step_to_lily (step)
2555 octave = mxl_unpitched.get_octave ()
2557 p.octave = octave - 4
2560 def musicxml_restdisplay_to_lily (mxl_rest):
2562 step = mxl_rest.get_step ()
2564 p = musicexp.Pitch ()
2565 p.step = musicxml_step_to_lily (step)
2566 octave = mxl_rest.get_octave ()
2568 p.octave = octave - 4
2571 def voices_in_part (part):
2572 """Return a Name -> Voice dictionary for PART"""
2574 part.extract_voices ()
2575 voices = part.get_voices ()
2576 part_info = part.get_staff_attributes ()
2578 return (voices, part_info)
2580 def voices_in_part_in_parts (parts):
2581 """return a Part -> Name -> Voice dictionary"""
2582 # don't crash if p doesn't have an id (that's invalid MusicXML,
2583 # but such files are out in the wild!
2586 voices = voices_in_part (p)
2587 if (hasattr (p, "id")):
2588 dictionary[p.id] = voices
2590 # TODO: extract correct part id from other sources
2591 dictionary[None] = voices
2595 def get_all_voices (parts):
2596 all_voices = voices_in_part_in_parts (parts)
2599 all_ly_staffinfo = {}
2600 for p, (name_voice, staff_info) in all_voices.items ():
2603 for n, v in name_voice.items ():
2604 progress (_ ("Converting to LilyPond expressions..."))
2605 # musicxml_voice_to_lily_voice returns (lily_voice, {nr->lyrics, nr->lyrics})
2606 part_ly_voices[n] = musicxml_voice_to_lily_voice (v)
2608 all_ly_voices[p] = part_ly_voices
2609 all_ly_staffinfo[p] = staff_info
2611 return (all_ly_voices, all_ly_staffinfo)
2614 def option_parser ():
2615 p = ly.get_option_parser (usage = _ ("musicxml2ly [OPTION]... FILE.xml"),
2617 _ ("""Convert MusicXML from FILE.xml to LilyPond input.
2618 If the given filename is -, musicxml2ly reads from the command line.
2619 """), add_help_option=False)
2621 p.add_option("-h", "--help",
2623 help=_ ("show this help and exit"))
2625 p.version = ('''%prog (LilyPond) @TOPLEVEL_VERSION@\n\n'''
2627 _ ("""Copyright (c) 2005--2010 by
2628 Han-Wen Nienhuys <hanwen@xs4all.nl>,
2629 Jan Nieuwenhuizen <janneke@gnu.org> and
2630 Reinhold Kainhofer <reinhold@kainhofer.com>
2634 This program is free software. It is covered by the GNU General Public
2635 License and you are welcome to change it and/or distribute copies of it
2636 under certain conditions. Invoke as `%s --warranty' for more
2637 information.""") % 'lilypond')
2639 p.add_option("--version",
2641 help=_ ("show version number and exit"))
2643 p.add_option ('-v', '--verbose',
2644 action = "store_true",
2646 help = _ ("be verbose"))
2648 p.add_option ('', '--lxml',
2649 action = "store_true",
2652 help = _ ("use lxml.etree; uses less memory and cpu time"))
2654 p.add_option ('-z', '--compressed',
2655 action = "store_true",
2656 dest = 'compressed',
2658 help = _ ("input file is a zip-compressed MusicXML file"))
2660 p.add_option ('-r', '--relative',
2661 action = "store_true",
2664 help = _ ("convert pitches in relative mode (default)"))
2666 p.add_option ('-a', '--absolute',
2667 action = "store_false",
2669 help = _ ("convert pitches in absolute mode"))
2671 p.add_option ('-l', '--language',
2672 metavar = _ ("LANG"),
2674 help = _ ("use a different language file 'LANG.ly' and corresponding pitch names, e.g. 'deutsch' for deutsch.ly"))
2676 p.add_option ('--nd', '--no-articulation-directions',
2677 action = "store_false",
2679 dest = "convert_directions",
2680 help = _ ("do not convert directions (^, _ or -) for articulations, dynamics, etc."))
2682 p.add_option ('--nrp', '--no-rest-positions',
2683 action = "store_false",
2685 dest = "convert_rest_positions",
2686 help = _ ("do not convert exact vertical positions of rests"))
2688 p.add_option ('--npl', '--no-page-layout',
2689 action = "store_false",
2691 dest = "convert_page_layout",
2692 help = _ ("do not convert the exact page layout and breaks"))
2694 p.add_option ('--no-beaming',
2695 action = "store_false",
2697 dest = "convert_beaming",
2698 help = _ ("do not convert beaming information, use lilypond's automatic beaming instead"))
2700 p.add_option ('-o', '--output',
2701 metavar = _ ("FILE"),
2705 dest = 'output_name',
2706 help = _ ("set output filename to FILE, stdout if -"))
2707 p.add_option_group ('',
2709 _ ("Report bugs via %s")
2710 % 'http://post.gmane.org/post.php'
2711 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
2714 def music_xml_voice_name_to_lily_name (part_id, name):
2715 str = "Part%sVoice%s" % (part_id, name)
2716 return musicxml_id_to_lily (str)
2718 def music_xml_lyrics_name_to_lily_name (part_id, name, lyricsnr):
2719 str = "Part%sVoice%sLyrics%s" % (part_id, name, lyricsnr)
2720 return musicxml_id_to_lily (str)
2722 def music_xml_figuredbass_name_to_lily_name (part_id, voicename):
2723 str = "Part%sVoice%sFiguredBass" % (part_id, voicename)
2724 return musicxml_id_to_lily (str)
2726 def music_xml_chordnames_name_to_lily_name (part_id, voicename):
2727 str = "Part%sVoice%sChords" % (part_id, voicename)
2728 return musicxml_id_to_lily (str)
2730 def print_voice_definitions (printer, part_list, voices):
2731 for part in part_list:
2733 nv_dict = voices.get (part_id, {})
2734 for (name, voice) in nv_dict.items ():
2735 k = music_xml_voice_name_to_lily_name (part_id, name)
2736 printer.dump ('%s = ' % k)
2737 voice.ly_voice.print_ly (printer)
2739 if voice.chordnames:
2740 cnname = music_xml_chordnames_name_to_lily_name (part_id, name)
2741 printer.dump ('%s = ' % cnname )
2742 voice.chordnames.print_ly (printer)
2744 for l in voice.lyrics_order:
2745 lname = music_xml_lyrics_name_to_lily_name (part_id, name, l)
2746 printer.dump ('%s = ' % lname )
2747 voice.lyrics_dict[l].print_ly (printer)
2749 if voice.figured_bass:
2750 fbname = music_xml_figuredbass_name_to_lily_name (part_id, name)
2751 printer.dump ('%s = ' % fbname )
2752 voice.figured_bass.print_ly (printer)
2757 return dict ([(elt,1) for elt in l]).keys ()
2759 # format the information about the staff in the form
2762 # [voiceid1, [lyricsid11, lyricsid12,...], figuredbassid1],
2763 # [voiceid2, [lyricsid21, lyricsid22,...], figuredbassid2],
2767 # raw_voices is of the form [(voicename, lyricsids, havefiguredbass)*]
2768 def format_staff_info (part_id, staff_id, raw_voices):
2770 for (v, lyricsids, figured_bass, chordnames) in raw_voices:
2771 voice_name = music_xml_voice_name_to_lily_name (part_id, v)
2772 voice_lyrics = [music_xml_lyrics_name_to_lily_name (part_id, v, l)
2774 figured_bass_name = ''
2776 figured_bass_name = music_xml_figuredbass_name_to_lily_name (part_id, v)
2777 chordnames_name = ''
2779 chordnames_name = music_xml_chordnames_name_to_lily_name (part_id, v)
2780 voices.append ([voice_name, voice_lyrics, figured_bass_name, chordnames_name])
2781 return [staff_id, voices]
2783 def update_score_setup (score_structure, part_list, voices):
2785 for part_definition in part_list:
2786 part_id = part_definition.id
2787 nv_dict = voices.get (part_id)
2789 error_message (_ ('unknown part in part-list: %s') % part_id)
2792 staves = reduce (lambda x,y: x+ y,
2793 [voice.voicedata._staves.keys ()
2794 for voice in nv_dict.values ()],
2797 if len (staves) > 1:
2799 staves = uniq_list (staves)
2802 thisstaff_raw_voices = [(voice_name, voice.lyrics_order, voice.figured_bass, voice.chordnames)
2803 for (voice_name, voice) in nv_dict.items ()
2804 if voice.voicedata._start_staff == s]
2805 staves_info.append (format_staff_info (part_id, s, thisstaff_raw_voices))
2807 thisstaff_raw_voices = [(voice_name, voice.lyrics_order, voice.figured_bass, voice.chordnames)
2808 for (voice_name, voice) in nv_dict.items ()]
2809 staves_info.append (format_staff_info (part_id, None, thisstaff_raw_voices))
2810 score_structure.set_part_information (part_id, staves_info)
2812 # Set global values in the \layout block, like auto-beaming etc.
2813 def update_layout_information ():
2814 if not conversion_settings.ignore_beaming and layout_information:
2815 layout_information.set_context_item ('Score', 'autoBeaming = ##f')
2817 def print_ly_preamble (printer, filename):
2818 printer.dump_version ()
2819 printer.print_verbatim ('%% automatically converted from %s\n' % filename)
2821 def print_ly_additional_definitions (printer, filename):
2822 if needed_additional_definitions:
2824 printer.print_verbatim ('%% additional definitions required by the score:')
2826 for a in set(needed_additional_definitions):
2827 printer.print_verbatim (additional_definitions.get (a, ''))
2831 # Read in the tree from the given I/O object (either file or string) and
2832 # demarshall it using the classes from the musicxml.py file
2833 def read_xml (io_object, use_lxml):
2836 tree = lxml.etree.parse (io_object)
2837 mxl_tree = musicxml.lxml_demarshal_node (tree.getroot ())
2840 from xml.dom import minidom, Node
2841 doc = minidom.parse(io_object)
2842 node = doc.documentElement
2843 return musicxml.minidom_demarshal_node (node)
2847 def read_musicxml (filename, compressed, use_lxml):
2851 progress (_ ("Input is compressed, extracting raw MusicXML data from stdin") )
2852 z = zipfile.ZipFile (sys.stdin)
2854 progress (_ ("Input file %s is compressed, extracting raw MusicXML data") % filename)
2855 z = zipfile.ZipFile (filename, "r")
2856 container_xml = z.read ("META-INF/container.xml")
2857 if not container_xml:
2859 container = read_xml (StringIO.StringIO (container_xml), use_lxml)
2862 rootfiles = container.get_maybe_exist_named_child ('rootfiles')
2865 rootfile_list = rootfiles.get_named_children ('rootfile')
2867 if len (rootfile_list) > 0:
2868 mxml_file = getattr (rootfile_list[0], 'full-path', None)
2870 raw_string = z.read (mxml_file)
2873 io_object = StringIO.StringIO (raw_string)
2874 elif filename == "-":
2875 io_object = sys.stdin
2877 io_object = filename
2879 return read_xml (io_object, use_lxml)
2882 def convert (filename, options):
2884 progress (_ ("Reading MusicXML from Standard input ...") )
2886 progress (_ ("Reading MusicXML from %s ...") % filename)
2888 tree = read_musicxml (filename, options.compressed, options.use_lxml)
2889 score_information = extract_score_information (tree)
2890 paper_information = extract_paper_information (tree)
2892 parts = tree.get_typed_children (musicxml.Part)
2893 (voices, staff_info) = get_all_voices (parts)
2896 mxl_pl = tree.get_maybe_exist_typed_child (musicxml.Part_list)
2898 score = extract_score_structure (mxl_pl, staff_info)
2899 part_list = mxl_pl.get_named_children ("score-part")
2901 # score information is contained in the <work>, <identification> or <movement-title> tags
2902 update_score_setup (score, part_list, voices)
2903 # After the conversion, update the list of settings for the \layout block
2904 update_layout_information ()
2906 if not options.output_name:
2907 options.output_name = os.path.basename (filename)
2908 options.output_name = os.path.splitext (options.output_name)[0]
2909 elif re.match (".*\.ly", options.output_name):
2910 options.output_name = os.path.splitext (options.output_name)[0]
2913 #defs_ly_name = options.output_name + '-defs.ly'
2914 if (options.output_name == "-"):
2915 output_ly_name = 'Standard output'
2917 output_ly_name = options.output_name + '.ly'
2919 progress (_ ("Output to `%s'") % output_ly_name)
2920 printer = musicexp.Output_printer()
2921 #progress (_ ("Output to `%s'") % defs_ly_name)
2922 if (options.output_name == "-"):
2923 printer.set_file (codecs.getwriter ("utf-8")(sys.stdout))
2925 printer.set_file (codecs.open (output_ly_name, 'wb', encoding='utf-8'))
2926 print_ly_preamble (printer, filename)
2927 print_ly_additional_definitions (printer, filename)
2928 if score_information:
2929 score_information.print_ly (printer)
2930 if paper_information and conversion_settings.convert_page_layout:
2931 paper_information.print_ly (printer)
2932 if layout_information:
2933 layout_information.print_ly (printer)
2934 print_voice_definitions (printer, part_list, voices)
2937 printer.dump ("% The score definition")
2939 score.print_ly (printer)
2944 def get_existing_filename_with_extension (filename, ext):
2945 if os.path.exists (filename):
2947 newfilename = filename + "." + ext
2948 if os.path.exists (newfilename):
2950 newfilename = filename + ext
2951 if os.path.exists (newfilename):
2956 opt_parser = option_parser()
2959 (options, args) = opt_parser.parse_args ()
2961 opt_parser.print_usage()
2964 if options.language:
2965 musicexp.set_pitch_language (options.language)
2966 needed_additional_definitions.append (options.language)
2967 additional_definitions[options.language] = "\\include \"%s.ly\"\n" % options.language
2968 conversion_settings.ignore_beaming = not options.convert_beaming
2969 conversion_settings.convert_page_layout = options.convert_page_layout
2971 # Allow the user to leave out the .xml or xml on the filename
2972 basefilename = args[0].decode('utf-8')
2973 if basefilename == "-": # Read from stdin
2976 filename = get_existing_filename_with_extension (basefilename, "xml")
2978 filename = get_existing_filename_with_extension (basefilename, "mxl")
2979 options.compressed = True
2980 if filename and filename.endswith ("mxl"):
2981 options.compressed = True
2983 if filename and (filename == "-" or os.path.exists (filename)):
2984 voices = convert (filename, options)
2986 progress (_ ("Unable to find input file %s") % basefilename)
2988 if __name__ == '__main__':