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