]> git.donarmstrong.com Git - lilypond.git/blob - ly/articulate.ly
1aa62d8e9d229a8049581235895fd3ced9ae32a2
[lilypond.git] / ly / articulate.ly
1 %
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 $
5 %
6 %
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.
10 %
11 %  WARNING: this file under GPLv3 only, not GPLv3+
12 %
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
19 %
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
23 % skip.
24 %
25 % It also tries to unfold trills turns etc., and take rallentendo
26 % and accelerando into account.
27 %
28 % As my scheme knowledge is poor (I was teaching myself as I went), there
29 % is much scope for improvement.
30
31 %
32 %%%USAGE
33 % In the \score section do:
34 % \articulate <<
35 %       all the rest of the score
36 % >>
37 % or use the lilywrap script.
38 %
39 % TO DO (prioritised, the ones that'll make the most difference first)
40 %
41 % * Dynamics.
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).
45 %
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.
49 %
50 % * add accel (to match rall), and molto rall. I've never seen
51 %   molto accel but some composer somewhere has probably used it.
52 %
53 % * Fermata, and Fermata Lunga
54 % * Add more synonyms for accel and rall: rit ritard stringendo
55 %
56 % * Phrasing.
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
60 %     the general case
61 %
62 % * Trill algorithm needs work.
63 %
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
79
80 % CHANGELOG
81 %  * David Kastrup: basic 2.15.28 compatibility by using event-chord-wrap!
82 %    This should really be done by rewriting the code more thoroughly.
83 %  * From Iain Nicol: appoggiatura timings were out; add staccatissimo; fix
84 %    trillSpanner endpoints.
85 %  * Also handle Breathing events (by throwing them away).  This isn't ideal;
86 %    one should really shorten the note before a little.  But I don't know
87 %    how to do lookahead in scheme.
88 %  * Also ignore explicit line breaks.
89 %  * Add Mordents (reported by Patrick Karl)
90 %
91
92 \version "2.17.11"
93
94 #(use-modules (srfi srfi-1))
95 #(use-modules (srfi srfi-11))
96 #(use-modules (ice-9 debug))
97 #(use-modules (scm display-lily))
98
99 % PARAMETERS
100 % How much to compress notes marked Staccato.  CPE Bach says `as short as
101 % may conveniently be played, as if the keys were too hot to touch'.
102 % Most modern sources say 1/2 the notated length of a note.
103 #(define ac:staccatoFactor '(1 . 2))
104
105 % How much to compress notes marked staccatissimo.
106 #(define ac:staccatissimoFactor '(1 . 4))
107
108 % And tenuto (if we ever implement time stealing, this should be >1.0)
109 #(define ac:tenutoFactor '(1 . 1))
110
111 % How much to articulate normal notes.  CPE Bach says 1/2 (and
112 % staccato should be `as short as may conveniently be played') but this
113 % sounds too short for modern music.  7/8 sounds about right.
114 #(define ac:normalFactor '(7 . 8))
115
116 % How much to slow down for a rall. or a poco rall.
117 % (or speed up for accel or poco accel)
118 #(define ac:rallFactor (ly:make-moment 60/100)) % 40% slowdown
119 #(define ac:pocoRallFactor (ly:make-moment 90/100)) % 10% slowdown
120
121 % The absolute time for a twiddle in a trill, in minutes.
122 % Start with 1/4 seconds == 1/240 minutes
123 #(define ac:maxTwiddleTime (ly:make-moment 1/240))
124
125 % How long ordinary grace notes should be relative to their notated
126 % duration.  9/40 is LilyPond's built-in behaviour for MIDI output
127 % (though the notation reference says 1/4).
128 #(define ac:defaultGraceFactor 9/40)
129
130 % What proportion of an ordinary grace note's time should be stolen
131 % from preceding notes (as opposed to stealing from the principal note).
132 % Composers' intentions for this vary.  Taking all from the preceding
133 % notes is LilyPond's built-in behaviour for MIDI output.
134 #(define ac:defaultGraceBackwardness 1)
135
136
137 % Internal variables, don't touch.
138 % (should probably be part of a context somehow)
139
140 % Whether to slur, or not
141 #(define ac:inSlur #f)
142 #(define ac:inPhrasingSlur #f)
143
144 % Whether the current noteevent is in a trill spanner
145 #(define ac:inTrill #f)
146
147 % assume start in C major.  Key change events override this.
148 % Could get from context, but don't know how.
149 #(define ac:current-key (make-music
150           'KeyChangeEvent
151           'tonic
152           (ly:make-pitch -1 0 0)
153           'pitch-alist
154           (list (cons 0 0)
155                 (cons 1 0)
156                 (cons 2 0)
157                 (cons 3 0)
158                 (cons 4 0)
159                 (cons 5 0)
160                 (cons 6 0))))
161
162
163 #(define ac:currentTempo (ly:make-moment 15/1)) % 4 = 60, measured wholes per minute
164 #(define ac:lastTempo ac:currentTempo) % for 'a tempo' or 'tempo I'
165
166 % The duration of the current note.  Start at a crotchet
167 % for no good reason.
168 #(define ac:currentDuration (ly:make-duration 2 0 1/1))
169
170 % Amount of musical time (in whole notes) that we need to steal from the
171 % next events seen.
172 #(define ac:stealForward 0)
173
174 % List of events in the output so far, in reverse order, from which we can
175 % steal time.
176 #(define ac:eventsBackward '())
177
178 % Log events for the backward chain.
179 #(define (ac:logEventsBackward music)
180   (music-map
181    (lambda (m)
182     (case (ly:music-property m 'name)
183      ((EventChord)
184       (set! ac:eventsBackward (cons m ac:eventsBackward))
185       m)
186      ((BarCheck SkipMusic)
187       (let ((wm (make-sequential-music (list m))))
188        (set! ac:eventsBackward (cons wm ac:eventsBackward))
189        wm))
190      (else
191       m)))
192    music))
193
194 % Steal time from the backward chain.  Adds to ac:stealForward (with a
195 % warning) if it couldn't backward-steal all that was desired.
196 #(define (ac:stealTimeBackward tosteal)
197   (if (<= tosteal 0)
198    #t
199    (if (null? ac:eventsBackward)
200     (begin
201      (ly:warning (_ "articulation failed to steal ~a note backward at beginning of music; stealing forward instead") tosteal)
202      (set! ac:stealForward (+ ac:stealForward tosteal)))
203     (let*
204      ((lastev (car ac:eventsBackward))
205       (levlen (ly:moment-main (ly:music-length lastev))))
206      (if (< tosteal levlen)
207       (begin
208        (ly:music-compress lastev (ly:make-moment (/ (- levlen tosteal) levlen)))
209        #t)
210       (begin
211        (if (any (lambda (z) (eq? 'NoteEvent (ly:music-property z 'name)))
212                 (ly:music-property lastev 'elements))
213         (ly:warning (_ "stealing the entirety of a note's time")))
214        (set! (ly:music-property lastev 'elements) '())
215        (set! ac:eventsBackward (cdr ac:eventsBackward))
216        (ac:stealTimeBackward (- tosteal levlen))))))))
217
218 % Debugging: display a moment plus some text.
219 % Returns its moment argument so can be used in-line.
220 #(define (display-moment  text m)
221   (display text)
222   (display (list (ly:moment-main-numerator m) "/" (ly:moment-main-denominator m)))
223   m
224 )
225
226 % Track tempo (and maybe later, other context properties)
227 % as they change.  Needs to better cope with saving only Tempo I,
228 % otherwise "a tempo" goes back to the tempo before the last change.
229 #(define (ac:adjust-props sym music)
230   (case sym
231    ((tempoWholesPerMinute)
232     (set! ac:currentTempo (ly:music-property music 'value))
233     (set! ac:lastTempo ac:currentTempo)
234   )))
235
236 % Raise note one step in the current diatonic scale.
237 #(define (ac:up note)
238   (let* ((pitch (ly:music-property note 'pitch))
239          (notename (ly:pitch-notename pitch))
240          (new-notename (if (eq? notename 6) 0 (+ 1 notename)))
241          (alterations (ly:music-property ac:current-key 'pitch-alist))
242          (new-alteration (cdr (assq new-notename alterations)))
243          (new-octave (if (eq? new-notename 0) (+ 1 (ly:pitch-octave pitch))
244                       (ly:pitch-octave pitch)))
245        )
246    (set! (ly:music-property note 'pitch)(ly:make-pitch new-octave new-notename new-alteration))))
247
248
249 % Lower note one step in the current diatonic scale.
250 #(define (ac:down note)
251   (begin  (let* ((pitch (ly:music-property note 'pitch))
252          (notename (ly:pitch-notename pitch))
253          (new-notename (if (eq? notename 0) 6 (- notename 1)))
254          (alterations (ly:music-property ac:current-key 'pitch-alist))
255          (new-alteration (cdr (assq new-notename alterations)))
256          (new-octave (if (eq? new-notename 6) (- (ly:pitch-octave pitch) 1)
257                       (ly:pitch-octave pitch)))
258        )
259    (set! (ly:music-property note 'pitch)(ly:make-pitch new-octave new-notename new-alteration))))
260 )
261
262 % Shorten a note, and save the note's original duration in ac:currentDuration
263 #(define (ac:articulate-one-note m fraction)
264   "Replace m with m*fraction"
265   (if  (eq? 'NoteEvent (ly:music-property m 'name))
266    (let*
267     ((dur (ly:music-property m 'duration))
268      (l (ly:duration-log dur))
269      (d (ly:duration-dot-count dur))
270      (factor (ly:duration-factor dur))
271      (num (car fraction))
272      (denom (cdr fraction)))
273     (begin
274      (set! ac:currentDuration dur)
275      (set! (ly:music-property m 'duration)
276       (ly:make-duration l d
277        (* num (car factor))
278        (* denom (cdr factor))))))
279    m))
280
281 % helper routine to set duration.
282 #(define (ac:setduration music duration)
283   "Set a note's duration."
284   (let ((eventtype (ly:music-property music 'name)))
285    (if
286     (or
287      (eq? eventtype 'NoteEvent)
288      (eq? eventtype 'RestEvent)
289      (eq? eventtype 'SkipEvent))
290     (set! (ly:music-property music 'duration) duration))))
291
292 % Add an articulation event to a note.
293 % Used in afterGrace to mark all notes as tenuto, so they're not shortened
294 #(define (ac:add-articulation type music)
295     (music-map (lambda (m)
296                 (if (eq? 'EventChord (ly:music-property m 'name))
297                  (set! (ly:music-property m 'elements)
298                   (append (ly:music-property m 'elements)
299                    (list (make-music 'ArticulationEvent 'articulation-type type)))))
300                 m)
301      music))
302
303 % Convert a long note to an equivalent set of short notes, tied together.
304 % This is needed to get smooth dynamics changes.
305 % Need to deal properly with stuff other than the notes (dynamics, markup etc)
306 % Still experimental, so disabled for now.
307 #(define (ac:to128 music) music)
308
309 #(define (ac:to128_disabled music)
310   (if (or (eq? 'SkipEvent (ly:music-property music 'name))
311         (eq? 'NoteEvent (ly:music-property music 'name)))
312    (let* ((dur (ly:music-property music 'duration))
313           (log2 (ly:duration-log dur))
314          (shiftcount (- 6 log2))
315          (lastm (ly:music-deep-copy (shift-duration-log music shiftcount 0))))
316    (set! (ly:music-property music 'elements)
317     (cons (make-music 'TieEvent) (ly:music-property music 'elements)))
318    (make-sequential-music (list
319                            (make-repeat "unfold" (1- (expt 2 shiftcount))
320                             (make-sequential-music (list music)) '())
321                            lastm)))
322  music))
323
324
325 % absolute time in minutes of a length of music, as a rational number (moment)
326 #(define (ac:abstime music)
327   (ly:moment-div (ly:music-length music) ac:currentTempo))
328
329 % convert absolute time (in minutes) to a moment in the current tempo
330 #(define (ac:abs->mom m)
331   (ly:moment-mul m ac:currentTempo))
332
333
334 % a moment that is ac:maxTwiddletime seconds at the current tempo.
335 #(define (ac:targetTwiddleTime)
336   (ac:abs->mom ac:maxTwiddleTime))
337
338
339 % Nearest twiddletime (in minutes) achievable with power-of-2 divisions of
340 % the original music.  (twiddletime is the time for one pair of notes
341 % in a trill)
342 % If the music has a precomputed twiddletime (e.g., from \afterGrace) use that.
343 #(define (ac:twiddletime music)
344   (let* ((tr (filter (lambda (x)
345                      (and (eq? 'ArticulationEvent (ly:music-property x 'name))
346                       (string= "trill" (ly:music-property x 'articulation-type))))
347               (ly:music-property music 'elements)))
348          (pre-t (if (pair? tr) (ly:music-property (car tr) 'twiddle)
349                  '()))
350          (hemisemimom (ly:make-moment 1/64))
351          (t (ac:targetTwiddleTime)))
352    (if (ly:moment? pre-t)
353     pre-t
354     hemisemimom)))
355
356
357
358 % Note: I'm assuming early music practice of starting on the auxiliary note.
359 % Needs to add gruppetto if it's a long trill (TODO)
360 #(define (ac:trill music)
361   " Replace music with time-compressed repeats of the music,
362     maybe accelerating if the length is longer than a crotchet "
363   (let* ((hemisemidur (ly:make-duration 5 0 1/1))
364          (orig-len  (ly:music-length music))
365          (t (ac:twiddletime music))
366          (uppernote '())
367          (note_moment (ly:moment-mul t (ly:make-moment 1/2)))
368          (c1 (ly:moment-div orig-len t))
369          (c2 (inexact->exact
370               (round (/ (ly:moment-main-numerator c1)
371                       (* 2 (ly:moment-main-denominator c1))))))
372          (count (if (< c2 2) 2 c2)))
373
374    (set! (ly:music-property music 'elements)
375     (filter (lambda (y) (eq? 'NoteEvent (ly:music-property y 'name)))
376      (ly:music-property music 'elements)))
377    (map (lambda (y) (ac:setduration y hemisemidur))
378     (ly:music-property music 'elements))
379    (set! uppernote (ly:music-deep-copy music))
380    (map (lambda (y) (ac:up y))
381     (filter
382      (lambda (z) (eq? 'NoteEvent (ly:music-property z 'name)))
383      (ly:music-property uppernote 'elements)))
384
385    (let* ((trillMusicElements
386           (let loop ((so_far (list uppernote music))
387                      (c count))
388            (if (> c 1)
389             (loop (append (list (ly:music-deep-copy uppernote) (ly:music-deep-copy music)) so_far) (1- c))
390             so_far)))
391           (trillMusic (make-sequential-music trillMusicElements))
392           (newlen (ly:music-length trillMusic))
393           (factor (ly:moment-div  orig-len newlen)))
394     (ly:music-compress trillMusic factor)
395 ; accelerating the music seems to put lily into an infinite loop in
396 ; its layout and midi engines.
397 ;    (let* ((realfactor (exp (* (/ 1.0 count) (log 0.75))))
398 ;          (factor (ly:make-moment (inexact->exact (round (* 1024 realfactor)))
399 ;                   1024)))
400 ;     (ac:accel trillMusic factor))
401  )))
402
403
404 % Copy music and strip articulations, ties, etc., for generating
405 % mordents etc.
406 #(define (ac:note-copy music)
407   "return a copy of music that is only notes, no articulations, ties, slurs etc"
408   (let ((new-music (ly:music-deep-copy music)))
409    (set! (ly:music-property new-music 'articulations) '())
410    (set! (ly:music-property new-music 'elements)
411     (filter (lambda (y) (eq? 'NoteEvent (ly:music-property y 'name)))
412      (ly:music-property new-music 'elements)))
413    new-music))
414
415 %
416 % Generate a tempoChangeEvent and its associated property setting.
417 %
418 #(define (ac:tempoChange tempo)
419   (make-sequential-music
420    (list (make-music 'TempoChangeEvent
421           'metronome-count
422           tempo
423           'tempo-unit
424           (ly:make-duration 0 0 1/1))
425     (context-spec-music
426     (make-property-set 'tempoWholesPerMinute  tempo) 'Score))))
427
428 %
429 % Totally unfold repeats, so that the non-obvious sequencing doesn't
430 % confuse us.  This is necessary for time stealing to work, because
431 % that relies on the sequence in which we see events matching their
432 % audible sequence.  Also unfold multi-measure rests to equivalent
433 % skips, with preceding and following bar checks, so that time stealing
434 % can change the length of the pause without falling foul of the
435 % implicit bar checks.
436 %
437 #(define (ac:unfoldMusic music)
438   (music-map
439    (lambda (m)
440     (case (ly:music-property m 'name)
441      ((UnfoldedRepeatedMusic)
442       (let
443        ((body (ly:music-property m 'element))
444         (altl (ly:music-property m 'elements))
445         (rc (ly:music-property m 'repeat-count)))
446        (if (null? altl)
447         (make-sequential-music
448          (list-tabulate rc (lambda (i) (ly:music-deep-copy body))))
449         (let ((ealtl (if (> (length altl) rc) (take altl rc) altl)))
450          (make-sequential-music
451           (apply append!
452            (append!
453             (list-tabulate
454              (- rc (length ealtl))
455              (lambda (i) (list (ly:music-deep-copy body) (ly:music-deep-copy (car ealtl)))))
456             (map (lambda (alt) (list (ly:music-deep-copy body) alt)) ealtl))))))))
457      ((EventChord)
458       (let-values
459        (((trem evl)
460          (partition (lambda (v) (eq? (ly:music-property v 'name) 'TremoloEvent))
461           (ly:music-property m 'elements))))
462        (if (null? trem)
463         m
464         (let*
465          ((tremtype (ly:music-property (car trem) 'tremolo-type))
466           (tremtype-log (1- (integer-length tremtype)))
467           (durev (find (lambda (v) (not (null? (ly:music-property v 'duration)))) evl))
468           (totaldur (if durev (ly:music-property durev 'duration) (ly:make-duration tremtype-log 0 1)))
469           (tgt-nrep (/ (duration-visual-length totaldur) (duration-log-factor tremtype-log)))
470           (eff-nrep (max (truncate tgt-nrep) 1))
471           (tremdur (ly:make-duration tremtype-log 0
472                     (* (/ tgt-nrep eff-nrep) (ly:duration-scale totaldur)))))
473          (or (and (= eff-nrep tgt-nrep) (= (ash 1 tremtype-log) tremtype))
474           (ly:warning (_ "non-integer tremolo ~a:~a")
475            (duration->lily-string (duration-visual totaldur) #:force-duration #t #:time-scale 1)
476            tremtype))
477          (for-each
478           (lambda (v)
479            (or (null? (ly:music-property v 'duration))
480             (set! (ly:music-property v 'duration) tremdur)))
481           evl)
482          (set! (ly:music-property m 'elements) evl)
483          (make-sequential-music
484           (list-tabulate eff-nrep (lambda (i) (ly:music-deep-copy m))))))))
485      ((MultiMeasureRestMusic)
486       (make-sequential-music
487        (list
488         (make-music 'BarCheck)
489         (make-music 'SkipMusic 'duration (ly:music-property m 'duration))
490         (make-music 'BarCheck))))
491      (else
492       m)))
493    (unfold-repeats music)))
494
495 % If there's an articulation, use it.
496 % If in a slur, use (1 . 1) instead.
497 % Treat phrasing slurs as slurs, but allow explicit articulation.
498 % (Maybe should treat staccato under a phrasing slur as mezzo-staccato?)
499 %
500 % Expect an EventChord.
501 %
502 % trills, turns, ornaments etc.  are also treated as Articulations.
503 % Split into two functions:
504 %  ac:getactions traverses the elements in the EventChord
505 %               and calculates the parameters.
506 %  ac:articulate-chord applies the actions to each NoteEvent in
507 %               the EventChord.
508 #(define (ac:getactions music)
509   (let  loop ((factor ac:normalFactor)
510               (newelements '())
511               (es (ly:music-property music 'elements))
512               (actions '()))
513    (if (null? es)
514     (begin
515      (set! (ly:music-property music 'elements) (reverse newelements))
516      (if
517       (not (any (lambda (m) (music-is-of-type? m 'rhythmic-event))
518                 newelements))
519       actions
520       (append
521        (let ((st ac:stealForward))
522         (if (= st 0)
523          '()
524          (begin
525           (set! ac:stealForward 0)
526           (list 'steal st))))
527        actions
528        (cond
529         (ac:inTrill '(trill))
530         ((and (eq? factor ac:normalFactor) (or ac:inSlur ac:inPhrasingSlur))
531          (list 'articulation  '(1 . 1)))
532         (else (list 'articulation  factor))))))
533     ; else part
534     (let ((e (car es))
535           (tail (cdr es)))
536      (case (ly:music-property e 'name)
537
538       ((BeamEvent) ; throw away beam events, or they'll be duplicated by turn or trill
539        (loop factor newelements tail actions))
540
541       ((LineBreakEvent FingeringEvent MarkEvent BreathingEvent TieEvent SkipEvent RestEvent) ; pass through some events.
542        (loop (cons 1 1) (cons e newelements) tail actions))
543
544       ((ArticulationEvent)
545        (let ((articname (ly:music-property e 'articulation-type)))
546         ; TODO: add more here
547         (cond
548          ((string= articname "staccato")
549           (loop ac:staccatoFactor newelements tail actions))
550          ((string= articname "staccatissimo")
551           (loop ac:staccatissimoFactor newelements tail actions))
552          ((string= articname "tenuto")
553           (loop ac:tenutoFactor newelements tail actions))
554          ((string= articname "mordent")
555           (loop (cons 1 1) newelements tail (cons 'mordent actions)))
556          ((string= articname "prall")
557           (loop (cons 1 1) newelements tail (cons 'prall actions)))
558          ((string= articname "trill")
559           (loop (cons 1 1) newelements tail (cons 'trill actions)))
560          ((string= articname "turn")
561           (loop (cons 1 1) newelements tail (cons 'turn actions)))
562          (else (loop factor (cons e newelements) tail actions)))))
563
564       ((TextScriptEvent)
565        (let ((t (ly:music-property e 'text)))
566         (if (not (string? t))
567          (loop factor (cons e newelements) tail actions)
568          (begin
569           (cond
570            ((or
571              (string= t "rall")
572              (string= t "Rall")
573              (string= t "rit.")
574              (string= t "rall."))
575             (loop factor (cons e newelements) tail (cons 'rall actions)))
576            ((or
577              (string= t "accelerando")
578              (string= t "accel")
579              (string= t "accel."))
580             (loop factor (cons e newelements) tail (cons 'accel actions)))
581            ((or
582              (string= t "poco accel."))
583             (loop factor (cons e newelements) tail (cons 'pocoAccel actions)))
584            ((or
585              (string= t "poco rall.")
586              (string= t "poco rit."))
587             (loop factor (cons e newelements) tail (cons 'pocoRall actions)))
588            ((or (string= t "a tempo")
589              (string= t "tempo I"))
590           (loop factor (cons e newelements) tail (cons 'aTempo actions)))
591            (else (loop factor (cons e newelements) tail actions)))))))
592
593       ((SlurEvent)
594        (let ((direction (ly:music-property e 'span-direction)))
595         (set! ac:inSlur (eq? direction -1))
596         (loop factor newelements tail actions)))
597
598       ((TrillSpanEvent)
599        (let ((direction (ly:music-property e 'span-direction)))
600         (set! ac:inTrill (eq? direction -1))
601         (if ac:inTrill
602          (loop factor newelements tail (cons 'trill actions))
603          (loop factor (cons e newelements) tail actions))))
604
605       ((PhrasingSlurEvent)
606        (let ((direction (ly:music-property e 'span-direction)))
607         (set! ac:inPhrasingSlur (eq? direction -1))
608         (loop factor newelements tail actions)))
609
610       (else (loop factor (cons e newelements) tail actions)))))))
611
612
613
614 #(define (ac:articulate-chord music)
615   (cond
616    ((eq? 'EventChord (ly:music-property music 'name))
617     (ac:logEventsBackward
618      (let loop ((actions (ac:getactions music)))
619       (if (null? actions)
620         (if (ly:moment<? (ly:make-moment 1/4) (ly:music-length music))
621          (ac:to128  music)
622          music)
623
624       (case (car actions)
625
626        ((articulation)
627         (map
628          (lambda (x) (ac:articulate-one-note x (cadr actions)))
629          (ly:music-property music 'elements))
630         (let*
631          ((num (caadr actions))
632           (denom (cdadr actions))
633           (mult (ly:duration-factor ac:currentDuration))
634           (newnum (* (- denom num) (car mult)))
635           (newdenom (* (cdr mult) denom))
636           (len (ly:duration-log ac:currentDuration))
637           (dots (ly:duration-dot-count ac:currentDuration)))
638
639          (if (not (eq? num denom))
640           (make-sequential-music
641            (list (ac:to128 music)
642            (make-music 'EventChord 'elements
643             (list
644              (make-music 'RestEvent 'duration (ly:make-duration len dots newnum newdenom))))))
645           music)))
646
647        ((accel)
648         (set! ac:lastTempo ac:currentTempo)
649         (set! ac:currentTempo (ly:moment-div ac:currentTempo ac:rallFactor))
650         (let ((pset (ac:tempoChange ac:currentTempo)))
651          (if (null? (cdr actions))
652           (make-sequential-music (list pset music))
653           (make-sequential-music
654            (list pset (loop (cdr actions)))))))
655
656        ((pocoAccel)
657         (set! ac:lastTempo ac:currentTempo)
658         (set! ac:currentTempo (ly:moment-div ac:currentTempo ac:pocoRallFactor))
659         (let ((pset (ac:tempoChange ac:currentTempo)))
660          (if (null? (cdr actions))
661           (make-sequential-music (list pset music))
662           (make-sequential-music
663            (list pset (loop (cdr actions)))))))
664
665        ((rall)
666         (set! ac:lastTempo ac:currentTempo)
667         (set! ac:currentTempo (ly:moment-mul ac:currentTempo ac:rallFactor))
668         (let ((pset (ac:tempoChange ac:currentTempo)))
669          (if (null? (cdr actions))
670           (make-sequential-music (list pset music))
671           (make-sequential-music
672            (list pset (loop (cdr actions)))))))
673
674        ((pocoRall)
675         (set! ac:lastTempo ac:currentTempo)
676         (set! ac:currentTempo (ly:moment-mul ac:currentTempo ac:pocoRallFactor))
677         (let ((pset (ac:tempoChange ac:currentTempo)))
678          (if (null? (cdr actions))
679           (make-sequential-music (list pset music))
680           (make-sequential-music
681            (list pset (loop (cdr actions)))))))
682
683        ((aTempo)
684         (set! ac:currentTempo ac:lastTempo)
685
686         (let ((pset (ac:tempoChange ac:currentTempo)))
687          (if (null? (cdr actions))
688           (make-sequential-music (list pset music))
689           (make-sequential-music
690            (list pset (loop (cdr actions)))))))
691
692        ((trill)
693          (ac:trill music))
694
695        ((prall)
696         ; A pralltriller symbol can either mean an inverted mordent
697         ; or a half-shake -- a short, two twiddle trill.
698         ; We implement as a half-shake.
699         (let*
700          ((origlength (ly:music-length music))
701           (gracedur (ly:make-duration 5 0 1/1))
702           (gracenote (ac:note-copy music))
703           (abovenote (ac:note-copy music))
704           (abovenoteTwo (ac:note-copy music))
705           (mainnote (ly:music-deep-copy music)))
706
707          (map (lambda (y) (ac:setduration y gracedur))
708           (ly:music-property gracenote 'elements))
709          (map (lambda (y) (ac:setduration y gracedur))
710           (ly:music-property abovenote 'elements))
711          (map (lambda (y) (ac:setduration y gracedur))
712           (ly:music-property abovenoteTwo 'elements))
713          (map (lambda (y) (ac:up y))
714           (filter
715            (lambda (z) (eq? 'NoteEvent (ly:music-property z 'name)))
716            (ly:music-property abovenote 'elements)))
717          (map (lambda (y) (ac:up y))
718           (filter
719            (lambda (z) (eq? 'NoteEvent (ly:music-property z 'name)))
720            (ly:music-property abovenoteTwo 'elements)))
721          (let* ((prallMusic (make-sequential-music
722                               (list abovenote gracenote abovenoteTwo mainnote)))
723                  (newlen (ly:music-length prallMusic))
724                  (factor (ly:moment-div origlength newlen)))
725            (ly:music-compress prallMusic factor))))
726
727        ((mordent)
728         (let*
729          ((origlength (ly:music-length music))
730           (gracedur (ly:make-duration 5 0 1/1))
731           (gracenote (ac:note-copy music))
732           (belownote (ac:note-copy music)))
733          (map (lambda (y) (ac:setduration y gracedur))
734           (ly:music-property gracenote 'elements))
735          (map (lambda (y) (ac:setduration y gracedur))
736                (ly:music-property belownote 'elements))
737          (map (lambda (y) (ac:down y))
738           (filter
739            (lambda (z) (eq? 'NoteEvent (ly:music-property z 'name)))
740            (ly:music-property belownote 'elements)))
741
742          (let* ((mordentMusic (make-sequential-music (list gracenote belownote music)))
743                 (newlen (ly:music-length mordentMusic))
744                 (factor (ly:moment-div origlength newlen)))
745           (ly:music-compress mordentMusic factor))))
746
747        ((turn)
748         (let*
749          ((dur (ly:music-property
750                 (car (ly:music-property music 'elements)) 'duration))
751           (factor (ly:duration-factor dur))
752           (newdur (ly:make-duration (+ (ly:duration-log dur) 2)
753                    (ly:duration-dot-count dur) (car factor)(cdr factor))))
754          (begin
755           (map (lambda (y) (ac:setduration y newdur))
756            (ly:music-property music 'elements))
757           (let* ((above (ly:music-deep-copy music))
758                  (below (ly:music-deep-copy music))
759                  (newmusic (make-sequential-music (list above music below music))))
760            (begin
761             (map (lambda (y) (ac:down y))
762              (filter
763               (lambda (z) (eq? 'NoteEvent (ly:music-property z 'name)))
764               (ly:music-property below 'elements)))
765             (map (lambda (y) (ac:up y))
766              (filter
767               (lambda (z) (eq? 'NoteEvent (ly:music-property z 'name)))
768               (ly:music-property above 'elements)))
769             newmusic)))))
770        ((steal)
771         (let
772          ((totallen (ly:moment-main (ly:music-length music)))
773           (steallen (cadr actions)))
774          (if (>= steallen totallen)
775           (begin
776            (if (any (lambda (z) (eq? 'NoteEvent (ly:music-property z 'name)))
777                     (ly:music-property music 'elements))
778             (ly:warning (_ "stealing the entirety of a note's time")))
779            (set! ac:stealForward (- steallen totallen))
780            (make-sequential-music '()))
781           (begin
782            (ly:music-compress music (ly:make-moment (/ (- totallen steallen) totallen)))
783            (loop (cddr actions))))))
784      )))))
785
786    ((eq? 'GraceMusic (ly:music-property music 'name))
787     (let
788      ((first-ev
789        (call-with-current-continuation
790         (lambda (yield-fev)
791          (music-map
792           (lambda (m)
793            (if (eq? 'EventChord (ly:music-property m 'name))
794             (yield-fev m)
795             m))
796           music)
797          #f))))
798      (if first-ev
799       (let ((fev-pos (find-tail (lambda (m) (eq? m first-ev)) ac:eventsBackward)))
800        (if fev-pos
801         (set! ac:eventsBackward (cdr fev-pos))
802         (ly:warning (_ "articulation of grace notes has gone awry"))))))
803     (let*
804      ((gmus (ly:music-compress (ly:music-property music 'element)
805                                (ly:make-moment ac:defaultGraceFactor)))
806       (glen (ly:moment-main (ly:music-length gmus))))
807      (ac:stealTimeBackward (* glen ac:defaultGraceBackwardness))
808      (set! ac:stealForward (+ ac:stealForward (* glen (- 1 ac:defaultGraceBackwardness))))
809      gmus))
810
811    ((memq (ly:music-property music 'name) '(BarCheck SkipMusic))
812     (let ((totallen (ly:moment-main (ly:music-length music)))
813           (steallen ac:stealForward))
814      (cond
815       ((= steallen 0)
816        (ac:logEventsBackward music))
817       ((< steallen totallen)
818        (set! ac:stealForward 0)
819        (ac:logEventsBackward
820         (ly:music-compress music (ly:make-moment (/ (- totallen steallen) totallen)))))
821       (else
822        (set! ac:stealForward (- steallen totallen))
823        (make-sequential-music '())))))
824
825    ((eq? 'KeyChangeEvent (ly:music-property music 'name))
826     (set! ac:current-key music)
827     music)
828
829    ((eq? 'PropertySet (ly:music-property music 'name))
830     (ac:adjust-props (ly:music-property music 'symbol) music)
831     music)
832
833    (else music)))
834
835
836
837 % At last ... here's the music function that applies all the above to a
838 % score.
839 articulate = #(define-music-function (parser location music)
840                (ly:music?)
841                "Adjust times of note to add tenuto, staccato and
842                 normal articulations.
843                 "
844                (dynamic-wind
845                 (lambda ()
846                  (set! ac:stealForward 0)
847                  (set! ac:eventsBackward '()))
848                 (lambda ()
849                  (music-map
850                   ac:articulate-chord
851                   (ac:unfoldMusic (event-chord-wrap! music parser))))
852                 (lambda ()
853                  (or (= ac:stealForward 0)
854                   (begin
855                    (ly:warning (_ "articulation failed to steal ~a note at end of music") ac:stealForward)
856                    (set! ac:stealForward 0)))
857                  (set! ac:eventsBackward '()))))
858
859
860 % Override \afterGrace to be in terms of audio, not spacing.
861 % Special handling for a gruppetto after a trill.
862 afterGrace =
863 #(define-music-function
864   (parser location main grace)
865   (ly:music? ly:music?)
866
867   (set! main (event-chord-wrap! main parser))
868   (set! grace (event-chord-wrap! grace parser))
869   (let*
870    ((main-length (ly:music-length main))
871     (grace-orig-length (ly:music-length grace))
872     (gracelen (ac:twiddletime main))
873     (grace-factor (ly:moment-div gracelen grace-orig-length))
874     (new-main-length (ly:moment-sub main-length gracelen))
875     (factor (ly:moment-div new-main-length main-length))
876   )
877    (map (lambda (y) (set! (ly:music-property y 'twiddle) gracelen))
878          (filter (lambda (z)
879                   (and
880                    (eq? 'ArticulationEvent (ly:music-property z 'name))
881                    (string= "trill" (ly:music-property z 'articulation-type))))
882           (ly:music-property main 'elements)))
883    (ac:add-articulation "tenuto" grace)
884    (make-sequential-music  (list (ly:music-compress main factor) (ly:music-compress grace grace-factor)))))
885
886 % An appoggiatura takes half the duration of the main note,
887 % or 1/3 if the note is dotted (i.e., half the undotted equivalent time)
888 % Somewhere around the end of the 19th, start of 20th century the rules
889 % changed, but my main interest is early music.
890 appoggiatura =
891 #(define-music-function (parser location grace main)
892   (ly:music? ly:music?)
893   (set! grace (event-chord-wrap! grace parser))
894   (set! main (event-chord-wrap! main parser))
895   (let* ((maindur (ly:music-length main))
896          (grace-orig-len (ly:music-length grace))
897          (main-orig-len (ly:music-length main))
898          (numerator (ly:moment-main-numerator maindur))
899          (factor (if (eq? (remainder numerator 3) 0)
900                   (ly:make-moment 1/3) (ly:make-moment 1/2))))
901    (ly:music-compress grace
902     (ly:moment-mul factor (ly:moment-div main-orig-len grace-orig-len)))
903    (ly:music-compress main (ly:moment-sub (ly:make-moment 1/1) factor))
904
905     (set! (ly:music-property grace 'elements)
906      (append (ly:music-property grace 'elements)
907       (list (make-music 'SlurEvent 'span-direction -1))))
908     (set! (ly:music-property main 'elements)
909      (append (ly:music-property main 'elements)
910       (list (make-music 'SlurEvent 'span-direction 1))))
911      (make-sequential-music (list grace main))))
912