ardour
midi_clock_slave.cc
Go to the documentation of this file.
1 /*
2  Copyright (C) 2008 Paul Davis
3  Author: Hans Baier
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9 
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  GNU General Public License for more details.
14 
15  You should have received a copy of the GNU General Public License
16  along with this program; if not, write to the Free Software
17  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 
19 */
20 
21 #include <cmath>
22 #include <errno.h>
23 #include <sys/types.h>
24 #include <unistd.h>
25 #include "pbd/error.h"
26 #include "pbd/failed_constructor.h"
27 #include "pbd/pthread_utils.h"
28 #include "pbd/convert.h"
29 
30 #include "midi++/port.h"
31 
32 #include "ardour/debug.h"
33 #include "ardour/midi_buffer.h"
34 #include "ardour/midi_port.h"
35 #include "ardour/slave.h"
36 #include "ardour/tempo.h"
37 
38 #include "i18n.h"
39 
40 using namespace std;
41 using namespace ARDOUR;
42 using namespace MIDI;
43 using namespace PBD;
44 
45 MIDIClock_Slave::MIDIClock_Slave (Session& s, MidiPort& p, int ppqn)
46  : ppqn (ppqn)
47  , bandwidth (2.0 / 60.0) // 1 BpM = 1 / 60 Hz
48 {
50  rebind (p);
51  reset ();
52 }
53 
55  : session(session_proxy)
56  , ppqn (ppqn)
57  , bandwidth (2.0 / 60.0) // 1 BpM = 1 / 60 Hz
58 {
59  reset ();
60 }
61 
63 {
64  delete session;
65 }
66 
67 void
69 {
70  DEBUG_TRACE (DEBUG::MidiClock, string_compose ("MIDIClock_Slave: connecting to port %1\n", port.name()));
71 
73 
74  port.self_parser().timing.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::update_midi_clock, this, _1, _2));
75  port.self_parser().start.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::start, this, _1, _2));
76  port.self_parser().contineu.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::contineu, this, _1, _2));
77  port.self_parser().stop.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::stop, this, _1, _2));
78  port.self_parser().position.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::position, this, _1, _2, 3));
79 
80 }
81 
82 void
84 {
85  const Tempo& current_tempo = session->tempo_map().tempo_at(time);
86  double frames_per_beat = current_tempo.frames_per_beat(session->frame_rate());
87 
88  double quarter_notes_per_beat = 4.0 / current_tempo.note_type();
89  double frames_per_quarter_note = frames_per_beat / quarter_notes_per_beat;
90 
91  one_ppqn_in_frames = frames_per_quarter_note / double (ppqn);
92  // DEBUG_TRACE (DEBUG::MidiClock, string_compose ("at %1, one ppqn = %2\n", time, one_ppqn_in_frames));
93 }
94 
96 MIDIClock_Slave::calculate_song_position(uint16_t song_position_in_sixteenth_notes)
97 {
98  framepos_t song_position_frames = 0;
99  for (uint16_t i = 1; i <= song_position_in_sixteenth_notes; ++i) {
100  // one quarter note contains ppqn pulses, so a sixteenth note is ppqn / 4 pulses
101  calculate_one_ppqn_in_frames_at(song_position_frames);
102  song_position_frames += one_ppqn_in_frames * (framepos_t)(ppqn / 4);
103  }
104 
105  return song_position_frames;
106 }
107 
108 void
110 {
111  // omega = 2 * PI * Bandwidth / MIDI clock frame frequency in Hz
112  omega = 2.0 * M_PI * bandwidth * one_ppqn_in_frames / session->frame_rate();
113  b = 1.4142135623730950488 * omega;
114  c = omega * omega;
115 }
116 
117 void
118 MIDIClock_Slave::update_midi_clock (Parser& /*parser*/, framepos_t timestamp)
119 {
120  // some pieces of hardware send MIDI Clock all the time
121  if ( (!_starting) && (!_started) ) {
122  return;
123  }
124 
125  pframes_t cycle_offset = timestamp - session->sample_time_at_cycle_start();
126 
128 
129  framepos_t elapsed_since_start = timestamp - first_timestamp;
130  double error = 0;
131 
132  if (_starting || last_timestamp == 0) {
133  midi_clock_count = 0;
134 
135  first_timestamp = timestamp;
136  elapsed_since_start = should_be_position;
137 
138  DEBUG_TRACE (DEBUG::MidiClock, string_compose ("first clock message after start received @ %1\n", timestamp));
139 
140  // calculate filter coefficients
142 
143  // initialize DLL
144  e2 = double(one_ppqn_in_frames) / double(session->frame_rate());
145  t0 = double(elapsed_since_start) / double(session->frame_rate());
146  t1 = t0 + e2;
147 
148  // let ardour go after first MIDI Clock Event
149  _starting = false;
150  } else {
154 
155  // calculate loop error
156  // we use session->transport_frame() instead of t1 here
157  // because t1 is used to calculate the transport speed,
158  // so the loop will compensate for accumulating rounding errors
159  error = (double(should_be_position) - (double(session->transport_frame()) + double(cycle_offset)));
160  e = error / double(session->frame_rate());
162 
163  // update DLL
164  t0 = t1;
165  t1 += b * e + e2;
166  e2 += c * e;
167  }
168 
169  DEBUG_TRACE (DEBUG::MidiClock, string_compose ("clock #%1 @ %2 should-be %3 transport %4 error %5 appspeed %6 "
170  "read-delta %7 should-be delta %8 t1-t0 %9 t0 %10 t1 %11 framerate %12 engine %13\n",
171  midi_clock_count, // #
172  elapsed_since_start, // @
173  should_be_position, // should-be
174  session->transport_frame(), // transport
175  error, // error
176  ((t1 - t0) * session->frame_rate()) / one_ppqn_in_frames, // appspeed
177  timestamp - last_timestamp, // read delta
178  one_ppqn_in_frames, // should-be delta
179  (t1 - t0) * session->frame_rate(), // t1-t0
180  t0 * session->frame_rate(), // t0
181  t1 * session->frame_rate(), // t1
182  session->frame_rate(), // framerate
184 
185  ));
186 
187  last_timestamp = timestamp;
188 }
189 
190 void
191 MIDIClock_Slave::start (Parser& /*parser*/, framepos_t timestamp)
192 {
193  DEBUG_TRACE (DEBUG::MidiClock, string_compose ("MIDIClock_Slave got start message at time %1 engine time %2 transport_frame %3\n", timestamp, session->frame_time(), session->transport_frame()));
194 
195  if (!_started) {
196  reset();
197 
198  _started = true;
199  _starting = true;
200 
202  }
203 }
204 
205 void
207 {
208  DEBUG_TRACE (DEBUG::MidiClock, string_compose ("MidiClock_Slave reset(): calculated filter bandwidth is %1 for period size %2\n", bandwidth, session->frames_per_cycle()));
209 
211  last_timestamp = 0;
212 
213  _starting = true;
214  _started = true;
215 
216  // session->request_locate(0, false);
217  current_delta = 0;
218 }
219 
220 void
221 MIDIClock_Slave::contineu (Parser& /*parser*/, framepos_t /*timestamp*/)
222 {
223  DEBUG_TRACE (DEBUG::MidiClock, "MIDIClock_Slave got continue message\n");
224 
225  if (!_started) {
226  _starting = true;
227  _started = true;
228  }
229 }
230 
231 
232 void
233 MIDIClock_Slave::stop (Parser& /*parser*/, framepos_t /*timestamp*/)
234 {
235  DEBUG_TRACE (DEBUG::MidiClock, "MIDIClock_Slave got stop message\n");
236 
237  if (_started || _starting) {
238  _starting = false;
239  _started = false;
240  // locate to last MIDI clock position
242 
243  // we need to go back to the last MIDI beat (6 ppqn)
244  // and lets hope the tempo didnt change in the meantime :)
245 
246  // begin at the should be position, because
247  // that is the position of the last MIDI Clock
248  // message and that is probably what the master
249  // expects where we are right now
250  framepos_t stop_position = should_be_position;
251 
252  // find out the last MIDI beat: go back #midi_clocks mod 6
253  // and lets hope the tempo didnt change in those last 6 beats :)
254  stop_position -= (midi_clock_count % 6) * one_ppqn_in_frames;
255 
256  session->request_locate(stop_position, false);
257  should_be_position = stop_position;
258  last_timestamp = 0;
259  }
260 }
261 
262 void
263 MIDIClock_Slave::position (Parser& /*parser*/, MIDI::byte* message, size_t size)
264 {
265  // we are note supposed to get position messages while we are running
266  // so lets be robust and ignore those
267  if (_started || _starting) {
268  return;
269  }
270 
271  assert(size == 3);
272  MIDI::byte lsb = message[1];
273  MIDI::byte msb = message[2];
274  assert((lsb <= 0x7f) && (msb <= 0x7f));
275 
276  uint16_t position_in_sixteenth_notes = (uint16_t(msb) << 7) | uint16_t(lsb);
277  framepos_t position_in_frames = calculate_song_position(position_in_sixteenth_notes);
278 
279  DEBUG_TRACE (DEBUG::MidiClock, string_compose ("Song Position: %1 frames: %2\n", position_in_sixteenth_notes, position_in_frames));
280 
281  session->request_locate(position_in_frames, false);
282  should_be_position = position_in_frames;
283  last_timestamp = 0;
284 
285 }
286 
287 bool
289 {
290  return true;
291 }
292 
293 bool
295 {
296  return true;
297 }
298 
299 bool
301 {
302  return false;
303 }
304 
305 bool
307 {
308  /* no timecode for 1/4 second ? conclude that its stopped */
309  if (last_timestamp &&
310  now > last_timestamp &&
311  now - last_timestamp > session->frame_rate() / 4) {
312  DEBUG_TRACE (DEBUG::MidiClock, "No MIDI Clock frames received for some time, stopping!\n");
313  pos = should_be_position;
316  return true;
317  } else {
318  return false;
319  }
320 }
321 
322 bool
324 {
325  if (!_started || _starting) {
326  speed = 0.0;
327  pos = should_be_position;
328  return true;
329  }
330 
331  framepos_t engine_now = session->frame_time();
332 
333  if (stop_if_no_more_clock_events(pos, engine_now)) {
334  return false;
335  }
336 
337  // calculate speed
338  speed = ((t1 - t0) * session->frame_rate()) / one_ppqn_in_frames;
339 
340  // provide a 0.1% deadzone to lock the speed
341  if (fabs(speed - 1.0) <= 0.001)
342  speed = 1.0;
343 
344  // calculate position
345  if (engine_now > last_timestamp) {
346  // we are in between MIDI clock messages
347  // so we interpolate position according to speed
348  framecnt_t elapsed = engine_now - last_timestamp;
349  pos = (framepos_t) (should_be_position + double(elapsed) * speed);
350  } else {
351  // A new MIDI clock message has arrived this cycle
352  pos = should_be_position;
353  }
354 
355  DEBUG_TRACE (DEBUG::MidiClock, string_compose ("speed_and_position: speed %1 should-be %2 transport %3 \n", speed, pos, session->transport_frame()));
356 
357  return true;
358 }
359 
362 {
363  // one beat
365 }
366 
367 std::string
369 {
370  char delta[80];
371  if (last_timestamp == 0 || _starting) {
372  snprintf(delta, sizeof(delta), "\u2012\u2012\u2012\u2012");
373  } else {
374  snprintf(delta, sizeof(delta), "\u0394<span foreground=\"green\" face=\"monospace\" >%s%s%" PRIi64 "</span>sm",
376  }
377  return std::string(delta);
378 }
379 
framepos_t calculate_song_position(uint16_t song_position_in_sixteenth_notes)
ISlaveSessionProxy * session
Definition: slave.h:431
#define LEADINGZERO(A)
Definition: slave.h:41
virtual void request_transport_speed(double)
Definition: slave.h:198
void update_midi_clock(MIDI::Parser &parser, framepos_t timestamp)
framepos_t last_timestamp
the time stamp and should-be transport position of the last inbound MIDI clock message ...
Definition: slave.h:444
double should_be_position
Definition: slave.h:445
We need this wrapper for testability, it's just too hard to mock up a session class.
Definition: slave.h:183
MIDI::Parser & self_parser()
Definition: midi_port.h:61
void start(MIDI::Parser &parser, framepos_t timestamp)
void contineu(MIDI::Parser &parser, framepos_t timestamp)
uint32_t pframes_t
Definition: types.h:61
virtual framepos_t transport_frame() const
Definition: slave.h:190
Definition: Beats.hpp:239
LIBPBD_API Transmitter error
virtual framecnt_t frame_rate() const
Definition: slave.h:187
double e
loop error = real value - expected value
Definition: slave.h:460
std::string name() const
Definition: port.h:54
PBD::ScopedConnectionList port_connections
Definition: slave.h:432
double one_ppqn_in_frames
the duration of one ppqn in frame time
Definition: slave.h:438
double frames_per_beat(framecnt_t sr) const
Definition: tempo.h:55
double bandwidth
DLL filter bandwidth.
Definition: slave.h:466
std::string approximate_current_delta() const
int64_t framecnt_t
Definition: types.h:76
int ppqn
pulses per quarter note for one MIDI clock frame (default 24)
Definition: slave.h:435
#define PLUSMINUS(A)
Definition: slave.h:40
Definition: amp.h:29
virtual framepos_t frame_time() const
Definition: slave.h:193
void stop(MIDI::Parser &parser, framepos_t timestamp)
frameoffset_t current_delta
Definition: slave.h:471
#define DEBUG_TRACE(bits, str)
Definition: debug.h:55
int64_t framepos_t
Definition: types.h:66
LIBARDOUR_API uint64_t MidiClock
Definition: debug.cc:46
void calculate_one_ppqn_in_frames_at(framepos_t time)
double b
DLL filter coefficients.
Definition: slave.h:469
double t0
time at the beginning of the MIDI clock frame
Definition: slave.h:454
bool speed_and_position(double &, framepos_t &)
Definition: debug.h:30
bool stop_if_no_more_clock_events(framepos_t &pos, framepos_t now)
virtual TempoMap & tempo_map() const
Definition: slave.h:186
bool _started
whether transport should be rolling
Definition: slave.h:487
The Session Proxy for use in real Ardour.
Definition: slave.h:203
framepos_t first_timestamp
the timestamp of the first MIDI clock message
Definition: slave.h:441
virtual void request_locate(framepos_t, bool with_roll=false)
Definition: slave.h:195
MIDIClock_Slave(Session &, MidiPort &, int ppqn=24)
virtual framepos_t sample_time_at_cycle_start() const
Definition: slave.h:192
void position(MIDI::Parser &parser, MIDI::byte *message, size_t size)
virtual pframes_t frames_per_cycle() const
Definition: slave.h:188
framecnt_t resolution() const
double e2
second order loop error
Definition: slave.h:463
double note_type() const
Definition: tempo.h:54
const Tempo & tempo_at(framepos_t) const
Definition: tempo.cc:1617
Definition: ardour.h:41
std::string string_compose(const std::string &fmt, const T1 &o1)
Definition: compose.h:208
double t1
calculated end of the MIDI clock frame
Definition: slave.h:457