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