/*
- 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
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-
-*/
+ * Copyright (C) 2008-2013 Hans Baier <hansfbaier@googlemail.com>
+ * Copyright (C) 2009-2010 Carl Hetherington <carl@carlh.net>
+ * Copyright (C) 2009-2012 David Robillard <d@drobilla.net>
+ * Copyright (C) 2009-2019 Paul Davis <paul@linuxaudiosystems.com>
+ * Copyright (C) 2012-2013 Robin Gareus <robin@gareus.org>
+ * Copyright (C) 2013-2018 John Emmas <john@creativepost.co.uk>
+ * Copyright (C) 2015-2016 Nick Mainsbridge <mainsbridge@gmail.com>
+ *
+ * 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
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
#include <cmath>
#include <errno.h>
#include "midi++/port.h"
+#include "ardour/audioengine.h"
#include "ardour/debug.h"
#include "ardour/midi_buffer.h"
#include "ardour/midi_port.h"
-#include "ardour/slave.h"
+#include "ardour/session.h"
#include "ardour/tempo.h"
+#include "ardour/transport_master.h"
+#include "ardour/transport_master_manager.h"
-#include "i18n.h"
+#include "pbd/i18n.h"
using namespace std;
using namespace ARDOUR;
using namespace MIDI;
using namespace PBD;
-MIDIClock_Slave::MIDIClock_Slave (Session& s, MidiPort& p, int ppqn)
- : ppqn (ppqn)
- , bandwidth (10.0 / 60.0) // 1 BpM = 1 / 60 Hz
+#define ENGINE AudioEngine::instance()
+
+MIDIClock_TransportMaster::MIDIClock_TransportMaster (std::string const & name, int ppqn)
+ : TransportMaster (MIDIClock, name)
+ , ppqn (ppqn)
+ , midi_clock_count (0)
+ , _running (false)
+ , _bpm (0)
{
- session = (ISlaveSessionProxy *) new SlaveSessionProxy(s);
- rebind (p);
- reset ();
}
-MIDIClock_Slave::MIDIClock_Slave (ISlaveSessionProxy* session_proxy, int ppqn)
- : session(session_proxy)
- , ppqn (ppqn)
- , bandwidth (10.0 / 60.0) // 1 BpM = 1 / 60 Hz
+MIDIClock_TransportMaster::~MIDIClock_TransportMaster()
{
- reset ();
+ port_connections.drop_connections ();
}
-MIDIClock_Slave::~MIDIClock_Slave()
+void
+MIDIClock_TransportMaster::init ()
{
- delete session;
+ midi_clock_count = 0;
+ current.reset ();
}
void
-MIDIClock_Slave::rebind (MidiPort& port)
+MIDIClock_TransportMaster::create_port ()
{
- DEBUG_TRACE (DEBUG::MidiClock, string_compose ("MIDIClock_Slave: connecting to port %1\n", port.name()));
+ if ((_port = create_midi_port (string_compose ("%1 in", _name))) == 0) {
+ throw failed_constructor();
+ }
+}
- port_connections.drop_connections ();
+void
+MIDIClock_TransportMaster::set_session (Session *session)
+{
+ port_connections.drop_connections();
+ _session = session;
+
+ /* only connect to signals if we have a proxy, because otherwise we
+ * cannot interpet incoming data (no tempo map etc.)
+ */
- port.self_parser().timing.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::update_midi_clock, this, _1, _2));
- port.self_parser().start.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::start, this, _1, _2));
- port.self_parser().contineu.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::contineu, this, _1, _2));
- port.self_parser().stop.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::stop, this, _1, _2));
- port.self_parser().position.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::position, this, _1, _2, 3));
+ if (_session) {
+ parser.timing.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::update_midi_clock, this, _1, _2));
+ parser.start.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::start, this, _1, _2));
+ parser.contineu.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::contineu, this, _1, _2));
+ parser.stop.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::stop, this, _1, _2));
+ parser.position.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::position, this, _1, _2, _3, _4));
+ reset (true);
+ }
}
void
-MIDIClock_Slave::calculate_one_ppqn_in_frames_at(framepos_t time)
+MIDIClock_TransportMaster::pre_process (MIDI::pframes_t nframes, samplepos_t now, boost::optional<samplepos_t> session_pos)
{
- const Tempo& current_tempo = session->tempo_map().tempo_at(time);
- double frames_per_beat = current_tempo.frames_per_beat(session->frame_rate());
+ /* Read and parse incoming MIDI */
+
+ DEBUG_TRACE (DEBUG::MidiClock, string_compose ("preprocess with lt = %1 @ %2, running ? %3\n", current.timestamp, now, _running));
+
+ _midi_port->read_and_parse_entire_midi_buffer_with_no_speed_adjustment (nframes, parser, now);
+
+ /* no clock messages ever, or no clock messages for 1/4 second ? conclude that its stopped */
+
+ if (!current.timestamp || (now > current.timestamp && ((now - current.timestamp) > (ENGINE->sample_rate() / 4)))) {
+ _bpm = 0.0;
+ _running = false;
+ _current_delta = 0;
+ midi_clock_count = 0;
+
+ DEBUG_TRACE (DEBUG::MidiClock, "No MIDI Clock messages received for some time, stopping!\n");
+ return;
+ }
+
+ if (session_pos) {
+ const samplepos_t current_pos = current.position + ((now - current.timestamp) * current.speed);
+ _current_delta = current_pos - *session_pos;
+ } else {
+ _current_delta = 0;
+ }
- double quarter_notes_per_beat = 4.0 / current_tempo.note_type();
- double frames_per_quarter_note = frames_per_beat / quarter_notes_per_beat;
+ DEBUG_TRACE (DEBUG::MidiClock, string_compose ("speed_and_position: speed %1 should-be %2 transport %3 \n", current.speed, current.position, _session->transport_sample()));
+}
- one_ppqn_in_frames = frames_per_quarter_note / double (ppqn);
- // DEBUG_TRACE (DEBUG::MidiClock, string_compose ("at %1, one ppqn = %2\n", time, one_ppqn_in_frames));
+void
+MIDIClock_TransportMaster::calculate_one_ppqn_in_samples_at(samplepos_t time)
+{
+ const double samples_per_quarter_note = _session->tempo_map().samples_per_quarter_note_at (time, ENGINE->sample_rate());
+
+ one_ppqn_in_samples = samples_per_quarter_note / double (ppqn);
+ // DEBUG_TRACE (DEBUG::MidiClock, string_compose ("at %1, one ppqn = %2\n", time, one_ppqn_in_samples));
}
-ARDOUR::framepos_t
-MIDIClock_Slave::calculate_song_position(uint16_t song_position_in_sixteenth_notes)
+ARDOUR::samplepos_t
+MIDIClock_TransportMaster::calculate_song_position(uint16_t song_position_in_sixteenth_notes)
{
- framepos_t song_position_frames = 0;
+ samplepos_t song_position_samples = 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 * (framepos_t)(ppqn / 4);
+ calculate_one_ppqn_in_samples_at(song_position_samples);
+ song_position_samples += one_ppqn_in_samples * (samplepos_t)(ppqn / 4);
}
- return song_position_frames;
+ return song_position_samples;
}
void
-MIDIClock_Slave::calculate_filter_coefficients()
+MIDIClock_TransportMaster::calculate_filter_coefficients (double qpm)
{
- // omega = 2 * PI * Bandwidth / MIDI clock frame frequency in Hz
- omega = 2.0 * M_PI * bandwidth * one_ppqn_in_frames / session->frame_rate();
- b = 1.4142135623730950488 * omega;
+ /* Paul says: I don't understand this computation of bandwidth
+ */
+
+ const double bandwidth = 2.0 / qpm;
+
+ /* Frequency of the clock messages is ENGINE->sample_rate() / * one_ppqn_in_samples, per second or in Hz */
+ const double freq = (double) ENGINE->sample_rate() / one_ppqn_in_samples;
+
+ const double omega = 2.0 * M_PI * bandwidth / freq;
+ b = 1.4142135623730950488 * omega; // sqrt (2.0) * omega
c = omega * omega;
+
+ DEBUG_TRACE (DEBUG::MidiClock, string_compose ("DLL coefficients: bw:%1 omega:%2 b:%3 c:%4\n", bandwidth, omega, b, c));
}
void
-MIDIClock_Slave::update_midi_clock (Parser& /*parser*/, framepos_t timestamp)
+MIDIClock_TransportMaster::update_midi_clock (Parser& /*parser*/, samplepos_t timestamp)
{
- // some pieces of hardware send MIDI Clock all the time
- if ( (!_starting) && (!_started) ) {
- return;
- }
+ samplepos_t elapsed_since_start = timestamp - first_timestamp;
+ double e = 0;
- calculate_one_ppqn_in_frames_at(should_be_position);
+ calculate_one_ppqn_in_samples_at (current.position);
- framepos_t elapsed_since_start = timestamp - first_timestamp;
- double error = 0;
+ DEBUG_TRACE (DEBUG::MidiClock, string_compose ("clock count %1, sbp %2\n", midi_clock_count, current.position));
- if (_starting || last_timestamp == 0) {
- midi_clock_count = 0;
+ if (midi_clock_count == 0) {
+ /* second 0xf8 message after start/reset has arrived */
first_timestamp = timestamp;
- elapsed_since_start = should_be_position;
+ current.update (0, timestamp, 0);
- // calculate filter coefficients
- calculate_filter_coefficients();
+ DEBUG_TRACE (DEBUG::MidiClock, string_compose ("first clock message after start received @ %1\n", timestamp));
- // initialize DLL
- e2 = double(one_ppqn_in_frames) / double(session->frame_rate());
- t0 = double(elapsed_since_start) / double(session->frame_rate());
- t1 = t0 + e2;
+ midi_clock_count++;
+
+ current.position += one_ppqn_in_samples;
+
+ } else if (midi_clock_count == 1) {
+
+ /* second 0xf8 message has arrived. we can now estimate QPM
+ * (quarters per minute, and fully initialize the DLL
+ */
+
+ e = timestamp - current.timestamp;
+
+ const samplecnt_t samples_per_quarter = e * 24;
+ _bpm = (ENGINE->sample_rate() * 60.0) / samples_per_quarter;
+
+ calculate_filter_coefficients (_bpm);
+
+ /* finish DLL initialization */
+
+ t0 = timestamp;
+ e2 = e;
+ t1 = t0 + e2; /* timestamp we predict for the next 0xf8 clock message */
- // 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->transport_frame()));
- e = error / double(session->frame_rate());
- current_delta = error;
-
- // update DLL
+ current.update (one_ppqn_in_samples, timestamp, 0);
+
+ } else {
+
+ /* 3rd or later MIDI clock message. We can now compute actual
+ * speed (and tempo) with the DLL
+ */
+
+ e = timestamp - t1; // error between actual time of arrival of clock message and our predicted time
t0 = t1;
t1 += b * e + e2;
e2 += c * e;
+
+ const double samples_per_quarter = (timestamp - current.timestamp) * 24.0;
+ const double instantaneous_bpm = (ENGINE->sample_rate() * 60.0) / samples_per_quarter;
+
+ const double predicted_clock_interval_in_samples = (t1 - t0);
+
+ /* _speed is relative to session tempo map */
+
+ double speed = predicted_clock_interval_in_samples / one_ppqn_in_samples;
+
+ /* _bpm (really, _qpm) is absolute */
+
+ /* detect substantial changes in apparent tempo (defined as a
+ * change of more than 20% of the current tempo.
+ */
+
+ const double lpf_coeff = 0.063;
+
+ if (fabs (instantaneous_bpm - _bpm) > (0.20 * _bpm)) {
+ _bpm = instantaneous_bpm;
+ } else {
+ _bpm += lpf_coeff * (instantaneous_bpm - _bpm);
+ }
+
+ calculate_filter_coefficients (_bpm);
+
+ // need at least two clock events to compute speed
+
+ if (!_running) {
+ DEBUG_TRACE (DEBUG::MidiClock, string_compose ("start mclock running with speed = %1\n", (t1 - t0) / one_ppqn_in_samples));
+ _running = true;
+ }
+
+ midi_clock_count++;
+ current.update (current.position + one_ppqn_in_samples, timestamp, speed);
+
+ if (TransportMasterManager::instance().current().get() == this) {
+ _session->maybe_update_tempo_from_midiclock_tempo (_bpm);
+ }
}
- DEBUG_TRACE (DEBUG::MidiClock, string_compose ("clock #%1 @ %2 arrived %3 (theoretical) audible %4 transport %5 error %6 "
- "read delta %7 should-be delta %8 t1-t0 %9 t0 %10 t1 %11 framerate %12 appspeed %13\n",
- midi_clock_count,
- elapsed_since_start,
- should_be_position,
- session->audible_frame(),
- session->transport_frame(),
- error,
- timestamp - last_timestamp,
- one_ppqn_in_frames,
- (t1 -t0) * session->frame_rate(),
- t0 * session->frame_rate(),
- t1 * session->frame_rate(),
- session->frame_rate(),
- ((t1 - t0) * session->frame_rate()) / one_ppqn_in_frames));
-
- last_timestamp = timestamp;
+ DEBUG_TRACE (DEBUG::MidiClock, string_compose ("clock #%1 @ %2 should-be %3 transport %4 error %5 appspeed %6 "
+ "read-delta %7 should-be delta %8 t1-t0 %9 t0 %10 t1 %11 framerate %12 engine %13 running %14\n",
+ midi_clock_count, // #
+ elapsed_since_start, // @
+ current.position, // should-be
+ _session->transport_sample(), // transport
+ e, // error
+ (t1 - t0) / one_ppqn_in_samples, // appspeed
+ timestamp - current.timestamp, // read delta
+ one_ppqn_in_samples, // should-be delta
+ (t1 - t0), // t1-t0
+ t0, // t0
+ t1, // t1
+ ENGINE->sample_rate(), // framerate
+ ENGINE->sample_time(),
+ _running
+
+ ));
}
void
-MIDIClock_Slave::start (Parser& /*parser*/, framepos_t timestamp)
+MIDIClock_TransportMaster::start (Parser& /*parser*/, samplepos_t timestamp)
{
- DEBUG_TRACE (DEBUG::MidiClock, string_compose ("MIDIClock_Slave got start message at time %1 engine time %2\n", timestamp, session->frame_time()));
+ DEBUG_TRACE (DEBUG::MidiClock, string_compose ("MIDIClock_TransportMaster got start message at time %1 engine time %2 transport_sample %3\n", timestamp, ENGINE->sample_time(), _session->transport_sample()));
- if (!_started) {
- reset();
-
- _started = true;
- _starting = true;
-
- should_be_position = session->transport_frame();
+ if (!_running) {
+ reset(true);
+ _running = true;
+ current.update (_session->transport_sample(), timestamp, 0);
}
}
void
-MIDIClock_Slave::reset ()
+MIDIClock_TransportMaster::reset (bool with_position)
{
- should_be_position = session->transport_frame();
- last_timestamp = 0;
+ DEBUG_TRACE (DEBUG::MidiClock, string_compose ("MidiClock Master reset(): calculated filter for period size %2\n", ENGINE->samples_per_cycle()));
- _starting = true;
- _started = true;
+ if (with_position) {
+ current.update (_session->transport_sample(), 0, 0);
+ } else {
+ current.reset ();
+ }
- // session->request_locate(0, false);
- current_delta = 0;
+ _running = false;
+ _current_delta = 0;
}
void
-MIDIClock_Slave::contineu (Parser& /*parser*/, framepos_t /*timestamp*/)
+MIDIClock_TransportMaster::contineu (Parser& /*parser*/, samplepos_t /*timestamp*/)
{
- DEBUG_TRACE (DEBUG::MidiClock, "MIDIClock_Slave got continue message\n");
+ DEBUG_TRACE (DEBUG::MidiClock, "MIDIClock_TransportMaster got continue message\n");
- if (!_started) {
- _starting = true;
- _started = true;
- }
+ _running = true;
}
-
void
-MIDIClock_Slave::stop (Parser& /*parser*/, framepos_t /*timestamp*/)
+MIDIClock_TransportMaster::stop (Parser& /*parser*/, samplepos_t timestamp)
{
- DEBUG_TRACE (DEBUG::MidiClock, "MIDIClock_Slave got stop message\n");
+ DEBUG_TRACE (DEBUG::MidiClock, "MIDIClock_TransportMaster got stop message\n");
- if (_started || _starting) {
- _starting = false;
- _started = false;
- // locate to last MIDI clock position
- session->request_transport_speed(0.0);
+ if (_running) {
+ _running = false;
// we need to go back to the last MIDI beat (6 ppqn)
// and lets hope the tempo didnt change in the meantime :)
// that is the position of the last MIDI Clock
// message and that is probably what the master
// expects where we are right now
- framepos_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;
+ current.update (current.position - (midi_clock_count % 6) * one_ppqn_in_samples, 0, 0);
}
}
void
-MIDIClock_Slave::position (Parser& /*parser*/, MIDI::byte* message, size_t size)
+MIDIClock_TransportMaster::position (Parser& /*parser*/, MIDI::byte* message, size_t size, samplepos_t timestamp)
{
- // we are note supposed to get position messages while we are running
+ // we are not supposed to get position messages while we are running
// so lets be robust and ignore those
- if (_started || _starting) {
+ if (_running) {
return;
}
assert((lsb <= 0x7f) && (msb <= 0x7f));
uint16_t position_in_sixteenth_notes = (uint16_t(msb) << 7) | uint16_t(lsb);
- framepos_t position_in_frames = calculate_song_position(position_in_sixteenth_notes);
-
- DEBUG_TRACE (DEBUG::MidiClock, string_compose ("Song Position: %1 frames: %2\n", position_in_sixteenth_notes, position_in_frames));
+ samplepos_t position_in_samples = calculate_song_position(position_in_sixteenth_notes);
- session->request_locate(position_in_frames, false);
- should_be_position = position_in_frames;
- last_timestamp = 0;
+ DEBUG_TRACE (DEBUG::MidiClock, string_compose ("Song Position: %1 samples: %2\n", position_in_sixteenth_notes, position_in_samples));
+ current.update (position_in_samples, timestamp, current.speed);
}
bool
-MIDIClock_Slave::locked () const
+MIDIClock_TransportMaster::locked () const
{
return true;
}
bool
-MIDIClock_Slave::ok() const
+MIDIClock_TransportMaster::ok() const
{
return true;
}
bool
-MIDIClock_Slave::starting() const
+MIDIClock_TransportMaster::starting() const
{
return false;
}
-bool
-MIDIClock_Slave::stop_if_no_more_clock_events(framepos_t& pos, framepos_t now)
+ARDOUR::samplecnt_t
+MIDIClock_TransportMaster::update_interval() const
{
- /* no timecode for 1/4 second ? conclude that its stopped */
- if (last_timestamp &&
- now > last_timestamp &&
- now - last_timestamp > session->frame_rate() / 4) {
- DEBUG_TRACE (DEBUG::MidiClock, "No MIDI Clock frames received for some time, stopping!\n");
- pos = should_be_position;
- session->request_transport_speed (0);
- session->request_locate (should_be_position, false);
- return true;
- } else {
- return false;
+ if (one_ppqn_in_samples) {
+ return resolution ();
}
+
+ return AudioEngine::instance()->sample_rate() / 120 / 4; /* pure guesswork */
}
-bool
-MIDIClock_Slave::speed_and_position (double& speed, framepos_t& pos)
+ARDOUR::samplecnt_t
+MIDIClock_TransportMaster::resolution() const
{
- if (!_started || _starting) {
- speed = 0.0;
- pos = should_be_position;
- return true;
- }
-
- framepos_t engine_now = session->frame_time();
-
- if (stop_if_no_more_clock_events(pos, engine_now)) {
- return false;
- }
-
- // calculate speed
- speed = ((t1 - t0) * session->frame_rate()) / one_ppqn_in_frames;
-
- // provide a 0.1% deadzone to lock the speed
- if (fabs(speed - 1.0) <= 0.001)
- speed = 1.0;
-
- // calculate position
- if (engine_now > last_timestamp) {
- // we are in between MIDI clock messages
- // so we interpolate position according to speed
- framecnt_t elapsed = engine_now - last_timestamp;
- pos = (framepos_t) (should_be_position + double(elapsed) * speed);
- } else {
- // A new MIDI clock message has arrived this cycle
- pos = should_be_position;
- }
-
- DEBUG_TRACE (DEBUG::MidiClock, string_compose ("speed_and_position: %1 & %2 <-> %3 (transport)\n", speed, pos, session->transport_frame()));
-
- return true;
+ // one beat
+ return (samplecnt_t) one_ppqn_in_samples * ppqn;
}
-ARDOUR::framecnt_t
-MIDIClock_Slave::resolution() const
+std::string
+MIDIClock_TransportMaster::position_string () const
{
- // one beat
- return (framecnt_t) one_ppqn_in_frames * ppqn;
+ return std::string();
}
std::string
-MIDIClock_Slave::approximate_current_delta() const
+MIDIClock_TransportMaster::delta_string() const
{
char delta[80];
- if (last_timestamp == 0 || _starting) {
+ SafeTime last;
+ current.safe_read (last);
+
+ if (last.timestamp == 0 || starting()) {
snprintf(delta, sizeof(delta), "\u2012\u2012\u2012\u2012");
} else {
snprintf(delta, sizeof(delta), "\u0394<span foreground=\"green\" face=\"monospace\" >%s%s%" PRIi64 "</span>sm",
- LEADINGZERO(abs(current_delta)), PLUSMINUS(-current_delta), abs(current_delta));
+ LEADINGZERO(abs(_current_delta)), PLUSMINUS(-_current_delta), abs(_current_delta));
}
return std::string(delta);
}
+void
+MIDIClock_TransportMaster::unregister_port ()
+{
+ _midi_port.reset ();
+ TransportMaster::unregister_port ();
+}
+