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