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