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