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