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