more MTC stuff, including toggleable use of torben's PI controller
[ardour.git] / libs / ardour / ardour / slave.h
1 /*
2     Copyright (C) 2002 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 #ifndef __ardour_slave_h__
21 #define __ardour_slave_h__
22
23 #include <vector>
24
25 #include <jack/jack.h>
26
27 #include <sigc++/signal.h>
28 #include "ardour/types.h"
29 #include "midi++/parser.h"
30 #include "midi++/types.h"
31
32 class PIController;
33
34 namespace MIDI {
35         class Port;
36 }
37
38 namespace ARDOUR {
39
40 class TempoMap;
41 class Session;
42
43 /**
44  * @class Slave
45  *
46  * @brief The Slave interface can be used to sync ARDOURs tempo to an external source
47  * like MTC, MIDI Clock, etc.
48  *
49  * The name of the interface may be a bit misleading: A subclass of Slave actually
50  * acts as a time master for ARDOUR, that means ARDOUR will try to follow the
51  * speed and transport position of the implementation of Slave.
52  * Therefore it is rather that class, that makes ARDOUR a slave by connecting it
53  * to its external time master.
54  */
55 class Slave {
56   public:
57         Slave() { }
58         virtual ~Slave() {}
59
60         /**
61          * This is the most important function to implement:
62          * Each process cycle, Session::follow_slave will call this method.
63          *  and after the method call they should
64          *
65          * Session::follow_slave will then try to follow the given
66          * <emph>position</emph> using a delay locked loop (DLL),
67          * starting with the first given transport speed.
68          * If the values of speed and position contradict each other,
69          * ARDOUR will always follow the position and disregard the speed.
70          * Although, a correct speed is important so that ARDOUR
71          * can sync to the master time source quickly.
72          *
73          * For background information on delay locked loops,
74          * see http://www.kokkinizita.net/papers/usingdll.pdf
75          *
76          * The method has the following precondition:
77          * <ul>
78          *   <li>
79          *       Slave::ok() should return true, otherwise playback will stop
80          *       immediately and the method will not be called
81          *   </li>
82          *   <li>
83          *     when the references speed and position are passed into the Slave
84          *     they are uninitialized
85          *   </li>
86          * </ul>
87          *
88          * After the method call the following postconditions should be met:
89          * <ul>
90          *    <li>
91          *       The first position value on transport start should be 0,
92          *       otherwise ARDOUR will try to locate to the new position
93          *       rather than move to it
94          *    </li>
95          *    <li>
96          *      the references speed and position should be assigned
97          *      to the Slaves current requested transport speed
98          *      and transport position.
99          *    </li>
100          *   <li>
101          *     Slave::resolution() should be greater than the maximum distance of
102          *     ARDOURs transport position to the slaves requested transport position.
103          *   </li>
104          *   <li>Slave::locked() should return true, otherwise Session::no_roll will be called</li>
105          *   <li>Slave::starting() should be false, otherwise the transport will not move until it becomes true</li>     *
106          * </ul>
107          *
108          * @param speed - The transport speed requested
109          * @param position - The transport position requested
110          * @return - The return value is currently ignored (see Session::follow_slave)
111          */
112         virtual bool speed_and_position (double& speed, nframes64_t& position) = 0;
113
114         /**
115          * reports to ARDOUR whether the Slave is currently synced to its external
116          * time source.
117          *
118          * @return - when returning false, the transport will stop rolling
119          */
120         virtual bool locked() const = 0;
121
122         /**
123          * reports to ARDOUR whether the slave is in a sane state
124          *
125          * @return - when returning false, the transport will be stopped and the slave
126          * disconnected from ARDOUR.
127          */
128         virtual bool ok() const = 0;
129
130         /**
131          * reports to ARDOUR whether the slave is in the process of starting
132          * to roll
133          *
134          * @return - when returning false, transport will not move until this method returns true
135          */
136         virtual bool starting() const { return false; }
137
138         /**
139          * @return - the timing resolution of the Slave - If the distance of ARDOURs transport
140          * to the slave becomes greater than the resolution, sound will stop
141          */
142         virtual nframes_t resolution() const = 0;
143
144         /**
145          * @return - when returning true, ARDOUR will wait for seekahead_distance() before transport
146          * starts rolling
147          */
148         virtual bool requires_seekahead () const = 0;
149
150         /**
151          * @return the number of frames that this slave wants to seek ahead. Relevant
152          * only if @func requires_seekahead() returns true.
153          */
154
155         virtual nframes64_t seekahead_distance() const { return 0; }
156
157         /**
158          * @return - when returning true, ARDOUR will use transport speed 1.0 no matter what
159          *           the slave returns
160          */
161         virtual bool is_always_synced() const { return false; }
162
163         /**
164          * @return - whether ARDOUR should use the slave speed without any adjustments
165          */
166         virtual bool give_slave_full_control_over_transport_speed() const { return false; }
167 };
168
169 /// We need this wrapper for testability, it's just too hard to mock up a session class
170 class ISlaveSessionProxy {
171   public:
172         virtual TempoMap& tempo_map()                 const   { return *((TempoMap *) 0); }
173         virtual nframes_t   frame_rate()                const   { return 0; }
174         virtual nframes64_t audible_frame ()            const   { return 0; }
175         virtual nframes64_t transport_frame ()          const   { return 0; }
176         virtual nframes_t   frames_since_cycle_start () const   { return 0; }
177         virtual nframes64_t frame_time ()               const   { return 0; }
178
179         virtual void request_locate (nframes64_t /*frame*/, bool with_roll = false) {
180                 (void) with_roll;
181         }
182         virtual void request_transport_speed (double /*speed*/)                   {}
183 };
184
185
186 /// The Session Proxy for use in real Ardour
187 class SlaveSessionProxy : public ISlaveSessionProxy {
188         Session&    session;
189
190   public:
191         SlaveSessionProxy(Session &s) : session(s) {}
192
193         TempoMap&   tempo_map()                 const;
194         nframes_t   frame_rate()                const;
195         nframes64_t audible_frame ()            const;
196         nframes64_t transport_frame ()          const;
197         nframes_t   frames_since_cycle_start () const;
198         nframes64_t frame_time ()               const;
199
200         void request_locate (nframes64_t frame, bool with_roll = false);
201         void request_transport_speed (double speed);
202 };
203
204 struct SafeTime {
205     volatile int guard1;
206     nframes64_t  position;
207     nframes64_t  timestamp;
208     double       speed;
209     volatile int guard2;
210     
211     SafeTime() {
212             guard1 = 0;
213             position = 0;
214             timestamp = 0;
215             speed = 0;
216             guard2 = 0;
217     }
218 };
219
220 class MTC_Slave : public Slave, public sigc::trackable {
221   public:
222         MTC_Slave (Session&, MIDI::Port&);
223         ~MTC_Slave ();
224
225         void rebind (MIDI::Port&);
226         bool speed_and_position (double&, nframes64_t&);
227
228         bool locked() const;
229         bool ok() const;
230         void handle_locate (const MIDI::byte*);
231
232         nframes_t resolution() const;
233         bool requires_seekahead () const { return true; }
234         nframes64_t seekahead_distance() const;
235         bool give_slave_full_control_over_transport_speed() const;
236
237   private:
238         Session&    session;
239         MIDI::Port* port;
240         std::vector<sigc::connection> connections;
241         bool        can_notify_on_unknown_rate;
242         PIController* pic;
243
244         SafeTime    current;
245         nframes_t   mtc_frame;               /* current time */
246         nframes_t   last_inbound_frame;      /* when we got it; audio clocked */
247         MIDI::byte  last_mtc_fps_byte;
248         nframes64_t window_begin;
249         nframes64_t window_end;
250         nframes64_t    last_mtc_timestamp;
251         nframes64_t    last_mtc_frame;
252         bool           did_reset_tc_format;
253         TimecodeFormat saved_tc_format;
254         size_t         speed_accumulator_size;
255         double*        speed_accumulator;
256         size_t         speed_accumulator_cnt;
257         bool           have_first_speed_accumulator;
258         double         average_speed;
259
260         void reset ();
261         void update_mtc_qtr (MIDI::Parser&, int, nframes_t);
262         void update_mtc_time (const MIDI::byte *, bool, nframes_t);
263         void update_mtc_status (MIDI::MTC_Status);
264         void read_current (SafeTime *) const;
265         void reset_window (nframes64_t);
266         bool outside_window (nframes64_t) const;
267         void process_apparent_speed (double);
268 };
269
270 class MIDIClock_Slave : public Slave, public sigc::trackable {
271   public:
272         MIDIClock_Slave (Session&, MIDI::Port&, int ppqn = 24);
273
274         /// Constructor for unit tests
275         MIDIClock_Slave (ISlaveSessionProxy* session_proxy, int ppqn = 24);
276         ~MIDIClock_Slave ();
277
278         void rebind (MIDI::Port&);
279         bool speed_and_position (double&, nframes64_t&);
280
281         bool locked() const;
282         bool ok() const;
283         bool starting() const;
284
285         nframes_t resolution() const;
286         bool requires_seekahead () const { return false; }
287         bool give_slave_full_control_over_transport_speed() const { return true; }
288
289         void set_bandwidth (double a_bandwith) { bandwidth = a_bandwith; }
290
291   private:
292         ISlaveSessionProxy* session;
293         MIDI::Port* port;
294         std::vector<sigc::connection> connections;
295
296         /// pulses per quarter note for one MIDI clock frame (default 24)
297         int         ppqn;
298
299         /// the duration of one ppqn in frame time
300         double      one_ppqn_in_frames;
301
302         /// the timestamp of the first MIDI clock message
303         nframes_t   first_timestamp;
304
305         /// the time stamp and should-be transport position of the last inbound MIDI clock message
306         nframes_t   last_timestamp;
307         double      should_be_position;
308
309         /// the number of midi clock messages received (zero-based)
310         /// since start
311         long midi_clock_count;
312
313         //the delay locked loop (DLL), see www.kokkinizita.net/papers/usingdll.pdf
314
315         /// time at the beginning of the MIDI clock frame
316         double t0;
317
318         /// calculated end of the MIDI clock frame
319         double t1;
320
321         /// loop error = real value - expected value
322         double e;
323
324         /// second order loop error
325         double e2;
326
327         /// DLL filter bandwidth
328         double bandwidth;
329
330         /// DLL filter coefficients
331         double b, c, omega;
332
333         void reset ();
334         void start (MIDI::Parser& parser, nframes64_t timestamp);
335         void contineu (MIDI::Parser& parser, nframes64_t timestamp);
336         void stop (MIDI::Parser& parser, nframes64_t timestamp);
337         void position (MIDI::Parser& parser, MIDI::byte* message, size_t size);
338         // we can't use continue because it is a C++ keyword
339         void calculate_one_ppqn_in_frames_at(nframes64_t time);
340         nframes64_t calculate_song_position(uint16_t song_position_in_sixteenth_notes);
341         void calculate_filter_coefficients();
342         void update_midi_clock (MIDI::Parser& parser, nframes64_t timestamp);
343         void read_current (SafeTime *) const;
344         bool stop_if_no_more_clock_events(nframes64_t& pos, nframes64_t now);
345
346         /// whether transport should be rolling
347         bool _started;
348
349         /// is true if the MIDI Start message has just been received until
350         /// the first MIDI Clock Event
351         bool _starting;
352 };
353
354 class JACK_Slave : public Slave
355 {
356   public:
357         JACK_Slave (jack_client_t*);
358         ~JACK_Slave ();
359
360         bool speed_and_position (double& speed, nframes64_t& pos);
361
362         bool starting() const { return _starting; }
363         bool locked() const;
364         bool ok() const;
365         nframes_t resolution() const { return 1; }
366         bool requires_seekahead () const { return false; }
367         void reset_client (jack_client_t* jack);
368         bool is_always_synced() const { return true; }
369
370   private:
371         jack_client_t* jack;
372         double speed;
373         bool _starting;
374 };
375
376 } /* namespace */
377
378 #endif /* __ardour_slave_h__ */