monster commit: transport mgmt changes from 2.X (omnibus edition); make slave use...
[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 <errno.h>
22 #include <poll.h>
23 #include <sys/types.h>
24 #include <unistd.h>
25 #include "pbd/error.h"
26 #include "pbd/failed_constructor.h"
27 #include "pbd/pthread_utils.h"
28
29 #include "midi++/port.h"
30 #include "midi++/jack.h"
31 #include "ardour/slave.h"
32 #include "ardour/session.h"
33 #include "ardour/audioengine.h"
34 #include "ardour/cycles.h"
35 #include "ardour/tempo.h"
36
37
38 #include "i18n.h"
39
40 using namespace std;
41 using namespace ARDOUR;
42 using namespace sigc;
43 using namespace MIDI;
44 using namespace PBD;
45
46 MIDIClock_Slave::MIDIClock_Slave (Session& s, MIDI::Port& p, int ppqn)
47         : ppqn (ppqn)
48         , bandwidth (30.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 (30.0 / 60.0) // 1 BpM = 1 / 60 Hz
59 {
60         session = session_proxy;
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         for (vector<sigc::connection>::iterator i = connections.begin(); i != connections.end(); ++i) {
73                 (*i).disconnect ();
74         }
75
76         port = &p;
77
78         #ifdef DEBUG_MIDI_CLOCK
79                 std::cerr << "MIDIClock_Slave: connecting to port " << port->name() << std::endl;
80         #endif
81
82         connections.push_back (port->input()->timing.connect   (mem_fun (*this, &MIDIClock_Slave::update_midi_clock)));
83         connections.push_back (port->input()->start.connect    (mem_fun (*this, &MIDIClock_Slave::start)));
84         connections.push_back (port->input()->contineu.connect (mem_fun (*this, &MIDIClock_Slave::contineu)));
85         connections.push_back (port->input()->stop.connect     (mem_fun (*this, &MIDIClock_Slave::stop)));
86         connections.push_back (port->input()->position.connect (mem_fun (*this, &MIDIClock_Slave::position)));
87 }
88
89 void
90 MIDIClock_Slave::calculate_one_ppqn_in_frames_at(nframes64_t time)
91 {
92         const Tempo& current_tempo = session->tempo_map().tempo_at(time);
93         const Meter& current_meter = session->tempo_map().meter_at(time);
94         double frames_per_beat =
95                 current_tempo.frames_per_beat(session->frame_rate(),
96                                               current_meter);
97
98         double quarter_notes_per_beat = 4.0 / current_tempo.note_type();
99         double frames_per_quarter_note = frames_per_beat / quarter_notes_per_beat;
100
101         one_ppqn_in_frames = frames_per_quarter_note / double (ppqn);
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 * 3.14159265358979323846 * 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->transport_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         #ifdef DEBUG_MIDI_CLOCK
174                 cerr
175                                   << "MIDI Clock #" << midi_clock_count
176                                   //<< "@" << timestamp
177                                   << " arrived at: " << elapsed_since_start << " (elapsed time) "
178                                   << " should-be transport: " << should_be_position
179                                   << " audible: " << session->audible_frame()
180                                   << " real transport: " << session->transport_frame()
181                                   << " error: " << error
182                                   //<< " engine: " << session->frame_time()
183                                   << " real delta: " << timestamp - last_timestamp
184                                   << " should-be delta: " << one_ppqn_in_frames
185                                   << " t1-t0: " << (t1 -t0) * session->frame_rate()
186                                   << " t0: " << t0 * session->frame_rate()
187                                   << " t1: " << t1 * session->frame_rate()
188                                   << " frame-rate: " << session->frame_rate()
189                                   << endl;
190
191                 cerr      << "frames since cycle start: " << session->frames_since_cycle_start() << endl;
192         #endif // DEBUG_MIDI_CLOCK
193
194         last_timestamp = timestamp;
195 }
196
197 void
198 MIDIClock_Slave::start (Parser& /*parser*/, nframes64_t /*timestamp*/)
199 {
200         #ifdef DEBUG_MIDI_CLOCK
201                 cerr << "MIDIClock_Slave got start message at time "  <<  timestamp << " engine time: " << session->frame_time() << endl;
202         #endif
203
204         if (!_started) {
205                 reset();
206
207                 _started = true;
208                 _starting = true;
209         }
210 }
211
212 void
213 MIDIClock_Slave::reset ()
214 {
215
216         should_be_position = 0;
217         last_timestamp = 0;
218
219         _starting = false;
220         _started  = false;
221
222         session->request_locate(0, false);
223 }
224
225 void
226 MIDIClock_Slave::contineu (Parser& /*parser*/, nframes64_t /*timestamp*/)
227 {
228         #ifdef DEBUG_MIDI_CLOCK
229                 std::cerr << "MIDIClock_Slave got continue message" << endl;
230         #endif
231         if (!_started) {
232                 _starting = true;
233                 _started  = true;
234         }
235 }
236
237
238 void
239 MIDIClock_Slave::stop (Parser& /*parser*/, nframes64_t /*timestamp*/)
240 {
241         #ifdef DEBUG_MIDI_CLOCK
242                 std::cerr << "MIDIClock_Slave got stop message" << endl;
243         #endif
244
245         if (_started || _starting) {
246                 _starting = false;
247                 _started  = false;
248                 // locate to last MIDI clock position
249                 session->request_transport_speed(0.0);
250
251                 // we need to go back to the last MIDI beat (6 ppqn)
252                 // and lets hope the tempo didnt change in the meantime :)
253
254                 // begin at the should be position, because
255                 // that is the position of the last MIDI Clock
256                 // message and that is probably what the master
257                 // expects where we are right now
258                 nframes64_t stop_position = should_be_position;
259
260                 // find out the last MIDI beat: go back #midi_clocks mod 6
261                 // and lets hope the tempo didnt change in those last 6 beats :)
262                 stop_position -= (midi_clock_count % 6) * one_ppqn_in_frames;
263
264                 session->request_locate(stop_position, false);
265                 should_be_position = stop_position;
266                 last_timestamp = 0;
267         }
268 }
269
270 void
271 MIDIClock_Slave::position (Parser& /*parser*/, byte* message, size_t size)
272 {
273         // we are note supposed to get position messages while we are running
274         // so lets be robust and ignore those
275         if (_started || _starting) {
276                 return;
277         }
278
279         assert(size == 3);
280         byte lsb = message[1];
281         byte msb = message[2];
282         assert((lsb <= 0x7f) && (msb <= 0x7f));
283
284         uint16_t position_in_sixteenth_notes = (uint16_t(msb) << 7) | uint16_t(lsb);
285         nframes64_t position_in_frames = calculate_song_position(position_in_sixteenth_notes);
286
287         #ifdef DEBUG_MIDI_CLOCK
288         cerr << "Song Position: " << position_in_sixteenth_notes << " frames: " << position_in_frames << endl;
289         #endif
290
291         session->request_locate(position_in_frames, false);
292         should_be_position  = position_in_frames;
293         last_timestamp = 0;
294
295 }
296
297 bool
298 MIDIClock_Slave::locked () const
299 {
300         return true;
301 }
302
303 bool
304 MIDIClock_Slave::ok() const
305 {
306         return true;
307 }
308
309 bool
310 MIDIClock_Slave::starting() const
311 {
312         return false;
313 }
314
315 bool
316 MIDIClock_Slave::stop_if_no_more_clock_events(nframes64_t& pos, nframes64_t now)
317 {
318         /* no timecode for 1/4 second ? conclude that its stopped */
319         if (last_timestamp &&
320             now > last_timestamp &&
321             now - last_timestamp > session->frame_rate() / 4) {
322         #ifdef DEBUG_MIDI_CLOCK
323                         cerr << "No MIDI Clock frames received for some time, stopping!" << endl;
324         #endif
325                 pos = should_be_position;
326                 session->request_transport_speed (0);
327                 session->request_locate (should_be_position, false);
328                 return true;
329         } else {
330                 return false;
331         }
332 }
333
334 bool
335 MIDIClock_Slave::speed_and_position (double& speed, nframes64_t& pos)
336 {
337         if (!_started || _starting) {
338                 speed = 0.0;
339                 pos   = should_be_position;
340                 return true;
341         }
342
343         nframes64_t engine_now = session->frame_time();
344
345         if (stop_if_no_more_clock_events(pos, engine_now)) {
346                 return false;
347         }
348
349         // calculate speed
350         speed = ((t1 - t0) * session->frame_rate()) / one_ppqn_in_frames;
351
352         // calculate position
353         if (engine_now > last_timestamp) {
354                 // we are in between MIDI clock messages
355                 // so we interpolate position according to speed
356                 nframes64_t elapsed = engine_now - last_timestamp;
357                 pos = (nframes64_t) (should_be_position + double(elapsed) * speed);
358         } else {
359                 // A new MIDI clock message has arrived this cycle
360                 pos = should_be_position;
361         }
362
363         #ifdef DEBUG_MIDI_CLOCK
364         cerr << "speed_and_position: " << speed << " & " << pos << " <-> " << session->transport_frame() << " (transport)" << endl;
365         #endif
366
367         return true;
368 }
369
370 ARDOUR::nframes_t
371 MIDIClock_Slave::resolution() const
372 {
373         // one beat
374         return (nframes_t) one_ppqn_in_frames * ppqn;
375 }
376