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