remove using namespace sigc everywhere to ensure clarity over which bind/mem_fun...
[ardour.git] / libs / ardour / midi_clock_slave.cc
index 888ead0805d8e786d2906f9d6a3c88cc58823745..e2b83a1e65d3c2a2c3c879fb11f6c094e2fccf93 100644 (file)
@@ -1,5 +1,6 @@
 /*
-    Copyright (C) 2002-4 Paul Davis
+    Copyright (C) 2008 Paul Davis
+    Author: Hans Baier
 
     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 <poll.h>
 #include <sys/types.h>
 #include <unistd.h>
-#include <pbd/error.h>
-#include <pbd/failed_constructor.h>
-#include <pbd/pthread_utils.h>
+#include "pbd/error.h"
+#include "pbd/failed_constructor.h"
+#include "pbd/pthread_utils.h"
 
-#include <midi++/port.h>
-#include <midi++/jack.h>
-#include <ardour/slave.h>
-#include <ardour/session.h>
-#include <ardour/audioengine.h>
-#include <ardour/cycles.h>
-#include <ardour/tempo.h>
+#include "midi++/port.h"
+#include "midi++/jack.h"
+#include "ardour/slave.h"
+#include "ardour/session.h"
+#include "ardour/audioengine.h"
+#include "ardour/cycles.h"
+#include "ardour/tempo.h"
 
 
 #include "i18n.h"
 
+using namespace std;
 using namespace ARDOUR;
-using namespace sigc;
 using namespace MIDI;
 using namespace PBD;
 
 MIDIClock_Slave::MIDIClock_Slave (Session& s, MIDI::Port& p, int ppqn)
-       : session (s)
-       , ppqn (ppqn)
-       , accumulator_index (0)
-       , average (0.0)
+       : ppqn (ppqn)
+       , bandwidth (30.0 / 60.0) // 1 BpM = 1 / 60 Hz
 {
+       session = (ISlaveSessionProxy *) new SlaveSessionProxy(s);
        rebind (p);
        reset ();
+}
 
-       for(int i = 0; i < accumulator_size; i++)
-               accumulator[i]=0.0;
+MIDIClock_Slave::MIDIClock_Slave (ISlaveSessionProxy* session_proxy, int ppqn)
+       : session(session_proxy)
+       , ppqn (ppqn)
+       , bandwidth (30.0 / 60.0) // 1 BpM = 1 / 60 Hz
+{
+       session = session_proxy;
+       reset ();
 }
 
 MIDIClock_Slave::~MIDIClock_Slave()
 {
+  delete session;
 }
 
 void
@@ -67,131 +74,223 @@ MIDIClock_Slave::rebind (MIDI::Port& p)
 
        port = &p;
 
-       std::cerr << "MIDIClock_Slave: connecting to port " << port->name() << std::endl;
+       #ifdef DEBUG_MIDI_CLOCK
+               std::cerr << "MIDIClock_Slave: connecting to port " << port->name() << std::endl;
+       #endif
 
-       connections.push_back (port->input()->timing.connect (mem_fun (*this, &MIDIClock_Slave::update_midi_clock)));
-       connections.push_back (port->input()->start.connect  (mem_fun (*this, &MIDIClock_Slave::start)));
-       connections.push_back (port->input()->stop.connect   (mem_fun (*this, &MIDIClock_Slave::stop)));
+       connections.push_back (port->input()->timing.connect   (sigc::mem_fun (*this, &MIDIClock_Slave::update_midi_clock)));
+       connections.push_back (port->input()->start.connect    (sigc::mem_fun (*this, &MIDIClock_Slave::start)));
+       connections.push_back (port->input()->contineu.connect (sigc::mem_fun (*this, &MIDIClock_Slave::contineu)));
+       connections.push_back (port->input()->stop.connect     (sigc::mem_fun (*this, &MIDIClock_Slave::stop)));
+       connections.push_back (port->input()->position.connect (sigc::mem_fun (*this, &MIDIClock_Slave::position)));
 }
 
 void
-MIDIClock_Slave::update_midi_clock (Parser& parser, nframes_t timestamp)
-{      
-       nframes_t now = timestamp;
-
-       SafeTime last;
-       read_current (&last);
-               
-       const Tempo& current_tempo = session.tempo_map().tempo_at(now);
-       const Meter& current_meter = session.tempo_map().meter_at(now);
+MIDIClock_Slave::calculate_one_ppqn_in_frames_at(nframes64_t time)
+{
+       const Tempo& current_tempo = session->tempo_map().tempo_at(time);
+       const Meter& current_meter = session->tempo_map().meter_at(time);
        double frames_per_beat =
-               current_tempo.frames_per_beat(session.frame_rate(),
+               current_tempo.frames_per_beat(session->frame_rate(),
                                              current_meter);
 
        double quarter_notes_per_beat = 4.0 / current_tempo.note_type();
        double frames_per_quarter_note = frames_per_beat / quarter_notes_per_beat;
 
-       one_ppqn_in_frames = frames_per_quarter_note / ppqn;
-       
-       // for the first MIDI clock event we dont have any past
-       // data, so we assume a sane tempo
-       if(last.timestamp == 0) {
-               midi_clock_frame = one_ppqn_in_frames;
-       } else {
-               midi_clock_frame = now - last.timestamp;
-       }
-       
-       
-       // moving average over incoming intervals
-       accumulator[accumulator_index++] = (float) midi_clock_frame;
-       if(accumulator_index == accumulator_size)
-               accumulator_index = 0;
-       
-       average = 0.0;
-       for(int i = 0; i < accumulator_size; i++)
-               average += accumulator[i];
-       average /= accumulator_size;
-       
-       
-#if 1
-       JACK_MidiPort *jack_port = dynamic_cast<JACK_MidiPort *>(port);
-       pthread_t process_thread_id = 0;
-       if(jack_port) {
-               process_thread_id = jack_port->get_process_thread();
+       one_ppqn_in_frames = frames_per_quarter_note / double (ppqn);
+}
+
+ARDOUR::nframes64_t
+MIDIClock_Slave::calculate_song_position(uint16_t song_position_in_sixteenth_notes)
+{
+       nframes64_t song_position_frames = 0;
+       for (uint16_t i = 1; i <= song_position_in_sixteenth_notes; ++i) {
+               // one quarter note contains ppqn pulses, so a sixteenth note is ppqn / 4 pulses
+               calculate_one_ppqn_in_frames_at(song_position_frames);
+               song_position_frames += one_ppqn_in_frames * (nframes64_t)(ppqn / 4);
        }
-       
-       std::cerr 
-                 << " got MIDI Clock message at time " << now  
-                 << " session time: " << session.engine().frame_time() 
-                 << " real delta: " << midi_clock_frame 
-                 << " reference: " << one_ppqn_in_frames
-                 << " average: " << average
-                 << std::endl;
-#endif
-       
-       current.guard1++;
-       current.position += midi_clock_frame;
-       current.timestamp = now;
-       current.guard2++;
-
-       last_inbound_frame = now;
+
+       return song_position_frames;
 }
 
 void
-MIDIClock_Slave::start (Parser& parser, nframes_t timestamp)
+MIDIClock_Slave::calculate_filter_coefficients()
 {
-       
-       nframes_t now = timestamp;
-       cerr << "MIDIClock_Slave got start message at time "  <<  now 
-            << " session time: " << session.engine().frame_time() << endl;
+       // omega = 2 * PI * Bandwidth / MIDI clock frame frequency in Hz
+       omega = 2.0 * 3.14159265358979323846 * bandwidth * one_ppqn_in_frames / session->frame_rate();
+       b = 1.4142135623730950488 * omega;
+       c = omega * omega;
+}
 
-       if(!locked()) {
-               cerr << "Did not start because not locked!" << endl;
+void
+MIDIClock_Slave::update_midi_clock (Parser& /*parser*/, nframes64_t timestamp)
+{
+       // some pieces of hardware send MIDI Clock all the time
+       if ( (!_starting) && (!_started) ) {
                return;
        }
-       
-       midi_clock_frame = 0;
-       
-       session.request_transport_speed(one_ppqn_in_frames / average);
-       current.guard1++;
-       current.position = 0;
-       current.timestamp = now;
-       current.guard2++;
-       
-       _started = true;
+
+       calculate_one_ppqn_in_frames_at(should_be_position);
+
+       nframes64_t elapsed_since_start = timestamp - first_timestamp;
+       double error = 0;
+
+       if (_starting || last_timestamp == 0) {
+               midi_clock_count = 0;
+
+               first_timestamp = timestamp;
+               elapsed_since_start = should_be_position;
+
+               // calculate filter coefficients
+               calculate_filter_coefficients();
+
+               // initialize DLL
+               e2 = double(one_ppqn_in_frames) / double(session->frame_rate());
+               t0 = double(elapsed_since_start) / double(session->frame_rate());
+               t1 = t0 + e2;
+
+               // let ardour go after first MIDI Clock Event
+               _starting = false;
+       } else {
+               midi_clock_count++;
+               should_be_position  += one_ppqn_in_frames;
+               calculate_filter_coefficients();
+
+               // calculate loop error
+               // we use session->transport_frame() instead of t1 here
+               // because t1 is used to calculate the transport speed,
+               // so the loop will compensate for accumulating rounding errors
+               error = (double(should_be_position) - double(session->audible_frame()));
+               e = error / double(session->frame_rate());
+
+               // update DLL
+               t0 = t1;
+               t1 += b * e + e2;
+               e2 += c * e;
+       }
+
+       #ifdef DEBUG_MIDI_CLOCK
+               cerr
+                                 << "MIDI Clock #" << midi_clock_count
+                                 //<< "@" << timestamp
+                                 << " arrived at: " << elapsed_since_start << " (elapsed time) "
+                                 << " should-be transport: " << should_be_position
+                                 << " audible: " << session->audible_frame()
+                                 << " real transport: " << session->transport_frame()
+                                 << " error: " << error
+                                 //<< " engine: " << session->frame_time()
+                                 << " real delta: " << timestamp - last_timestamp
+                                 << " should-be delta: " << one_ppqn_in_frames
+                                 << " t1-t0: " << (t1 -t0) * session->frame_rate()
+                                 << " t0: " << t0 * session->frame_rate()
+                                 << " t1: " << t1 * session->frame_rate()
+                                 << " frame-rate: " << session->frame_rate()
+                                 << endl;
+
+               cerr      << "frames since cycle start: " << session->frames_since_cycle_start() << endl;
+       #endif // DEBUG_MIDI_CLOCK
+
+       last_timestamp = timestamp;
+}
+
+void
+MIDIClock_Slave::start (Parser& /*parser*/, nframes64_t /*timestamp*/)
+{
+       #ifdef DEBUG_MIDI_CLOCK
+               cerr << "MIDIClock_Slave got start message at time "  <<  timestamp << " engine time: " << session->frame_time() << endl;
+       #endif
+
+       if (!_started) {
+               reset();
+
+               _started = true;
+               _starting = true;
+       }
+}
+
+void
+MIDIClock_Slave::reset ()
+{
+
+       should_be_position = 0;
+       last_timestamp = 0;
+
+       _starting = false;
+       _started  = false;
+
+       session->request_locate(0, false);
 }
 
 void
