2 % Copyright (C) 2008, 2009, 2010, 2011 NICTA
3 % Author: Peter Chubb <peter.chubb AT nicta.com.au>
4 % $Id: articulate.ly,v 1.7 2011-03-24 00:40:00 peterc Exp $
7 % This program is free software; you can redistribute it and/or modify
8 % it under the terms of the GNU General Public License, version 3,
9 % as published by the Free Software Foundation.
11 % WARNING: this file under GPLv3 only, not GPLv3+
13 % This program is distributed in the hope that it will be useful,
14 % but WITHOUT ANY WARRANTY; without even the implied warranty of
15 % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16 % See the GNU General Public License for more details. It is
17 % available in the Lilypond source tree, or at
18 % http://www.gnu.org/licenses/gpl-3.0.html
20 % This script tries to make MIDI output from LilyPond a little more realistic.
21 % It tries to take articulations (slurs, staccato, etc) into account, by
22 % replacing notes with sequential music of suitably time-scaled note plus
25 % It also tries to unfold trills turns etc., and take rallentendo
26 % and accelerando into account.
28 % As my scheme knowledge is poor (I was teaching myself as I went), there
29 % is much scope for improvement.
33 % In the \score section do:
34 % \unfoldRepeats \articulate <<
35 % all the rest of the score
37 % or use the lilywrap script.
39 % TO DO (prioritised, the ones that'll make the most difference first)
42 % * Fix quantisation for dynamics on single note (replace note
43 % with tied 128th notes?) -- started, needs work.
44 % * Make \fp do the right thing (loud start, then quiet).
46 % * Inegalite. Notes on-beat steal time from notes off-beat.
47 % Degree of stealing is a parameter: from 1.0 (straight)
48 % to 1.5 (extreme swing). Also fix tenuto to use this.
50 % * add accel (to match rall), and molto rall. I've never seen
51 % molto accel but some composer somewhere has probably used it.
53 % * Fermata, and Fermata Lunga
54 % * Add more synonyms for accel and rall: rit ritard stringendo
57 % * Rall at end of piece
58 % * Very slight accel into a phrase, rall out of it.
59 % * Dynamics during a phrase???? unclear how these should be in
62 % * Trill algorithm needs work.
64 % * Cope with more ornaments/articulations.
65 % inverted-turns, etc.
66 % -- accent needs better control of dynamics.
67 % -- Articulations: mezzo-staccato, portato.
68 % -- Handling of generic ornaments (in lily, `\stopped'; in
69 % most early music: ornament this note (trill, turn
70 % or mordent as the player wishes))
71 % * Automatic gruppetto at end of trill; better handling of
72 % initial/final grace notes on trill
73 % * Automatic ornaments.
74 % * Spot cadences and ornament
75 % * Look for quaver-dotted note for trills, for example.
76 % * Fill in steps. (Needs lookahead/lookbehind.)
77 % * `afterturn' -- a turn after the start of a note.
78 % * accidentals for trills and turns
81 % * From Iain Nicol: appoggiatura timings were out; add staccatissimo; fix
82 % trillSpanner endpoints.
83 % * Also handle Breathing events (by throwing them away). This isn't ideal;
84 % one should really shorten the note before a little. But I don't know
85 % how to do lookahead in scheme.
86 % * Also ignore explicit line breaks.
87 % * Add Mordents (reported by Patrick Karl)
92 #(use-modules (ice-9 debug))
93 #(use-modules (scm display-lily))
96 % How much to compress notes marked Staccato. CPE Bach says `as short as
97 % may conveniently be played, as if the keys were too hot to touch'.
98 % Most modern sources say 1/2 the notated length of a note.
99 #(define ac:staccatoFactor '(1 . 2))
101 % How much to compress notes marked staccatissimo.
102 #(define ac:staccatissimoFactor '(1 . 4))
104 % And tenuto (if we ever implement time stealing, this should be >1.0)
105 #(define ac:tenutoFactor '(1 . 1))
107 % How much to articulate normal notes. CPE Bach says 1/2 (and
108 % staccato should be `as short as may conveniently be played') but this
109 % sounds too short for modern music. 7/8 sounds about right.
110 #(define ac:normalFactor '(7 . 8))
112 % How much to slow down for a rall. or a poco rall.
113 % (or speed up for accel or poco accel)
114 #(define ac:rallFactor (ly:make-moment 60 100)) % 40% slowdown
115 #(define ac:pocoRallFactor (ly:make-moment 90 100)) % 10% slowdown
117 % The absolute time for a twiddle in a trill, in minutes.
118 % Start with 1/4 seconds == 1/240 minutes
119 #(define ac:maxTwiddleTime (ly:make-moment 1 240))
122 % Internal variables, don't touch.
123 % (should probably be part of a context somehow)
125 % Whether to slur, or not
126 #(define ac:inSlur #f)
127 #(define ac:inPhrasingSlur #f)
129 % Whether the current noteevent is in a trill spanner
130 #(define ac:inTrill #f)
132 % assume start in C major. Key change events override this.
133 % Could get from context, but don't know how.
134 #(define ac:current-key (make-music
137 (ly:make-pitch -1 0 0)
148 #(define ac:currentTempo (ly:make-moment 15 1)) % 4 = 60, measured wholes per minute
149 #(define ac:lastTempo ac:currentTempo) % for 'a tempo' or 'tempo I'
151 % The duration of the current note. Start at a crotchet
152 % for no good reason.
153 #(define ac:currentDuration (ly:make-duration 2 0 1 1))
155 % Debugging: display a moment plus some text.
156 % Returns its moment argument so can be used in-line.
157 #(define (display-moment text m)
159 (display (list (ly:moment-main-numerator m) "/" (ly:moment-main-denominator m)))
163 % Track tempo (and maybe later, other context properties)
164 % as they change. Needs to better cope with saving only Tempo I,
165 % otherwise "a tempo" goes back to the tempo before the last change.
166 #(define (ac:adjust-props sym music)
168 ((tempoWholesPerMinute)
169 (set! ac:currentTempo (ly:music-property music 'value))
170 (set! ac:lastTempo ac:currentTempo)
173 % Raise note one step in the current diatonic scale.
174 #(define (ac:up note)
175 (let* ((pitch (ly:music-property note 'pitch))
176 (notename (ly:pitch-notename pitch))
177 (new-notename (if (eq? notename 6) 0 (+ 1 notename)))
178 (alterations (ly:music-property ac:current-key 'pitch-alist))
179 (new-alteration (cdr (assq new-notename alterations)))
180 (new-octave (if (eq? new-notename 0) (+ 1 (ly:pitch-octave pitch))
181 (ly:pitch-octave pitch)))
183 (set! (ly:music-property note 'pitch)(ly:make-pitch new-octave new-notename new-alteration))))
186 % Lower note one step in the current diatonic scale.
187 #(define (ac:down note)
188 (begin (let* ((pitch (ly:music-property note 'pitch))
189 (notename (ly:pitch-notename pitch))
190 (new-notename (if (eq? notename 0) 6 (- notename 1)))
191 (alterations (ly:music-property ac:current-key 'pitch-alist))
192 (new-alteration (cdr (assq new-notename alterations)))
193 (new-octave (if (eq? new-notename 6) (- (ly:pitch-octave pitch) 1)
194 (ly:pitch-octave pitch)))
196 (set! (ly:music-property note 'pitch)(ly:make-pitch new-octave new-notename new-alteration))))
199 % Shorten a note, and save the note's original duration in ac:currentDuration
200 #(define (ac:articulate-one-note m fraction)
201 "Replace m with m*fraction"
202 (if (eq? 'NoteEvent (ly:music-property m 'name))
204 ((dur (ly:music-property m 'duration))
205 (l (ly:duration-log dur))
206 (d (ly:duration-dot-count dur))
207 (factor (ly:duration-factor dur))
209 (denom (cdr fraction)))
211 (set! ac:currentDuration dur)
212 (set! (ly:music-property m 'duration)
213 (ly:make-duration l d
215 (* denom (cdr factor))))))
218 % helper routine to set duration.
219 #(define (ac:setduration music duration)
220 "Set a note's duration."
221 (let ((eventtype (ly:music-property music 'name)))
224 (eq? eventtype 'NoteEvent)
225 (eq? eventtype 'RestEvent)
226 (eq? eventtype 'SkipEvent))
227 (set! (ly:music-property music 'duration) duration))))
229 % Add an articulation event to a note.
230 % Used in afterGrace to mark all notes as tenuto, so they're not shortened
231 #(define (ac:add-articulation type music)
232 (music-map (lambda (m)
233 (if (eq? 'EventChord (ly:music-property m 'name))
234 (set! (ly:music-property m 'elements)
235 (append (ly:music-property m 'elements)
236 (list (make-music 'ArticulationEvent 'articulation-type type)))))
240 % Convert a long note to an equivalent set of short notes, tied together.
241 % This is needed to get smooth dynamics changes.
242 % Need to deal properly with stuff other than the notes (dynamics, markup etc)
243 % Still experimental, so disabled for now.
244 #(define (ac:to128 music) music)
246 #(define (ac:to128_disabled music)
247 (if (or (eq? 'SkipEvent (ly:music-property music 'name))
248 (eq? 'NoteEvent (ly:music-property music 'name)))
249 (let* ((dur (ly:music-property music 'duration))
250 (log2 (ly:duration-log dur))
251 (shiftcount (- 6 log2))
252 (lastm (ly:music-deep-copy (shift-duration-log music shiftcount 0))))
253 (set! (ly:music-property music 'elements)
254 (cons (make-music 'TieEvent) (ly:music-property music 'elements)))
255 (make-sequential-music (list
256 (make-repeat "unfold" (1- (expt 2 shiftcount))
257 (make-sequential-music (list music)) '())
262 % absolute time in minutes of a length of music, as a rational number (moment)
263 #(define (ac:abstime music)
264 (ly:moment-div (ly:music-length music) ac:currentTempo))
266 % convert absolute time (in minutes) to a moment in the current tempo
267 #(define (ac:abs->mom m)
268 (ly:moment-mul m ac:currentTempo))
271 % a moment that is ac:maxTwiddletime seconds at the current tempo.
272 #(define (ac:targetTwiddleTime)
273 (ac:abs->mom ac:maxTwiddleTime))
276 % Nearest twiddletime (in minutes) achievable with power-of-2 divisions of
277 % the original music. (twiddletime is the time for one pair of notes
279 % If the music has a precomputed twiddletime (e.g., from \afterGrace) use that.
280 #(define (ac:twiddletime music)
281 (let* ((tr (filter (lambda (x)
282 (and (eq? 'ArticulationEvent (ly:music-property x 'name))
283 (string= "trill" (ly:music-property x 'articulation-type))))
284 (ly:music-property music 'elements)))
285 (pre-t (if (pair? tr) (ly:music-property (car tr) 'twiddle)
287 (t (ac:targetTwiddleTime)))
288 (if (ly:moment? pre-t)
290 (let loop ((len (ly:music-length music)))
291 (if (ly:moment<? t len)
292 (loop (ly:moment-mul len (ly:make-moment 1 2)))
297 % Note: I'm assuming early music practice of starting on the auxiliary note.
298 % Needs to add gruppetto if it's a long trill (TODO)
299 #(define (ac:trill music)
300 " Replace music with time-compressed repeats of the music,
301 maybe accelerating if the length is longer than a crotchet "
302 (let* ((hemisemidur (ly:make-duration 5 0 1 1))
303 (orig-len (ly:music-length music))
304 (t (ac:twiddletime music))
306 (note_moment (ly:moment-mul t (ly:make-moment 1 2)))
307 (c1 (ly:moment-div orig-len note_moment))
309 (round (/ (ly:moment-main-numerator c1)
310 (* 2 (ly:moment-main-denominator c1))))))
311 (count (if (< c2 2) 2 c2)))
313 (set! (ly:music-property music 'elements)
314 (filter (lambda (y) (eq? 'NoteEvent (ly:music-property y 'name)))
315 (ly:music-property music 'elements)))
316 (map (lambda (y) (ac:setduration y hemisemidur))
317 (ly:music-property music 'elements))
318 (set! uppernote (ly:music-deep-copy music))
319 (map (lambda (y) (ac:up y))
321 (lambda (z) (eq? 'NoteEvent (ly:music-property z 'name)))
322 (ly:music-property uppernote 'elements)))
324 (let* ((trillMusicElements
325 (let loop ((so_far (list uppernote music))
328 (loop (append (list (ly:music-deep-copy uppernote) (ly:music-deep-copy music)) so_far) (1- c))
330 (trillMusic (make-sequential-music trillMusicElements))
331 (newlen (ly:music-length trillMusic))
332 (factor (ly:moment-div orig-len newlen)))
333 (ly:music-compress trillMusic factor)
334 ; accelerating the music seems to put lily into an infinite loop in
335 ; its layout and midi engines.
336 ; (let* ((realfactor (exp (* (/ 1.0 count) (log 0.75))))
337 ; (factor (ly:make-moment (inexact->exact (round (* 1024 realfactor)))
339 ; (ac:accel trillMusic factor))
345 % If there's an articulation, use it.
346 % If in a slur, use (1 . 1) instead.
347 % Treat phrasing slurs as slurs, but allow explicit articulation.
348 % (Maybe should treat staccato under a phrasing slur as mezzo-staccato?)
350 % Expect an EventChord.
352 % trills, turns, ornaments etc. are also treated as Articulations.
353 % Split into two functions:
354 % ac:getactions traverses the elements in the EventChord
355 % and calculates the parameters.
356 % ac:articulate-chord applies the actions to each NoteEvent in
358 #(define (ac:getactions music)
359 (let loop ((factor ac:normalFactor)
361 (es (ly:music-property music 'elements))
365 (set! (ly:music-property music 'elements) (reverse newelements))
367 (ac:inTrill (cons 'trill actions))
368 ((and (eq? factor ac:normalFactor) (or ac:inSlur ac:inPhrasingSlur))
369 (append actions (list 'articulation '(1 . 1)) ))
370 (else (append actions (list 'articulation factor)))))
374 (case (ly:music-property e 'name)
376 ((BeamEvent) ; throw away beam events, or they'll be duplicated by turn or trill
377 (loop factor newelements tail actions))
378 ((LineBreakEvent) ; pass through linebreak events.
379 (loop (cons 1 1) (cons e newelements) tail actions))
380 ((FingeringEvent) ; and fingering events too.
381 (loop factor newelements tail actions))
383 ((BreathingEvent) ; throw away BreathingEvent ---
384 ; should really shorten previous note a little.
385 (loop (cons 1 1) (cons e newelements) tail actions))
388 (loop (cons 1 1) (cons e newelements) tail actions))
391 (loop (cons 1 1) (cons e newelements) tail actions))
394 (loop (cons 1 1) (cons e newelements) tail actions))
397 (let ((articname (ly:music-property e 'articulation-type)))
398 ; TODO: add more here
400 ((string= articname "staccato")
401 (loop ac:staccatoFactor newelements tail actions))
402 ((string= articname "staccatissimo")
403 (loop ac:staccatissimoFactor newelements tail actions))
404 ((string= articname "tenuto")
405 (loop ac:tenutoFactor newelements tail actions))
406 ((string= articname "mordent")
407 (loop (cons 1 1) newelements tail (cons 'mordent actions)))
408 ((string= articname "prall")
409 (loop (cons 1 1) newelements tail (cons 'trill actions)))
410 ((string= articname "trill")
411 (loop (cons 1 1) newelements tail (cons 'trill actions)))
412 ((string= articname "turn")
413 (loop (cons 1 1) newelements tail (cons 'turn actions)))
414 (else (loop factor (cons e newelements) tail actions)))))
417 (let ((t (ly:music-property e 'text)))
418 (if (not (string? t))
419 (loop factor (cons e newelements) tail actions)
427 (loop factor (cons e newelements) tail (cons 'rall actions)))
429 (string= t "poco rall.")
430 (string= t "poco rit."))
431 (loop factor (cons e newelements) tail (cons 'pocoRall actions)))
432 ((or (string= t "a tempo")
433 (string= t "tempo I"))
434 (loop factor (cons e newelements) tail (cons 'aTempo actions)))
435 (else (loop factor (cons e newelements) tail actions)))))))
438 (let ((direction (ly:music-property e 'span-direction)))
439 (set! ac:inSlur (eq? direction -1))
440 (loop factor newelements tail actions)))
443 (let ((direction (ly:music-property e 'span-direction)))
444 (set! ac:inTrill (eq? direction -1))
446 (loop factor newelements tail (cons 'trill actions))
447 (loop factor (cons e newelements) tail actions))))
450 (let ((direction (ly:music-property e 'span-direction)))
451 (set! ac:inPhrasingSlur (eq? direction -1))
452 (loop factor newelements tail actions)))
454 (else (loop factor (cons e newelements) tail actions)))))))
458 #(define (ac:articulate-chord music)
462 ((eq? 'EventChord (ly:music-property music 'name))
463 (let loop ((actions (ac:getactions music)))
465 (if (ly:moment> (ly:music-length music) (make-moment 1 4))
473 (lambda (x) (ac:articulate-one-note x (cadr actions)))
474 (ly:music-property music 'elements))
476 ((num (caadr actions))
477 (denom (cdadr actions))
478 (mult (ly:duration-factor ac:currentDuration))
479 (newnum (* (- denom num) (car mult)))
480 (newdenom (* (cdr mult) denom))
481 (len (ly:duration-log ac:currentDuration))
482 (dots (ly:duration-dot-count ac:currentDuration)))
484 (if (not (eq? num denom))
485 (make-sequential-music
486 (list (ac:to128 music)
487 (make-music 'EventChord 'elements
489 (make-music 'RestEvent 'duration (ly:make-duration len dots newnum newdenom))))))
493 (set! ac:currentTempo (ly:moment-mul ac:currentTempo ac:rallFactor))
494 (let ((pset (make-music 'PropertySet
498 'tempoWholesPerMinute)))
499 (if (null? (cdr actions))
500 (make-sequential-music (list pset music))
501 (make-sequential-music
502 (list pset (loop (cdr actions)))))))
505 (set! ac:currentTempo (ly:moment-mul ac:currentTempo ac:pocoRallFactor))
506 (let ((pset (make-music 'PropertySet
510 'tempoWholesPerMinute)))
511 (if (null? (cdr actions))
512 (make-sequential-music (list pset music))
513 (make-sequential-music
514 (list pset (loop (cdr actions)))))))
517 (set! ac:currentTempo ac:lastTempo)
518 (let ((pset (make-music 'PropertySet
522 'tempoWholesPerMinute)))
523 (if (null? (cdr actions))
524 (make-sequential-music (list pset music))
525 (make-sequential-music
526 (list pset (loop (cdr actions)))))))
533 ((dur (ly:music-property
534 (car (ly:music-property music 'elements)) 'duration))
535 (factor (ly:duration-factor dur))
536 (gracenote (ly:music-deep-copy music))
537 (mainnote (ly:music-deep-copy music))
538 (belownote (ly:music-deep-copy music))
539 (mordent (make-sequential-music (list gracenote belownote)))
542 (music-map (lambda (n)
543 (if (eq? 'NoteEvent (ly:music-property n 'name))
544 (set! (ly:music-property n 'duration)(ly:make-duration 3 0 1 1)))
547 (map (lambda (y) (ac:down y))
549 (lambda (z) (eq? 'NoteEvent (ly:music-property z 'name)))
550 (ly:music-property belownote 'elements)))
551 (make-sequential-music (list (make-grace-music mordent) mainnote)))))
554 ((dur (ly:music-property
555 (car (ly:music-property music 'elements)) 'duration))
556 (factor (ly:duration-factor dur))
557 (newdur (ly:make-duration (+ (ly:duration-log dur) 2)
558 (ly:duration-dot-count dur) (car factor)(cdr factor))))
560 (map (lambda (y) (ac:setduration y newdur))
561 (ly:music-property music 'elements))
562 (let* ((above (ly:music-deep-copy music))
563 (below (ly:music-deep-copy music))
564 (newmusic (make-sequential-music (list above music below music))))
566 (map (lambda (y) (ac:down y))
568 (lambda (z) (eq? 'NoteEvent (ly:music-property z 'name)))
569 (ly:music-property below 'elements)))
570 (map (lambda (y) (ac:up y))
572 (lambda (z) (eq? 'NoteEvent (ly:music-property z 'name)))
573 (ly:music-property above 'elements)))
577 ((eq? 'KeyChangeEvent (ly:music-property music 'name))
578 (set! ac:current-key music)
582 ((eq? 'PropertySet (ly:music-property music 'name))
583 (ac:adjust-props (ly:music-property music 'symbol) music)
591 % At last ... here's the music function that aplies all the above to a
593 articulate = #(define-music-function (parser location music)
595 "Adjust times of note to add tenuto, staccato and
596 normal articulations.
598 (music-map ac:articulate-chord music)
602 % Override \afterGrace to be in terms of audio, not spacing.
603 % Special handling for a gruppetto after a trill.
605 #(define-music-function
606 (parser location main grace)
607 (ly:music? ly:music?)p
610 ((main-length (ly:music-length main))
611 (grace-orig-length (ly:music-length grace))
612 (gracelen (ac:twiddletime main))
613 (grace-factor (ly:moment-div gracelen grace-orig-length))
614 (new-main-length (ly:moment-sub main-length gracelen))
615 (factor (ly:moment-div new-main-length main-length))
617 (map (lambda (y) (set! (ly:music-property y 'twiddle) gracelen))
620 (eq? 'ArticulationEvent (ly:music-property z 'name))
621 (string= "trill" (ly:music-property z 'articulation-type))))
622 (ly:music-property main 'elements)))
623 (ac:add-articulation "tenuto" grace)
624 (make-sequential-music (list (ly:music-compress main factor) (ly:music-compress grace grace-factor)))))
626 % An appoggiatura takes half the duration of the main note,
627 % or 1/3 if the note is dotted (i.e., half the undotted equivalent time)
628 % Somewhere around the end of the 19th, start of 20th century the rules
629 % changed, but my main interest is early music.
631 #(define-music-function (parser location grace main)
632 (ly:music? ly:music?)
633 (let* ((maindur (ly:music-length main))
634 (grace-orig-len (ly:music-length grace))
635 (main-orig-len (ly:music-length main))
636 (numerator (ly:moment-main-numerator maindur))
637 (factor (if (eq? (remainder numerator 3) 0)
638 (ly:make-moment 1 3) (ly:make-moment 1 2))))
639 (ly:music-compress grace
640 (ly:moment-mul factor (ly:moment-div main-orig-len grace-orig-len)))
641 (ly:music-compress main (ly:moment-sub (ly:make-moment 1 1) factor))
643 (set! (ly:music-property grace 'elements)
644 (append (ly:music-property grace 'elements)
645 (list (make-music 'SlurEvent 'span-direction -1))))
646 (set! (ly:music-property main 'elements)
647 (append (ly:music-property main 'elements)
648 (list (make-music 'SlurEvent 'span-direction 1))))
649 (make-sequential-music (list grace main))))