add finite state machine to control/manage transport state
[ardour.git] / libs / ardour / midi_clock_slave.cc
1 /*
2  * Copyright (C) 2008-2013 Hans Baier <hansfbaier@googlemail.com>
3  * Copyright (C) 2009-2010 Carl Hetherington <carl@carlh.net>
4  * Copyright (C) 2009-2012 David Robillard <d@drobilla.net>
5  * Copyright (C) 2009-2019 Paul Davis <paul@linuxaudiosystems.com>
6  * Copyright (C) 2012-2013 Robin Gareus <robin@gareus.org>
7  * Copyright (C) 2013-2018 John Emmas <john@creativepost.co.uk>
8  * Copyright (C) 2015-2016 Nick Mainsbridge <mainsbridge@gmail.com>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License along
21  * with this program; if not, write to the Free Software Foundation, Inc.,
22  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23  */
24
25 #include <cmath>
26 #include <errno.h>
27 #include <sys/types.h>
28 #include <unistd.h>
29 #include "pbd/error.h"
30 #include "pbd/failed_constructor.h"
31 #include "pbd/pthread_utils.h"
32 #include "pbd/convert.h"
33
34 #include "midi++/port.h"
35
36 #include "ardour/audioengine.h"
37 #include "ardour/debug.h"
38 #include "ardour/midi_buffer.h"
39 #include "ardour/midi_port.h"
40 #include "ardour/session.h"
41 #include "ardour/tempo.h"
42 #include "ardour/transport_master.h"
43 #include "ardour/transport_master_manager.h"
44
45 #include "pbd/i18n.h"
46
47 using namespace std;
48 using namespace ARDOUR;
49 using namespace MIDI;
50 using namespace PBD;
51
52 #define ENGINE AudioEngine::instance()
53
54 MIDIClock_TransportMaster::MIDIClock_TransportMaster (std::string const & name, int ppqn)
55         : TransportMaster (MIDIClock, name)
56         , ppqn (ppqn)
57         , midi_clock_count (0)
58         , _running (false)
59         , _bpm (0)
60 {
61 }
62
63 MIDIClock_TransportMaster::~MIDIClock_TransportMaster()
64 {
65         port_connections.drop_connections ();
66 }
67
68 void
69 MIDIClock_TransportMaster::init ()
70 {
71         midi_clock_count = 0;
72         current.reset ();
73 }
74
75 void
76 MIDIClock_TransportMaster::create_port ()
77 {
78         if ((_port = create_midi_port (string_compose ("%1 in", _name))) == 0) {
79                 throw failed_constructor();
80         }
81 }
82
83 void
84 MIDIClock_TransportMaster::set_session (Session *session)
85 {
86         port_connections.drop_connections();
87         _session = session;
88
89         /* only connect to signals if we have a proxy, because otherwise we
90          * cannot interpet incoming data (no tempo map etc.)
91          */
92
93         if (_session) {
94                 parser.timing.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::update_midi_clock, this, _1, _2));
95                 parser.start.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::start, this, _1, _2));
96                 parser.contineu.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::contineu, this, _1, _2));
97                 parser.stop.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::stop, this, _1, _2));
98                 parser.position.connect_same_thread (port_connections, boost::bind (&MIDIClock_TransportMaster::position, this, _1, _2, _3, _4));
99
100                 reset (true);
101         }
102 }
103
104 void
105 MIDIClock_TransportMaster::pre_process (MIDI::pframes_t nframes, samplepos_t now, boost::optional<samplepos_t> session_pos)
106 {
107         /* Read and parse incoming MIDI */
108
109         DEBUG_TRACE (DEBUG::MidiClock, string_compose ("preprocess with lt = %1 @ %2, running ? %3\n", current.timestamp, now, _running));
110
111         _midi_port->read_and_parse_entire_midi_buffer_with_no_speed_adjustment (nframes, parser, now);
112
113         /* no clock messages ever, or no clock messages for 1/4 second ? conclude that its stopped */
114
115         if (!current.timestamp || (now > current.timestamp && ((now - current.timestamp) > (ENGINE->sample_rate() / 4)))) {
116                 _bpm = 0.0;
117                 _running = false;
118                 _current_delta = 0;
119                 midi_clock_count = 0;
120
121                 DEBUG_TRACE (DEBUG::MidiClock, "No MIDI Clock messages received for some time, stopping!\n");
122                 return;
123         }
124
125         if (session_pos) {
126                 const samplepos_t current_pos = current.position + ((now - current.timestamp) * current.speed);
127                 _current_delta = current_pos - *session_pos;
128         } else {
129                 _current_delta = 0;
130         }
131
132         DEBUG_TRACE (DEBUG::MidiClock, string_compose ("speed_and_position: speed %1 should-be %2 transport %3 \n", current.speed, current.position, _session->transport_sample()));
133 }
134
135 void
136 MIDIClock_TransportMaster::calculate_one_ppqn_in_samples_at(samplepos_t time)
137 {
138         const double samples_per_quarter_note = _session->tempo_map().samples_per_quarter_note_at (time, ENGINE->sample_rate());
139
140         one_ppqn_in_samples = samples_per_quarter_note / double (ppqn);
141         // DEBUG_TRACE (DEBUG::MidiClock, string_compose ("at %1, one ppqn = %2\n", time, one_ppqn_in_samples));
142 }
143
144 ARDOUR::samplepos_t
145 MIDIClock_TransportMaster::calculate_song_position(uint16_t song_position_in_sixteenth_notes)
146 {
147         samplepos_t song_position_samples = 0;
148         for (uint16_t i = 1; i <= song_position_in_sixteenth_notes; ++i) {
149                 // one quarter note contains ppqn pulses, so a sixteenth note is ppqn / 4 pulses
150                 calculate_one_ppqn_in_samples_at(song_position_samples);
151                 song_position_samples += one_ppqn_in_samples * (samplepos_t)(ppqn / 4);
152         }
153
154         return song_position_samples;
155 }
156
157 void
158 MIDIClock_TransportMaster::calculate_filter_coefficients (double qpm)
159 {
160         /* Paul says: I don't understand this computation of bandwidth
161         */
162
163         const double bandwidth = 2.0 / qpm;
164
165         /* Frequency of the clock messages is ENGINE->sample_rate() / * one_ppqn_in_samples, per second or in Hz */
166         const double freq = (double) ENGINE->sample_rate() / one_ppqn_in_samples;
167
168         const double omega = 2.0 * M_PI * bandwidth / freq;
169         b = 1.4142135623730950488 * omega; // sqrt (2.0) * omega
170         c = omega * omega;
171
172         DEBUG_TRACE (DEBUG::MidiClock, string_compose ("DLL coefficients: bw:%1 omega:%2 b:%3 c:%4\n", bandwidth, omega, b, c));
173 }
174
175 void
176 MIDIClock_TransportMaster::update_midi_clock (Parser& /*parser*/, samplepos_t timestamp)
177 {
178         samplepos_t elapsed_since_start = timestamp - first_timestamp;
179         double e = 0;
180
181         calculate_one_ppqn_in_samples_at (current.position);
182
183         DEBUG_TRACE (DEBUG::MidiClock, string_compose ("clock count %1, sbp %2\n", midi_clock_count, current.position));
184
185         if (midi_clock_count == 0) {
186                 /* second 0xf8 message after start/reset has arrived */
187
188                 first_timestamp = timestamp;
189                 current.update (0, timestamp, 0);
190
191                 DEBUG_TRACE (DEBUG::MidiClock, string_compose ("first clock message after start received @ %1\n", timestamp));
192
193                 midi_clock_count++;
194
195                 current.position += one_ppqn_in_samples;
196
197         } else if (midi_clock_count == 1) {
198
199                 /* second 0xf8 message has arrived. we can now estimate QPM
200                  * (quarters per minute, and fully initialize the DLL
201                  */
202
203                 e  = timestamp - current.timestamp;
204
205                 const samplecnt_t samples_per_quarter = e * 24;
206                 _bpm = (ENGINE->sample_rate() * 60.0) / samples_per_quarter;
207
208                 calculate_filter_coefficients (_bpm);
209
210                 /* finish DLL initialization */
211
212                 t0 = timestamp;
213                 e2 = e;
214                 t1 = t0 + e2; /* timestamp we predict for the next 0xf8 clock message */
215
216                 midi_clock_count++;
217                 current.update (one_ppqn_in_samples, timestamp, 0);
218
219         } else {
220
221                 /* 3rd or later MIDI clock message. We can now compute actual
222                  * speed (and tempo) with the DLL
223                  */
224
225                 e = timestamp - t1; // error between actual time of arrival of clock message and our predicted time
226                 t0 = t1;
227                 t1 += b * e + e2;
228                 e2 += c * e;
229
230                 const double samples_per_quarter = (timestamp - current.timestamp) * 24.0;
231                 const double instantaneous_bpm = (ENGINE->sample_rate() * 60.0) / samples_per_quarter;
232
233                 const double predicted_clock_interval_in_samples = (t1 - t0);
234
235                 /* _speed is relative to session tempo map */
236
237                 double speed = predicted_clock_interval_in_samples / one_ppqn_in_samples;
238
239                 /* _bpm (really, _qpm) is absolute */
240
241                 /* detect substantial changes in apparent tempo (defined as a
242                  * change of more than 20% of the current tempo.
243                  */
244
245                 const double lpf_coeff = 0.063;
246
247                 if (fabs (instantaneous_bpm - _bpm) > (0.20 * _bpm)) {
248                         _bpm = instantaneous_bpm;
249                 } else {
250                         _bpm += lpf_coeff * (instantaneous_bpm - _bpm);
251                 }
252
253                 calculate_filter_coefficients (_bpm);
254
255                 // need at least two clock events to compute speed
256
257                 if (!_running) {
258                         DEBUG_TRACE (DEBUG::MidiClock, string_compose ("start mclock running with speed = %1\n", (t1 - t0) / one_ppqn_in_samples));
259                         _running = true;
260                 }
261
262                 midi_clock_count++;
263                 current.update (current.position + one_ppqn_in_samples, timestamp, speed);
264
265                 if (TransportMasterManager::instance().current().get() == this) {
266                         _session->maybe_update_tempo_from_midiclock_tempo (_bpm);
267                 }
268         }
269
270         DEBUG_TRACE (DEBUG::MidiClock, string_compose ("clock #%1 @ %2 should-be %3 transport %4 error %5 appspeed %6 "
271                                                        "read-delta %7 should-be delta %8 t1-t0 %9 t0 %10 t1 %11 framerate %12 engine %13 running %14\n",
272                                                        midi_clock_count,                                          // #
273                                                        elapsed_since_start,                                       // @
274                                                        current.position,                                        // should-be
275                                                        _session->transport_sample(),                                // transport
276                                                        e,                                                     // error
277                                                        (t1 - t0) / one_ppqn_in_samples, // appspeed
278                                                        timestamp - current.timestamp,                                // read delta
279                                                        one_ppqn_in_samples,                                        // should-be delta
280                                                        (t1 - t0),                         // t1-t0
281                                                        t0,                                // t0
282                                                        t1,                                // t1
283                                                        ENGINE->sample_rate(),                                      // framerate
284                                                        ENGINE->sample_time(),
285                                                        _running
286
287         ));
288 }
289
290 void
291 MIDIClock_TransportMaster::start (Parser& /*parser*/, samplepos_t timestamp)
292 {
293         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()));
294
295         if (!_running) {
296                 reset(true);
297                 _running = true;
298                 current.update (_session->transport_sample(), timestamp, 0);
299         }
300 }
301
302 void
303 MIDIClock_TransportMaster::reset (bool with_position)
304 {
305         DEBUG_TRACE (DEBUG::MidiClock, string_compose ("MidiClock Master reset(): calculated filter for period size %2\n", ENGINE->samples_per_cycle()));
306
307         if (with_position) {
308                 current.update (_session->transport_sample(), 0, 0);
309         } else {
310                 current.reset ();
311         }
312
313         _running = false;
314         _current_delta = 0;
315 }
316
317 void
318 MIDIClock_TransportMaster::contineu (Parser& /*parser*/, samplepos_t /*timestamp*/)
319 {
320         DEBUG_TRACE (DEBUG::MidiClock, "MIDIClock_TransportMaster got continue message\n");
321
322         _running = true;
323 }
324
325 void
326 MIDIClock_TransportMaster::stop (Parser& /*parser*/, samplepos_t timestamp)
327 {
328         DEBUG_TRACE (DEBUG::MidiClock, "MIDIClock_TransportMaster got stop message\n");
329
330         if (_running) {
331                 _running = false;
332
333                 // we need to go back to the last MIDI beat (6 ppqn)
334                 // and lets hope the tempo didnt change in the meantime :)
335
336                 // begin at the should be position, because
337                 // that is the position of the last MIDI Clock
338                 // message and that is probably what the master
339                 // expects where we are right now
340                 //
341                 // find out the last MIDI beat: go back #midi_clocks mod 6
342                 // and lets hope the tempo didnt change in those last 6 beats :)
343                 current.update (current.position - (midi_clock_count % 6) * one_ppqn_in_samples, 0, 0);
344         }
345 }
346
347 void
348 MIDIClock_TransportMaster::position (Parser& /*parser*/, MIDI::byte* message, size_t size, samplepos_t timestamp)
349 {
350         // we are not supposed to get position messages while we are running
351         // so lets be robust and ignore those
352         if (_running) {
353                 return;
354         }
355
356         assert(size == 3);
357         MIDI::byte lsb = message[1];
358         MIDI::byte msb = message[2];
359         assert((lsb <= 0x7f) && (msb <= 0x7f));
360
361         uint16_t position_in_sixteenth_notes = (uint16_t(msb) << 7) | uint16_t(lsb);
362         samplepos_t position_in_samples = calculate_song_position(position_in_sixteenth_notes);
363
364         DEBUG_TRACE (DEBUG::MidiClock, string_compose ("Song Position: %1 samples: %2\n", position_in_sixteenth_notes, position_in_samples));
365
366         current.update (position_in_samples, timestamp, current.speed);
367 }
368
369 bool
370 MIDIClock_TransportMaster::locked () const
371 {
372         return true;
373 }
374
375 bool
376 MIDIClock_TransportMaster::ok() const
377 {
378         return true;
379 }
380
381 bool
382 MIDIClock_TransportMaster::starting() const
383 {
384         return false;
385 }
386
387 ARDOUR::samplecnt_t
388 MIDIClock_TransportMaster::update_interval() const
389 {
390         if (one_ppqn_in_samples) {
391                 return resolution ();
392         }
393
394         return AudioEngine::instance()->sample_rate() / 120 / 4; /* pure guesswork */
395 }
396
397 ARDOUR::samplecnt_t
398 MIDIClock_TransportMaster::resolution() const
399 {
400         // one beat
401         return (samplecnt_t) one_ppqn_in_samples * ppqn;
402 }
403
404 std::string
405 MIDIClock_TransportMaster::position_string () const
406 {
407         return std::string();
408 }
409
410 std::string
411 MIDIClock_TransportMaster::delta_string() const
412 {
413         char delta[80];
414         SafeTime last;
415         current.safe_read (last);
416
417         if (last.timestamp == 0 || starting()) {
418                 snprintf(delta, sizeof(delta), "\u2012\u2012\u2012\u2012");
419         } else {
420                 snprintf(delta, sizeof(delta), "\u0394<span foreground=\"green\" face=\"monospace\" >%s%s%" PRIi64 "</span>sm",
421                                 LEADINGZERO(abs(_current_delta)), PLUSMINUS(-_current_delta), abs(_current_delta));
422         }
423         return std::string(delta);
424 }
425
426 void
427 MIDIClock_TransportMaster::unregister_port ()
428 {
429         _midi_port.reset ();
430         TransportMaster::unregister_port ();
431 }
432