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