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