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