2 Copyright (C) 2002 Paul Davis
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.
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.
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.
20 #ifndef __ardour_slave_h__
21 #define __ardour_slave_h__
25 #include <glibmm/threads.h>
27 #include <jack/jack.h>
29 #include "pbd/signals.h"
31 #include "timecode/time.h"
33 #include "ardour/types.h"
34 #include "midi++/parser.h"
35 #include "midi++/types.h"
41 // used for approximate_current_delta():
42 #define PLUSMINUS(A) ( ((A)<0) ? "-" : (((A)>0) ? "+" : "\u00B1") )
56 * @brief The Slave interface can be used to sync ARDOURs tempo to an external source
57 * like MTC, MIDI Clock, etc.
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.
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
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.
83 * For background information on delay locked loops,
84 * see http://www.kokkinizita.net/papers/usingdll.pdf
86 * The method has the following precondition:
89 * Slave::ok() should return true, otherwise playback will stop
90 * immediately and the method will not be called
93 * when the references speed and position are passed into the Slave
94 * they are uninitialized
98 * After the method call the following postconditions should be met:
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
106 * the references speed and position should be assigned
107 * to the Slaves current requested transport speed
108 * and transport position.
111 * Slave::resolution() should be greater than the maximum distance of
112 * ARDOURs transport position to the slaves requested transport position.
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> *
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)
122 virtual bool speed_and_position (double& speed, framepos_t& position) = 0;
125 * reports to ARDOUR whether the Slave is currently synced to its external
128 * @return - when returning false, the transport will stop rolling
130 virtual bool locked() const = 0;
133 * reports to ARDOUR whether the slave is in a sane state
135 * @return - when returning false, the transport will be stopped and the slave
136 * disconnected from ARDOUR.
138 virtual bool ok() const = 0;
141 * reports to ARDOUR whether the slave is in the process of starting
144 * @return - when returning false, transport will not move until this method returns true
146 virtual bool starting() const { return false; }
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
152 virtual framecnt_t resolution() const = 0;
155 * @return - when returning true, ARDOUR will wait for seekahead_distance() before transport
158 virtual bool requires_seekahead () const = 0;
161 * @return the number of frames that this slave wants to seek ahead. Relevant
162 * only if requires_seekahead() returns true.
165 virtual framecnt_t seekahead_distance() const { return 0; }
168 * @return - when returning true, ARDOUR will use transport speed 1.0 no matter what
171 virtual bool is_always_synced() const { return false; }
174 * @return - whether ARDOUR should use the slave speed without any adjustments
176 virtual bool give_slave_full_control_over_transport_speed() const { return false; }
179 * @return - current time-delta between engine and sync-source
181 virtual std::string approximate_current_delta() const { return ""; }
185 /// We need this wrapper for testability, it's just too hard to mock up a session class
186 class ISlaveSessionProxy {
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; }
196 virtual void request_locate (framepos_t /*frame*/, bool with_roll = false) {
199 virtual void request_transport_speed (double /*speed*/) {}
203 /// The Session Proxy for use in real Ardour
204 class SlaveSessionProxy : public ISlaveSessionProxy {
208 SlaveSessionProxy(Session &s) : session(s) {}
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;
217 void request_locate (framepos_t frame, bool with_roll = false);
218 void request_transport_speed (double speed);
224 framepos_t timestamp;
237 class TimecodeSlave : public Slave {
241 virtual Timecode::TimecodeFormat apparent_timecode_format() const = 0;
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.
248 virtual std::string approximate_current_position() const = 0;
251 class MTC_Slave : public TimecodeSlave {
253 MTC_Slave (Session&, MIDI::Port&);
256 void rebind (MIDI::Port&);
257 bool speed_and_position (double&, framepos_t&);
261 void handle_locate (const MIDI::byte*);
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;
268 Timecode::TimecodeFormat apparent_timecode_format() const;
269 std::string approximate_current_position() const;
270 std::string approximate_current_delta() const;
275 PBD::ScopedConnectionList port_connections;
276 bool can_notify_on_unknown_rate;
278 static const int frame_tolerance;
281 framepos_t mtc_frame; /* current time */
282 framepos_t last_inbound_frame; /* when we got it; audio clocked */
283 MIDI::byte last_mtc_fps_byte;
284 framepos_t window_begin;
285 framepos_t window_end;
286 framepos_t first_mtc_timestamp;
287 bool did_reset_tc_format;
288 Timecode::TimecodeFormat saved_tc_format;
289 Glib::Threads::Mutex reset_lock;
290 uint32_t reset_pending;
292 int transport_direction;
296 double speedup_due_to_tc_mismatch;
297 double quarter_frame_duration;
298 Timecode::TimecodeFormat mtc_timecode;
299 Timecode::TimecodeFormat a3e_timecode;
300 Timecode::Time timecode;
301 bool printed_timecode_warning;
302 frameoffset_t current_delta;
304 /* DLL - chase MTC */
305 double t0; ///< time at the beginning of the MTC quater frame
306 double t1; ///< calculated end of the MTC quater frame
307 double e2; ///< second order loop error
308 double b, c, omega; ///< DLL filter coefficients
310 /* DLL - sync engine */
311 int engine_dll_initstate;
312 double te0; ///< time at the beginning of the engine process
313 double te1; ///< calculated sync time
314 double ee2; ///< second order loop error
315 double be, ce, oe; ///< DLL filter coefficients
317 void reset (bool with_pos);
318 void queue_reset (bool with_pos);
321 void update_mtc_qtr (MIDI::Parser&, int, framepos_t);
322 void update_mtc_time (const MIDI::byte *, bool, framepos_t);
323 void update_mtc_status (MIDI::MTC_Status);
324 void read_current (SafeTime *) const;
325 void reset_window (framepos_t);
326 bool outside_window (framepos_t) const;
327 void init_mtc_dll(framepos_t, double);
328 void init_engine_dll (framepos_t, framepos_t);
332 class LTC_Slave : public TimecodeSlave {
334 LTC_Slave (Session&);
337 bool speed_and_position (double&, framepos_t&);
342 framecnt_t resolution () const;
343 bool requires_seekahead () const { return false; }
344 framecnt_t seekahead_distance () const { return 0; }
345 bool give_slave_full_control_over_transport_speed() const { return true; }
347 Timecode::TimecodeFormat apparent_timecode_format() const;
348 std::string approximate_current_position() const;
349 std::string approximate_current_delta() const;
352 void parse_ltc(const jack_nframes_t, const jack_default_audio_sample_t * const, const framecnt_t);
353 void process_ltc(framepos_t const);
354 void init_engine_dll (framepos_t, int32_t);
355 bool detect_discontinuity(LTCFrameExt *, int, bool);
356 bool detect_ltc_fps(int, bool);
357 bool equal_ltc_frame_time(LTCFrame *a, LTCFrame *b);
360 void resync_latency();
363 bool did_reset_tc_format;
364 Timecode::TimecodeFormat saved_tc_format;
366 LTCDecoder * decoder;
367 double frames_per_ltc_frame;
368 Timecode::Time timecode;
369 LTCFrameExt prev_frame;
372 framecnt_t monotonic_cnt;
373 framecnt_t last_timestamp;
374 framecnt_t last_ltc_frame;
376 frameoffset_t current_delta;
379 int ltc_detect_fps_cnt;
380 int ltc_detect_fps_max;
381 bool printed_timecode_warning;
382 Timecode::TimecodeFormat ltc_timecode;
383 Timecode::TimecodeFormat a3e_timecode;
385 PBD::ScopedConnectionList port_connections;
386 jack_latency_range_t ltc_slave_latency;
388 /* DLL - chase LTC */
389 int transport_direction;
390 int engine_dll_initstate;
391 double t0; ///< time at the beginning of the MTC quater frame
392 double t1; ///< calculated end of the MTC quater frame
393 double e2; ///< second order loop error
394 double b, c; ///< DLL filter coefficients
398 class MIDIClock_Slave : public Slave {
400 MIDIClock_Slave (Session&, MIDI::Port&, int ppqn = 24);
402 /// Constructor for unit tests
403 MIDIClock_Slave (ISlaveSessionProxy* session_proxy = 0, int ppqn = 24);
406 void rebind (MIDI::Port&);
407 bool speed_and_position (double&, framepos_t&);
411 bool starting() const;
413 framecnt_t resolution () const;
414 bool requires_seekahead () const { return false; }
415 bool give_slave_full_control_over_transport_speed() const { return true; }
417 void set_bandwidth (double a_bandwith) { bandwidth = a_bandwith; }
418 std::string approximate_current_delta() const;
421 ISlaveSessionProxy* session;
423 PBD::ScopedConnectionList port_connections;
425 /// pulses per quarter note for one MIDI clock frame (default 24)
428 /// the duration of one ppqn in frame time
429 double one_ppqn_in_frames;
431 /// the timestamp of the first MIDI clock message
432 framepos_t first_timestamp;
434 /// the time stamp and should-be transport position of the last inbound MIDI clock message
435 framepos_t last_timestamp;
436 double should_be_position;
438 /// the number of midi clock messages received (zero-based)
440 long midi_clock_count;
442 //the delay locked loop (DLL), see www.kokkinizita.net/papers/usingdll.pdf
444 /// time at the beginning of the MIDI clock frame
447 /// calculated end of the MIDI clock frame
450 /// loop error = real value - expected value
453 /// second order loop error
456 /// DLL filter bandwidth
459 /// DLL filter coefficients
462 frameoffset_t current_delta;
465 void start (MIDI::Parser& parser, framepos_t timestamp);
466 void contineu (MIDI::Parser& parser, framepos_t timestamp);
467 void stop (MIDI::Parser& parser, framepos_t timestamp);
468 void position (MIDI::Parser& parser, MIDI::byte* message, size_t size);
469 // we can't use continue because it is a C++ keyword
470 void calculate_one_ppqn_in_frames_at(framepos_t time);
471 framepos_t calculate_song_position(uint16_t song_position_in_sixteenth_notes);
472 void calculate_filter_coefficients();
473 void update_midi_clock (MIDI::Parser& parser, framepos_t timestamp);
474 void read_current (SafeTime *) const;
475 bool stop_if_no_more_clock_events(framepos_t& pos, framepos_t now);
477 /// whether transport should be rolling
480 /// is true if the MIDI Start message has just been received until
481 /// the first MIDI Clock Event
485 class JACK_Slave : public Slave
488 JACK_Slave (jack_client_t*);
491 bool speed_and_position (double& speed, framepos_t& pos);
493 bool starting() const { return _starting; }
496 framecnt_t resolution () const { return 1; }
497 bool requires_seekahead () const { return false; }
498 void reset_client (jack_client_t* jack);
499 bool is_always_synced() const { return true; }
509 #endif /* __ardour_slave_h__ */