-MIDIClock_Slave::stop (Parser& parser, nframes_t timestamp)
+MIDIClock_Slave::contineu (Parser& /*parser*/, nframes64_t /*timestamp*/)
 {
-       std::cerr << "MIDIClock_Slave got stop message" << endl;
+       #ifdef DEBUG_MIDI_CLOCK
+               std::cerr << "MIDIClock_Slave got continue message" << endl;
+       #endif
+       if (!_started) {
+               _starting = true;
+               _started  = true;
+       }
+}
 
-       midi_clock_frame = 0;
 
-       current.guard1++;
-       current.position = 0;
-       current.timestamp = 0;
-       current.guard2++;
-       
-       _started = false;
-       reset();
+void
+MIDIClock_Slave::stop (Parser& /*parser*/, nframes64_t /*timestamp*/)
+{
+       #ifdef DEBUG_MIDI_CLOCK
+               std::cerr << "MIDIClock_Slave got stop message" << endl;
+       #endif
+
+       if (_started || _starting) {
+               _starting = false;
+               _started  = false;
+               // locate to last MIDI clock position
+               session->request_transport_speed(0.0);
+
+               // we need to go back to the last MIDI beat (6 ppqn)
+               // and lets hope the tempo didnt change in the meantime :)
+
+               // begin at the should be position, because
+               // that is the position of the last MIDI Clock
+               // message and that is probably what the master
+               // expects where we are right now
+               nframes64_t stop_position = should_be_position;
+
+               // find out the last MIDI beat: go back #midi_clocks mod 6
+               // and lets hope the tempo didnt change in those last 6 beats :)
+               stop_position -= (midi_clock_count % 6) * one_ppqn_in_frames;
+
+               session->request_locate(stop_position, false);
+               should_be_position = stop_position;
+               last_timestamp = 0;
+       }
 }
 
 void
