* got MIDI clock working really smoothly (29 frames until sync, ardour transport...
[ardour.git] / libs / ardour / midi_clock_slave.cc
1 /*
2     Copyright (C) 2002-4 Paul Davis
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         , accumulator_index (0)
48         , average_midi_clock_frame_duration (0.0)
49 {
50         rebind (p);
51         reset ();
52
53         for(int i = 0; i < accumulator_size; i++)
54                 accumulator[i]=0.0;
55 }
56
57 MIDIClock_Slave::~MIDIClock_Slave()
58 {
59 }
60
61 void
62 MIDIClock_Slave::rebind (MIDI::Port& p)
63 {
64         for (vector<sigc::connection>::iterator i = connections.begin(); i != connections.end(); ++i) {
65                 (*i).disconnect ();
66         }
67
68         port = &p;
69
70         std::cerr << "MIDIClock_Slave: connecting to port " << port->name() << std::endl;
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()->stop.connect   (mem_fun (*this, &MIDIClock_Slave::stop)));
75 }
76
77 void
78 MIDIClock_Slave::update_midi_clock (Parser& parser, nframes_t timestamp)
79 {       
80         nframes_t now = timestamp;
81
82         SafeTime last;
83         read_current (&last);
84                 
85         const Tempo& current_tempo = session.tempo_map().tempo_at(now);
86         const Meter& current_meter = session.tempo_map().meter_at(now);
87         double frames_per_beat =
88                 current_tempo.frames_per_beat(session.frame_rate(),
89                                               current_meter);
90
91         double quarter_notes_per_beat = 4.0 / current_tempo.note_type();
92         double frames_per_quarter_note = frames_per_beat / quarter_notes_per_beat;
93
94         one_ppqn_in_frames = frames_per_quarter_note / ppqn;
95         
96         // for the first MIDI clock event we dont have any past
97         // data, so we assume a sane tempo
98         if(last.timestamp == 0) {
99                 current_midi_clock_frame_duration = one_ppqn_in_frames;
100         } else {
101                 current_midi_clock_frame_duration = now - last.timestamp;
102         }
103         
104         
105         // moving average over incoming intervals
106         accumulator[accumulator_index++] = (float) current_midi_clock_frame_duration;
107         if(accumulator_index == accumulator_size)
108                 accumulator_index = 0;
109         
110         average_midi_clock_frame_duration = 0.0;
111         for(int i = 0; i < accumulator_size; i++)
112                 average_midi_clock_frame_duration += accumulator[i];
113         average_midi_clock_frame_duration /= accumulator_size;
114         
115         
116 #if 0
117         JACK_MidiPort *jack_port = dynamic_cast<JACK_MidiPort *>(port);
118         pthread_t process_thread_id = 0;
119         if(jack_port) {
120                 process_thread_id = jack_port->get_process_thread();
121         }
122         
123         std::cerr 
124                   << " got MIDI Clock message at time " << now  
125                   << " session time: " << session.engine().frame_time() 
126                   << " transport position: " << session.transport_frame()
127                   << " real delta: " << current_midi_clock_frame_duration 
128                   << " reference: " << one_ppqn_in_frames
129                   << " average: " << average_midi_clock_frame_duration
130                   << std::endl;
131 #endif
132         
133         current.guard1++;
134         current.position += one_ppqn_in_frames;
135         current.timestamp = now;
136         current.guard2++;
137
138         last_inbound_frame = now;
139 }
140
141 void
142 MIDIClock_Slave::start (Parser& parser, nframes_t timestamp)
143 {
144         
145         nframes_t now = timestamp;
146         
147         //cerr << "MIDIClock_Slave got start message at time "  <<  now << " session time: " << session.engine().frame_time() << endl;
148
149         if(!locked()) {
150                 cerr << "Did not start because not locked!" << endl;
151                 return;
152         }
153         
154         current_midi_clock_frame_duration = 0;
155         
156         session.request_transport_speed(one_ppqn_in_frames / average_midi_clock_frame_duration);
157         current.guard1++;
158         current.position = 0;
159         current.timestamp = now;
160         current.guard2++;
161         
162         _started = true;
163         _starting = true;
164 }
165
166 void
167 MIDIClock_Slave::stop (Parser& parser, nframes_t timestamp)
168 {
169         //std::cerr << "MIDIClock_Slave got stop message" << endl;
170
171         current_midi_clock_frame_duration = 0;
172
173         current.guard1++;
174         current.position = 0;
175         current.timestamp = 0;
176         current.guard2++;
177         
178         _started = false;
179         reset();
180 }
181
182 void
183 MIDIClock_Slave::read_current (SafeTime *st) const
184 {
185         int tries = 0;
186         do {
187                 if (tries == 10) {
188                         error << _("MIDI Clock Slave: atomic read of current time failed, sleeping!") << endmsg;
189                         usleep (20);
190                         tries = 0;
191                 }
192
193                 *st = current;
194                 tries++;
195
196         } while (st->guard1 != st->guard2);
197 }
198
199 bool
200 MIDIClock_Slave::locked () const
201 {
202         return true;
203 }
204
205 bool
206 MIDIClock_Slave::ok() const
207 {
208         return true;
209 }
210
211 bool
212 MIDIClock_Slave::speed_and_position (float& speed, nframes_t& pos)
213 {
214         float previous_speed;
215         
216         nframes_t now = session.engine().frame_time();
217         
218         if(!_started) {
219                 speed = 0.0;
220                 pos = 0;
221                 previous_speed = one_ppqn_in_frames / average_midi_clock_frame_duration;
222                 return true;
223         }
224                 
225
226         SafeTime last;
227         read_current (&last);
228
229         /* no timecode for 1/4 second ? conclude that its stopped */
230
231         if (last_inbound_frame && 
232             now > last_inbound_frame && 
233             now - last_inbound_frame > session.frame_rate() / 4) {
234                 //cerr << "No MIDI Clock frames received for some time, stopping!" << endl;
235                 pos = last.position;
236                 session.request_locate (pos, false);
237                 session.request_transport_speed (0);
238                 this->stop(*port->input(), now);
239                 reset();
240                 return false;
241         }
242
243         //cerr << " now: " << now << " last: " << last.timestamp;
244
245         speed = one_ppqn_in_frames / average_midi_clock_frame_duration;
246         //cerr << " final speed: " << speed;
247         
248         if (now > last.timestamp) {
249                 // we are in between MIDI clock messages
250                 // so we interpolate position according to speed
251                 nframes_t elapsed = now - last.timestamp;
252                 nframes_t delta = elapsed * speed;
253                 //cerr << " elapsed: " << elapsed << " elapsed (scaled)  " << delta;
254                 pos = last.position + delta;
255         } else {
256                 // A new MIDI clock message has arrived this cycle
257                 pos = (last.position + session.transport_frame()) / 2.0;
258                 previous_speed = speed;
259         }
260         
261         /*
262    cerr << " transport position now: " <<  session.transport_frame(); 
263    cerr << " calculated position: " << pos; 
264    cerr << endl;
265    */
266    
267    // we want start on frame 0 on the first call after a MIDI start
268    if(_starting) {
269            pos = 0;
270            _starting = false;
271    }
272    
273         return true;
274 }
275
276 ARDOUR::nframes_t
277 MIDIClock_Slave::resolution() const
278 {
279         return (nframes_t) one_ppqn_in_frames * 24;
280 }
281
282 void
283 MIDIClock_Slave::reset ()
284 {
285
286         last_inbound_frame = 0;
287         current.guard1++;
288         current.position = 0;
289         current.timestamp = 0;
290         current.guard2++;
291         
292         session.request_locate(0, false);
293 }