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