]> git.donarmstrong.com Git - lilypond.git/blob - scm/part-combiner.scm
Issue 4356: Part combiner: generate mark events in Scheme (not C++)
[lilypond.git] / scm / part-combiner.scm
1 ;;;; This file is part of LilyPond, the GNU music typesetter.
2 ;;;;
3 ;;;; Copyright (C) 2004--2015 Han-Wen Nienhuys <hanwen@xs4all.nl>
4 ;;;;
5 ;;;; LilyPond is free software: you can redistribute it and/or modify
6 ;;;; it under the terms of the GNU General Public License as published by
7 ;;;; the Free Software Foundation, either version 3 of the License, or
8 ;;;; (at your option) any later version.
9 ;;;;
10 ;;;; LilyPond is distributed in the hope that it will be useful,
11 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 ;;;; GNU General Public License for more details.
14 ;;;;
15 ;;;; You should have received a copy of the GNU General Public License
16 ;;;; along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
17
18 ;; todo: figure out how to make module,
19 ;; without breaking nested ly scopes
20
21 (define-class <Voice-state> ()
22   (event-list #:init-value '() #:accessor events #:init-keyword #:events)
23   (when-moment #:accessor moment #:init-keyword #:moment)
24   (tuning #:accessor tuning #:init-keyword #:tuning)
25   (split-index #:accessor split-index)
26   (vector-index)
27   (state-vector)
28   ;;;
29   ;; spanner-state is an alist
30   ;; of (SYMBOL . RESULT-INDEX), which indicates where
31   ;; said spanner was started.
32   (spanner-state #:init-value '() #:accessor span-state))
33
34 (define-method (write (x <Voice-state> ) file)
35   (display (moment x) file)
36   (display " evs = " file)
37   (display (events x) file)
38   (display " active = " file)
39   (display (span-state x) file)
40   (display "\n" file))
41
42 (define-method (note-events (vs <Voice-state>))
43   (define (f? x)
44     (ly:in-event-class? x 'note-event))
45   (filter f? (events vs)))
46
47 ; Return a list of note events which is sorted and stripped of
48 ; properties that we do not want to prevent combining parts.
49 (define-method (comparable-note-events (vs <Voice-state>))
50   (define (note<? note1 note2)
51     (let ((p1 (ly:event-property note1 'pitch))
52           (p2 (ly:event-property note2 'pitch)))
53       (cond ((ly:pitch<? p1 p2) #t)
54             ((ly:pitch<? p2 p1) #f)
55             (else (ly:duration<? (ly:event-property note1 'duration)
56                                  (ly:event-property note2 'duration))))))
57   ;; TODO we probably should compare articulations too
58   (sort (map (lambda (x)
59                (ly:make-stream-event
60                 (ly:make-event-class 'note-event)
61                 (list (cons 'duration (ly:event-property x 'duration))
62                       (cons 'pitch (ly:event-property x 'pitch)))))
63              (note-events vs))
64         note<?))
65
66 (define-method (rest-and-skip-events (vs <Voice-state>))
67   (define (f? x)
68     (or (ly:in-event-class? x 'rest-event)
69         (ly:in-event-class? x 'skip-event)))
70   (filter f? (events vs)))
71
72 (define-method (any-mmrest-events (vs <Voice-state>))
73   (define (f? x)
74     (ly:in-event-class? x 'multi-measure-rest-event))
75   (any f? (events vs)))
76
77 (define-method (previous-voice-state (vs <Voice-state>))
78   (let ((i (slot-ref vs 'vector-index))
79         (v (slot-ref vs 'state-vector)))
80     (if (< 0 i)
81         (vector-ref v (1- i))
82         #f)))
83
84 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
85
86 (define-class <Split-state> ()
87   ;; The automatically determined split configuration
88   (configuration #:init-value '() #:accessor configuration)
89   ;; Allow overriding split configuration, takes precedence over configuration
90   (forced-configuration #:init-value #f #:accessor forced-configuration)
91   (when-moment #:accessor moment #:init-keyword #:moment)
92   ;; voice-states are states starting with the Split-state or later
93   ;;
94   (is #:init-keyword #:voice-states #:accessor voice-states)
95   (synced  #:init-keyword #:synced #:init-value  #f #:getter synced?))
96
97
98 (define-method (write (x <Split-state> ) f)
99   (display (moment x) f)
100   (display " = " f)
101   (display (configuration x) f)
102   (if (synced? x)
103       (display " synced "))
104   (display "\n" f))
105
106 (define-method (current-or-previous-voice-states (ss <Split-state>))
107   "Return voice states meeting the following conditions.  For a voice
108 in sync, return the current voice state.  For a voice out of sync,
109 return the previous voice state."
110   (let* ((vss (voice-states ss))
111          (vs1 (car vss))
112          (vs2 (cdr vss)))
113     (if (and vs1 (not (equal? (moment vs1) (moment ss))))
114         (set! vs1 (previous-voice-state vs1)))
115     (if (and vs2 (not (equal? (moment vs2) (moment ss))))
116         (set! vs2 (previous-voice-state vs2)))
117     (cons vs1 vs2)))
118
119 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
120
121
122 (define (previous-span-state vs)
123   (let ((p (previous-voice-state vs)))
124     (if p (span-state p) '())))
125
126 (define (make-voice-states evl)
127   (let ((vec (list->vector (map (lambda (v)
128                                   (make <Voice-state>
129                                     #:moment (caar v)
130                                     #:tuning (cdar v)
131                                     #:events (map car (cdr v))))
132                                 evl))))
133     (do ((i 0 (1+ i)))
134         ((= i (vector-length vec)) vec)
135       (slot-set! (vector-ref vec i) 'vector-index i)
136       (slot-set! (vector-ref vec i) 'state-vector vec))))
137
138 (define (make-split-state vs1 vs2)
139   "Merge lists VS1 and VS2, containing Voice-state objects into vector
140 of Split-state objects, crosslinking the Split-state vector and
141 Voice-state objects
142 "
143   (define (helper ss-idx ss-list idx1 idx2)
144     (let* ((state1 (if (< idx1 (vector-length vs1)) (vector-ref vs1 idx1) #f))
145            (state2 (if (< idx2 (vector-length vs2)) (vector-ref vs2 idx2) #f))
146            (min (cond ((and state1 state2) (moment-min (moment state1) (moment state2)))
147                       (state1 (moment state1))
148                       (state2 (moment state2))
149                       (else #f)))
150            (inc1 (if (and state1 (equal? min (moment state1))) 1 0))
151            (inc2 (if (and state2 (equal? min (moment state2))) 1 0))
152            (ss-object (if min
153                           (make <Split-state>
154                             #:moment min
155                             #:voice-states (cons state1 state2)
156                             #:synced (= inc1 inc2))
157                           #f)))
158       (if state1
159           (set! (split-index state1) ss-idx))
160       (if state2
161           (set! (split-index state2) ss-idx))
162       (if min
163           (helper (1+ ss-idx)
164                   (cons ss-object ss-list)
165                   (+ idx1 inc1)
166                   (+ idx2 inc2))
167           ss-list)))
168   (list->vector (reverse! (helper 0 '() 0  0) '())))
169
170 (define (analyse-spanner-states voice-state-vec)
171
172   (define (helper index active)
173     "Analyse EVS at INDEX, given state ACTIVE."
174
175     (define (analyse-tie-start active ev)
176       (if (ly:in-event-class? ev 'tie-event)
177           (acons 'tie (split-index (vector-ref voice-state-vec index))
178                  active)
179           active))
180
181     (define (analyse-tie-end active ev)
182       (if (ly:in-event-class? ev 'note-event)
183           (assoc-remove! active 'tie)
184           active))
185
186     (define (analyse-absdyn-end active ev)
187       (if (or (ly:in-event-class? ev 'absolute-dynamic-event)
188               (and (ly:in-event-class? ev 'span-dynamic-event)
189                    (equal? STOP (ly:event-property ev 'span-direction))))
190           (assoc-remove! (assoc-remove! active 'cresc) 'decr)
191           active))
192
193     (define (active<? a b)
194       (cond ((symbol<? (car a) (car b)) #t)
195             ((symbol<? (car b) (car a)) #f)
196             (else (< (cdr a) (cdr b)))))
197
198     (define (analyse-span-event active ev)
199       (let* ((name (car (ly:event-property ev 'class)))
200              (key (cond ((equal? name 'slur-event) 'slur)
201                         ((equal? name 'phrasing-slur-event) 'tie)
202                         ((equal? name 'beam-event) 'beam)
203                         ((equal? name 'crescendo-event) 'cresc)
204                         ((equal? name 'decrescendo-event) 'decr)
205                         (else #f)))
206              (sp (ly:event-property ev 'span-direction)))
207         (if (and (symbol? key) (ly:dir? sp))
208             (if (= sp STOP)
209                 (assoc-remove! active key)
210                 (acons key
211                        (split-index (vector-ref voice-state-vec index))
212                        active))
213             active)))
214
215     (define (analyse-events active evs)
216       "Run all analyzers on ACTIVE and EVS"
217       (define (run-analyzer analyzer active evs)
218         (if (pair? evs)
219             (run-analyzer analyzer (analyzer active (car evs)) (cdr evs))
220             active))
221       (define (run-analyzers analyzers active evs)
222         (if (pair? analyzers)
223             (run-analyzers (cdr analyzers)
224                            (run-analyzer (car analyzers) active evs)
225                            evs)
226             active))
227       (sort ;; todo: use fold or somesuch.
228        (run-analyzers (list analyse-absdyn-end analyse-span-event
229                             ;; note: tie-start/span comes after tie-end/absdyn.
230                             analyse-tie-end analyse-tie-start)
231                       active evs)
232        active<?))
233
234     ;; must copy, since we use assoc-remove!
235     (if (< index (vector-length voice-state-vec))
236         (begin
237           (set! active (analyse-events active (events (vector-ref voice-state-vec index))))
238           (set! (span-state (vector-ref voice-state-vec index))
239                 (list-copy active))
240           (helper (1+ index) active))))
241
242   (helper 0 '()))
243
244 (define recording-group-functions
245   ;;Selected parts from @var{toplevel-music-functions} not requiring @code{parser}.
246   (list
247    (lambda (music) (expand-repeat-chords! '(rhythmic-event) music))
248    expand-repeat-notes!))
249
250
251 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
252 (define-public (recording-group-emulate music odef)
253   "Interpret @var{music} according to @var{odef}, but store all events
254 in a chronological list, similar to the @code{Recording_group_engraver} in
255 LilyPond version 2.8 and earlier."
256   (let*
257       ((context-list '())
258        (now-mom (ly:make-moment 0 0))
259        (global (ly:make-global-context odef))
260        (mom-listener (ly:make-listener
261                       (lambda (tev) (set! now-mom (ly:event-property tev 'moment)))))
262        (new-context-listener
263         (ly:make-listener
264          (lambda (sev)
265            (let*
266                ((child (ly:event-property sev 'context))
267                 (this-moment-list (cons (ly:context-id child) '()))
268                 (dummy (set! context-list (cons this-moment-list context-list)))
269                 (acc '())
270                 (accumulate-event-listener
271                  (ly:make-listener (lambda (ev)
272                                      (set! acc (cons (cons ev #t) acc)))))
273                 (save-acc-listener
274                  (ly:make-listener (lambda (tev)
275                                      (if (pair? acc)
276                                          (let ((this-moment
277                                                 (cons (cons now-mom
278                                                             (ly:context-property child 'instrumentTransposition))
279                                                       ;; The accumulate-event-listener above creates
280                                                       ;; the list of events in reverse order, so we
281                                                       ;; have to revert it to the original order again
282                                                       (reverse acc))))
283                                            (set-cdr! this-moment-list
284                                                      (cons this-moment (cdr this-moment-list)))
285                                            (set! acc '())))))))
286              (ly:add-listener accumulate-event-listener
287                               (ly:context-event-source child) 'StreamEvent)
288              (ly:add-listener save-acc-listener
289                               (ly:context-event-source global) 'OneTimeStep))))))
290     (ly:add-listener new-context-listener
291                      (ly:context-events-below global) 'AnnounceNewContext)
292     (ly:add-listener mom-listener (ly:context-event-source global) 'Prepare)
293     (ly:interpret-music-expression
294      (make-non-relative-music
295       (fold (lambda (x m) (x m)) music recording-group-functions))
296      global)
297     context-list))
298
299 (define-public (make-part-combine-music parser music-list direction chord-range)
300   (let* ((m (make-music 'PartCombineMusic))
301          (m1 (make-non-relative-music (context-spec-music (first music-list) 'Voice "one")))
302          (m2  (make-non-relative-music  (context-spec-music (second music-list) 'Voice "two")))
303          (listener (ly:parser-lookup parser 'partCombineListener))
304          (evs2 (recording-group-emulate m2 listener))
305          (evs1 (recording-group-emulate m1 listener)))
306
307     (set! (ly:music-property m 'elements) (list m1 m2))
308     (set! (ly:music-property m 'direction) direction)
309     (set! (ly:music-property m 'split-list)
310           (if (and (assoc "one" evs1) (assoc "two" evs2))
311               (determine-split-list (reverse! (assoc-get "one" evs1) '())
312                                     (reverse! (assoc-get "two" evs2) '())
313                                     chord-range)
314               '()))
315     m))
316
317 (define-public (determine-split-list evl1 evl2 chord-range)
318   "@var{evl1} and @var{evl2} should be ascending. @var{chord-range} is a pair of numbers (min . max) defining the distance in steps between notes that may be combined into a chord or unison."
319   (let* ((pc-debug #f)
320          (voice-state-vec1 (make-voice-states evl1))
321          (voice-state-vec2 (make-voice-states evl2))
322          (result (make-split-state voice-state-vec1 voice-state-vec2))
323          (chord-min-diff (car chord-range))
324          (chord-max-diff (cdr chord-range)))
325
326     ;; Go through all moments recursively and check if the events of that
327     ;; moment contain a part-combine-force-event override. If so, store its
328     ;; value in the forced-configuration field, which will override. The
329     ;; previous configuration is used to determine non-terminated settings.
330     (define (analyse-forced-combine result-idx prev-res)
331
332       (define (get-forced-event x)
333         (and (ly:in-event-class? x 'part-combine-force-event)
334              (cons (ly:event-property x 'forced-type)
335                    (ly:event-property x 'once))))
336       (define (part-combine-events vs)
337         (if (not vs)
338             '()
339             (filter-map get-forced-event (events vs))))
340       ;; end part-combine-events
341
342       ;; forced-result: Take the previous config and analyse whether
343       ;; any change happened.... Return new once and permanent config
344       (define (forced-result evt state)
345         ;; sanity check, evt should always be (new-state . once)
346         (if (not (and (pair? evt) (pair? state)))
347             state
348             (if (cdr evt)
349                 ;; Once-event, leave permanent state unchanged
350                 (cons (car evt) (cdr state))
351                 ;; permanent change, leave once state unchanged
352                 (cons (car state) (car evt)))))
353       ;; end forced-combine-result
354
355       ;; body of analyse-forced-combine:
356       (if (< result-idx (vector-length result))
357           (let* ((now-state (vector-ref result result-idx)) ; current result
358                  ;; Extract all part-combine force events
359                  (evts (if (synced? now-state)
360                            (append
361                             (part-combine-events (car (voice-states now-state)))
362                             (part-combine-events (cdr (voice-states now-state))))
363                            '()))
364                  ;; result is (once-state permament-state):
365                  (state (fold forced-result (cons 'automatic prev-res) evts))
366                  ;; Now let once override permanent changes:
367                  (force-state (if (equal? (car state) 'automatic)
368                                   (cdr state)
369                                   (car state))))
370             (set! (forced-configuration (vector-ref result result-idx))
371                   force-state)
372             ;; For the next moment, ignore the once override (car stat)
373             ;; and pass on the permanent override, stored as (cdr state)
374             (analyse-forced-combine (1+ result-idx) (cdr state)))))
375     ;; end analyse-forced-combine
376
377
378     (define (analyse-time-step result-idx)
379       (define (put x . index)
380         "Put the result to X, starting from INDEX backwards.
381
382 Only set if not set previously.
383 "
384         (let ((i (if (pair? index) (car index) result-idx)))
385           (if (and (<= 0 i)
386                    (not (symbol? (configuration (vector-ref result i)))))
387               (begin
388                 (set! (configuration (vector-ref result i)) x)
389                 (put x (1- i))))))
390
391       (define (copy-state-from state-vec vs)
392         (define (copy-one-state key-idx)
393           (let* ((idx (cdr key-idx))
394                  (prev-ss (vector-ref result idx))
395                  (prev (configuration prev-ss)))
396             (if (symbol? prev)
397                 (put prev))))
398         (for-each copy-one-state (span-state vs)))
399
400       (define (analyse-notes now-state)
401         (let* ((vs1 (car (voice-states now-state)))
402                (vs2 (cdr (voice-states now-state)))
403                (notes1 (comparable-note-events vs1))
404                (notes2 (comparable-note-events vs2)))
405           (cond
406            ;; if neither part has notes, do nothing
407            ((and (not (pair? notes1)) (not (pair? notes2))))
408
409            ;; if one part has notes and the other does not
410            ((or (not (pair? notes1)) (not (pair? notes2))) (put 'apart))
411
412            ;; if either part has a chord
413            ((or (> (length notes1) 1) 
414                 (> (length notes2) 1))
415             (if (and (<= chord-min-diff 0) ; user requests combined unisons
416                      (equal? notes1 notes2)) ; both parts have the same chord
417                 (put 'chords)
418                 (put 'apart)))
419
420            ;; if the durations are different
421            ;; TODO articulations too?
422            ((and (not (equal? (ly:event-property (car notes1) 'duration)
423                               (ly:event-property (car notes2) 'duration))))
424             (put 'apart))
425
426            (else
427             ;; Is the interval outside of chord-range?
428             (if (let ((diff (ly:pitch-steps
429                              (ly:pitch-diff 
430                               (ly:event-property (car notes1) 'pitch)
431                               (ly:event-property (car notes2) 'pitch)))))
432                   (or (< diff chord-min-diff)
433                       (> diff chord-max-diff)
434                       ))
435                 (put 'apart)
436                 ;; copy previous split state from spanner state
437                 (begin
438                   (if (previous-voice-state vs1)
439                       (copy-state-from voice-state-vec1
440                                        (previous-voice-state vs1)))
441                   (if (previous-voice-state vs2)
442                       (copy-state-from voice-state-vec2
443                                        (previous-voice-state vs2)))
444                   (if (and (null? (span-state vs1)) (null? (span-state vs2)))
445                       (put 'chords))))))))
446
447       (if (< result-idx (vector-length result))
448           (let* ((now-state (vector-ref result result-idx))
449                  (vs1 (car (voice-states now-state)))
450                  (vs2 (cdr (voice-states now-state))))
451
452             (cond ((not vs1) (put 'apart))
453                   ((not vs2) (put 'apart))
454                   (else
455                    (let ((active1 (previous-span-state vs1))
456                          (active2 (previous-span-state vs2))
457                          (new-active1 (span-state vs1))
458                          (new-active2 (span-state vs2)))
459                      (if #f ; debug
460                          (display (list (moment now-state) result-idx
461                                         active1 "->" new-active1
462                                         active2 "->" new-active2
463                                         "\n")))
464                      (if (and (synced? now-state)
465                               (equal? active1 active2)
466                               (equal? new-active1 new-active2))
467                          (analyse-notes now-state)
468
469                          ;; active states different:
470                          (put 'apart)))
471
472                    ;; go to the next one, if it exists.
473                    (analyse-time-step (1+ result-idx)))))))
474
475     (define (analyse-a2 result-idx)
476       (if (< result-idx (vector-length result))
477           (let* ((now-state (vector-ref result result-idx))
478                  (vs1 (car (voice-states now-state)))
479                  (vs2 (cdr (voice-states now-state))))
480
481             (define (analyse-synced-silence)
482               (let ((rests1 (if vs1 (rest-and-skip-events vs1) '()))
483                     (rests2 (if vs2 (rest-and-skip-events vs2) '())))
484                 (cond
485
486                  ;; multi-measure rests (probably), which the
487                  ;; part-combine iterator handles well
488                  ((and (= 0 (length rests1))
489                        (= 0 (length rests2)))
490                   (set! (configuration now-state) 'unisilence))
491
492                  ;; equal rests or equal skips, but not one of each
493                  ((and (= 1 (length rests1))
494                        (= 1 (length rests2))
495                        (equal? (ly:event-property (car rests1) 'class)
496                                (ly:event-property (car rests2) 'class))
497                        (equal? (ly:event-property (car rests1) 'duration)
498                                (ly:event-property (car rests2) 'duration)))
499                   (set! (configuration now-state) 'unisilence))
500
501                  ;; rests of different durations or mixed with
502                  ;; skips or multi-measure rests
503                  (else
504                   ;; TODO For skips, route the rest to the shared
505                   ;; voice and the skip to the voice for its part?
506                   (set! (configuration now-state) 'apart-silence))
507
508                  )))
509
510             (define (analyse-unsynced-silence vs1 vs2)
511               (let ((any-mmrests1 (if vs1 (any-mmrest-events vs1) #f))
512                     (any-mmrests2 (if vs2 (any-mmrest-events vs2) #f)))
513                 (cond
514                  ;; If a multi-measure rest begins now while the other
515                  ;; part has an ongoing multi-measure rest (or has
516                  ;; ended), start displaying the one that begins now.
517                  ((and any-mmrests1
518                        (equal? (moment vs1) (moment now-state))
519                        (or (not vs2) any-mmrests2))
520                   (set! (configuration now-state) 'silence1))
521
522                  ;; as above with parts swapped
523                  ((and any-mmrests2
524                        (equal? (moment vs2) (moment now-state))
525                        (or (not vs1) any-mmrests1))
526                   (set! (configuration now-state) 'silence2))
527                  )))
528
529             (if (or vs1 vs2)
530                 (let ((notes1 (if vs1 (comparable-note-events vs1) '()))
531                       (notes2 (if vs2 (comparable-note-events vs2) '())))
532                   (cond ((and (equal? (configuration now-state) 'chords)
533                               (pair? notes1)
534                               (equal? notes1 notes2))
535                          (set! (configuration now-state) 'unisono))
536
537                         ((synced? now-state)
538                          (if (and (= 0 (length notes1))
539                                   (= 0 (length notes2)))
540                              (analyse-synced-silence)))
541
542                         (else ;; not synchronized
543                          (let* ((vss
544                                  (current-or-previous-voice-states now-state))
545                                 (vs1 (car vss))
546                                 (vs2 (cdr vss)))
547                            (if (and
548                                 (or (not vs1) (= 0 (length (note-events vs1))))
549                                 (or (not vs2) (= 0 (length (note-events vs2)))))
550                                (analyse-unsynced-silence vs1 vs2))))
551                         )))
552             (analyse-a2 (1+ result-idx)))))
553
554     (define (analyse-solo12 result-idx)
555
556       (define (previous-config vs)
557         (let* ((pvs (previous-voice-state vs))
558                (spi (if pvs (split-index pvs) #f))
559                (prev-split (if spi (vector-ref result spi) #f)))
560           (if prev-split
561               (configuration prev-split)
562               'apart)))
563
564       (define (put-range x a b)
565         ;; (display (list "put range "  x a b "\n"))
566         (do ((i a (1+ i)))
567             ((> i b) b)
568           (set! (configuration (vector-ref result i)) x)))
569
570       (define (put x)
571         ;; (display (list "putting "  x "\n"))
572         (set! (configuration (vector-ref result result-idx)) x))
573
574       (define (current-voice-state now-state voice-num)
575         (define vs ((if (= 1 voice-num) car cdr)
576                     (voice-states now-state)))
577         (if (or (not vs) (equal? (moment now-state) (moment vs)))
578             vs
579             (previous-voice-state vs)))
580
581       (define (try-solo type start-idx current-idx)
582         "Find a maximum stretch that can be marked as solo.  Only set
583 the mark when there are no spanners active.
584
585       return next idx to analyse.
586 "
587         (if (< current-idx (vector-length result))
588             (let* ((now-state (vector-ref result current-idx))
589                    (solo-state (current-voice-state now-state (if (equal? type 'solo1) 1 2)))
590                    (silent-state (current-voice-state now-state (if (equal? type 'solo1) 2 1)))
591                    (silent-notes (if silent-state (note-events silent-state) '()))
592                    (solo-notes (if solo-state (note-events solo-state) '())))
593               ;; (display (list "trying " type " at "  (moment now-state) solo-state silent-state        "\n"))
594               (cond ((not (equal? (configuration now-state) 'apart))
595                      current-idx)
596                     ((> (length silent-notes) 0) start-idx)
597                     ((not solo-state)
598                      (put-range type start-idx current-idx)
599                      current-idx)
600                     ((and
601                       (null? (span-state solo-state)))
602
603                      ;;
604                      ;; This includes rests. This isn't a problem: long rests
605                      ;; will be shared with the silent voice, and be marked
606                      ;; as unisilence. Therefore, long rests won't
607                      ;;  accidentally be part of a solo.
608                      ;;
609                      (put-range type start-idx current-idx)
610                      (try-solo type (1+ current-idx) (1+  current-idx)))
611                     (else
612                      (try-solo type start-idx (1+ current-idx)))))
613             ;; try-solo
614             start-idx))
615
616       (define (analyse-apart-silence result-idx)
617         "Analyse 'apart-silence starting at RESULT-IDX.  Return next index."
618         (let* ((now-state (vector-ref result result-idx))
619                (vs1 (current-voice-state now-state 1))
620                (vs2 (current-voice-state now-state 2))
621                (rests1 (if vs1 (rest-and-skip-events vs1) '()))
622                (rests2 (if vs2 (rest-and-skip-events vs2) '()))
623                (prev-state (if (> result-idx 0)
624                                (vector-ref result (- result-idx 1))
625                                #f))
626                (prev-config (if prev-state
627                                 (configuration prev-state)
628                                 'apart-silence)))
629           (cond
630            ;; rest with multi-measure rest: choose the rest
631            ((and (synced? now-state)
632                  (= 1 (length rests1))
633                  (ly:in-event-class? (car rests1) 'rest-event)
634                  (= 0 (length rests2))) ; probably mmrest
635             (put 'silence1))
636
637            ;; as above with parts swapped
638            ((and (synced? now-state)
639                  (= 1 (length rests2))
640                  (ly:in-event-class? (car rests2) 'rest-event)
641                  (= 0 (length rests1))) ; probably mmrest
642             (put 'silence2))
643
644            ((synced? now-state)
645             (put 'apart-silence))
646
647            ;; remain in the silence1/2 states until resync
648            ((equal? prev-config 'silence1)
649             (put 'silence1))
650
651            ((equal? prev-config 'silence2)
652             (put 'silence2))
653
654            (else
655             (put 'apart-silence)))
656
657           (1+ result-idx)))
658
659       (define (analyse-apart result-idx)
660         "Analyse 'apart starting at RESULT-IDX.  Return next index."
661         (let* ((now-state (vector-ref result result-idx))
662                (vs1 (current-voice-state now-state 1))
663                (vs2 (current-voice-state now-state 2))
664                ;; (vs1 (car (voice-states now-state)))
665                ;; (vs2 (cdr (voice-states now-state)))
666                (notes1 (if vs1 (note-events vs1) '()))
667                (notes2 (if vs2 (note-events vs2) '()))
668                (n1 (length notes1))
669                (n2 (length notes2)))
670           ;; (display (list "analyzing step " result-idx "  moment " (moment now-state) vs1 vs2  "\n"))
671           (max
672            ;; we should always increase.
673            (cond ((and (= n1 0) (= n2 0))
674                   ;; If we hit this, it means that the previous passes
675                   ;; have designated as 'apart what is really
676                   ;; 'apart-silence.
677                   (analyse-apart-silence result-idx))
678                  ((and (= n2 0)
679                        (equal? (moment vs1) (moment now-state))
680                        (null? (previous-span-state vs1)))
681                   (try-solo 'solo1 result-idx result-idx))
682                  ((and (= n1 0)
683                        (equal? (moment vs2) (moment now-state))
684                        (null? (previous-span-state vs2)))
685                   (try-solo 'solo2 result-idx result-idx))
686
687                  (else (1+ result-idx)))
688            ;; analyse-moment
689            (1+ result-idx))))
690
691       (if (< result-idx (vector-length result))
692           (let ((conf (configuration (vector-ref result result-idx))))
693             (cond
694              ((equal? conf 'apart)
695               (analyse-solo12 (analyse-apart result-idx)))
696              ((equal? conf 'apart-silence)
697               (analyse-solo12 (analyse-apart-silence result-idx)))
698              (else
699               (analyse-solo12 (1+ result-idx))))))) ; analyse-solo12
700
701     (analyse-spanner-states voice-state-vec1)
702     (analyse-spanner-states voice-state-vec2)
703     (if #f
704         (begin
705           (display voice-state-vec1)
706           (display "***\n")
707           (display voice-state-vec2)
708           (display "***\n")
709           (display result)
710           (display "***\n")))
711
712     ;; Extract all forced combine strategies, i.e. events inserted by
713     ;; \partcombine(Apart|Automatic|SoloI|SoloII|Chords)[Once]
714     ;; They will in the end override the automaically determined ones.
715     ;; Initial state for both voices is no override
716     (analyse-forced-combine 0 #f)
717     ;; Now go through all time steps in a loop and find a combination strategy
718     ;; based only on the events of that one moment (i.e. neglecting longer
719     ;; periods of solo/apart, etc.)
720     (analyse-time-step 0)
721     ;; (display result)
722     ;; Check for unisono or unisilence moments
723     (analyse-a2 0)
724     ;;(display result)
725     (analyse-solo12 0)
726     ;; (display result)
727     (set! result (map
728                   ;; forced-configuration overrides, if it is set
729                   (lambda (x) (cons (moment x) (or (forced-configuration x) (configuration x))))
730                   (vector->list result)))
731     (if #f ;; pc-debug
732         (display result))
733     result))
734
735 (define-public default-part-combine-mark-state-machine
736   ;; (current-state . ((split-state-event .
737   ;;                      (output-voice output-event next-state)) ...))
738   '((Initial . ((solo1   . (solo   SoloOneEvent Solo1))
739                 (solo2   . (solo   SoloTwoEvent Solo2))
740                 (unisono . (shared UnisonoEvent Unisono))))
741     (Solo1   . ((apart   . (#f     #f           Initial))
742                 (chords  . (#f     #f           Initial))
743                 (solo2   . (solo   SoloTwoEvent Solo2))
744                 (unisono . (shared UnisonoEvent Unisono))))
745     (Solo2   . ((apart   . (#f     #f           Initial))
746                 (chords  . (#f     #f           Initial))
747                 (solo1   . (solo   SoloOneEvent Solo1))
748                 (unisono . (shared UnisonoEvent Unisono))))
749     (Unisono . ((apart   . (#f     #f           Initial))
750                 (chords  . (#f     #f           Initial))
751                 (solo1   . (solo   SoloOneEvent Solo1))
752                 (solo2   . (solo   SoloTwoEvent Solo2))))))
753
754 (define-public (make-part-combine-marks state-machine split-list)
755   "Generate a sequence of part combiner events from a split list"
756
757   (define (get-state state-name)
758     (assq-ref state-machine state-name))
759
760   (let ((full-seq '()) ; sequence of { \context Voice = "x" {} ... }
761         (segment '()) ; sequence within \context Voice = "x" {...}
762         (prev-moment ZERO-MOMENT)
763         (prev-voice #f)
764         (state (get-state 'Initial)))
765
766     (define (commit-segment)
767       "Add the current segment to the full sequence and begin another."
768       (if (pair? segment)
769           (set! full-seq
770                 (cons (make-music 'ContextSpeccedMusic
771                                   'context-id (symbol->string prev-voice)
772                                   'context-type 'Voice
773                                   'element (make-sequential-music (reverse! segment)))
774                       full-seq)))
775       (set! segment '()))
776
777     (define (handle-split split)
778       (let* ((moment (car split))
779              (action (assq-ref state (cdr split))))
780         (if action
781             (let ((voice (car action))
782                   (part-combine-event (cadr action))
783                   (next-state-name (caddr action)))
784               (if part-combine-event
785                   (let ((dur (ly:moment-sub moment prev-moment)))
786                     ;; start a new segment when the voice changes
787                     (if (not (eq? voice prev-voice))
788                         (begin
789                           (commit-segment)
790                           (set! prev-voice voice)))
791                     (if (not (equal? dur ZERO-MOMENT))
792                         (set! segment (cons (make-music 'SkipEvent
793                                                           'duration (make-duration-of-length dur)) segment)))
794                     (set! segment (cons (make-music part-combine-event) segment))
795
796                     (set! prev-moment moment)))
797               (set! state (get-state next-state-name))))))
798
799     (for-each handle-split split-list)
800     (commit-segment)
801     (make-sequential-music (reverse! full-seq))))
802
803 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
804
805 (define-public (add-quotable parser name mus)
806   (let* ((tab (eval 'musicQuotes (current-module)))
807          (voicename (get-next-unique-voice-name))
808          ;; recording-group-emulate returns an assoc list (reversed!), so
809          ;; hand it a proper unique context name and extract that key:
810          (ctx-spec (context-spec-music mus 'Voice voicename))
811          (listener (ly:parser-lookup parser 'partCombineListener))
812          (context-list (reverse (recording-group-emulate ctx-spec listener)))
813          (raw-voice (assoc voicename context-list))
814          (quote-contents (if (pair? raw-voice) (cdr raw-voice) '())))
815
816     ;; If the context-specced quoted music does not contain anything, try to
817     ;; use the first child, i.e. the next in context-list after voicename
818     ;; That's the case e.g. for \addQuote "x" \relative c \new Voice {...}
819     (if (null? quote-contents)
820         (let find-non-empty ((current-tail (member raw-voice context-list)))
821           ;; if voice has contents, use them, otherwise check next ctx
822           (cond ((null? current-tail) #f)
823                 ((and (pair? (car current-tail))
824                       (pair? (cdar current-tail)))
825                  (set! quote-contents (cdar current-tail)))
826                 (else (find-non-empty (cdr current-tail))))))
827
828     (if (not (null? quote-contents))
829         (hash-set! tab name (list->vector (reverse! quote-contents '())))
830         (ly:music-warning mus (ly:format (_ "quoted music `~a' is empty") name)))))