Add bbt_add that does not take Metric parameter.
[ardour.git] / libs / ardour / tempo.cc
index ab7b7c096eeb619a0f7bc5fbf117c0b035a72e03..d7300f937b9f4b592aa1299a52bd082c8334c8db 100644 (file)
@@ -1,5 +1,5 @@
 /*
-    Copyright (C) 2000-2002 Paul Davis 
+    Copyright (C) 2000-2002 Paul Davis
 
     This program is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published by
 #include <sigc++/bind.h>
 
 #include <glibmm/thread.h>
-#include <pbd/xml++.h>
-#include <ardour/tempo.h>
-#include <ardour/utils.h>
+#include "pbd/xml++.h"
+#include "ardour/debug.h"
+#include "ardour/tempo.h"
+#include "ardour/utils.h"
 
 #include "i18n.h"
 #include <locale.h>
@@ -91,7 +92,7 @@ TempoSection::TempoSection (const XMLNode& node)
                error << _("TempoSection XML node has an illegal \"beats_per_minute\" value") << endmsg;
                throw failed_constructor();
        }
-       
+
        if ((prop = node.property ("note-type")) == 0) {
                /* older session, make note type be quarter by default */
                _note_type = 4.0;
@@ -107,7 +108,7 @@ TempoSection::TempoSection (const XMLNode& node)
                throw failed_constructor();
        }
 
-       set_movable (prop->value() == "yes");
+       set_movable (string_is_affirmative (prop->value()));
 }
 
 XMLNode&
@@ -117,7 +118,7 @@ TempoSection::get_state() const
        char buf[256];
        LocaleGuard lg (X_("POSIX"));
 
-       snprintf (buf, sizeof (buf), "%" PRIu32 "|%" PRIu32 "|%" PRIu32, 
+       snprintf (buf, sizeof (buf), "%" PRIu32 "|%" PRIu32 "|%" PRIu32,
                  start().bars,
                  start().beats,
                  start().ticks);
@@ -172,7 +173,7 @@ MeterSection::MeterSection (const XMLNode& node)
                error << _("MeterSection XML node has no \"note-type\" property") << endmsg;
                throw failed_constructor();
        }
-       
+
        if (sscanf (prop->value().c_str(), "%lf", &_note_type) != 1 || _note_type < 0.0) {
                error << _("MeterSection XML node has an illegal \"note-type\" value") << endmsg;
                throw failed_constructor();
@@ -183,7 +184,7 @@ MeterSection::MeterSection (const XMLNode& node)
                throw failed_constructor();
        }
 
-       set_movable (prop->value() == "yes");
+       set_movable (string_is_affirmative (prop->value()));
 }
 
 XMLNode&
@@ -193,7 +194,7 @@ MeterSection::get_state() const
        char buf[256];
        LocaleGuard lg (X_("POSIX"));
 
-       snprintf (buf, sizeof (buf), "%" PRIu32 "|%" PRIu32 "|%" PRIu32, 
+       snprintf (buf, sizeof (buf), "%" PRIu32 "|%" PRIu32 "|%" PRIu32,
                  start().bars,
                  start().beats,
                  start().ticks);
@@ -222,7 +223,7 @@ TempoMap::TempoMap (nframes_t fr)
        _frame_rate = fr;
        last_bbt_valid = false;
        BBT_Time start;
-       
+
        start.bars = 1;
        start.beats = 1;
        start.ticks = 0;
@@ -234,7 +235,7 @@ TempoMap::TempoMap (nframes_t fr)
        m->set_movable (false);
 
        /* note: frame time is correct (zero) for both of these */
-       
+
        metrics->push_back (t);
        metrics->push_back (m);
 }
@@ -262,7 +263,7 @@ TempoMap::move_metric_section (MetricSection& section, const BBT_Time& when)
 
                nframes_t prev_frame = round_to_type (frame, -1, Beat);
                nframes_t next_frame = round_to_type (frame, 1, Beat);
-               
+
                // cerr << "previous beat at " << prev_frame << " next at " << next_frame << endl;
 
                /* use the closest beat */
@@ -272,7 +273,7 @@ TempoMap::move_metric_section (MetricSection& section, const BBT_Time& when)
                } else {
                        frame = next_frame;
                }
-               
+
                // cerr << "actual frame time = " << frame << endl;
                section.set_frame (frame);
                // cerr << "frame time = " << section.frame() << endl;
@@ -369,7 +370,7 @@ TempoMap::do_insert (MetricSection* section, bool with_bbt)
        Metrics::iterator i;
 
        for (i = metrics->begin(); i != metrics->end(); ++i) {
-               
+
                if (with_bbt) {
                        if ((*i)->start() < section->start()) {
                                continue;
@@ -377,19 +378,19 @@ TempoMap::do_insert (MetricSection* section, bool with_bbt)
                } else {
                        if ((*i)->frame() < section->frame()) {
                                continue;
-                       }                       
+                       }
                }
 
                metrics->insert (i, section);
                break;
        }
-       
+
        if (i == metrics->end()) {
                metrics->insert (metrics->end(), section);
        }
