midi_clock_slave: fix wrong calculation of loop error
[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 <poll.h>
24 #include <sys/types.h>
25 #include <unistd.h>
26 #include "pbd/error.h"
27 #include "pbd/failed_constructor.h"
28 #include "pbd/pthread_utils.h"
29 #include "pbd/convert.h"
30
31 #include "midi++/port.h"
32
33 #include "ardour/debug.h"
34 #include "ardour/midi_buffer.h"
35 #include "ardour/midi_port.h"
36 #include "ardour/slave.h"
37 #include "ardour/tempo.h"
38
39 #include "i18n.h"
40
41 using namespace std;
42 using namespace ARDOUR;
43 using namespace MIDI;
44 using namespace PBD;
45
46 MIDIClock_Slave::MIDIClock_Slave (Session& s, MidiPort& p, int ppqn)
47         : ppqn (ppqn)
48         , bandwidth (10.0 / 60.0) // 1 BpM = 1 / 60 Hz
49 {
50         session = (ISlaveSessionProxy *) new SlaveSessionProxy(s);
51         rebind (p);
52         reset ();
53 }
54
55 MIDIClock_Slave::MIDIClock_Slave (ISlaveSessionProxy* session_proxy, int ppqn)
56         : session(session_proxy)
57         , ppqn (ppqn)
58         , bandwidth (10.0 / 60.0) // 1 BpM = 1 / 60 Hz
59 {
60         reset ();
61 }
62
63 MIDIClock_Slave::~MIDIClock_Slave()
64 {
65         delete session;
66 }
67
68 void
69 MIDIClock_Slave::rebind (MidiPort& port)
70 {
71         DEBUG_TRACE (DEBUG::MidiClock, string_compose ("MIDIClock_Slave: connecting to port %1\n", port.name()));
72
73         port_connections.drop_connections ();
74
75         port.self_parser().timing.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::update_midi_clock, this, _1, _2));
76         port.self_parser().start.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::start, this, _1, _2));
77         port.self_parser().contineu.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::contineu, this, _1, _2));
78         port.self_parser().stop.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::stop, this, _1, _2));
79         port.self_parser().position.connect_same_thread (port_connections, boost::bind (&MIDIClock_Slave::position, this, _1, _2, 3));
80
81 }
82
83 void
84 MIDIClock_Slave::calculate_one_ppqn_in_frames_at(framepos_t time)
85 {
86         const Tempo& current_tempo = session->tempo_map().tempo_at(time);
87         double frames_per_beat = current_tempo.frames_per_beat(session->frame_rate());
88
89         double quarter_notes_per_beat = 4.0 / current_tempo.note_type();
90         double frames_per_quarter_note = frames_per_beat / quarter_notes_per_beat;
91
92         one_ppqn_in_frames = frames_per_quarter_note / double (ppqn);
93         // DEBUG_TRACE (DEBUG::MidiClock, string_compose ("at %1, one ppqn = %2\n", time, one_ppqn_in_frames));
94 }
95
96 ARDOUR::framepos_t
97 MIDIClock_Slave::calculate_song_position(uint16_t song_position_in_sixteenth_notes)
98 {
99         framepos_t song_position_frames = 0;
100         for (uint16_t i = 1; i <= song_position_in_sixteenth_notes; ++i) {
101                 // one quarter note contains ppqn pulses, so a sixteenth note is ppqn / 4 pulses
102                 calculate_one_ppqn_in_frames_at(song_position_frames);
103                 song_position_frames += one_ppqn_in_frames * (framepos_t)(ppqn / 4);
104         }
105
106         return song_position_frames;
107 }
108
109 void
110 MIDIClock_Slave::calculate_filter_coefficients()
111 {
112         // omega = 2 * PI * Bandwidth / MIDI clock frame frequency in Hz
113         omega = 2.0 * M_PI * bandwidth * one_ppqn_in_frames / session->frame_rate();
114         b = 1.4142135623730950488 * omega;
115         c = omega * omega;
116 }
117
118 void
119 MIDIClock_Slave::update_midi_clock (Parser& /*parser*/, framepos_t timestamp)
120 {
121         // some pieces of hardware send MIDI Clock all the time
122         if ( (!_starting) && (!_started) ) {
123                 return;
124         }
125
126         pframes_t cycle_offset = timestamp - session->sample_time_at_cycle_start();
127
128         calculate_one_ppqn_in_frames_at(should_be_position);
129
130         framepos_t elapsed_since_start = timestamp - first_timestamp;
131         double error = 0;
132
133         if (_starting || last_timestamp == 0) {
134                 midi_clock_count = 0;
135
136                 first_timestamp = timestamp;
137                 elapsed_since_start = should_be_position;
138
139                 DEBUG_TRACE (DEBUG::MidiClock, string_compose ("first clock message after start received @ %1\n", timestamp));
140
141                 // calculate filter coefficients
142                 calculate_filter_coefficients();
143
144                 // initialize DLL
145                 e2 = double(one_ppqn_in_frames) / double(session->frame_rate());
146                 t0 = double(elapsed_since_start) / double(session->frame_rate());
147                 t1 = t0 + e2;
148
149                 // let ardour go after first MIDI Clock Event
150                 _starting = false;
151         } else {
152                 midi_clock_count++;
153                 should_be_position  += one_ppqn_in_frames;
154                 calculate_filter_coefficients();
155
156                 // calculate loop error
157                 // we use session->transport_frame() instead of t1 here
158                 // because t1 is used to calculate the transport speed,
159                 // so the loop will compensate for accumulating rounding errors
160                 error = (double(should_be_position) - (double(session->transport_frame()) + double(cycle_offset)));
161                 e = error / double(session->frame_rate());
162                 current_delta = error;
163
164                 // update DLL
165                 t0 = t1;
166                 t1 += b * e + e2;
167                 e2 += c * e;
168         }
169
170         DEBUG_TRACE (DEBUG::MidiClock, string_compose ("clock #%1 @ %2 should-be %3 transport %4 error %5 appspeed %6 "
171                                                        "read-delta %7 should-be delta %8 t1-t0 %9 t0 %10 t1 %11 framerate %12 engine %13\n",
172                                                        midi_clock_count,                                          // #
173                                                        elapsed_since_start,                                       // @
174                                                        should_be_position,                                        // should-be
175                                                        session->transport_frame(),                                // transport
176                                                        error,                                                     // error
177                                                        ((t1 - t0) * session->frame_rate()) / one_ppqn_in_frames, // appspeed
178                                                        timestamp - last_timestamp,                                // read delta
179                                                        one_ppqn_in_frames,                                        // should-be delta
180                                                        (t1 - t0) * session->frame_rate(),                         // t1-t0
181                                                        t0 * session->frame_rate(),                                // t0
182                                                        t1 * session->frame_rate(),                                // t1
183                                                        session->frame_rate(),                                      // framerate
184                                                        session->frame_time()
185
186         ));
187
188         last_timestamp = timestamp;
189 }
190
191 void
192 MIDIClock_Slave::start (Parser& /*parser*/, framepos_t timestamp)
193 {
194         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()));
195
196         if (!_started) {
197                 reset();
198
199                 _started = true;
200                 _starting = true;
201
202                 should_be_position = session->transport_frame();
203         }
204 }
205
206 void
207 MIDIClock_Slave::reset ()
208 {
209         bandwidth = (256.0 / session->frames_per_cycle()) * 10.0 / 60.0;
210         DEBUG_TRACE (DEBUG::MidiClock, string_compose ("MidiClock_Slave reset(): calculated filter bandwidth is %1 for period size %2\n", bandwidth, session->frames_per_cycle()));
211
212         should_be_position = session->transport_frame();
213         last_timestamp = 0;
214
215         _starting = true;
216         _started  = true;
217
218         // session->request_locate(0, false);
219         current_delta = 0;
220 }
221
222 void
223 MIDIClock_Slave::contineu (Parser& /*parser*/, framepos_t /*timestamp*/)
224 {
225         DEBUG_TRACE (DEBUG::MidiClock, "MIDIClock_Slave got continue message\n");
226
227         if (!_started) {
228                 _starting = true;
229                 _started  = true;
230         }
231 }
232
233
234 void
235 MIDIClock_Slave::stop (Parser& /*parser*/, framepos_t /*timestamp*/)
236 {
237         DEBUG_TRACE (DEBUG::MidiClock, "MIDIClock_Slave got stop message\n");
238
239         if (_started || _starting) {
240                 _starting = false;
241                 _started  = false;
242                 // locate to last MIDI clock position
243                 session->request_transport_speed(0.0);
244
245                 // we need to go back to the last MIDI beat (6 ppqn)
246                 // and lets hope the tempo didnt change in the meantime :)
247
248                 // begin at the should be position, because
249                 // that is the position of the last MIDI Clock
250                 // message and that is probably what the master
251                 // expects where we are right now
252                 framepos_t stop_position = should_be_position;
253
254                 // find out the last MIDI beat: go back #midi_clocks mod 6
255                 // and lets hope the tempo didnt change in those last 6 beats :)
256                 stop_position -= (midi_clock_count % 6) * one_ppqn_in_frames;
257
258                 session->request_locate(stop_position, false);
259                 should_be_position = stop_position;
260                 last_timestamp = 0;
261         }
262 }
263
264 void
265 MIDIClock_Slave::position (Parser& /*parser*/, byte* message, size_t size)
266 {
267         // we are note supposed to get position messages while we are running
268         // so lets be robust and ignore those
269         if (_started || _starting) {
270                 return;
271         }
272
273         assert(size == 3);
274         byte lsb = message[1];
275         byte msb = message[2];
276         assert((lsb <= 0x7f) && (msb <= 0x7f));
277
278         uint16_t position_in_sixteenth_notes = (uint16_t(msb) << 7) | uint16_t(lsb);
279         framepos_t position_in_frames = calculate_song_position(position_in_sixteenth_notes);
280
281         DEBUG_TRACE (DEBUG::MidiClock, string_compose ("Song Position: %1 frames: %2\n", position_in_sixteenth_notes, position_in_frames));
282
283         session->request_locate(position_in_frames, false);
284         should_be_position  = position_in_frames;
285         last_timestamp = 0;
286
287 }
288
289 bool
290 MIDIClock_Slave::locked () const
291 {
292         return true;
293 }
294
295 bool
296 MIDIClock_Slave::ok() const
297 {
298         return true;
299 }
300
301 bool
302 MIDIClock_Slave::starting() const
303 {
304         return false;
305 }
306
307 bool
308 MIDIClock_Slave::stop_if_no_more_clock_events(framepos_t& pos, framepos_t now)
309 {
310         /* no timecode for 1/4 second ? conclude that its stopped */
311         if (last_timestamp &&
312             now > last_timestamp &&
313             now - last_timestamp > session->frame_rate() / 4) {
314                 DEBUG_TRACE (DEBUG::MidiClock, "No MIDI Clock frames received for some time, stopping!\n");
315                 pos = should_be_position;
316                 session->request_transport_speed (0);
317                 session->request_locate (should_be_position, false);
318                 return true;
319         } else {
320                 return false;
321         }
322 }
323
324 bool
325 MIDIClock_Slave::speed_and_position (double& speed, framepos_t& pos)
326 {
327         if (!_started || _starting) {
328                 speed = 0.0;
329                 pos   = should_be_position;
330                 return true;
331         }
332
333         framepos_t engine_now = session->frame_time();
334
335         if (stop_if_no_more_clock_events(pos, engine_now)) {
336                 return false;
337         }
338
339         // calculate speed
340         speed = ((t1 - t0) * session->frame_rate()) / one_ppqn_in_frames;
341
342         // provide a 0.1% deadzone to lock the speed
343         if (fabs(speed - 1.0) <= 0.001)
344                 speed = 1.0;
345
346         // calculate position
347         if (engine_now > last_timestamp) {
348                 // we are in between MIDI clock messages
349                 // so we interpolate position according to speed
350                 framecnt_t elapsed = engine_now - last_timestamp;
351                 pos = (framepos_t) (should_be_position + double(elapsed) * speed);
352         } else {
353                 // A new MIDI clock message has arrived this cycle
354                 pos = should_be_position;
355         }
356
357         DEBUG_TRACE (DEBUG::MidiClock, string_compose ("speed_and_position: speed %1 should-be %2 transport %3 \n", speed, pos, session->transport_frame()));
358
359         return true;
360 }
361
362 ARDOUR::framecnt_t
363 MIDIClock_Slave::resolution() const
364 {
365         // one beat
366         return (framecnt_t) one_ppqn_in_frames * ppqn;
367 }
368
369 std::string
370 MIDIClock_Slave::approximate_current_delta() const
371 {
372         char delta[80];
373         if (last_timestamp == 0 || _starting) {
374                 snprintf(delta, sizeof(delta), "\u2012\u2012\u2012\u2012");
375         } else {
376                 snprintf(delta, sizeof(delta), "\u0394<span foreground=\"green\" face=\"monospace\" >%s%s%" PRIi64 "</span>sm",
377                                 LEADINGZERO(abs(current_delta)), PLUSMINUS(-current_delta), abs(current_delta));
378         }
379         return std::string(delta);
380 }
381