-MIDIClock_Slave::read_current (SafeTime *st) const
+MIDIClock_Slave::position (Parser& /*parser*/, byte* message, size_t size)
 {
-       int tries = 0;
-       do {
-               if (tries == 10) {
-                       error << _("MIDI Clock Slave: atomic read of current time failed, sleeping!") << endmsg;
-                       usleep (20);
-                       tries = 0;
-               }
-
-               *st = current;
-               tries++;
-
-       } while (st->guard1 != st->guard2);
+       // we are note supposed to get position messages while we are running
+       // so lets be robust and ignore those
+       if (_started || _starting) {
+               return;
+       }
+
+       assert(size == 3);
+       byte lsb = message[1];
+       byte msb = message[2];
+       assert((lsb <= 0x7f) && (msb <= 0x7f));
+
+       uint16_t position_in_sixteenth_notes = (uint16_t(msb) << 7) | uint16_t(lsb);
+       nframes64_t position_in_frames = calculate_song_position(position_in_sixteenth_notes);
+
+       #ifdef DEBUG_MIDI_CLOCK
+       cerr << "Song Position: " << position_in_sixteenth_notes << " frames: " << position_in_frames << endl;
+       #endif
+
+       session->request_locate(position_in_frames, false);
+       should_be_position  = position_in_frames;
+       last_timestamp = 0;
+
 }
 
 bool
