Optimize plugin-processing for non-automated params
[ardour.git] / libs / ardour / ardour / transport_master.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_transport_master_h__
21 #define __ardour_transport_master_h__
22
23 #include <vector>
24
25 #include <boost/optional.hpp>
26 #include <boost/atomic.hpp>
27
28 #include <glibmm/threads.h>
29 #include <glibmm/timer.h>
30
31 #include <ltc.h>
32
33 #include "pbd/i18n.h"
34 #include "pbd/properties.h"
35 #include "pbd/signals.h"
36 #include "pbd/stateful.h"
37
38 #include "temporal/time.h"
39
40 #include "ardour/libardour_visibility.h"
41 #include "ardour/region.h" /* for Properties::locked */
42 #include "ardour/types.h"
43
44 #include "midi++/parser.h"
45 #include "midi++/types.h"
46
47 /* used for delta_string(): */
48 #define PLUSMINUS(A) ( ((A)<0) ? "-" : (((A)>0) ? "+" : "\u00B1") )
49 #define LEADINGZERO(A) ( (A)<10 ? "   " : (A)<100 ? "  " : (A)<1000 ? " " : "" )
50
51 namespace ARDOUR {
52
53 class TempoMap;
54 class Session;
55 class AudioEngine;
56 class Location;
57 class MidiPort;
58 class AudioPort;
59 class Port;
60
61 namespace Properties {
62         LIBARDOUR_API extern PBD::PropertyDescriptor<bool> fr2997;
63         LIBARDOUR_API extern PBD::PropertyDescriptor<bool> collect;
64         LIBARDOUR_API extern PBD::PropertyDescriptor<bool> connected;
65         LIBARDOUR_API extern PBD::PropertyDescriptor<bool> sclock_synced;
66         LIBARDOUR_API extern PBD::PropertyDescriptor<ARDOUR::TransportRequestType> allowed_transport_requests;
67 };
68
69 struct LIBARDOUR_API SafeTime {
70
71         /* This object uses memory fences to provide psuedo-atomic updating of
72          * non-atomic data. If after reading guard1 and guard2 with correct
73          * memory fencing they have the same value, then we know that the other
74          * members are all internally consistent.
75          *
76          * Traditionally, one might do this with a mutex, but this object
77          * provides lock-free write update. The reader might block while
78          * waiting for consistency, but this is extraordinarily unlikely. In
79          * this sense, the design is similar to a spinlock.
80          *
81          * any update starts by incrementing guard1, with a memory fence to
82          * ensure no reordering of this w.r.t later operations.
83          *
84          * then we update the "non-atomic" data members.
85          *
86          * then we update guard2, with another memory fence to prevent
87          * reordering.
88          *
89          * ergo, if guard1 == guard2, the update of the non-atomic members is
90          * complete and the values stored there are consistent.
91          */
92
93         boost::atomic<int> guard1;
94         samplepos_t        position;
95         samplepos_t        timestamp;
96         double             speed;
97         boost::atomic<int> guard2;
98
99         SafeTime() {
100                 guard1.store (0);
101                 position = 0;
102                 timestamp = 0;
103                 speed = 0;
104                 guard2.store (0);
105         }
106
107         void reset () {
108                 guard1.store (0);
109                 position = 0;
110                 timestamp  = 0;
111                 speed = 0;
112                 guard2.store (0);
113         }
114
115         void update (samplepos_t p, samplepos_t t, double s) {
116                 guard1.fetch_add (1, boost::memory_order_acquire);
117                 position = p;
118                 timestamp = t;
119                 speed = s;
120                 guard2.fetch_add (1, boost::memory_order_acquire);
121         }
122
123         void safe_read (SafeTime& dst) const {
124                 int tries = 0;
125
126                 do {
127                         if (tries == 10) {
128                                 std::cerr << X_("SafeTime: atomic read of current time failed, sleeping!") << std::endl;
129                                 Glib::usleep (20);
130                                 tries = 0;
131                         }
132                         dst.guard1.store (guard1.load (boost::memory_order_seq_cst), boost::memory_order_seq_cst);
133                         dst.position = position;
134                         dst.timestamp = timestamp;
135                         dst.speed = speed;
136                         dst.guard2.store (guard2.load (boost::memory_order_seq_cst), boost::memory_order_seq_cst);
137                         tries++;
138
139                 } while (dst.guard1.load (boost::memory_order_seq_cst) != dst.guard2.load (boost::memory_order_seq_cst));
140         }
141 };
142
143 /**
144  * @class TransportMaster
145  *
146  * @brief The TransportMaster interface can be used to sync ARDOURs tempo to an external source
147  * like MTC, MIDI Clock, etc. as well as a single internal pseudo master we
148  * call "UI" because it is controlled from any of the user interfaces for
149  * Ardour (GUI, control surfaces, OSC, etc.)
150  *
151  */
152 class LIBARDOUR_API TransportMaster : public PBD::Stateful {
153   public:
154
155         TransportMaster (SyncSource t, std::string const & name);
156         virtual ~TransportMaster();
157
158         static boost::shared_ptr<TransportMaster> factory (SyncSource, std::string const &, bool removeable);
159         static boost::shared_ptr<TransportMaster> factory (XMLNode const &);
160
161         virtual void pre_process (pframes_t nframes, samplepos_t now, boost::optional<samplepos_t>) = 0;
162
163         /**
164          * This is the most important function to implement:
165          * Each process cycle, Session::follow_slave will call this method.
166          *  and after the method call they should
167          *
168          * Session::follow_slave will then try to follow the given
169          * <em>position</em> using a delay locked loop (DLL),
170          * starting with the first given transport speed.
171          * If the values of speed and position contradict each other,
172          * ARDOUR will always follow the position and disregard the speed.
173          * Although, a correct speed is important so that ARDOUR
174          * can sync to the master time source quickly.
175          *
176          * For background information on delay locked loops,
177          * see http://www.kokkinizita.net/papers/usingdll.pdf
178          *
179          * The method has the following precondition:
180          * <ul>
181          *   <li>
182          *       TransportMaster::ok() should return true, otherwise playback will stop
183          *       immediately and the method will not be called
184          *   </li>
185          *   <li>
186          *     when the references speed and position are passed into the TransportMaster
187          *     they are uninitialized
188          *   </li>
189          * </ul>
190          *
191          * After the method call the following postconditions should be met:
192          * <ul>
193          *    <li>
194          *       The first position value on transport start should be 0,
195          *       otherwise ARDOUR will try to locate to the new position
196          *       rather than move to it
197          *    </li>
198          *    <li>
199          *      the references speed and position should be assigned
200          *      to the TransportMasters current requested transport speed
201          *      and transport position.
202          *    </li>
203          *   <li>
204          *     TransportMaster::resolution() should be greater than the maximum distance of
205          *     ARDOURs transport position to the slaves requested transport position.
206          *   </li>
207          *   <li>TransportMaster::locked() should return true, otherwise Session::no_roll will be called</li>
208          *   <li>TransportMaster::starting() should be false, otherwise the transport will not move until it becomes true</li>   *
209          * </ul>
210          *
211          * @param speed - The transport speed requested
212          * @param position - The transport position requested
213          * @return - The return value is currently ignored (see Session::follow_slave)
214          */
215         virtual bool speed_and_position (double& speed, samplepos_t& position, samplepos_t & lp, samplepos_t & when, samplepos_t now);
216
217         /**
218          * reports to ARDOUR whether the TransportMaster is currently synced to its external
219          * time source.
220          *
221          * @return - when returning false, the transport will stop rolling
222          */
223         virtual bool locked() const = 0;
224
225         /**
226          * reports to ARDOUR whether the slave is in a sane state
227          *
228          * @return - when returning false, the transport will be stopped and the slave
229          * disconnected from ARDOUR.
230          */
231         virtual bool ok() const = 0;
232
233         /**
234          * reports to ARDOUR whether the slave is in the process of starting
235          * to roll
236          *
237          * @return - when returning false, transport will not move until this method returns true
238          */
239         virtual bool starting() const { return false; }
240
241         /**
242          * @return - the timing resolution of the TransportMaster - If the distance of ARDOURs transport
243          * to the slave becomes greater than the resolution, sound will stop
244          */
245         virtual samplecnt_t resolution() const = 0;
246
247         /**
248          * @return - the expected update interval for the data source used by
249          * this transport master. Even if the data is effectively continuous,
250          * this number indicates how long it is between changes to the known
251          * position of the master.
252          */
253         virtual samplecnt_t update_interval() const = 0;
254
255         /**
256          * @return - when returning true, ARDOUR will wait for seekahead_distance() before transport
257          * starts rolling
258          */
259         virtual bool requires_seekahead () const = 0;
260
261         /**
262          * @return the number of samples that this slave wants to seek ahead. Relevant
263          * only if requires_seekahead() returns true.
264          */
265
266         virtual samplecnt_t seekahead_distance() const { return 0; }
267
268         /**
269          * @return - when returning true, ARDOUR will use transport speed 1.0 no matter what
270          *           the slave returns
271          */
272         virtual bool sample_clock_synced() const { return _sclock_synced; }
273         virtual void set_sample_clock_synced (bool);
274
275         /**
276          * @return - current time-delta between engine and sync-source
277          */
278         virtual std::string delta_string() const { return ""; }
279
280         sampleoffset_t current_delta() const { return _current_delta; }
281
282         /* this is intended to be used by a UI and polled from a timeout. it should
283            return a string describing the current position of the TC source. it
284            should NOT do any computation, but should use a cached value
285            of the TC source position.
286         */
287         virtual std::string position_string() const = 0;
288
289         virtual bool can_loop() const { return false; }
290
291         virtual Location* loop_location() const { return 0; }
292         bool has_loop() const { return loop_location() != 0; }
293
294         SyncSource type() const { return _type; }
295         TransportRequestSource request_type() const {
296                 switch (_type) {
297                 case Engine: /* also JACK */
298                         return TRS_Engine;
299                 case MTC:
300                         return TRS_MTC;
301                 case LTC:
302                         return TRS_LTC;
303                 case MIDIClock:
304                         break;
305                 }
306                 return TRS_MIDIClock;
307         }
308
309         std::string name() const { return _name; }
310         void set_name (std::string const &);
311
312         int set_state (XMLNode const &, int);
313         XMLNode& get_state();
314
315         static const std::string state_node_name;
316         static void make_property_quarks ();
317
318         virtual void set_session (Session*);
319
320         boost::shared_ptr<Port> port() const { return _port; }
321
322         bool check_collect();
323         virtual void set_collect (bool);
324         bool collect() const { return _collect; }
325
326         /* called whenever the manager starts collecting (processing) this
327            transport master. Typically will re-initialize any state used to
328            deal with incoming data.
329         */
330         virtual void init() = 0;
331
332         virtual void check_backend() {}
333         virtual bool allow_request (TransportRequestSource, TransportRequestType) const;
334
335         TransportRequestType request_mask() const { return _request_mask; }
336         void set_request_mask (TransportRequestType);
337
338         void get_current (double&, samplepos_t&, samplepos_t);
339
340         /* this is set at construction, and not changeable later, so it is not
341          * a property
342          */
343
344         bool removeable () const { return _removeable; }
345         void set_removeable (bool yn) { _removeable = yn; }
346
347         std::string display_name (bool sh/*ort*/ = true) const;
348
349   protected:
350         SyncSource      _type;
351         PBD::Property<std::string>   _name;
352         Session*        _session;
353         sampleoffset_t  _current_delta;
354         bool            _pending_collect;
355         bool            _removeable;
356         PBD::Property<TransportRequestType> _request_mask; /* lists transport requests still accepted when we're in control */
357         PBD::Property<bool> _locked;
358         PBD::Property<bool> _sclock_synced;
359         PBD::Property<bool> _collect;
360         PBD::Property<bool> _connected;
361
362         SafeTime current;
363
364         /* DLL - chase incoming data */
365
366         int    transport_direction;
367         int    dll_initstate;
368
369         double t0;
370         double t1;
371         double e2;
372         double b, c;
373
374         boost::shared_ptr<Port>  _port;
375
376         PBD::ScopedConnection port_connection;
377         bool connection_handler (boost::weak_ptr<ARDOUR::Port>, std::string name1, boost::weak_ptr<ARDOUR::Port>, std::string name2, bool yn);
378
379         PBD::ScopedConnection backend_connection;
380
381         virtual void register_properties ();
382 };
383
384 /** a helper class for any TransportMaster that receives its input via a MIDI
385  * port
386  */
387 class LIBARDOUR_API TransportMasterViaMIDI {
388   public:
389         boost::shared_ptr<MidiPort> midi_port() const { return _midi_port; }
390         boost::shared_ptr<Port> create_midi_port (std::string const & port_name);
391
392   protected:
393         TransportMasterViaMIDI () {};
394
395         MIDI::Parser                 parser;
396         boost::shared_ptr<MidiPort> _midi_port;
397 };
398
399 class LIBARDOUR_API TimecodeTransportMaster : public TransportMaster {
400   public:
401         TimecodeTransportMaster (std::string const & name, SyncSource type);
402
403         virtual Timecode::TimecodeFormat apparent_timecode_format() const = 0;
404         samplepos_t        timecode_offset;
405         bool              timecode_negative_offset;
406
407         bool fr2997() const { return _fr2997; }
408         void set_fr2997 (bool);
409
410   protected:
411         void register_properties ();
412
413   private:
414         PBD::Property<bool> _fr2997;
415 };
416
417 class LIBARDOUR_API MTC_TransportMaster : public TimecodeTransportMaster, public TransportMasterViaMIDI {
418   public:
419         MTC_TransportMaster (std::string const &);
420         ~MTC_TransportMaster ();
421
422         void set_session (Session*);
423
424         void pre_process (pframes_t nframes, samplepos_t now, boost::optional<samplepos_t>);
425
426         bool locked() const;
427         bool ok() const;
428         void handle_locate (const MIDI::byte*);
429
430         samplecnt_t update_interval () const;
431         samplecnt_t resolution () const;
432         bool requires_seekahead () const { return false; }
433         samplecnt_t seekahead_distance() const;
434         void init ();
435
436         Timecode::TimecodeFormat apparent_timecode_format() const;
437         std::string position_string() const;
438         std::string delta_string() const;
439
440   private:
441         PBD::ScopedConnectionList port_connections;
442         PBD::ScopedConnection     config_connection;
443         bool        can_notify_on_unknown_rate;
444
445         static const int sample_tolerance;
446
447         samplepos_t    mtc_frame;               /* current time */
448         double         mtc_frame_dll;
449         samplepos_t    last_inbound_frame;      /* when we got it; audio clocked */
450         MIDI::byte     last_mtc_fps_byte;
451         samplepos_t    window_begin;
452         samplepos_t    window_end;
453         samplepos_t    first_mtc_timestamp;
454         bool           did_reset_tc_format;
455         Timecode::TimecodeFormat saved_tc_format;
456         Glib::Threads::Mutex    reset_lock;
457         uint32_t       reset_pending;
458         bool           reset_position;
459         int            transport_direction;
460         int            busy_guard1;
461         int            busy_guard2;
462
463         double         speedup_due_to_tc_mismatch;
464         double         quarter_frame_duration;
465         Timecode::TimecodeFormat mtc_timecode;
466         Timecode::TimecodeFormat a3e_timecode;
467         Timecode::Time timecode;
468         bool           printed_timecode_warning;
469
470         void reset (bool with_pos);
471         void queue_reset (bool with_pos);
472         void maybe_reset ();
473
474         void update_mtc_qtr (MIDI::Parser&, int, samplepos_t);
475         void update_mtc_time (const MIDI::byte *, bool, samplepos_t);
476         void update_mtc_status (MIDI::MTC_Status);
477         void reset_window (samplepos_t);
478         bool outside_window (samplepos_t) const;
479         void init_mtc_dll(samplepos_t, double);
480         void parse_timecode_offset();
481         void parameter_changed(std::string const & p);
482 };
483
484 class LIBARDOUR_API LTC_TransportMaster : public TimecodeTransportMaster {
485 public:
486         LTC_TransportMaster (std::string const &);
487         ~LTC_TransportMaster ();
488
489         void set_session (Session*);
490
491         void pre_process (pframes_t nframes, samplepos_t now, boost::optional<samplepos_t>);
492
493         bool locked() const;
494         bool ok() const;
495
496         samplecnt_t update_interval () const;
497         samplecnt_t resolution () const;
498         bool requires_seekahead () const { return false; }
499         samplecnt_t seekahead_distance () const { return 0; }
500         void init ();
501
502         Timecode::TimecodeFormat apparent_timecode_format() const;
503         std::string position_string() const;
504         std::string delta_string() const;
505
506   private:
507         void parse_ltc(const pframes_t, const Sample* const, const samplecnt_t);
508         void process_ltc(samplepos_t const);
509         void init_dll (samplepos_t, int32_t);
510         bool detect_discontinuity(LTCFrameExt *, int, bool);
511         bool detect_ltc_fps(int, bool);
512         bool equal_ltc_sample_time(LTCFrame *a, LTCFrame *b);
513         void reset (bool with_ts = true);
514         void resync_xrun();
515         void resync_latency();
516         void parse_timecode_offset();
517         void parameter_changed(std::string const & p);
518
519         bool           did_reset_tc_format;
520         Timecode::TimecodeFormat saved_tc_format;
521
522         LTCDecoder *   decoder;
523         double         samples_per_ltc_frame;
524         Timecode::Time timecode;
525         LTCFrameExt    prev_sample;
526         bool           fps_detected;
527
528         samplecnt_t    monotonic_cnt;
529         int            delayedlocked;
530
531         int            ltc_detect_fps_cnt;
532         int            ltc_detect_fps_max;
533         bool           printed_timecode_warning;
534         bool           sync_lock_broken;
535         Timecode::TimecodeFormat ltc_timecode;
536         Timecode::TimecodeFormat a3e_timecode;
537         double         samples_per_timecode_frame;
538
539         PBD::ScopedConnectionList port_connections;
540         PBD::ScopedConnection     config_connection;
541         LatencyRange  ltc_slave_latency;
542 };
543
544 class LIBARDOUR_API MIDIClock_TransportMaster : public TransportMaster, public TransportMasterViaMIDI {
545   public:
546         MIDIClock_TransportMaster (std::string const & name, int ppqn = 24);
547
548         /// Constructor for unit tests
549         ~MIDIClock_TransportMaster ();
550
551         void set_session (Session*);
552
553         void pre_process (pframes_t nframes, samplepos_t now, boost::optional<samplepos_t>);
554
555         void rebind (MidiPort&);
556
557         bool locked() const;
558         bool ok() const;
559         bool starting() const;
560
561         samplecnt_t update_interval () const;
562         samplecnt_t resolution () const;
563         bool requires_seekahead () const { return false; }
564         void init ();
565
566         std::string position_string() const;
567         std::string delta_string() const;
568
569         float bpm() const { return _bpm; }
570
571   protected:
572         PBD::ScopedConnectionList port_connections;
573
574         /// pulses per quarter note for one MIDI clock sample (default 24)
575         int         ppqn;
576
577         /// the duration of one ppqn in sample time
578         double      one_ppqn_in_samples;
579
580         /// the timestamp of the first MIDI clock message
581         samplepos_t  first_timestamp;
582
583         /// the time stamp and should-be transport position of the last inbound MIDI clock message
584         samplepos_t  last_timestamp;
585         double      should_be_position;
586
587         /// the number of midi clock messages received (zero-based)
588         /// since start
589         long midi_clock_count;
590
591         /// a DLL to track MIDI clock
592
593         double _speed;
594         bool _running;
595         double _bpm;
596
597         void reset ();
598         void start (MIDI::Parser& parser, samplepos_t timestamp);
599         void contineu (MIDI::Parser& parser, samplepos_t timestamp);
600         void stop (MIDI::Parser& parser, samplepos_t timestamp);
601         void position (MIDI::Parser& parser, MIDI::byte* message, size_t size, samplepos_t timestamp);
602         // we can't use continue because it is a C++ keyword
603         void calculate_one_ppqn_in_samples_at(samplepos_t time);
604         samplepos_t calculate_song_position(uint16_t song_position_in_sixteenth_notes);
605         void calculate_filter_coefficients (double qpm);
606         void update_midi_clock (MIDI::Parser& parser, samplepos_t timestamp);
607 };
608
609 class LIBARDOUR_API Engine_TransportMaster : public TransportMaster
610 {
611   public:
612         Engine_TransportMaster (AudioEngine&);
613         ~Engine_TransportMaster  ();
614
615         void pre_process (pframes_t nframes, samplepos_t now,  boost::optional<samplepos_t>);
616         bool speed_and_position (double& speed, samplepos_t& pos, samplepos_t &, samplepos_t &, samplepos_t);
617
618         bool starting() const { return _starting; }
619         bool locked() const;
620         bool ok() const;
621         samplecnt_t update_interval () const;
622         samplecnt_t resolution () const { return 1; }
623         bool requires_seekahead () const { return false; }
624         bool sample_clock_synced() const { return true; }
625         void init ();
626         void check_backend();
627         bool allow_request (TransportRequestSource, TransportRequestType) const;
628
629         std::string position_string() const;
630         std::string delta_string() const;
631
632   private:
633         AudioEngine& engine;
634         bool _starting;
635 };
636
637 } /* namespace */
638
639 #endif /* __ardour_transport_master_h__ */