2f8ff9d2917e4734c19cdb1b4133dbe1b421f2d0
[ardour.git] / libs / ardour / midi_clock_slave.cc
1 /*
2     Copyright (C) 2008 Hans Baier
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <errno.h>
21 #include <poll.h>
22 #include <sys/types.h>
23 #include <unistd.h>
24 #include <pbd/error.h>
25 #include <pbd/failed_constructor.h>
26 #include <pbd/pthread_utils.h>
27
28 #include <midi++/port.h>
29 #include <midi++/jack.h>
30 #include <ardour/slave.h>
31 #include <ardour/session.h>
32 #include <ardour/audioengine.h>
33 #include <ardour/cycles.h>
34 #include <ardour/tempo.h>
35
36
37 #include "i18n.h"
38
39 using namespace ARDOUR;
40 using namespace sigc;
41 using namespace MIDI;
42 using namespace PBD;
43
44 MIDIClock_Slave::MIDIClock_Slave (Session& s, MIDI::Port& p, int ppqn)
45         : session (s)
46         , ppqn (ppqn)
47         , bandwidth (30.0 / 60.0) // 1 BpM = 1 / 60 Hz
48 {
49         rebind (p);
50         reset ();
51 }
52
53 MIDIClock_Slave::~MIDIClock_Slave()
54 {
55 }
56
57 void
58 MIDIClock_Slave::rebind (MIDI::Port& p)
59 {
60         for (vector<sigc::connection>::iterator i = connections.begin(); i != connections.end(); ++i) {
61                 (*i).disconnect ();
62         }
63
64         port = &p;
65
66         #ifdef DEBUG_MIDI_CLOCK         
67                 std::cerr << "MIDIClock_Slave: connecting to port " << port->name() << std::endl;
68         #endif
69
70         connections.push_back (port->input()->timing.connect   (mem_fun (*this, &MIDIClock_Slave::update_midi_clock)));
71         connections.push_back (port->input()->start.connect    (mem_fun (*this, &MIDIClock_Slave::start)));
72         connections.push_back (port->input()->contineu.connect (mem_fun (*this, &MIDIClock_Slave::contineu)));
73         connections.push_back (port->input()->stop.connect     (mem_fun (*this, &MIDIClock_Slave::stop)));
74 }
75
76 void 
77 MIDIClock_Slave::calculate_one_ppqn_in_frames_at(nframes_t time)
78 {
79         const Tempo& current_tempo = session.tempo_map().tempo_at(time);
80         const Meter& current_meter = session.tempo_map().meter_at(time);
81         double frames_per_beat =
82                 current_tempo.frames_per_beat(session.frame_rate(),
83                                               current_meter);
84
85         double quarter_notes_per_beat = 4.0 / current_tempo.note_type();
86         double frames_per_quarter_note = frames_per_beat / quarter_notes_per_beat;
87
88         one_ppqn_in_frames = frames_per_quarter_note / double (ppqn);
89 }
90
91 void 
92 MIDIClock_Slave::calculate_filter_coefficients()
93 {
94         // omega = 2 * PI * Bandwidth / MIDI clock frame frequency in Hz
95         omega = 2.0 * 3.14159265358979323846 * bandwidth * one_ppqn_in_frames / session.frame_rate();
96         b = 1.4142135623730950488 * omega;
97         c = omega * omega;      
98 }
99
100 void
101 MIDIClock_Slave::update_midi_clock (Parser& parser, nframes_t timestamp)
102 {                                       
103         // the number of midi clock messages (zero-based)
104         static long midi_clock_count;
105         
106         calculate_one_ppqn_in_frames_at(last_position);
107         
108         nframes_t timestamp_relative_to_transport = timestamp - first_timestamp;
109         
110         if (_starting) {
111                 midi_clock_count = 0;
112                 assert(last_timestamp == 0);
113                 assert(last_position == 0);
114                 
115                 first_timestamp = timestamp;
116                 timestamp_relative_to_transport = 0;
117                 
118                 // calculate filter coefficients
119                 calculate_filter_coefficients();
120                 
121                 // initialize DLL
122                 e2 = double(one_ppqn_in_frames) / double(session.frame_rate());
123                 t0 = double(timestamp_relative_to_transport) / double(session.frame_rate());
124                 t1 = t0 + e2;
125                 
126                 // let ardour go after first MIDI Clock Event
127                 _starting = false;
128         } else {                
129                 midi_clock_count++;
130                 last_position  += one_ppqn_in_frames;
131                 calculate_filter_coefficients();
132
133                 // calculate loop error
134                 // we use session.transport_frame() instead of t1 here
135                 // because t1 is used to calculate the transport speed, and since this
136                 // is float, the loop will compensate for accumulating rounding errors
137                 e = (double(last_position) - double(session.transport_frame())) 
138                     / double(session.frame_rate());
139                 
140                 // update DLL
141                 t0 = t1;
142                 t1 += b * e + e2;
143                 e2 += c * e;
144                                 
145         }       
146         
147         #ifdef DEBUG_MIDI_CLOCK         
148                 std::cerr 
149                                   << "MIDI Clock #" << midi_clock_count
150                                   //<< "@" << timestamp  
151                                   << " (transport-relative: " << timestamp_relative_to_transport << " should be: " << last_position << ", delta: " << (double(last_position) - double(session.transport_frame())) <<" )"
152                                   << " transport: " << session.transport_frame()
153                                   //<< " engine: " << session.engine().frame_time() 
154                                   << " real delta: " << timestamp - last_timestamp 
155                                   << " reference: " << one_ppqn_in_frames
156                                   << " t1-t0: " << (t1 -t0) * session.frame_rate()
157                                   << " t0: " << t0 * session.frame_rate()
158                                   << " t1: " << t1 * session.frame_rate() 
159                                   << " frame-rate: " << session.frame_rate() 
160                                   << std::endl;
161         #endif // DEBUG_MIDI_CLOCK
162
163         last_timestamp = timestamp;
164 }
165
166 void
167 MIDIClock_Slave::start (Parser& parser, nframes_t timestamp)
168 {       
169         #ifdef DEBUG_MIDI_CLOCK 
170                 cerr << "MIDIClock_Slave got start message at time "  <<  timestamp << " session time: " << session.engine().frame_time() << endl;
171         #endif
172         
173         last_position = 0;
174         last_timestamp = 0;
175         
176         _started = true;
177         _starting = true;
178 }
179
180 void
181 MIDIClock_Slave::contineu (Parser& parser, nframes_t timestamp)
182 {
183         #ifdef DEBUG_MIDI_CLOCK 
184                 std::cerr << "MIDIClock_Slave got continue message" << endl;
185         #endif
186         start(parser, timestamp);
187 }
188
189
190 void
191 MIDIClock_Slave::stop (Parser& parser, nframes_t timestamp)
192 {
193         #ifdef DEBUG_MIDI_CLOCK 
194                 std::cerr << "MIDIClock_Slave got stop message" << endl;
195         #endif
196         
197         last_position = 0;
198         last_timestamp = 0;
199         
200         _started = false;
201         reset();
202 }
203
204 bool
205 MIDIClock_Slave::locked () const
206 {
207         return true;
208 }
209
210 bool
211 MIDIClock_Slave::ok() const
212 {
213         return true;
214 }
215
216 bool
217 MIDIClock_Slave::starting() const
218 {
219         return false;
220 }
221
222 bool
223 MIDIClock_Slave::stop_if_no_more_clock_events(nframes_t& pos, nframes_t now)
224 {
225         /* no timecode for 1/4 second ? conclude that its stopped */
226         if (last_timestamp && 
227             now > last_timestamp && 
228             now - last_timestamp > session.frame_rate() / 4) {
229         #ifdef DEBUG_MIDI_CLOCK                 
230                         cerr << "No MIDI Clock frames received for some time, stopping!" << endl;
231         #endif          
232                 pos = last_position;
233                 session.request_locate (pos, false);
234                 session.request_transport_speed (0);
235                 this->stop(*port->input(), now);
236                 reset();
237                 return true;
238         } else {
239                 return false;
240         }
241 }
242
243 bool
244 MIDIClock_Slave::speed_and_position (float& speed, nframes_t& pos)
245 {
246         if (!_started || _starting) {
247                 speed = 0.0;
248                 pos = 0;
249                 return true;
250         }
251                 
252         nframes_t engine_now = session.engine().frame_time();
253
254         if (stop_if_no_more_clock_events(pos, engine_now)) {
255                 return false;
256         }
257
258         // calculate speed
259         double speed_double = ((t1 - t0) * session.frame_rate()) / one_ppqn_in_frames;
260         speed = float(speed_double);
261         
262         // calculate position
263         if (engine_now > last_timestamp) {
264                 // we are in between MIDI clock messages
265                 // so we interpolate position according to speed
266                 nframes_t elapsed = engine_now - last_timestamp;
267                 pos = nframes_t (last_position + double(elapsed) * speed_double);
268         } else {
269                 // A new MIDI clock message has arrived this cycle
270                 pos = last_position;
271         }
272
273         return true;
274 }
275
276 ARDOUR::nframes_t
277 MIDIClock_Slave::resolution() const
278 {
279         // one beat
280         return (nframes_t) one_ppqn_in_frames * ppqn;
281 }
282
283 void
284 MIDIClock_Slave::reset ()
285 {
286
287         last_position = 0;              
288         last_timestamp = 0;
289         
290         session.request_locate(0, false);
291 }