-       
+
        timestamp_metrics (with_bbt);
-}      
+}
 
 void
 TempoMap::add_tempo (const Tempo& tempo, BBT_Time where)
@@ -398,9 +399,9 @@ TempoMap::add_tempo (const Tempo& tempo, BBT_Time where)
                Glib::RWLock::WriterLock lm (lock);
 
                /* new tempos always start on a beat */
-       
+
                where.ticks = 0;
-               
+
                do_insert (new TempoSection (where, tempo.beats_per_minute(), tempo.note_type()), true);
        }
 
@@ -423,10 +424,10 @@ TempoMap::replace_tempo (TempoSection& existing, const Tempo& replacement)
 {
        bool replaced = false;
 
-       { 
+       {
                Glib::RWLock::WriterLock lm (lock);
                Metrics::iterator i;
-               
+
                for (i = metrics->begin(); i != metrics->end(); ++i) {
                        TempoSection *ts;
 
@@ -441,7 +442,7 @@ TempoMap::replace_tempo (TempoSection& existing, const Tempo& replacement)
                        }
                }
        }
-       
+
        if (replaced) {
                StateChanged (Change (0));
        }
@@ -466,7 +467,7 @@ TempoMap::add_meter (const Meter& meter, BBT_Time where)
                }
 
                /* new meters *always* start on a beat. */
-               
+
                where.ticks = 0;
 
                do_insert (new MeterSection (where, meter.beats_per_bar(), meter.note_divisor()), true);
