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