new transport slave/master implementation, libs/ edition
[ardour.git] / libs / ardour / transport_master_manager.cc
1 /*
2  * Copyright (C) 2018 Paul Davis (paul@linuxaudiosystems.com)
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, or (at your option)
7  * 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 Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  */
18
19 #include "pbd/i18n.h"
20
21 #include "ardour/audioengine.h"
22 #include "ardour/debug.h"
23 #include "ardour/disk_reader.h"
24 #include "ardour/session.h"
25 #include "ardour/transport_master_manager.h"
26
27 #if __cplusplus > 199711L
28 #define local_signbit(x) std::signbit (x)
29 #else
30 #define local_signbit(x) ((((__int64*)(&z))*) & 0x8000000000000000)
31 #endif
32
33 using namespace ARDOUR;
34 using namespace PBD;
35
36 const std::string TransportMasterManager::state_node_name = X_("TransportMasters");
37 TransportMasterManager* TransportMasterManager::_instance = 0;
38
39 TransportMasterManager::TransportMasterManager()
40         : _master_speed (0)
41         , _master_position (0)
42         , _current_master (0)
43         , _session (0)
44         , _master_invalid_this_cycle (false)
45         , master_dll_initstate (0)
46 {
47 }
48
49 TransportMasterManager::~TransportMasterManager ()
50 {
51         clear ();
52 }
53
54 int
55 TransportMasterManager::init ()
56 {
57         try {
58                 /* setup default transport masters. Most people will never need any
59                    others
60                 */
61                 add (Engine, X_("JACK Transport"));
62                 add (MTC, X_("MTC"));
63                 add (LTC, X_("LTC"));
64                 add (MIDIClock, X_("MIDI Clock"));
65         } catch (...) {
66                 return -1;
67         }
68
69         _current_master = _transport_masters.back();
70
71         return 0;
72 }
73
74 void
75 TransportMasterManager::set_session (Session* s)
76 {
77         /* Called by AudioEngine in process context, synchronously with it's
78          * own "adoption" of the Session. The call will occur before the first
79          * call to ::pre_process_transport_masters().
80          */
81
82         Glib::Threads::RWLock::ReaderLock lm (lock);
83
84         config_connection.disconnect ();
85
86         _session = s;
87
88         for (TransportMasters::iterator tm = _transport_masters.begin(); tm != _transport_masters.end(); ++tm) {
89                 (*tm)->set_session (s);
90         }
91
92         if (_session) {
93                 _session->config.ParameterChanged.connect_same_thread (config_connection, boost::bind (&TransportMasterManager::parameter_changed, this, _1));
94         }
95
96 }
97
98 void
99 TransportMasterManager::parameter_changed (std::string const & what)
100 {
101         if (what == "external-sync") {
102                 if (!_session->config.get_external_sync()) {
103                         /* disabled */
104                         DiskReader::set_no_disk_output (false);
105                 }
106         }
107 }
108
109 TransportMasterManager&
110 TransportMasterManager::instance()
111 {
112         if (!_instance) {
113                 _instance = new TransportMasterManager();
114         }
115         return *_instance;
116 }
117
118 // Called from AudioEngine::process_callback() BEFORE Session::process() is called. Each transport master has processed any incoming data for this cycle,
119 // and this method computes the transport speed that Ardour should use to get into and remain in sync with the master.
120 //
121 double
122 TransportMasterManager::pre_process_transport_masters (pframes_t nframes, samplepos_t now)
123 {
124         Glib::Threads::RWLock::ReaderLock lm (lock, Glib::Threads::TRY_LOCK);
125
126         if (!lm.locked()) {
127                 return 1.0;
128         }
129
130         boost::optional<samplepos_t> session_pos;
131
132         if (_session) {
133                 session_pos = _session->audible_sample();
134         }
135
136         if (Config->get_run_all_transport_masters_always()) {
137                 for (TransportMasters::iterator tm = _transport_masters.begin(); tm != _transport_masters.end(); ++tm) {
138                         if ((*tm)->check_collect()) {
139                                 (*tm)->pre_process (nframes, now, session_pos);
140                         }
141                 }
142         }
143
144         if (!_session) {
145                 return 1.0;
146         }
147
148         /* if we're not running ALL transport masters, but still have a current
149          * one, then we should run that one all the time so that we know
150          * precisely where it is when we starting chasing it ...
151          */
152
153         if (!Config->get_run_all_transport_masters_always() && _current_master) {
154                 _current_master->pre_process (nframes, now, session_pos);
155         }
156
157         if (!_session->config.get_external_sync()) {
158                 DEBUG_TRACE (DEBUG::Slave, string_compose ("no external sync, use session actual speed of %1\n", _session->actual_speed() ? _session->actual_speed() : 1.0));
159                 return _session->actual_speed () ? _session->actual_speed() : 1.0;
160         }
161
162         /* --- NOT REACHED UNLESS CHASING (i.e. _session->config.get_external_sync() is true ------*/
163
164         if (!_current_master->ok()) {
165                 /* stop */
166                 _session->request_transport_speed (0.0, false, _current_master->request_type());
167                 DEBUG_TRACE (DEBUG::Slave, "no roll2 - master has failed\n");
168                 _master_invalid_this_cycle = true;
169                 return 1.0;
170         }
171
172         if (!_current_master->locked()) {
173                 DEBUG_TRACE (DEBUG::Slave, "no roll4 - not locked\n");
174                 _master_invalid_this_cycle = true;
175                 return 1.0;
176         }
177
178         double engine_speed;
179
180         if (!_current_master->speed_and_position (_master_speed, _master_position, now)) {
181                 return 1.0;
182         }
183
184         if (_master_speed != 0.0) {
185
186                 samplepos_t delta = _master_position;
187
188                 if (_session->compute_audible_delta (delta)) {
189
190                         if (master_dll_initstate == 0) {
191
192                                 init_transport_master_dll (_master_speed, _master_position);
193                                 // _master_invalid_this_cycle = true;
194                                 DEBUG_TRACE (DEBUG::Slave, "no roll3 - still initializing master DLL\n");
195                                 master_dll_initstate = _master_speed > 0.0 ? 1 : -1;
196
197                                 return 1.0;
198                         }
199
200                         /* compute delta or "error" between the computed master_position for
201                          * this cycle and the current session position.
202                          *
203                          * Remember: ::speed_and_position() is being called in process context
204                          * but returns the predicted speed+position for the start of this process cycle,
205                          * not just the most recent timestamp received by the current master object.
206                          */
207
208                         DEBUG_TRACE (DEBUG::Slave, string_compose ("master DLL: delta = %1 (%2 vs %3) res: %4\n", delta, _master_position, _session->transport_sample(), _current_master->resolution()));
209
210                         if (delta > _current_master->resolution()) {
211
212                                 // init_transport_master_dll (_master_speed, _master_position);
213
214                                 if (!_session->actively_recording()) {
215                                         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave delta %1 greater than slave resolution %2 => no disk output\n", delta, _current_master->resolution()));
216                                         /* run routes as normal, but no disk output */
217                                         DiskReader::set_no_disk_output (true);
218                                 } else {
219                                         DiskReader::set_no_disk_output (false);
220                                 }
221                         } else {
222                                 DiskReader::set_no_disk_output (false);
223                         }
224
225                         /* inject DLL with new data */
226
227                         DEBUG_TRACE (DEBUG::Slave, string_compose ("feed master DLL t0 %1 t1 %2 e %3 %4 e2 %5 sess %6\n", t0, t1, delta, _master_position, e2, _session->transport_sample()));
228
229                         const double e = delta;
230
231                         t0 = t1;
232                         t1 += b * e + e2;
233                         e2 += c * e;
234
235                         engine_speed = (t1 - t0) / nframes;
236
237                         DEBUG_TRACE (DEBUG::Slave, string_compose ("slave @ %1 speed %2 cur delta %3 matching speed %4\n", _master_position, _master_speed, delta, engine_speed));
238
239                         /* provide a .1% deadzone to lock the speed */
240                         if (fabs (engine_speed - 1.0) <= 0.001) {
241                                 engine_speed = 1.0;
242                         }
243
244                         if (_current_master->sample_clock_synced() && engine_speed != 0.0f) {
245
246                                 /* if the master is synced to our audio interface via word-clock or similar, then we assume that its speed is binary: 0.0 or 1.0
247                                    (since our sample clock cannot change with respect to it).
248                                 */
249                                 if (engine_speed > 0.0) {
250                                         engine_speed = 1.0;
251                                 } else if (engine_speed < 0.0) {
252                                         engine_speed = -1.0;
253                                 }
254                         }
255
256                         /* speed is set, we're locked, and good to go */
257                         DEBUG_TRACE (DEBUG::Slave, string_compose ("%1: computed speed-to-follow-master as %2\n", _current_master->name(), engine_speed));
258
259                 } else {
260
261                         /* session has not finished with latency compensation yet, so we cannot compute the
262                            difference between the master and the session.
263                         */
264                         engine_speed = 1.0;
265                 }
266
267         } else {
268
269                 engine_speed = 1.0;
270         }
271
272         _master_invalid_this_cycle = false;
273
274         DEBUG_TRACE (DEBUG::Slave, string_compose ("computed resampling ratio as %1 with position = %2 and speed = %3\n", engine_speed, _master_position, _master_speed));
275
276         return engine_speed;
277 }
278
279
280 void
281 TransportMasterManager::init_transport_master_dll (double speed, samplepos_t pos)
282 {
283         /* the bandwidth of the DLL is a trade-off,
284          * because the max-speed of the transport in ardour is
285          * limited to +-8.0, a larger bandwidth would cause oscillations
286          *
287          * But this is only really a problem if the user performs manual
288          * seeks while transport is running and slaved to some timecode-y master.
289          */
290
291         AudioEngine* ae = AudioEngine::instance();
292
293         double const omega = 2.0 * M_PI * double(ae->samples_per_cycle()) / 2.0 / double(ae->sample_rate());
294         b = 1.4142135623730950488 * omega;
295         c = omega * omega;
296
297         const int direction = (speed >= 0.0 ? 1 : -1);
298
299         master_dll_initstate = direction;
300
301         e2 = double (direction * ae->samples_per_cycle());
302         t0 = double (pos);
303         t1 = t0 + e2;
304
305         DEBUG_TRACE (DEBUG::Slave, string_compose ("[re-]init ENGINE DLL %1 %2 %3 from %4 %5\n", t0,  t1, e2, speed, pos));
306 }
307
308 int
309 TransportMasterManager::add (SyncSource type, std::string const & name)
310 {
311         int ret = 0;
312         boost::shared_ptr<TransportMaster> tm;
313
314         {
315                 Glib::Threads::RWLock::WriterLock lm (lock);
316                 tm = TransportMaster::factory (type, name);
317                 ret = add_locked (tm);
318         }
319
320         if (ret == 0) {
321                 Added (tm);
322         }
323
324         return ret;
325 }
326
327 int
328 TransportMasterManager::add_locked (boost::shared_ptr<TransportMaster> tm)
329 {
330         if (!tm) {
331                 return -1;
332         }
333
334         for (TransportMasters::const_iterator t = _transport_masters.begin(); t != _transport_masters.end(); ++t) {
335                 if ((*t)->name() == tm->name()) {
336                         error << string_compose (_("There is already a transport master named \"%1\" - not duplicated"), tm->name()) << endmsg;
337                         return -1;
338                 }
339         }
340
341         _transport_masters.push_back (tm);
342         return 0;
343 }
344
345 int
346 TransportMasterManager::remove (std::string const & name)
347 {
348         int ret = -1;
349         boost::shared_ptr<TransportMaster> tm;
350
351         {
352                 Glib::Threads::RWLock::WriterLock lm (lock);
353
354                 for (TransportMasters::iterator t = _transport_masters.begin(); t != _transport_masters.end(); ++t) {
355                         if ((*t)->name() == name) {
356                                 tm = *t;
357                                 _transport_masters.erase (t);
358                                 ret = 0;
359                                 break;
360                         }
361                 }
362         }
363
364         if (ret == 0 && tm) {
365                 Removed (tm);
366         }
367
368         return -1;
369 }
370
371 int
372 TransportMasterManager::set_current_locked (boost::shared_ptr<TransportMaster> c)
373 {
374         if (find (_transport_masters.begin(), _transport_masters.end(), c) == _transport_masters.end()) {
375                 warning << string_compose (X_("programming error: attempt to use unknown transport master named \"%1\"\n"), c->name());
376                 return -1;
377         }
378
379         _current_master = c;
380         _master_speed = 0;
381         _master_position = 0;
382
383         master_dll_initstate = 0;
384
385         DEBUG_TRACE (DEBUG::Slave, string_compose ("current transport master set to %1\n", c->name()));
386
387         return 0;
388 }
389
390 int
391 TransportMasterManager::set_current (boost::shared_ptr<TransportMaster> c)
392 {
393         int ret = -1;
394         boost::shared_ptr<TransportMaster> old (_current_master);
395
396         {
397                 Glib::Threads::RWLock::WriterLock lm (lock);
398                 ret = set_current_locked (c);
399         }
400
401         if (ret == 0) {
402                 CurrentChanged (old, _current_master); // EMIT SIGNAL
403         }
404
405         return ret;
406 }
407
408 int
409 TransportMasterManager::set_current (SyncSource ss)
410 {
411         int ret = -1;
412         boost::shared_ptr<TransportMaster> old (_current_master);
413
414         {
415                 Glib::Threads::RWLock::WriterLock lm (lock);
416
417                 for (TransportMasters::iterator t = _transport_masters.begin(); t != _transport_masters.end(); ++t) {
418                         if ((*t)->type() == ss) {
419                                 ret = set_current_locked (*t);
420                                 break;
421                         }
422                 }
423         }
424
425         if (ret == 0) {
426                 CurrentChanged (old, _current_master); // EMIT SIGNAL
427         }
428
429         return ret;
430 }
431
432
433 int
434 TransportMasterManager::set_current (std::string const & str)
435 {
436         int ret = -1;
437         boost::shared_ptr<TransportMaster> old (_current_master);
438
439         {
440                 Glib::Threads::RWLock::WriterLock lm (lock);
441
442                 for (TransportMasters::iterator t = _transport_masters.begin(); t != _transport_masters.end(); ++t) {
443                         if ((*t)->name() == str) {
444                                 ret = set_current_locked (*t);
445                                 break;
446                         }
447                 }
448         }
449
450         if (ret == 0) {
451                 CurrentChanged (old, _current_master); // EMIT SIGNAL
452         }
453
454         return ret;
455 }
456
457
458 void
459 TransportMasterManager::clear ()
460 {
461         {
462                 Glib::Threads::RWLock::WriterLock lm (lock);
463                 _transport_masters.clear ();
464         }
465
466         Removed (boost::shared_ptr<TransportMaster>());
467 }
468
469 int
470 TransportMasterManager::set_state (XMLNode const & node, int version)
471 {
472         assert (node.name() == state_node_name);
473
474         XMLNodeList const & children = node.children();
475
476
477         if (!children.empty()) {
478                 _transport_masters.clear ();
479         }
480
481         {
482                 Glib::Threads::RWLock::WriterLock lm (lock);
483
484
485                 for (XMLNodeList::const_iterator c = children.begin(); c != children.end(); ++c) {
486
487                         boost::shared_ptr<TransportMaster> tm = TransportMaster::factory (**c);
488
489                         if (add_locked (tm)) {
490                                 continue;
491                         }
492
493                         /* we know it is the last thing added to the list of masters */
494
495                         _transport_masters.back()->set_state (**c, version);
496                 }
497         }
498
499         std::string current_master;
500         if (node.get_property (X_("current"), current_master)) {
501                 set_current (current_master);
502         } else {
503                 set_current (MTC);
504         }
505
506         return 0;
507 }
508
509 XMLNode&
510 TransportMasterManager::get_state ()
511 {
512         XMLNode* node = new XMLNode (state_node_name);
513
514         node->set_property (X_("current"), _current_master->name());
515
516         Glib::Threads::RWLock::ReaderLock lm (lock);
517
518         for (TransportMasters::iterator t = _transport_masters.begin(); t != _transport_masters.end(); ++t) {
519                 node->add_child_nocopy ((*t)->get_state());
520         }
521
522         return *node;
523 }
524
525 boost::shared_ptr<TransportMaster>
526 TransportMasterManager::master_by_type (SyncSource src) const
527 {
528         Glib::Threads::RWLock::ReaderLock lm (lock);
529
530         for (TransportMasters::const_iterator tm = _transport_masters.begin(); tm != _transport_masters.end(); ++tm) {
531                 if ((*tm)->type() == src) {
532                         return *tm;
533                 }
534         }
535
536         return boost::shared_ptr<TransportMaster> ();
537 }