@@ -207,71 +306,70 @@ MIDIClock_Slave::ok() const
 }
 
 bool
-MIDIClock_Slave::speed_and_position (float& speed, nframes_t& pos)
+MIDIClock_Slave::starting() const
 {
-       
-       if(!_started) {
-               speed = 0.0;
-               pos = 0;
+       return false;
+}
+
+bool
+MIDIClock_Slave::stop_if_no_more_clock_events(nframes64_t& pos, nframes64_t now)
+{
+       /* no timecode for 1/4 second ? conclude that its stopped */
+       if (last_timestamp &&
+           now > last_timestamp &&
+           now - last_timestamp > session->frame_rate() / 4) {
+        #ifdef DEBUG_MIDI_CLOCK
+                       cerr << "No MIDI Clock frames received for some time, stopping!" << endl;
+        #endif
+               pos = should_be_position;
+               session->request_transport_speed (0);
+               session->request_locate (should_be_position, false);
                return true;
+       } else {
+               return false;
        }
-       
-       nframes_t now = session.engine().frame_time();
-       nframes_t frame_rate = session.frame_rate();
+}
 
-       SafeTime last;
-       read_current (&last);
+bool
+MIDIClock_Slave::speed_and_position (double& speed, nframes64_t& pos)
+{
+       if (!_started || _starting) {
+               speed = 0.0;
+               pos   = should_be_position;
+               return true;
+       }
 
-       /* no timecode for 1/4 second ? conclude that its stopped */
+       nframes64_t engine_now = session->frame_time();
 
-       if (last_inbound_frame && now > last_inbound_frame && now - last_inbound_frame > frame_rate / 4) {
-               cerr << "No MIDI Clock frames received for some time, stopping!" << endl;
-               pos = last.position;
-               session.request_locate (pos, false);
-               session.request_transport_speed (0);
-               this->stop(*port->input(), now);
-               reset();
+       if (stop_if_no_more_clock_events(pos, engine_now)) {
                return false;
        }
 
-       cerr << " now: " << now << " last: " << last.timestamp;
+       // calculate speed
+       speed = ((t1 - t0) * session->frame_rate()) / one_ppqn_in_frames;
 
-       speed = one_ppqn_in_frames / average;
-       cerr << " final speed: " << speed;
-       
-       if (now > last.timestamp) {
+       // calculate position
+       if (engine_now > last_timestamp) {
                // we are in between MIDI clock messages
                // so we interpolate position according to speed
-               nframes_t elapsed = now - last.timestamp;
-               cerr << " elapsed: " << elapsed << " elapsed (scaled)  " << elapsed * speed;
-               pos = last.position + elapsed * speed;
-               last.position = pos;
+               nframes64_t elapsed = engine_now - last_timestamp;
+               pos = (nframes64_t) (should_be_position + double(elapsed) * speed);
        } else {
-               // A new MIDI clock message has arrived this cycle              
-               pos = last.position;
+               // A new MIDI clock message has arrived this cycle
+               pos = should_be_position;
        }
-       
-   cerr << " position: " << pos; 
-   cerr << endl;
-       
+
+       #ifdef DEBUG_MIDI_CLOCK
+       cerr << "speed_and_position: " << speed << " & " << pos << " <-> " << session->transport_frame() << " (transport)" << endl;
+       #endif
+
        return true;
 }
 
 ARDOUR::nframes_t
 MIDIClock_Slave::resolution() const
 {
-       return (nframes_t) one_ppqn_in_frames * 24;
+       // one beat
+       return (nframes_t) one_ppqn_in_frames * ppqn;
 }
 
-void
-MIDIClock_Slave::reset ()
-{
-
-       last_inbound_frame = 0;
-       current.guard1++;
-       current.position = 0;
-       current.timestamp = 0;
-       current.guard2++;
-       
-       session.request_locate(0, false);
-}