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