* corrected copyright information
[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 }
76
77 void 
78 MIDIClock_Slave::calculate_one_ppqn_in_frames_at(nframes_t time)
79 {
80         const Tempo& current_tempo = session.tempo_map().tempo_at(time);
81         const Meter& current_meter = session.tempo_map().meter_at(time);
82         double frames_per_beat =
83                 current_tempo.frames_per_beat(session.frame_rate(),
84                                               current_meter);
85
86         double quarter_notes_per_beat = 4.0 / current_tempo.note_type();
87         double frames_per_quarter_note = frames_per_beat / quarter_notes_per_beat;
88
89         one_ppqn_in_frames = frames_per_quarter_note / double (ppqn);
90 }
91
92 void 
93 MIDIClock_Slave::calculate_filter_coefficients()
94 {
95         // omega = 2 * PI * Bandwidth / MIDI clock frame frequency in Hz
96         omega = 2.0 * 3.14159265358979323846 * bandwidth * one_ppqn_in_frames / session.frame_rate();
97         b = 1.4142135623730950488 * omega;
98         c = omega * omega;      
99 }
100
101 void
102 MIDIClock_Slave::update_midi_clock (Parser& parser, nframes_t timestamp)
103 {                                       
104         // the number of midi clock messages (zero-based)
105         static long midi_clock_count;
106         
107         calculate_one_ppqn_in_frames_at(last_position);
108         
109         nframes_t timestamp_relative_to_transport = timestamp - first_timestamp;
110         
111         if (_starting) {
112                 midi_clock_count = 0;
113                 assert(last_timestamp == 0);
114                 assert(last_position == 0);
115                 
116                 first_timestamp = timestamp;
117                 timestamp_relative_to_transport = 0;
118                 
119                 // calculate filter coefficients
120                 calculate_filter_coefficients();
121                 
122                 // initialize DLL
123                 e2 = double(one_ppqn_in_frames) / double(session.frame_rate());
124                 t0 = double(timestamp_relative_to_transport) / double(session.frame_rate());
125                 t1 = t0 + e2;
126                 
127                 // let ardour go after first MIDI Clock Event
128                 _starting = false;
129         } else {                
130                 midi_clock_count++;
131                 last_position  += one_ppqn_in_frames;
132                 calculate_filter_coefficients();
133
134                 // calculate loop error
135                 // we use session.transport_frame() instead of t1 here
136                 // because t1 is used to calculate the transport speed, and since this
137                 // is float, the loop will compensate for accumulating rounding errors
138                 e = (double(last_position) - double(session.transport_frame())) 
139                     / double(session.frame_rate());
140                 
141                 // update DLL
142                 t0 = t1;
143                 t1 += b * e + e2;
144                 e2 += c * e;
145                                 
146         }       
147         
148         #ifdef DEBUG_MIDI_CLOCK         
149                 std::cerr 
150                                   << "MIDI Clock #" << midi_clock_count
151                                   //<< "@" << timestamp  
152                                   << " (transport-relative: " << timestamp_relative_to_transport << " should be: " << last_position << ", delta: " << (double(last_position) - double(session.transport_frame())) <<" )"
153                                   << " transport: " << session.transport_frame()
154                                   //<< " engine: " << session.engine().frame_time() 
155                                   << " real delta: " << timestamp - last_timestamp 
156                                   << " reference: " << one_ppqn_in_frames
157                                   << " t1-t0: " << (t1 -t0) * session.frame_rate()
158                                   << " t0: " << t0 * session.frame_rate()
159                                   << " t1: " << t1 * session.frame_rate() 
160                                   << " frame-rate: " << session.frame_rate() 
161                                   << std::endl;
162         #endif // DEBUG_MIDI_CLOCK
163
164         last_timestamp = timestamp;
165 }
166
167 void
168 MIDIClock_Slave::start (Parser& parser, nframes_t timestamp)
169 {       
170         #ifdef DEBUG_MIDI_CLOCK 
171                 cerr << "MIDIClock_Slave got start message at time "  <<  timestamp << " session time: " << session.engine().frame_time() << endl;
172         #endif
173         
174         last_position = 0;
175         last_timestamp = 0;
176         
177         _started = true;
178         _starting = true;
179 }
180
181 void
182 MIDIClock_Slave::contineu (Parser& parser, nframes_t timestamp)
183 {
184         #ifdef DEBUG_MIDI_CLOCK 
185                 std::cerr << "MIDIClock_Slave got continue message" << endl;
186         #endif
187         start(parser, timestamp);
188 }
189
190
191 void
192 MIDIClock_Slave::stop (Parser& parser, nframes_t timestamp)
193 {
194         #ifdef DEBUG_MIDI_CLOCK 
195                 std::cerr << "MIDIClock_Slave got stop message" << endl;
196         #endif
197         
198         last_position = 0;
199         last_timestamp = 0;
200         
201         _started = false;
202         reset();
203 }
204
205 bool
206 MIDIClock_Slave::locked () const
207 {
208         return true;
209 }
210
211 bool
212 MIDIClock_Slave::ok() const
213 {
214         return true;
215 }
216
217 bool
218 MIDIClock_Slave::starting() const
219 {
220         return false;
221 }
222
223 bool
224 MIDIClock_Slave::stop_if_no_more_clock_events(nframes_t& pos, nframes_t now)
225 {
226         /* no timecode for 1/4 second ? conclude that its stopped */
227         if (last_timestamp && 
228             now > last_timestamp && 
229             now - last_timestamp > session.frame_rate() / 4) {
230         #ifdef DEBUG_MIDI_CLOCK                 
231                         cerr << "No MIDI Clock frames received for some time, stopping!" << endl;
232         #endif          
233                 pos = last_position;
234                 session.request_locate (pos, false);
235                 session.request_transport_speed (0);
236                 this->stop(*port->input(), now);
237                 reset();
238                 return true;
239         } else {
240                 return false;
241         }
242 }
243
244 bool
245 MIDIClock_Slave::speed_and_position (float& speed, nframes_t& pos)
246 {
247         if (!_started || _starting) {
248                 speed = 0.0;
249                 pos = 0;
250                 return true;
251         }
252                 
253         nframes_t engine_now = session.engine().frame_time();
254
255         if (stop_if_no_more_clock_events(pos, engine_now)) {
256                 return false;
257         }
258
259         // calculate speed
260         double speed_double = ((t1 - t0) * session.frame_rate()) / one_ppqn_in_frames;
261         speed = float(speed_double);
262         
263         // calculate position
264         if (engine_now > last_timestamp) {
265                 // we are in between MIDI clock messages
266                 // so we interpolate position according to speed
267                 nframes_t elapsed = engine_now - last_timestamp;
268                 pos = nframes_t (last_position + double(elapsed) * speed_double);
269         } else {
270                 // A new MIDI clock message has arrived this cycle
271                 pos = last_position;
272         }
273
274         return true;
275 }
276
277 ARDOUR::nframes_t
278 MIDIClock_Slave::resolution() const
279 {
280         // one beat
281         return (nframes_t) one_ppqn_in_frames * ppqn;
282 }
283
284 void
285 MIDIClock_Slave::reset ()
286 {
287
288         last_position = 0;              
289         last_timestamp = 0;
290         
291         session.request_locate(0, false);
292 }