]> git.donarmstrong.com Git - lilypond.git/blob - lily/dynamic-performer.cc
Fix ending the dynamic extent in Text_interface::interpret_markup
[lilypond.git] / lily / dynamic-performer.cc
1 /*
2   This file is part of LilyPond, the GNU music typesetter.
3
4   Copyright (C) 2000--2015 Jan Nieuwenhuizen <janneke@gnu.org>
5
6   LilyPond is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   LilyPond is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "performer.hh"
21 #include "audio-item.hh"
22 #include "std-vector.hh"
23 #include "stream-event.hh"
24 #include "international.hh"
25
26 #include "translator.icc"
27
28 class Dynamic_performer : public Performer
29 {
30 public:
31   TRANSLATOR_DECLARATIONS (Dynamic_performer);
32 protected:
33   virtual void acknowledge_audio_element (Audio_element_info info);
34   virtual void finalize ();
35   void stop_translation_timestep ();
36   void process_music ();
37   Real equalize_volume (Real);
38
39   void listen_decrescendo (Stream_event *);
40   void listen_crescendo (Stream_event *);
41   void listen_absolute_dynamic (Stream_event *);
42
43 private:
44   void close_and_enqueue_span ();
45   Real compute_departure_volume (Direction depart_dir,
46                                  Real start_vol,
47                                  Real end_vol,
48                                  Real min_vol,
49                                  Real max_vol);
50   bool drive_state_machine (Direction next_grow_dir);
51   // next_vol < 0 means select a target dynamic based on growth direction.
52   // return actual next volume (computed if not provided)
53   Real finish_queued_spans (Real next_vol = -1.0);
54   Real look_up_absolute_volume (SCM dynamicString,
55                                 Real defaultValue);
56
57 private:
58   // This performer queues a number of dynamic spans waiting for the following
59   // pattern before computing their volume levels.
60   //
61   //  1. the first (de)crescendo, followed by ...
62   //  2. zero or more spans that either change in the same direction as the
63   //     first or do not change, followed by ...
64   //  3. zero or more spans that either change in the opposite direction as the
65   //     first or do not change
66   //
67   // The search may be cut short by an absolute dynamic or the end of the
68   // context.
69   enum State
70   {
71     STATE_INITIAL = 0, // waiting for a (de)crescendo
72     STATE_DEPART, // enqueued the first span, gathering same-direction spans
73     STATE_RETURN // gathering opposite-direction spans
74   };
75
76   struct UnfinishedSpan
77   {
78     Audio_span_dynamic *dynamic_;
79     Direction grow_dir_;
80
81     UnfinishedSpan () : dynamic_ (0), grow_dir_ (CENTER) {}
82   };
83
84   struct DynamicQueue
85   {
86     vector<UnfinishedSpan> spans_;
87     // total duration of (de)crescendi (i.e. excluding fixed-volume spans)
88     Real change_duration_;
89     Real min_target_vol_;
90     Real max_target_vol_;
91
92     DynamicQueue () : change_duration_ (0) {}
93
94     void clear ()
95     {
96       spans_.clear ();
97       change_duration_ = 0;
98     }
99
100     void push_back (const UnfinishedSpan &span,
101                     Real min_target_vol,
102                     Real max_target_vol)
103     {
104       if (span.grow_dir_ != CENTER)
105         change_duration_ += span.dynamic_->get_duration ();
106       min_target_vol_ = min_target_vol;
107       max_target_vol_ = max_target_vol;
108       spans_.push_back (span);
109     }
110
111     void set_volume (Real start_vol, Real target_vol);
112   };
113
114 private:
115   vector<Audio_note *> notes_;
116   Stream_event *script_event_;
117   Drul_array<Stream_event *> span_events_;
118   Direction next_grow_dir_;
119   Direction depart_dir_;
120   UnfinishedSpan open_span_;
121   DynamicQueue depart_queue_;
122   DynamicQueue return_queue_;
123   State state_;
124 };
125
126 Dynamic_performer::Dynamic_performer ()
127   : script_event_ (0),
128     next_grow_dir_ (CENTER),
129     depart_dir_ (CENTER),
130     state_ (STATE_INITIAL)
131 {
132   span_events_[LEFT]
133   = span_events_[RIGHT] = 0;
134 }
135
136 void
137 Dynamic_performer::acknowledge_audio_element (Audio_element_info inf)
138 {
139   // Keep track of the notes played in this translation time step so that they
140   // can be pointed to the current dynamic in stop_translation_timestep.
141   if (Audio_note *n = dynamic_cast<Audio_note *> (inf.elem_)) {
142     notes_.push_back (n);
143   }
144 }
145
146 bool
147 Dynamic_performer::drive_state_machine (Direction next_grow_dir)
148 {
149   switch (state_)
150     {
151     case STATE_INITIAL:
152       if (next_grow_dir != CENTER)
153         {
154           state_ = STATE_DEPART;
155           depart_dir_ = next_grow_dir;
156         }
157       break;
158
159     case STATE_DEPART:
160       if (next_grow_dir == -depart_dir_)
161         state_ = STATE_RETURN;
162       break;
163
164     case STATE_RETURN:
165       if (next_grow_dir == depart_dir_)
166         {
167           state_ = STATE_DEPART;
168           return true;
169         }
170       break;
171     }
172
173   return false;
174 }
175
176 void
177 Dynamic_performer::close_and_enqueue_span ()
178 {
179   if (!open_span_.dynamic_)
180     programming_error ("no open dynamic span");
181   else
182     {
183       DynamicQueue &dq
184       = (state_ == STATE_RETURN) ? return_queue_ : depart_queue_;
185
186       // Changing equalizer settings in the course of the performance does not
187       // seem very likely.  This is a fig leaf: Equalize these limit volumes
188       // now as the required context properties are current.  Note that only
189       // the limits at the end of the last span in the queue are kept.
190
191       // Resist diminishing to silence.  (Idea: Look up "ppppp"
192       // with dynamicAbsoluteVolumeFunction, however that would yield 0.25.)
193       const Real min_target = equalize_volume (0.1);
194       const Real max_target
195       = equalize_volume (Audio_span_dynamic::MAXIMUM_VOLUME);
196
197       open_span_.dynamic_->set_end_moment (now_mom ());
198       dq.push_back (open_span_, min_target, max_target);
199     }
200
201   open_span_ = UnfinishedSpan ();
202 }
203
204 // Set the starting and target volume for each span in the queue.  The gain
205 // (loss) of any (de)crescendo is proportional to its share of the total time
206 // spent changing.
207 void
208 Dynamic_performer::DynamicQueue::set_volume (Real start_vol,
209                                              Real target_vol)
210 {
211   const Real gain = target_vol - start_vol;
212   Real dur = 0; // duration of (de)crescendi processed so far
213   Real vol = start_vol;
214   for (vector<UnfinishedSpan>::iterator it = spans_.begin ();
215        it != spans_.end (); ++it)
216     {
217       const Real prev_vol = vol;
218       if (it->grow_dir_ != CENTER)
219         {
220           // grant this (de)crescendo its portion of the gain
221           dur += it->dynamic_->get_duration ();
222           vol = start_vol + gain * (dur / change_duration_);
223         }
224       it->dynamic_->set_volume (prev_vol, vol);
225     }
226 }
227
228 // Return a volume which is reasonably distant from the given start and end
229 // volumes in the given direction, for use as a peak volume in a passage with a
230 // crescendo followed by a decrescendo (or vice versa).  If the given volumes
231 // are equal, the returned volume is a also reasonable target volume for a
232 // single (de)crescendo.
233 //
234 // The given minimum and maximum volumes are the allowable dynamic range.
235 Real
236 Dynamic_performer::compute_departure_volume (Direction depart_dir,
237                                              Real start_vol,
238                                              Real end_vol,
239                                              Real min_vol,
240                                              Real max_vol)
241 {
242   if (depart_dir == CENTER)
243     return start_vol;
244
245   // Try to find a volume that is a minimum distance from the starting and
246   // ending volumes.  If the endpoint volumes differ, the nearer one is padded
247   // less than the farther one.
248   //
249   // Example: mf < ... > p.  The legacy behavior was to use a 25% of the
250   // dynamic range for a (de)crescendo to an unspecified target, and this tries
251   // to preserve that, but is not possible to use a 25% change for both the
252   // crescendo and the decrescendo and meet the constraints of this example.
253   // The decrescendo is a greater change than the crescendo.  Believing that
254   // 25% is already more than enough for either, pad using 25% for the greater
255   // change and 7% for the lesser change.
256   //
257   // Idea: Use a context property or callback, e.g. the difference between two
258   // dynamics in dynamicAbsoluteVolumeFunction.  0.25 is the default difference
259   // between "p" and "ff". (Isn't that rather wide for this purpose?)  0.07 is
260   // the default difference between "mp" and "mf".
261   const Real far_padding = 0.25;
262   const Real near_padding = 0.07;
263
264   // If for some reason one of the endpoints is already below the supposed
265   // minimum or maximum, just accept it.
266   min_vol = min (min (min_vol, start_vol), end_vol);
267   max_vol = max (max (max_vol, start_vol), end_vol);
268
269   const Real vol_range = max_vol - min_vol;
270
271   const Real near_vol = minmax (depart_dir, start_vol, end_vol)
272                     + depart_dir * near_padding * vol_range;
273   const Real far_vol = minmax (-depart_dir, start_vol, end_vol)
274                    + depart_dir * far_padding * vol_range;
275   const Real depart_vol = minmax (depart_dir, near_vol, far_vol);
276   return max (min (depart_vol, max_vol), min_vol);
277 }
278
279 Real
280 Dynamic_performer::finish_queued_spans (Real next_vol)
281 {
282   if (depart_queue_.spans_.empty ())
283     {
284       programming_error ("no dynamic span to finish");
285       return next_vol;
286     }
287
288   const Real start_vol = depart_queue_.spans_.front ().dynamic_->get_start_volume ();
289
290   if (return_queue_.spans_.empty ())
291     {
292       Real depart_vol = next_vol;
293
294       // If the next dynamic is not specified or is inconsistent with the
295       // direction of growth, choose a reasonable target.
296       if ((next_vol < 0) || (depart_dir_ != sign (next_vol - start_vol)))
297         {
298           depart_vol = compute_departure_volume (depart_dir_,
299                                                  start_vol, start_vol,
300                                                  depart_queue_.min_target_vol_,
301                                                  depart_queue_.max_target_vol_);
302         }
303
304       depart_queue_.set_volume (start_vol, depart_vol);
305       depart_queue_.clear ();
306       return (next_vol >= 0) ? next_vol : depart_vol;
307     }
308   else
309     {
310       // If the next dynamic is not specified, return to the starting volume.
311       const Real return_vol = (next_vol >= 0) ? next_vol : start_vol;
312       Real depart_vol = compute_departure_volume (depart_dir_,
313                                                   start_vol, return_vol,
314                                                   depart_queue_.min_target_vol_,
315                                                   depart_queue_.max_target_vol_);
316       depart_queue_.set_volume (start_vol, depart_vol);
317       depart_queue_.clear ();
318       return_queue_.set_volume (depart_vol, return_vol);
319       return_queue_.clear ();
320       return return_vol;
321     }
322 }
323
324 Real
325 Dynamic_performer::equalize_volume (Real volume)
326 {
327   /*
328     properties override default equaliser setting
329   */
330   SCM min = get_property ("midiMinimumVolume");
331   SCM max = get_property ("midiMaximumVolume");
332   if (scm_is_number (min) || scm_is_number (max))
333     {
334       Interval iv (Audio_span_dynamic::MINIMUM_VOLUME,
335                    Audio_span_dynamic::MAXIMUM_VOLUME);
336       if (scm_is_number (min))
337         iv[MIN] = scm_to_double (min);
338       if (scm_is_number (max))
339         iv[MAX] = scm_to_double (max);
340       volume = iv[MIN] + iv.length () * volume;
341     }
342   else
343     {
344       /*
345         urg, code duplication:: staff_performer
346       */
347       SCM s = get_property ("midiInstrument");
348
349       if (!scm_is_string (s))
350         s = get_property ("instrumentName");
351
352       if (!scm_is_string (s))
353         s = scm_from_ascii_string ("piano");
354
355       SCM eq = get_property ("instrumentEqualizer");
356       if (ly_is_procedure (eq))
357         s = scm_call_1 (eq, s);
358
359       if (is_number_pair (s))
360         {
361           Interval iv = ly_scm2interval (s);
362           volume = iv[MIN] + iv.length () * volume;
363         }
364     }
365   return std::max (std::min (volume, Audio_span_dynamic::MAXIMUM_VOLUME),
366                    Audio_span_dynamic::MINIMUM_VOLUME);
367 }
368
369 void
370 Dynamic_performer::finalize ()
371 {
372   if (open_span_.dynamic_)
373     close_and_enqueue_span ();
374   finish_queued_spans ();
375 }
376
377 Real
378 Dynamic_performer::look_up_absolute_volume (SCM dynamicString,
379                                             Real defaultValue)
380 {
381   SCM proc = get_property ("dynamicAbsoluteVolumeFunction");
382
383   SCM svolume = SCM_EOL;
384   if (ly_is_procedure (proc))
385     svolume = scm_call_1 (proc, dynamicString);
386
387   return robust_scm2double (svolume, defaultValue);
388 }
389
390 void
391 Dynamic_performer::process_music ()
392 {
393   Real volume = -1;
394
395   if (script_event_) // explicit dynamic
396     {
397       volume = look_up_absolute_volume (script_event_->get_property ("text"),
398                                         Audio_span_dynamic::DEFAULT_VOLUME);
399       volume = equalize_volume (volume);
400     }
401   else if (!open_span_.dynamic_) // first time only
402     {
403       // Idea: look_up_absolute_volume (ly_symbol2scm ("mf")).
404       // It is likely to change regtests.
405       volume = equalize_volume (Audio_span_dynamic::DEFAULT_VOLUME);
406     }
407
408   // end the current span at relevant points
409   if (open_span_.dynamic_
410       && (span_events_[START] || span_events_[STOP] || script_event_))
411     {
412       close_and_enqueue_span ();
413       if (script_event_)
414         {
415           state_ = STATE_INITIAL;
416           volume = finish_queued_spans (volume);
417         }
418     }
419
420   // start a new span so that some dynamic is always in effect
421   if (!open_span_.dynamic_)
422     {
423       if (drive_state_machine (next_grow_dir_))
424         volume = finish_queued_spans (volume);
425
426       // if not known by now, use a default volume for robustness
427       if (volume < 0)
428         volume = equalize_volume (Audio_span_dynamic::DEFAULT_VOLUME);
429
430       Stream_event *cause
431       = span_events_[START] ? span_events_[START]
432         : script_event_ ? script_event_
433         : span_events_[STOP];
434
435       open_span_.dynamic_ = new Audio_span_dynamic (now_mom (), volume);
436       open_span_.grow_dir_ = next_grow_dir_;
437       announce_element (Audio_element_info (open_span_.dynamic_, cause));
438     }
439 }
440
441 void
442 Dynamic_performer::stop_translation_timestep ()
443 {
444   // link notes to the current dynamic
445   if (!open_span_.dynamic_)
446     programming_error("no current dynamic");
447   else
448     {
449       for (vector<Audio_note *>::const_iterator ni = notes_.begin ();
450            ni != notes_.end (); ++ni)
451         {
452           (*ni)->dynamic_ = open_span_.dynamic_;
453         }
454     }
455   notes_.clear ();
456
457   script_event_ = 0;
458   span_events_[LEFT]
459   = span_events_[RIGHT] = 0;
460   next_grow_dir_ = CENTER;
461 }
462
463 void
464 Dynamic_performer::listen_decrescendo (Stream_event *r)
465 {
466   Direction d = to_dir (r->get_property ("span-direction"));
467   if (ASSIGN_EVENT_ONCE (span_events_[d], r) && (d == START))
468     next_grow_dir_ = SMALLER;
469 }
470
471 void
472 Dynamic_performer::listen_crescendo (Stream_event *r)
473 {
474   Direction d = to_dir (r->get_property ("span-direction"));
475   if (ASSIGN_EVENT_ONCE (span_events_[d], r) && (d == START))
476     next_grow_dir_ = BIGGER;
477 }
478
479 void
480 Dynamic_performer::listen_absolute_dynamic (Stream_event *r)
481 {
482   ASSIGN_EVENT_ONCE (script_event_, r);
483 }
484
485 void
486 Dynamic_performer::boot ()
487 {
488   ADD_LISTENER (Dynamic_performer, decrescendo);
489   ADD_LISTENER (Dynamic_performer, crescendo);
490   ADD_LISTENER (Dynamic_performer, absolute_dynamic);
491 }
492
493 ADD_TRANSLATOR (Dynamic_performer,
494                 /* doc */
495                 "",
496
497                 /* create */
498                 "",
499
500                 /* read */
501                 "dynamicAbsoluteVolumeFunction "
502                 "instrumentEqualizer "
503                 "midiMaximumVolume "
504                 "midiMinimumVolume "
505                 "midiInstrument ",
506
507                 /* write */
508                 ""
509                );