Merge branch 'master' into windows+cc
[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 #include "ltc/ltc.h"
33
34 #include "ardour/types.h"
35 #include "midi++/parser.h"
36 #include "midi++/types.h"
37
38
39 /* used for approximate_current_delta(): */
40 #define PLUSMINUS(A) ( ((A)<0) ? "-" : (((A)>0) ? "+" : "\u00B1") )
41 #define LEADINGZERO(A) ( (A)<10 ? "   " : (A)<100 ? "  " : (A)<1000 ? " " : "" )
42
43 namespace ARDOUR {
44
45 class TempoMap;
46 class Session;
47 class AudioEngine;
48 class MidiPort;
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          * @return - current time-delta between engine and sync-source
177          */
178         virtual std::string approximate_current_delta() const { return ""; }
179
180 };
181
182 /// We need this wrapper for testability, it's just too hard to mock up a session class
183 class ISlaveSessionProxy {
184   public:
185         virtual ~ISlaveSessionProxy() {}
186         virtual TempoMap&  tempo_map()                 const   { return *((TempoMap *) 0); }
187         virtual framecnt_t frame_rate()                const   { return 0; }
188         virtual framepos_t audible_frame ()            const   { return 0; }
189         virtual framepos_t transport_frame ()          const   { return 0; }
190         virtual pframes_t  frames_since_cycle_start () const   { return 0; }
191         virtual framepos_t frame_time ()               const   { return 0; }
192
193         virtual void request_locate (framepos_t /*frame*/, bool with_roll = false) {
194                 (void) with_roll;
195         }
196         virtual void request_transport_speed (double /*speed*/)                   {}
197 };
198
199
200 /// The Session Proxy for use in real Ardour
201 class SlaveSessionProxy : public ISlaveSessionProxy {
202         Session&    session;
203
204   public:
205         SlaveSessionProxy(Session &s) : session(s) {}
206
207         TempoMap&  tempo_map()                 const;
208         framecnt_t frame_rate()                const;
209         framepos_t audible_frame ()            const;
210         framepos_t transport_frame ()          const;
211         pframes_t  frames_since_cycle_start () const;
212         framepos_t frame_time ()               const;
213
214         void request_locate (framepos_t frame, bool with_roll = false);
215         void request_transport_speed (double speed);
216 };
217
218 struct SafeTime {
219         volatile int guard1;
220         framepos_t   position;
221         framepos_t   timestamp;
222         double       speed;
223         volatile int guard2;
224
225         SafeTime() {
226                 guard1 = 0;
227                 position = 0;
228                 timestamp = 0;
229                 speed = 0;
230                 guard2 = 0;
231         }
232 };
233
234 class TimecodeSlave : public Slave {
235   public:
236     TimecodeSlave () {}
237
238     virtual Timecode::TimecodeFormat apparent_timecode_format() const = 0;
239
240     /* this is intended to be used by a UI and polled from a timeout. it should
241        return a string describing the current position of the TC source. it
242        should NOT do any computation, but should use a cached value
243        of the TC source position.
244     */
245     virtual std::string approximate_current_position() const = 0;
246
247     framepos_t        timecode_offset;
248     bool              timecode_negative_offset;
249 };
250
251 class MTC_Slave : public TimecodeSlave {
252   public:
253         MTC_Slave (Session&, MidiPort&);
254         ~MTC_Slave ();
255
256         void rebind (MidiPort&);
257         bool speed_and_position (double&, framepos_t&);
258
259         bool locked() const;
260         bool ok() const;
261         void handle_locate (const MIDI::byte*);
262
263         framecnt_t resolution () const;
264         bool requires_seekahead () const { return false; }
265         framecnt_t seekahead_distance() const;
266         bool give_slave_full_control_over_transport_speed() const;
267
268         Timecode::TimecodeFormat apparent_timecode_format() const;
269         std::string approximate_current_position() const;
270         std::string approximate_current_delta() const;
271
272   private:
273         Session&    session;
274         MidiPort*   port;
275         PBD::ScopedConnectionList port_connections;
276         PBD::ScopedConnection     config_connection;
277         bool        can_notify_on_unknown_rate;
278
279         static const int frame_tolerance;
280
281         SafeTime       current;
282         framepos_t     mtc_frame;               /* current time */
283         double         mtc_frame_dll;
284         framepos_t     last_inbound_frame;      /* when we got it; audio clocked */
285         MIDI::byte     last_mtc_fps_byte;
286         framepos_t     window_begin;
287         framepos_t     window_end;
288         framepos_t     first_mtc_timestamp;
289         bool           did_reset_tc_format;
290         Timecode::TimecodeFormat saved_tc_format;
291         Glib::Threads::Mutex    reset_lock;
292         uint32_t       reset_pending;
293         bool           reset_position;
294         int            transport_direction;
295         int            busy_guard1;
296         int            busy_guard2;
297
298         double         speedup_due_to_tc_mismatch;
299         double         quarter_frame_duration;
300         Timecode::TimecodeFormat mtc_timecode;
301         Timecode::TimecodeFormat a3e_timecode;
302         Timecode::Time timecode;
303         bool           printed_timecode_warning;
304         frameoffset_t  current_delta;
305
306         /* DLL - chase MTC */
307         double t0; ///< time at the beginning of the MTC quater frame
308         double t1; ///< calculated end of the MTC quater frame
309         double e2; ///< second order loop error
310         double b, c, omega; ///< DLL filter coefficients
311
312         /* DLL - sync engine */
313         int    engine_dll_initstate;
314         double te0; ///< time at the beginning of the engine process
315         double te1; ///< calculated sync time
316         double ee2; ///< second order loop error
317         double be, ce, oe; ///< DLL filter coefficients
318
319         void reset (bool with_pos);
320         void queue_reset (bool with_pos);
321         void maybe_reset ();
322
323         void update_mtc_qtr (MIDI::Parser&, int, framepos_t);
324         void update_mtc_time (const MIDI::byte *, bool, framepos_t);
325         void update_mtc_status (MIDI::MTC_Status);
326         void read_current (SafeTime *) const;
327         void reset_window (framepos_t);
328         bool outside_window (framepos_t) const;
329         void init_mtc_dll(framepos_t, double);
330         void init_engine_dll (framepos_t, framepos_t);
331         void parse_timecode_offset();
332         void parameter_changed(std::string const & p);
333 };
334
335 class LTC_Slave : public TimecodeSlave {
336 public:
337         LTC_Slave (Session&);
338         ~LTC_Slave ();
339
340         bool speed_and_position (double&, framepos_t&);
341
342         bool locked() const;
343         bool ok() const;
344
345         framecnt_t resolution () const;
346         bool requires_seekahead () const { return false; }
347         framecnt_t seekahead_distance () const { return 0; }
348         bool give_slave_full_control_over_transport_speed() const { return true; }
349
350         Timecode::TimecodeFormat apparent_timecode_format() const;
351         std::string approximate_current_position() const;
352         std::string approximate_current_delta() const;
353
354   private:
355         void parse_ltc(const pframes_t, const Sample* const, const framecnt_t);
356         void process_ltc(framepos_t const);
357         void init_engine_dll (framepos_t, int32_t);
358         bool detect_discontinuity(LTCFrameExt *, int, bool);
359         bool detect_ltc_fps(int, bool);
360         bool equal_ltc_frame_time(LTCFrame *a, LTCFrame *b);
361         void reset();
362         void resync_xrun();
363         void resync_latency();
364         void parse_timecode_offset();
365         void parameter_changed(std::string const & p);
366
367         Session&       session;
368         bool           did_reset_tc_format;
369         Timecode::TimecodeFormat saved_tc_format;
370
371         LTCDecoder *   decoder;
372         double         frames_per_ltc_frame;
373         Timecode::Time timecode;
374         LTCFrameExt    prev_frame;
375         bool           fps_detected;
376
377         framecnt_t     monotonic_cnt;
378         framecnt_t     last_timestamp;
379         framecnt_t     last_ltc_frame;
380         double         ltc_speed;
381         frameoffset_t  current_delta;
382         int            delayedlocked;
383
384         int            ltc_detect_fps_cnt;
385         int            ltc_detect_fps_max;
386         bool           printed_timecode_warning;
387         Timecode::TimecodeFormat ltc_timecode;
388         Timecode::TimecodeFormat a3e_timecode;
389
390         PBD::ScopedConnectionList port_connections;
391         PBD::ScopedConnection     config_connection;
392         LatencyRange  ltc_slave_latency;
393
394         /* DLL - chase LTC */
395         int    transport_direction;
396         int    engine_dll_initstate;
397         double t0; ///< time at the beginning of the MTC quater frame
398         double t1; ///< calculated end of the MTC quater frame
399         double e2; ///< second order loop error
400         double b, c; ///< DLL filter coefficients
401 };
402
403 class MIDIClock_Slave : public Slave {
404   public:
405         MIDIClock_Slave (Session&, MidiPort&, int ppqn = 24);
406
407         /// Constructor for unit tests
408         MIDIClock_Slave (ISlaveSessionProxy* session_proxy = 0, int ppqn = 24);
409         ~MIDIClock_Slave ();
410
411         void rebind (MidiPort&);
412         bool speed_and_position (double&, framepos_t&);
413
414         bool locked() const;
415         bool ok() const;
416         bool starting() const;
417
418         framecnt_t resolution () const;
419         bool requires_seekahead () const { return false; }
420         bool give_slave_full_control_over_transport_speed() const { return true; }
421
422         void set_bandwidth (double a_bandwith) { bandwidth = a_bandwith; }
423         std::string approximate_current_delta() const;
424
425   protected:
426         ISlaveSessionProxy* session;
427         PBD::ScopedConnectionList port_connections;
428
429         /// pulses per quarter note for one MIDI clock frame (default 24)
430         int         ppqn;
431
432         /// the duration of one ppqn in frame time
433         double      one_ppqn_in_frames;
434
435         /// the timestamp of the first MIDI clock message
436         framepos_t  first_timestamp;
437
438         /// the time stamp and should-be transport position of the last inbound MIDI clock message
439         framepos_t  last_timestamp;
440         double      should_be_position;
441
442         /// the number of midi clock messages received (zero-based)
443         /// since start
444         long midi_clock_count;
445
446         //the delay locked loop (DLL), see www.kokkinizita.net/papers/usingdll.pdf
447
448         /// time at the beginning of the MIDI clock frame
449         double t0;
450
451         /// calculated end of the MIDI clock frame
452         double t1;
453
454         /// loop error = real value - expected value
455         double e;
456
457         /// second order loop error
458         double e2;
459
460         /// DLL filter bandwidth
461         double bandwidth;
462
463         /// DLL filter coefficients
464         double b, c, omega;
465
466         frameoffset_t  current_delta;
467
468         void reset ();
469         void start (MIDI::Parser& parser, framepos_t timestamp);
470         void contineu (MIDI::Parser& parser, framepos_t timestamp);
471         void stop (MIDI::Parser& parser, framepos_t timestamp);
472         void position (MIDI::Parser& parser, MIDI::byte* message, size_t size);
473         // we can't use continue because it is a C++ keyword
474         void calculate_one_ppqn_in_frames_at(framepos_t time);
475         framepos_t calculate_song_position(uint16_t song_position_in_sixteenth_notes);
476         void calculate_filter_coefficients();
477         void update_midi_clock (MIDI::Parser& parser, framepos_t timestamp);
478         void read_current (SafeTime *) const;
479         bool stop_if_no_more_clock_events(framepos_t& pos, framepos_t now);
480
481         /// whether transport should be rolling
482         bool _started;
483
484         /// is true if the MIDI Start message has just been received until
485         /// the first MIDI Clock Event
486         bool _starting;
487 };
488
489 class Engine_Slave : public Slave
490 {
491   public:
492         Engine_Slave (AudioEngine&);
493         ~Engine_Slave ();
494
495         bool speed_and_position (double& speed, framepos_t& pos);
496
497         bool starting() const { return _starting; }
498         bool locked() const;
499         bool ok() const;
500         framecnt_t resolution () const { return 1; }
501         bool requires_seekahead () const { return false; }
502         bool is_always_synced() const { return true; }
503
504   private:
505         AudioEngine& engine;
506         double speed;
507         bool _starting;
508 };
509
510 } /* namespace */
511
512 #endif /* __ardour_slave_h__ */