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