Refactor tempo api, include quarter-note distance in frames method.
[ardour.git] / libs / ardour / ardour / tempo.h
1 /*
2     Copyright (C) 2000 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #ifndef __ardour_tempo_h__
21 #define __ardour_tempo_h__
22
23 #include <list>
24 #include <string>
25 #include <vector>
26 #include <cmath>
27 #include <glibmm/threads.h>
28
29 #include "pbd/undo.h"
30
31 #include "pbd/stateful.h"
32 #include "pbd/statefuldestructible.h"
33
34 #include "evoral/Beats.hpp"
35
36 #include "ardour/ardour.h"
37
38 class BBTTest;
39 class FrameposPlusBeatsTest;
40 class FrameposMinusBeatsTest;
41 class TempoTest;
42 class XMLNode;
43
44 namespace ARDOUR {
45
46 class Meter;
47 class TempoMap;
48
49 /** Tempo, the speed at which musical time progresses (BPM). */
50 class LIBARDOUR_API Tempo {
51   public:
52         /**
53          * @param bpm Beats Per Minute
54          * @param type Note Type (default `4': quarter note)
55          */
56         Tempo (double bpm, double type=4.0) // defaulting to quarter note
57                 : _beats_per_minute (bpm), _note_type(type) {}
58
59         /*
60            quarter note beats as distinct from a beat derived from meter and pulse.
61         */
62         double beats_per_minute () const { return _beats_per_minute; }
63         void set_beats_per_minute (double bpm) { _beats_per_minute = bpm; }
64         double note_type () const { return _note_type; }
65         /** audio samples per quarter note beat.
66          * this is only useful for constant tempo and should not be used.
67          * if you want an instantaneous value for this, use frames_per_beat_at() instead.
68          * @param sr samplerate
69          */
70         double frames_per_beat (framecnt_t sr) const {
71                 return (60.0 * sr) / _beats_per_minute;
72         }
73
74   protected:
75         double _beats_per_minute;
76         double _note_type;
77 };
78
79 /** Meter, or time signature (beats per bar, and which note type is a beat). */
80 class LIBARDOUR_API Meter {
81   public:
82         Meter (double dpb, double bt)
83                 : _divisions_per_bar (dpb), _note_type (bt) {}
84
85         double divisions_per_bar () const { return _divisions_per_bar; }
86         double note_divisor() const { return _note_type; }
87
88         double frames_per_bar (const Tempo&, framecnt_t sr) const;
89         double frames_per_grid (const Tempo&, framecnt_t sr) const;
90
91   protected:
92         /** The number of divisions in a bar.  This is a floating point value because
93             there are musical traditions on our planet that do not limit
94             themselves to integral numbers of beats per bar.
95         */
96         double _divisions_per_bar;
97
98         /** The type of "note" that a division represents.  For example, 4.0 is
99             a quarter (crotchet) note, 8.0 is an eighth (quaver) note, etc.
100         */
101         double _note_type;
102 };
103
104 /** A section of timeline with a certain Tempo or Meter. */
105 class LIBARDOUR_API MetricSection {
106   public:
107         MetricSection (double pulse, double minute, PositionLockStyle pls, bool is_tempo, framecnt_t sample_rate)
108                 : _pulse (pulse), _minute (minute), _movable (true), _position_lock_style (pls), _is_tempo (is_tempo), _sample_rate (sample_rate) {}
109
110         virtual ~MetricSection() {}
111
112         const double& pulse () const { return _pulse; }
113         void set_pulse (double pulse) { _pulse = pulse; }
114
115         double minute() const { return _minute; }
116         virtual void set_minute (double m) {
117                 _minute = m;
118         }
119
120         framepos_t frame () const { return frame_at_minute (_minute); }
121
122         void set_movable (bool yn) { _movable = yn; }
123         bool movable() const { return _movable; }
124
125         /* MeterSections are not stateful in the full sense,
126            but we do want them to control their own
127            XML state information.
128         */
129         virtual XMLNode& get_state() const = 0;
130
131         PositionLockStyle position_lock_style () const { return _position_lock_style; }
132         void set_position_lock_style (PositionLockStyle ps) { _position_lock_style = ps; }
133         bool is_tempo () const { return _is_tempo; }
134
135         framepos_t frame_at_minute (const double& time) const;
136         double minute_at_frame (const framepos_t& frame) const;
137
138 private:
139
140         double             _pulse;
141         double             _minute;
142         bool               _movable;
143         PositionLockStyle  _position_lock_style;
144         const bool         _is_tempo;
145         framecnt_t         _sample_rate;
146 };
147
148 /** A section of timeline with a certain Meter. */
149 class LIBARDOUR_API MeterSection : public MetricSection, public Meter {
150   public:
151         MeterSection (double pulse, double minute, double beat, const Timecode::BBT_Time& bbt, double bpb, double note_type, PositionLockStyle pls, framecnt_t sr)
152                 : MetricSection (pulse, minute, pls, false, sr), Meter (bpb, note_type), _bbt (bbt),  _beat (beat) {}
153
154         MeterSection (const XMLNode&, const framecnt_t sample_rate);
155
156         static const std::string xml_state_node_name;
157
158         XMLNode& get_state() const;
159
160         void set_beat (std::pair<double, Timecode::BBT_Time>& w) {
161                 _beat = w.first;
162                 _bbt = w.second;
163         }
164
165         const Timecode::BBT_Time& bbt() const { return _bbt; }
166         const double& beat () const { return _beat; }
167         void set_beat (double beat) { _beat = beat; }
168
169 private:
170         Timecode::BBT_Time _bbt;
171         double _beat;
172 };
173
174 /** A section of timeline with a certain Tempo. */
175 class LIBARDOUR_API TempoSection : public MetricSection, public Tempo {
176   public:
177         enum Type {
178                 Ramp,
179                 Constant,
180         };
181
182         TempoSection (const double& pulse, const double& minute, double qpm, double note_type, Type tempo_type, PositionLockStyle pls, framecnt_t sr)
183                 : MetricSection (pulse, minute, pls, true, sr), Tempo (qpm, note_type), _type (tempo_type), _c_func (0.0), _active (true), _locked_to_meter (false)  {}
184
185         TempoSection (const XMLNode&, const framecnt_t sample_rate);
186
187         static const std::string xml_state_node_name;
188
189         XMLNode& get_state() const;
190
191         double c_func () const { return _c_func; }
192         void set_c_func (double c_func) { _c_func = c_func; }
193
194         void set_type (Type type);
195         Type type () const { return _type; }
196
197         bool active () const { return _active; }
198         void set_active (bool yn) { _active = yn; }
199
200         bool locked_to_meter ()  const { return _locked_to_meter; }
201         void set_locked_to_meter (bool yn) { _locked_to_meter = yn; }
202
203         double tempo_at_minute (const double& minute) const;
204         double minute_at_tempo (const double& bpm, const double& pulse) const;
205
206         double tempo_at_pulse (const double& pulse) const;
207         double pulse_at_tempo (const double& bpm, const double& minute) const;
208
209         double pulse_at_frame (const framepos_t& frame) const;
210         framepos_t frame_at_pulse (const double& pulse) const;
211
212         double pulse_at_minute (const double& minute) const;
213         double minute_at_pulse (const double& pulse) const;
214
215         double compute_c_func_pulse (const double& end_bpm, const double& end_pulse) const;
216         double compute_c_func_minute (const double& end_bpm, const double& end_minute) const;
217
218         Timecode::BBT_Time legacy_bbt () { return _legacy_bbt; }
219
220   private:
221
222         /*  tempo ramp functions. zero-based with time in minutes,
223          * 'tick tempo' in ticks per minute and tempo in bpm.
224          *  time relative to section start.
225          */
226         double a_func (double end_tpm, double c_func) const;
227         double c_func (double end_tpm, double end_time) const;
228
229         double _tempo_at_time (const double& time) const;
230         double _time_at_tempo (const double& tempo) const;
231
232         double _tempo_at_pulse (const double& pulse) const;
233         double _pulse_at_tempo (const double& tempo) const;
234
235         double _pulse_at_time (const double& time) const;
236         double _time_at_pulse (const double& pulse) const;
237
238         /* this value provides a fractional offset into the bar in which
239            the tempo section is located in. A value of 0.0 indicates that
240            it occurs on the first beat of the bar, a value of 0.5 indicates
241            that it occurs halfway through the bar and so on.
242
243            this enables us to keep the tempo change at the same relative
244            position within the bar if/when the meter changes.
245         */
246         Type _type;
247         double _c_func;
248         bool _active;
249         bool _locked_to_meter;
250         Timecode::BBT_Time _legacy_bbt;
251 };
252
253 typedef std::list<MetricSection*> Metrics;
254
255 /** Helper class to keep track of the Meter *AND* Tempo in effect
256     at a given point in time.
257 */
258 class LIBARDOUR_API TempoMetric {
259   public:
260         TempoMetric (const Meter& m, const Tempo& t)
261                 : _meter (&m), _tempo (&t), _minute (0.0), _pulse (0.0) {}
262
263         void set_tempo (const Tempo& t)              { _tempo = &t; }
264         void set_meter (const Meter& m)              { _meter = &m; }
265         void set_minute (double m)                   { _minute = m; }
266         void set_pulse (const double& p)             { _pulse = p; }
267
268         void set_metric (const MetricSection* section) {
269                 const MeterSection* meter;
270                 const TempoSection* tempo;
271                 if ((meter = dynamic_cast<const MeterSection*>(section))) {
272                         set_meter(*meter);
273                 } else if ((tempo = dynamic_cast<const TempoSection*>(section))) {
274                         set_tempo(*tempo);
275                 }
276
277                 set_minute (section->minute());
278                 set_pulse (section->pulse());
279         }
280
281         const Meter&              meter() const { return *_meter; }
282         const Tempo&              tempo() const { return *_tempo; }
283         double                    minute() const { return _minute; }
284         const double&             pulse() const { return _pulse; }
285
286   private:
287         const Meter*       _meter;
288         const Tempo*       _tempo;
289         double             _minute;
290         double             _pulse;
291 };
292
293 /** Tempo Map - mapping of timecode to musical time.
294  * convert audio-samples, sample-rate to Bar/Beat/Tick, Meter/Tempo
295  */
296 class LIBARDOUR_API TempoMap : public PBD::StatefulDestructible
297 {
298   public:
299         TempoMap (framecnt_t frame_rate);
300         ~TempoMap();
301
302         /* measure-based stuff */
303
304         enum BBTPointType {
305                 Bar,
306                 Beat,
307         };
308
309         struct BBTPoint {
310                 framepos_t          frame;
311                 Meter               meter;
312                 Tempo               tempo;
313                 double              c;
314                 uint32_t            bar;
315                 uint32_t            beat;
316
317                 BBTPoint (const MeterSection& m, const Tempo& t, framepos_t f,
318                           uint32_t b, uint32_t e, double func_c)
319                 : frame (f), meter (m.divisions_per_bar(), m.note_divisor()), tempo (t.beats_per_minute(), t.note_type()), c (func_c), bar (b), beat (e) {}
320
321                 Timecode::BBT_Time bbt() const { return Timecode::BBT_Time (bar, beat, 0); }
322                 operator Timecode::BBT_Time() const { return bbt(); }
323                 operator framepos_t() const { return frame; }
324                 bool is_bar() const { return beat == 1; }
325         };
326
327         template<class T> void apply_with_metrics (T& obj, void (T::*method)(const Metrics&)) {
328                 Glib::Threads::RWLock::ReaderLock lm (lock);
329                 (obj.*method)(_metrics);
330         }
331
332         void get_grid (std::vector<BBTPoint>&,
333                        framepos_t start, framepos_t end, uint32_t bar_mod = 0);
334
335         static const Tempo& default_tempo() { return _default_tempo; }
336         static const Meter& default_meter() { return _default_meter; }
337
338         /* because tempos may be ramped, this is only valid for the instant requested.*/
339         double frames_per_beat_at (const framepos_t&, const framecnt_t& sr) const;
340
341         const TempoSection& tempo_section_at_frame (framepos_t frame) const;
342         const MeterSection& meter_section_at_frame (framepos_t frame) const;
343         const MeterSection& meter_section_at_beat (double beat) const;
344
345         /** add a tempo section locked to pls. ignored values will be set in recompute_tempi()
346          * @param pulse pulse position of new section. ignored if pls == AudioTime
347          * @param frame frame position of new section. ignored if pls == MusicTime
348          * @param type type of new tempo section (Ramp, Constant)
349          */
350         TempoSection* add_tempo (const Tempo&, const double& pulse, const framepos_t& frame, TempoSection::Type type, PositionLockStyle pls);
351
352         /** add an meter section locked to pls.. ignored values will be set in recompute_meters()
353          * @param beat beat position of new section
354          * @param where bbt position of new section
355          * @param frame frame position of new section. ignored if pls == MusicTime
356          */
357         MeterSection* add_meter (const Meter&, const double& beat, const Timecode::BBT_Time& where, PositionLockStyle pls);
358
359         void remove_tempo (const TempoSection&, bool send_signal);
360         void remove_meter (const MeterSection&, bool send_signal);
361
362         void replace_tempo (const TempoSection&, const Tempo&, const double& pulse, const framepos_t& frame
363                             , TempoSection::Type type, PositionLockStyle pls);
364
365         void replace_meter (const MeterSection&, const Meter&, const Timecode::BBT_Time& where, PositionLockStyle pls);
366
367         framepos_t round_to_bar  (framepos_t frame, RoundMode dir);
368         framepos_t round_to_beat (framepos_t frame, RoundMode dir);
369         framepos_t round_to_beat_subdivision (framepos_t fr, int sub_num, RoundMode dir);
370         framepos_t round_to_quarter_note_subdivision (framepos_t fr, int sub_num, RoundMode dir);
371
372         void set_length (framepos_t frames);
373
374         XMLNode& get_state (void);
375         int set_state (const XMLNode&, int version);
376
377         void dump (const Metrics& metrics, std::ostream&) const;
378         void clear ();
379
380         TempoMetric metric_at (Timecode::BBT_Time bbt) const;
381
382         /** Return the TempoMetric at frame @p t, and point @p last to the latest
383          * metric change <= t, if it is non-NULL.
384          */
385         TempoMetric metric_at (framepos_t, Metrics::const_iterator* last=NULL) const;
386
387         Metrics::const_iterator metrics_end() { return _metrics.end(); }
388
389         void change_existing_tempo_at (framepos_t, double bpm, double note_type);
390         void change_initial_tempo (double bpm, double note_type);
391
392         void insert_time (framepos_t, framecnt_t);
393         bool remove_time (framepos_t where, framecnt_t amount);  //returns true if anything was moved
394
395         int n_tempos () const;
396         int n_meters () const;
397
398         framecnt_t frame_rate () const { return _frame_rate; }
399
400         /* TEMPO- AND METER-SENSITIVE FUNCTIONS
401
402            bbt_at_frame(), frame_at_bbt(), beat_at_frame(), frame_at_beat(), tempo_at_beat()
403            and bbt_duration_at()
404            are all sensitive to tempo and meter, and will give answers
405            that align with the grid formed by tempo and meter sections.
406
407            They SHOULD NOT be used to determine the position of events
408            whose location is canonically defined in Evoral::Beats.
409         */
410
411         double beat_at_frame (const framecnt_t& frame) const;
412         framepos_t frame_at_beat (const double& beat) const;
413
414         Tempo tempo_at_frame (const framepos_t& frame) const;
415         framepos_t frame_at_tempo (const Tempo& tempo) const;
416
417         Tempo tempo_at_beat (const double& beat) const;
418         double beat_at_tempo (const Tempo& tempo) const;
419
420         const Meter& meter_at_frame (framepos_t) const;
421
422         double pulse_at_beat (const double& beat) const;
423         double beat_at_pulse (const double& pulse) const;
424
425         double pulse_at_frame (const framecnt_t& frame) const;
426         framepos_t frame_at_pulse (const double& pulse) const;
427
428         /* bbt - it's nearly always better to use beats.*/
429         Timecode::BBT_Time bbt_at_frame (framepos_t when);
430         Timecode::BBT_Time bbt_at_frame_rt (framepos_t when);
431         framepos_t frame_at_bbt (const Timecode::BBT_Time&);
432
433         double beat_at_bbt (const Timecode::BBT_Time& bbt);
434         Timecode::BBT_Time bbt_at_beat (const double& beats);
435
436         double pulse_at_bbt (const Timecode::BBT_Time& bbt);
437         double pulse_at_bbt_rt (const Timecode::BBT_Time& bbt);
438         Timecode::BBT_Time bbt_at_pulse (const double& pulse);
439
440         framecnt_t bbt_duration_at (framepos_t, const Timecode::BBT_Time&, int dir);
441
442         /* TEMPO-SENSITIVE FUNCTIONS
443
444            These next 2 functions will all take tempo in account and should be
445            used to determine position (and in the last case, distance in beats)
446            when tempo matters but meter does not.
447
448            They SHOULD be used to determine the position of events
449            whose location is canonically defined in Evoral::Beats.
450         */
451
452         framepos_t framepos_plus_qn (framepos_t, Evoral::Beats) const;
453         Evoral::Beats framewalk_to_qn (framepos_t pos, framecnt_t distance) const;
454
455         framepos_t framepos_plus_bbt (framepos_t pos, Timecode::BBT_Time b) const;
456
457         double quarter_note_at_frame (const framepos_t frame);
458         double quarter_note_at_frame_rt (const framepos_t frame);
459         framepos_t frame_at_quarter_note (const double quarter_note);
460         double quarter_note_at_beat (const double beat);
461         double beat_at_quarter_note (const double beat);
462
463         framecnt_t frames_between_quarter_notes (const double start, const double end);
464
465         void gui_move_tempo (TempoSection*, const framepos_t& frame, const int& sub_num);
466         void gui_move_meter (MeterSection*, const framepos_t& frame);
467         bool gui_change_tempo (TempoSection*, const Tempo& bpm);
468         void gui_dilate_tempo (TempoSection* tempo, const framepos_t& frame, const framepos_t& end_frame, const double& pulse);
469
470         double exact_beat_at_frame (const framepos_t& frame, const int32_t sub_num);
471         double exact_qn_at_frame (const framepos_t& frame, const int32_t sub_num);
472
473         std::pair<double, framepos_t> predict_tempo_position (TempoSection* section, const Timecode::BBT_Time& bbt);
474         bool can_solve_bbt (TempoSection* section, const Timecode::BBT_Time& bbt);
475
476         PBD::Signal0<void> MetricPositionChanged;
477         void fix_legacy_session();
478
479 private:
480
481         double beat_at_minute_locked (const Metrics& metrics, const double& minute) const;
482         double minute_at_beat_locked (const Metrics& metrics, const double& beat) const;
483
484         double pulse_at_beat_locked (const Metrics& metrics, const double& beat) const;
485         double beat_at_pulse_locked (const Metrics& metrics, const double& pulse) const;
486
487         double pulse_at_minute_locked (const Metrics& metrics, const double& minute) const;
488         double minute_at_pulse_locked (const Metrics& metrics, const double& pulse) const;
489
490         Tempo tempo_at_minute_locked (const Metrics& metrics, const double& minute) const;
491         double minute_at_tempo_locked (const Metrics& metrics, const Tempo& tempo) const;
492
493         Tempo tempo_at_pulse_locked (const Metrics& metrics, const double& pulse) const;
494         double pulse_at_tempo_locked (const Metrics& metrics, const Tempo& tempo) const;
495
496         Timecode::BBT_Time bbt_at_minute_locked (const Metrics& metrics, const double& minute) const;
497         double minute_at_bbt_locked (const Metrics& metrics, const Timecode::BBT_Time&) const;
498
499         double beat_at_bbt_locked (const Metrics& metrics, const Timecode::BBT_Time& bbt) const ;
500         Timecode::BBT_Time bbt_at_beat_locked (const Metrics& metrics, const double& beats) const;
501
502         double pulse_at_bbt_locked (const Metrics& metrics, const Timecode::BBT_Time& bbt) const;
503         Timecode::BBT_Time bbt_at_pulse_locked (const Metrics& metrics, const double& pulse) const;
504
505         double minute_at_quarter_note_locked (const Metrics& metrics, const double quarter_note) const;
506         double quarter_note_at_minute_locked (const Metrics& metrics, const double minute) const;
507
508         double quarter_note_at_beat_locked (const Metrics& metrics, const double beat) const;
509         double beat_at_quarter_note_locked (const Metrics& metrics, const double beat) const;
510
511         double minutes_between_quarter_notes_locked (const Metrics& metrics, const double start_qn, const double end_qn);
512
513         const TempoSection& tempo_section_at_minute_locked (const Metrics& metrics, double minute) const;
514         const TempoSection& tempo_section_at_beat_locked (const Metrics& metrics, const double& beat) const;
515
516         const MeterSection& meter_section_at_minute_locked (const Metrics& metrics, double minute) const;
517         const MeterSection& meter_section_at_beat_locked (const Metrics& metrics, const double& beat) const;
518
519         bool check_solved (const Metrics& metrics) const;
520         bool set_active_tempos (const Metrics& metrics, const framepos_t& frame);
521
522         bool solve_map_minute (Metrics& metrics, TempoSection* section, const double& minute);
523         bool solve_map_pulse (Metrics& metrics, TempoSection* section, const double& pulse);
524         bool solve_map_minute (Metrics& metrics, MeterSection* section, const double& minute);
525         bool solve_map_bbt (Metrics& metrics, MeterSection* section, const Timecode::BBT_Time& bbt);
526
527         double exact_beat_at_frame_locked (const Metrics& metrics, const framepos_t& frame, const int32_t sub_num);
528         double exact_qn_at_frame_locked (const Metrics& metrics, const framepos_t& frame, const int32_t sub_num);
529
530         double minute_at_frame (const framepos_t frame) const;
531         framepos_t frame_at_minute (const double minute) const;
532
533         friend class ::BBTTest;
534         friend class ::FrameposPlusBeatsTest;
535         friend class ::FrameposMinusBeatsTest;
536         friend class ::TempoTest;
537
538         static Tempo    _default_tempo;
539         static Meter    _default_meter;
540
541         Metrics                       _metrics;
542         framecnt_t                    _frame_rate;
543         mutable Glib::Threads::RWLock lock;
544
545         void recompute_tempi (Metrics& metrics);
546         void recompute_meters (Metrics& metrics);
547         void recompute_map (Metrics& metrics, framepos_t end = -1);
548
549         framepos_t round_to_type (framepos_t fr, RoundMode dir, BBTPointType);
550
551         const MeterSection& first_meter() const;
552         MeterSection&       first_meter();
553         const TempoSection& first_tempo() const;
554         TempoSection&       first_tempo();
555
556         void do_insert (MetricSection* section);
557
558         TempoSection* add_tempo_locked (const Tempo&, double pulse, double minute
559                                , TempoSection::Type type, PositionLockStyle pls, bool recompute, bool locked_to_meter = false);
560
561         MeterSection* add_meter_locked (const Meter&, double beat, const Timecode::BBT_Time& where, PositionLockStyle pls, bool recompute);
562
563         bool remove_tempo_locked (const TempoSection&);
564         bool remove_meter_locked (const MeterSection&);
565
566         TempoSection* copy_metrics_and_point (const Metrics& metrics, Metrics& copy, TempoSection* section);
567         MeterSection* copy_metrics_and_point (const Metrics& metrics, Metrics& copy, MeterSection* section);
568 };
569
570 }; /* namespace ARDOUR */
571
572 std::ostream& operator<< (std::ostream&, const ARDOUR::Meter&);
573 std::ostream& operator<< (std::ostream&, const ARDOUR::Tempo&);
574 std::ostream& operator<< (std::ostream&, const ARDOUR::MetricSection&);
575
576 #endif /* __ardour_tempo_h__ */