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