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