@@ -491,14 +492,14 @@ TempoMap::replace_meter (MeterSection& existing, const Meter& replacement)
 {
        bool replaced = false;
 
-       { 
+       {
                Glib::RWLock::WriterLock lm (lock);
                Metrics::iterator i;
-               
+
                for (i = metrics->begin(); i != metrics->end(); ++i) {
                        MeterSection *ms;
                        if ((ms = dynamic_cast<MeterSection*>(*i)) != 0 && ms == &existing) {
-                               
+
                                *((Meter*) ms) = replacement;
 
                                replaced = true;
@@ -507,7 +508,7 @@ TempoMap::replace_meter (MeterSection& existing, const Meter& replacement)
                        }
                }
        }
-       
+
        if (replaced) {
                StateChanged (Change (0));
        }
@@ -625,17 +626,17 @@ TempoMap::timestamp_metrics (bool use_bbt)
                BBT_Time end;
 
                for (i = metrics->begin(); i != metrics->end(); ++i) {
-                       
+
                        end = (*i)->start();
-                       
+
                        section_frames = count_frames_between_metrics (*meter, *tempo, start, end);
-                       
+
                        current += section_frames;
-                       
+
                        start = end;
-                       
+
                        (*i)->set_frame (current);
-                       
+
                        if ((t = dynamic_cast<TempoSection*>(*i)) != 0) {
                                tempo = t;
                        } else if ((m = dynamic_cast<MeterSection*>(*i)) != 0) {
@@ -656,28 +657,29 @@ TempoMap::timestamp_metrics (bool use_bbt)
                for (i = metrics->begin(); i != metrics->end(); ++i) {
 
                        BBT_Time bbt;
-                       Metric metric (*meter, *tempo);
-                       
+                       TempoMetric metric (*meter, *tempo);
+
                        if (prev) {
                                metric.set_start (prev->start());
+                               metric.set_frame (prev->frame());
                        } else {
                                // metric will be at frames=0 bbt=1|1|0 by default
                                // which is correct for our purpose
                        }
-               
+
                        bbt_time_with_metric ((*i)->frame(), bbt, metric);
 
                        // cerr << "timestamp @ " << (*i)->frame() << " with " << bbt.bars << "|" << bbt.beats << "|" << bbt.ticks << " => ";
-                       
+
 
                        if (first) {
                                first = false;
                        } else {
-                               
+
                                if (bbt.ticks > Meter::ticks_per_beat/2) {
                                        /* round up to next beat */
                                        bbt.beats += 1;
-                               } 
+                               }
 
                                bbt.ticks = 0;
 
@@ -687,9 +689,9 @@ TempoMap::timestamp_metrics (bool use_bbt)
                                        bbt.beats = 1;
                                }
                        }
-                       
+
                        //s cerr << bbt.bars << "|" << bbt.beats << "|" << bbt.ticks << endl;
-                       
+
                        (*i)->set_start (bbt);
 
                        if ((t = dynamic_cast<TempoSection*>(*i)) != 0) {
@@ -712,10 +714,10 @@ TempoMap::timestamp_metrics (bool use_bbt)
 
 }
 
-TempoMap::Metric
+TempoMetric
 TempoMap::metric_at (nframes_t frame) const
 {
-       Metric m (first_meter(), first_tempo());
+       TempoMetric m (first_meter(), first_tempo());
        const Meter* meter;
        const Tempo* tempo;
 
@@ -741,14 +743,14 @@ TempoMap::metric_at (nframes_t frame) const
                m.set_frame ((*i)->frame ());
                m.set_start ((*i)->start ());
        }
-       
+
        return m;
 }
 
-TempoMap::Metric
+TempoMetric
 TempoMap::metric_at (BBT_Time bbt) const
 {
-       Metric m (first_meter(), first_tempo());
+       TempoMetric m (first_meter(), first_tempo());
        const Meter* meter;
        const Tempo* tempo;
 
@@ -772,7 +774,7 @@ TempoMap::metric_at (BBT_Time bbt) const
                } else if ((meter = dynamic_cast<const MeterSection*>(*i)) != 0) {
                        m.set_meter (*meter);
                }
-               
+
                m.set_frame ((*i)->frame ());
                m.set_start (section_start);
        }
@@ -783,8 +785,8 @@ TempoMap::metric_at (BBT_Time bbt) const
 void
 TempoMap::bbt_time (nframes_t frame, BBT_Time& bbt) const
 {
-        {
-               Glib::RWLock::ReaderLock lm (lock);
+       {
+               Glib::RWLock::ReaderLock lm (lock);
                bbt_time_unlocked (frame, bbt);
        }
 }
@@ -796,57 +798,55 @@ TempoMap::bbt_time_unlocked (nframes_t frame, BBT_Time& bbt) const
 }
 
 void
-TempoMap::bbt_time_with_metric (nframes_t frame, BBT_Time& bbt, const Metric& metric) const
+TempoMap::bbt_time_with_metric (nframes_t frame, BBT_Time& bbt, const TempoMetric& metric) const
 {
        nframes_t frame_diff;
 
-       uint32_t xtra_bars = 0;
-       double xtra_beats = 0;
-       double beats = 0;
-
        // cerr << "---- BBT time for " << frame << " using metric @ " << metric.frame() << " BBT " << metric.start() << endl;
 
        const double beats_per_bar = metric.meter().beats_per_bar();
-       const double frames_per_bar = metric.meter().frames_per_bar (metric.tempo(), _frame_rate);
-       const double beat_frames = metric.tempo().frames_per_beat (_frame_rate, metric.meter());
+       const double ticks_per_frame = metric.tempo().frames_per_beat (_frame_rate, metric.meter()) / Meter::ticks_per_beat;
 
        /* now compute how far beyond that point we actually are. */
 
        frame_diff = frame - metric.frame();
-       
-       // cerr << "----\tdelta = " << frame_diff << endl;
-
-       xtra_bars = (uint32_t) floor (frame_diff / frames_per_bar);
-       frame_diff -= (uint32_t) floor (xtra_bars * frames_per_bar);
-       xtra_beats = (double) frame_diff / beat_frames;
-
-       // cerr << "---\tmeaning " << xtra_bars << " xtra bars and " << xtra_beats << " xtra beats\n";
-
-       /* and set the returned value */
-
-       /* and correct beat/bar shifts to match the meter.
-         remember: beat and bar counting is 1-based, 
-         not zero-based 
-         also the meter may contain a fraction
-       */
-       
-       bbt.bars = metric.start().bars + xtra_bars; 
 
-       beats = (double) metric.start().beats + xtra_beats;
-       
-       bbt.bars += (uint32_t) floor(beats/ (beats_per_bar+1) );
+        bbt.ticks = metric.start().ticks + (uint32_t)round((double)frame_diff / ticks_per_frame);
+        uint32_t xtra_beats = bbt.ticks / (uint32_t)Meter::ticks_per_beat;
+        bbt.ticks %= (uint32_t)Meter::ticks_per_beat;
+
+        bbt.beats = metric.start().beats + xtra_beats - 1; // correction for 1-based counting, see below for matching operation.
+        bbt.bars = metric.start().bars + (uint32_t)floor((double)bbt.beats / beats_per_bar);
+        bbt.beats = (uint32_t)fmod((double)bbt.beats, beats_per_bar);
+
+        /* if we have a fractional number of beats per bar, we see if
+           we're in the last beat (the fractional one).  if so, we
+           round ticks appropriately and bump to the next bar. */
+        double beat_fraction = beats_per_bar - floor(beats_per_bar);
+        /* XXX one problem here is that I'm not sure how to handle
+           fractional beats that don't evenly divide ticks_per_beat.
+           If they aren't handled consistently, I would guess we'll
+           continue to have strange discrepancies occuring.  Perhaps
+           this will also behave badly in the case of meters like
+           0.1/4, but I can't be bothered to test that.
+        */
+        uint32_t ticks_on_last_beat = (uint32_t)floor(Meter::ticks_per_beat * beat_fraction);
+        if(bbt.beats > (uint32_t)floor(beats_per_bar) &&
+           bbt.ticks >= ticks_on_last_beat) {
+          bbt.ticks -= ticks_on_last_beat;
+          bbt.beats = 0;
+          bbt.bars++;
+        }
+
+        bbt.beats++; // correction for 1-based counting, see above for matching operation.
 
-       beats = fmod(beats - 1, beats_per_bar )+ 1.0;
-       bbt.ticks = (uint32_t)( round((beats - floor(beats)) *(double) Meter::ticks_per_beat));
-       bbt.beats = (uint32_t) floor(beats);
-       
        // cerr << "-----\t RETURN " << bbt << endl;
 }
 
-nframes_t 
+nframes_t
 TempoMap::count_frames_between ( const BBT_Time& start, const BBT_Time& end) const
 {
-        /* for this to work with fractional measure types, start and end have to be "legal" BBT types, 
+        /* for this to work with fractional measure types, start and end have to be "legal" BBT types,
           that means that the beats and ticks should be inside a bar
        */
 
@@ -854,21 +854,21 @@ TempoMap::count_frames_between ( const BBT_Time& start, const BBT_Time& end) con
        nframes_t start_frame = 0;
        nframes_t end_frame = 0;
 
-       Metric m = metric_at (start);
+       TempoMetric m = metric_at (start);
 
        uint32_t bar_offset = start.bars - m.start().bars;
 
-       double  beat_offset = bar_offset*m.meter().beats_per_bar() - (m.start().beats-1) + (start.beats -1) 
+       double  beat_offset = bar_offset*m.meter().beats_per_bar() - (m.start().beats-1) + (start.beats -1)
                + start.ticks/Meter::ticks_per_beat;
 
 
        start_frame = m.frame() + (nframes_t) rint( beat_offset * m.tempo().frames_per_beat(_frame_rate, m.meter()));
 
-       m =  metric_at(end);
+       m =  metric_at(end);
 
        bar_offset = end.bars - m.start().bars;
 
-       beat_offset = bar_offset * m.meter().beats_per_bar() - (m.start().beats -1) + (end.beats - 1) 
+       beat_offset = bar_offset * m.meter().beats_per_bar() - (m.start().beats -1) + (end.beats - 1)
                + end.ticks/Meter::ticks_per_beat;
 
        end_frame = m.frame() + (nframes_t) rint(beat_offset * m.tempo().frames_per_beat(_frame_rate, m.meter()));
@@ -876,13 +876,13 @@ TempoMap::count_frames_between ( const BBT_Time& start, const BBT_Time& end) con
        frames = end_frame - start_frame;
 
        return frames;
-       
-}      
 
-nframes_t 
+}
+
+nframes_t
 TempoMap::count_frames_between_metrics (const Meter& meter, const Tempo& tempo, const BBT_Time& start, const BBT_Time& end) const
 {
-        /* this is used in timestamping the metrics by actually counting the beats */ 
+        /* this is used in timestamping the metrics by actually counting the beats */
 
        nframes_t frames = 0;
        uint32_t bar = start.bars;
@@ -897,7 +897,7 @@ TempoMap::count_frames_between_metrics (const Meter& meter, const Tempo& tempo,
        frames = 0;
 
        while (bar < end.bars || (bar == end.bars && beat < end.beats)) {
-               
+
                if (beat >= beats_per_bar) {
                        beat = 1;
                        ++bar;
@@ -906,7 +906,7 @@ TempoMap::count_frames_between_metrics (const Meter& meter, const Tempo& tempo,
                        if (beat > beats_per_bar) {
 
                                /* this is a fractional beat at the end of a fractional bar
-                                  so it should only count for the fraction 
+                                  so it should only count for the fraction
                                */
 
                                beats_counted -= (ceil(beats_per_bar) - beats_per_bar);
@@ -918,18 +918,18 @@ TempoMap::count_frames_between_metrics (const Meter& meter, const Tempo& tempo,
                }
        }
 
-       // cerr << "Counted " << beats_counted << " from " << start << " to " << end 
-       // << " bpb were " << beats_per_bar 
+       // cerr << "Counted " << beats_counted << " from " << start << " to " << end
+       // << " bpb were " << beats_per_bar
        // << " fpb was " << beat_frames
        // << endl;
-       
+
        frames = (nframes_t) floor (beats_counted * beat_frames);
 
        return frames;
-       
-}      
 
-nframes_t 
+}
+
+nframes_t
 TempoMap::frame_time (const BBT_Time& bbt) const
 {
        BBT_Time start ; /* 1|1|0 */
@@ -937,13 +937,13 @@ TempoMap::frame_time (const BBT_Time& bbt) const
        return  count_frames_between ( start, bbt);
 }
 
-nframes_t 
+nframes_t
 TempoMap::bbt_duration_at (nframes_t pos, const BBT_Time& bbt, int dir) const
 {
        nframes_t frames = 0;
 
        BBT_Time when;
-       bbt_time(pos,when);
+       bbt_time(pos, when);
 
        {
                Glib::RWLock::ReaderLock lm (lock);
@@ -953,7 +953,7 @@ TempoMap::bbt_duration_at (nframes_t pos, const BBT_Time& bbt, int dir) const
        return frames;
 }
 
-nframes_t 
+nframes_t
 TempoMap::bbt_duration_at_unlocked (const BBT_Time& when, const BBT_Time& bbt, int dir) const
 {
 
@@ -961,35 +961,35 @@ TempoMap::bbt_duration_at_unlocked (const BBT_Time& when, const BBT_Time& bbt, i
 
        double beats_per_bar;
        BBT_Time result;
-       
-       result.bars = max(1U,when.bars + dir * bbt.bars) ;
+
+       result.bars = max(1U, when.bars + dir * bbt.bars) ;
        result.beats = 1;
        result.ticks = 0;
 
-       Metric  metric = metric_at(result);
+       TempoMetric     metric = metric_at(result);
        beats_per_bar = metric.meter().beats_per_bar();
 
 
 
-        /*reduce things to legal bbt  values 
+        /*reduce things to legal bbt  values
          we have to handle possible fractional=shorter beats at the end of measures
           and things like 0|11|9000  as a duration in a 4.5/4 measure
-         the musical decision is that the fractional beat is also a beat , although a shorter one 
+         the musical decision is that the fractional beat is also a beat , although a shorter one
        */
 
-    
+
        if (dir >= 0) {
                result.beats = when.beats +  bbt.beats;
                result.ticks = when.ticks +  bbt.ticks;
 
-               while (result.beats >= (beats_per_bar+1)) {
+               while (result.beats >= (beats_per_bar + 1)) {
                        result.bars++;
                        result.beats -=  (uint32_t) ceil(beats_per_bar);
                        metric = metric_at(result); // maybe there is a meter change
                        beats_per_bar = metric.meter().beats_per_bar();
-                       
+
                }
-               /*we now counted the beats and landed in the target measure, now deal with ticks 
+               /*we now counted the beats and landed in the target measure, now deal with ticks
                  this seems complicated, but we want to deal with the corner case of a sequence of time signatures like 0.2/4-0.7/4
                  and with request like bbt = 3|2|9000 ,so we repeat the same loop but add ticks
                */
@@ -998,43 +998,43 @@ TempoMap::bbt_duration_at_unlocked (const BBT_Time& when, const BBT_Time& bbt, i
                 */
 
                uint32_t ticks_at_beat = (uint32_t) ( result.beats == ceil(beats_per_bar) ?
-                                       (1 - (ceil(beats_per_bar) - beats_per_bar))* Meter::ticks_per_beat 
+                                       (1 - (ceil(beats_per_bar) - beats_per_bar))* Meter::ticks_per_beat
                                           : Meter::ticks_per_beat );
 
                while (result.ticks >= ticks_at_beat) {
                        result.beats++;
                        result.ticks -= ticks_at_beat;
-                       if  (result.beats >= (beats_per_bar+1)) {
+                       if  (result.beats >= (beats_per_bar + 1)) {
                                result.bars++;
                                result.beats = 1;
                                metric = metric_at(result); // maybe there is a meter change
                                beats_per_bar = metric.meter().beats_per_bar();
                        }
                        ticks_at_beat= (uint32_t) ( result.beats == ceil(beats_per_bar) ?
-                                      (1 - (ceil(beats_per_bar) - beats_per_bar) )* Meter::ticks_per_beat 
+                                      (1 - (ceil(beats_per_bar) - beats_per_bar) ) * Meter::ticks_per_beat
                                       : Meter::ticks_per_beat);
 
                }
 
-         
+
        } else {
                uint32_t b = bbt.beats;
 
                 /* count beats */
                while( b > when.beats ) {
-                       
+
                        result.bars = max(1U,result.bars-- ) ;
                        metric = metric_at(result); // maybe there is a meter change
                        beats_per_bar = metric.meter().beats_per_bar();
                        if (b >= ceil(beats_per_bar)) {
-                               
+
                                b -= (uint32_t) ceil(beats_per_bar);
                        } else {
-                               b = (uint32_t) ceil(beats_per_bar)- b + when.beats ;
+                               b = (uint32_t) ceil(beats_per_bar) - b + when.beats ;
                        }
                }
                result.beats = when.beats - b;
-                
+
                 /*count ticks */
 
                if (bbt.ticks <= when.ticks) {
@@ -1047,18 +1047,18 @@ TempoMap::bbt_duration_at_unlocked (const BBT_Time& when, const BBT_Time& bbt, i
                        do {
 
                                if (result.beats == 1) {
-                                       result.bars = max(1U,result.bars-- ) ;
+                                       result.bars = max(1U, result.bars-- ) ;
                                        metric = metric_at(result); // maybe there is a meter change
                                        beats_per_bar = metric.meter().beats_per_bar();
                                        result.beats = (uint32_t) ceil(beats_per_bar);
-                                       ticks_at_beat = (uint32_t) ((1 - (ceil(beats_per_bar) - beats_per_bar))* Meter::ticks_per_beat) ;
+                                       ticks_at_beat = (uint32_t) ((1 - (ceil(beats_per_bar) - beats_per_bar)) * Meter::ticks_per_beat) ;
                                } else {
                                        result.beats --;
                                        ticks_at_beat = (uint32_t) Meter::ticks_per_beat;
                                }
-                                               
+
                                if (t <= ticks_at_beat) {
-                                       result.ticks = ticks_at_beat - t; 
+                                       result.ticks = ticks_at_beat - t;
                                } else {
                                        t-= ticks_at_beat;
                                }
@@ -1100,30 +1100,91 @@ TempoMap::round_to_beat (nframes_t fr, int dir)
 }
 
 nframes_t
-
-TempoMap::round_to_beat_subdivision (nframes_t fr, int sub_num)
+TempoMap::round_to_beat_subdivision (nframes_t fr, int sub_num, int dir)
 {
 
        BBT_Time the_beat;
        uint32_t ticks_one_half_subdivisions_worth;
        uint32_t ticks_one_subdivisions_worth;
+       uint32_t difference;
 
        bbt_time(fr, the_beat);
 
        ticks_one_subdivisions_worth = (uint32_t)Meter::ticks_per_beat / sub_num;
        ticks_one_half_subdivisions_worth = ticks_one_subdivisions_worth / 2;
 
-       if (the_beat.ticks % ticks_one_subdivisions_worth > ticks_one_half_subdivisions_worth) {
-         uint32_t difference = ticks_one_subdivisions_worth - (the_beat.ticks % ticks_one_subdivisions_worth);
-         if (the_beat.ticks + difference >= (uint32_t)Meter::ticks_per_beat) {
-           the_beat.beats++;
-           the_beat.ticks += difference;
-           the_beat.ticks -= (uint32_t)Meter::ticks_per_beat;
-         } else {  
-           the_beat.ticks += difference;
-         }
+       if (dir > 0) {
+
+               /* round to next */
+
+               uint32_t mod = the_beat.ticks % ticks_one_subdivisions_worth;
+
+               if (mod == 0) {
+                       /* right on the subdivision, so the difference is just the subdivision ticks */
+                       difference = ticks_one_subdivisions_worth;
+
+               } else {
+                       /* not on subdivision, compute distance to next subdivision */
+
+                       difference = ticks_one_subdivisions_worth - mod;
+               }
+
+               if (the_beat.ticks + difference >= (uint32_t)Meter::ticks_per_beat) {
+                       the_beat.beats++;
+                       the_beat.ticks += difference;
+                       the_beat.ticks -= (uint32_t)Meter::ticks_per_beat;
+               } else {
+                       the_beat.ticks += difference;
+               }
+
+       } else if (dir < 0) {
+
+               /* round to previous */
+
+               uint32_t mod = the_beat.ticks % ticks_one_subdivisions_worth;
+
+               if (mod == 0) {
+                       /* right on the subdivision, so the difference is just the subdivision ticks */
+                       difference = ticks_one_subdivisions_worth;
+                       cerr << "On the sub, move by 1 sub = " << difference << endl;
+               } else {
+                       /* not on subdivision, compute distance to previous subdivision, which
+                          is just the modulus.
+                       */
+
+                       difference = mod;
+                       cerr << "off the sub, move by 1 sub = " << difference << endl;
+               }
+
+
+               cerr << "ticks = " << the_beat.ticks << endl;
+
+               if (the_beat.ticks < difference) {
+                       cerr << "backup beats, set ticks to "
+                            << (uint32_t)Meter::ticks_per_beat - difference << endl;
+                       the_beat.beats--;
+                       the_beat.ticks = (uint32_t)Meter::ticks_per_beat - difference;
+               } else {
+                       cerr << " reduce ticks\n";
+                       the_beat.ticks -= difference;
+               }
+
        } else {
-         the_beat.ticks -= the_beat.ticks % ticks_one_subdivisions_worth;
+               /* round to nearest */
+
+               if (the_beat.ticks % ticks_one_subdivisions_worth > ticks_one_half_subdivisions_worth) {
+                       difference = ticks_one_subdivisions_worth - (the_beat.ticks % ticks_one_subdivisions_worth);
+                       if (the_beat.ticks + difference >= (uint32_t)Meter::ticks_per_beat) {
+                               the_beat.beats++;
+                               the_beat.ticks += difference;
+                               the_beat.ticks -= (uint32_t)Meter::ticks_per_beat;
+                       } else {
+                               the_beat.ticks += difference;
+                       }
+               } else {
+                       // difference = ticks_one_subdivisions_worth - (the_beat.ticks % ticks_one_subdivisions_worth);
+                       the_beat.ticks -= the_beat.ticks % ticks_one_subdivisions_worth;
+               }
        }
 
        return frame_time (the_beat);
@@ -1132,15 +1193,19 @@ TempoMap::round_to_beat_subdivision (nframes_t fr, int sub_num)
 nframes_t
 TempoMap::round_to_type (nframes_t frame, int dir, BBTPointType type)
 {
-       Metric metric = metric_at (frame);
+       TempoMetric metric = metric_at (frame);
        BBT_Time bbt;
        BBT_Time start;
        bbt_time_with_metric (frame, bbt, metric);
 
+
        switch (type) {
        case Bar:
+               DEBUG_TRACE(DEBUG::SnapBBT, string_compose ("round from %1 (%3) to bars in direction %2\n", frame, (dir < 0 ? "back" : "forward"), bbt));
                if (dir < 0) {
-                       /* relax */
+                       if (bbt.bars > 1) {
+                               bbt.bars--;
+                       }
                } else if (dir > 0) {
                        if (bbt.beats > 0) {
                                bbt.bars++;
@@ -1155,10 +1220,14 @@ TempoMap::round_to_type (nframes_t frame, int dir, BBTPointType type)
                bbt.beats = 1;
                bbt.ticks = 0;
                break;
-       
+
        case Beat:
+               DEBUG_TRACE(DEBUG::SnapBBT, string_compose ("round from %1 (%3) to beat in direction %2\n", frame, (dir < 0 ? "back" : "forward"), bbt));
                if (dir < 0) {
-                       /* relax */
+                       if (bbt.beats > 1) {
+                               bbt.beats--;
+                       } 
+
                } else if (dir > 0) {
                        if (bbt.ticks > 0) {
                                bbt.beats++;
@@ -1176,14 +1245,10 @@ TempoMap::round_to_type (nframes_t frame, int dir, BBTPointType type)
                }
                bbt.ticks = 0;
                break;
-       
+
        }
-       
-       /* 
-       cerr << "for " << frame << " round to " << bbt << " using "
-            << metric.start()
-            << endl;
-       */
+
+       DEBUG_TRACE(DEBUG::SnapBBT, string_compose ("\tat %1 count frames from %2 to %3 = %4\n", metric.frame(), metric.start(), bbt, count_frames_between (metric.start(), bbt)));
        return metric.frame() + count_frames_between (metric.start(), bbt);
 }
 
@@ -1228,7 +1293,7 @@ TempoMap::get_points (nframes_t lower, nframes_t upper) const
        }
 
        /* We now have:
-          
+
           meter -> the Meter for "lower"
           tempo -> the Tempo for "lower"
           i     -> for first new metric after "lower", possibly metrics->end()
@@ -1239,7 +1304,7 @@ TempoMap::get_points (nframes_t lower, nframes_t upper) const
        beats_per_bar = meter->beats_per_bar ();
        frames_per_bar = meter->frames_per_bar (*tempo, _frame_rate);
        beat_frames = tempo->frames_per_beat (_frame_rate, *meter);
-       
+
        if (meter->frame() > tempo->frame()) {
                bar = meter->start().bars;
                beat = meter->start().beats;
@@ -1254,7 +1319,7 @@ TempoMap::get_points (nframes_t lower, nframes_t upper) const
           lower frame bound passed in.  assumes that current is initialized
           above to be on a beat.
        */
-       
+
        delta_bars = (lower-current) / frames_per_bar;
        delta_beats = modf(delta_bars, &dummy) * beats_per_bar;
        current += (floor(delta_bars) * frames_per_bar) +  (floor(delta_beats) * beat_frames);
@@ -1264,21 +1329,21 @@ TempoMap::get_points (nframes_t lower, nframes_t upper) const
        beat += (uint32_t) (floor(delta_beats));
 
        points = new BBTPointList;
-               
+
        do {
 
                if (i == metrics->end()) {
                        limit = upper;
                        // cerr << "== limit set to end of request @ " << limit << endl;
                } else {
-                       // cerr << "== limit set to next metric @ " << (*i)->frame() << endl;
+                       // cerr << "== limit set to next metric @ " << (*i)->frame() << endl;
                        limit = (*i)->frame();
                }
 
                limit = min (limit, upper);
 
                while (current < limit) {
-                       
+
                        /* if we're at the start of a bar, add bar point */
 
                        if (beat == 1) {
@@ -1300,7 +1365,7 @@ TempoMap::get_points (nframes_t lower, nframes_t upper) const
                                }
                                beat_frame += beat_frames;
                                current+= beat_frames;
-                              
+
                                beat++;
                        }
 
@@ -1321,8 +1386,8 @@ TempoMap::get_points (nframes_t lower, nframes_t upper) const
                                   just filled had  10 beat marks,
                                   but the bar end is 1/2 beat before
                                   the last beat mark.
-                                  And it is also possible that a tempo 
-                                  change occured in the middle of a bar, 
+                                  And it is also possible that a tempo
+                                  change occured in the middle of a bar,
                                   so we subtract the possible extra fraction from the current
                                */
 
@@ -1337,8 +1402,8 @@ TempoMap::get_points (nframes_t lower, nframes_t upper) const
                                }
                                bar++;
                                beat = 1;
-                       } 
-               
+                       }
+
                }
 
                /* if we're done, then we're done */
@@ -1367,14 +1432,14 @@ TempoMap::get_points (nframes_t lower, nframes_t upper) const
                        beats_per_bar = meter->beats_per_bar ();
                        frames_per_bar = meter->frames_per_bar (*tempo, _frame_rate);
                        beat_frames = tempo->frames_per_beat (_frame_rate, *meter);
-                       
+
                        ++i;
                }
 
        } while (1);
 
        return points;
-}      
+}
 
 const TempoSection&
 TempoMap::tempo_section_at (nframes_t frame)
@@ -1382,7 +1447,7 @@ TempoMap::tempo_section_at (nframes_t frame)
        Glib::RWLock::ReaderLock lm (lock);
        Metrics::iterator i;
        TempoSection* prev = 0;
-       
+
        for (i = metrics->begin(); i != metrics->end(); ++i) {
                TempoSection* t;
 
@@ -1404,17 +1469,17 @@ TempoMap::tempo_section_at (nframes_t frame)
 }
 
 const Tempo&
-TempoMap::tempo_at (nframes_t frame)
+TempoMap::tempo_at (nframes_t frame) const
 {
-       Metric m (metric_at (frame));
+       TempoMetric m (metric_at (frame));
        return m.tempo();
 }
 
 
 const Meter&
-TempoMap::meter_at (nframes_t frame)
+TempoMap::meter_at (nframes_t frame) const
 {
-       Metric m (metric_at (frame));
+       TempoMetric m (metric_at (frame));
        return m.meter();
 }
 
@@ -1435,7 +1500,7 @@ TempoMap::get_state ()
 }
 
 int
-TempoMap::set_state (const XMLNode& node)
+TempoMap::set_state (const XMLNode& node, int /*version*/)
 {
        {
                Glib::RWLock::WriterLock lm (lock);
@@ -1443,32 +1508,32 @@ TempoMap::set_state (const XMLNode& node)
                XMLNodeList nlist;
                XMLNodeConstIterator niter;
                Metrics old_metrics (*metrics);
-               
+
                metrics->clear();
 
                nlist = node.children();
-               
+
                for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
                        XMLNode* child = *niter;
-                       
+
                        if (child->name() == TempoSection::xml_state_node_name) {
-                               
+
                                try {
                                        metrics->push_back (new TempoSection (*child));
                                }
-                               
+
                                catch (failed_constructor& err){
                                        error << _("Tempo map: could not set new state, restoring old one.") << endmsg;
                                        *metrics = old_metrics;
                                        break;
                                }
-                               
+
                        } else if (child->name() == MeterSection::xml_state_node_name) {
-                               
+
                                try {
                                        metrics->push_back (new MeterSection (*child));
                                }
-                               
+
                                catch (failed_constructor& err) {
                                        error << _("Tempo map: could not set new state, restoring old one.") << endmsg;
                                        *metrics = old_metrics;
@@ -1476,15 +1541,15 @@ TempoMap::set_state (const XMLNode& node)
                                }
                        }
                }
-               
+
                if (niter == nlist.end()) {
-                       
+
                        MetricSectionSorter cmp;
                        metrics->sort (cmp);
                        timestamp_metrics (true);
                }
        }
-       
+
        StateChanged (Change (0));
 
        return 0;
@@ -1495,14 +1560,14 @@ TempoMap::dump (std::ostream& o) const
 {
        const MeterSection* m;
        const TempoSection* t;
-       
+
        for (Metrics::const_iterator i = metrics->begin(); i != metrics->end(); ++i) {
 
                if ((t = dynamic_cast<const TempoSection*>(*i)) != 0) {
                        o << "Tempo @ " << *i << ' ' << t->beats_per_minute() << " BPM (denom = " << t->note_type() << ") at " << t->start() << " frame= " << t->frame() << " (move? "
                          << t->movable() << ')' << endl;
                } else if ((m = dynamic_cast<const MeterSection*>(*i)) != 0) {
-                       o << "Meter @ " << *i << ' ' << m->beats_per_bar() << '/' << m->note_divisor() << " at " << m->start() << " frame= " << m->frame() 
+                       o << "Meter @ " << *i << ' ' << m->beats_per_bar() << '/' << m->note_divisor() << " at " << m->start() << " frame= " << m->frame()
                          << " (move? " << m->movable() << ')' << endl;
                }
        }
@@ -1537,3 +1602,38 @@ TempoMap::n_meters() const
 
        return cnt;
 }
+
+void
+TempoMap::insert_time (nframes_t where, nframes_t amount)
+{
+       for (Metrics::iterator i = metrics->begin(); i != metrics->end(); ++i) {
+               if ((*i)->frame() >= where) {
+                       (*i)->set_frame ((*i)->frame() + amount);
+               }
+       }
+
+       timestamp_metrics (false);
+
+       StateChanged (Change (0));
+}
+
+BBT_Time
+TempoMap::bbt_add (const BBT_Time& a, const BBT_Time& b, const TempoMetric& /*metric*/)
+{
+       // FIXME: Obviously not correct!
+       return BBT_Time(a.bars + b.bars, a.beats + b.beats, a.ticks + b.ticks);
+}
+
+BBT_Time
+TempoMap::bbt_add (const BBT_Time& a, const BBT_Time& b)
+{
+       // FIXME: Obviously not correct!
+       return BBT_Time(a.bars + b.bars, a.beats + b.beats, a.ticks + b.ticks);
+}
+
+BBT_Time
+TempoMap::bbt_subtract (const BBT_Time& a, const BBT_Time& b)
+{
+       // FIXME: Obviously not correct!
+       return BBT_Time(a.bars - b.bars, a.beats - b.beats, a.ticks - b.ticks);
+}