goodbye USE_TRACKS_CODE_FEATURES and is_tracks_build
[ardour.git] / libs / ardour / audioengine.cc
1 /*
2  * Copyright (C) 2005-2019 Paul Davis <paul@linuxaudiosystems.com>
3  * Copyright (C) 2006-2016 David Robillard <d@drobilla.net>
4  * Copyright (C) 2007-2012 Carl Hetherington <carl@carlh.net>
5  * Copyright (C) 2008-2010 Sakari Bergen <sakari.bergen@beatwaves.net>
6  * Copyright (C) 2008 Hans Baier <hansfbaier@googlemail.com>
7  * Copyright (C) 2012-2019 Robin Gareus <robin@gareus.org>
8  * Copyright (C) 2013-2014 John Emmas <john@creativepost.co.uk>
9  * Copyright (C) 2013-2015 Tim Mayberry <mojofunk@gmail.com>
10  * Copyright (C) 2015 GZharun <grygoriiz@wavesglobal.com>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License along
23  * with this program; if not, write to the Free Software Foundation, Inc.,
24  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25  */
26
27 #include <unistd.h>
28 #include <cerrno>
29 #include <vector>
30 #include <exception>
31 #include <stdexcept>
32 #include <sstream>
33 #include <cmath>
34
35 #include <glibmm/timer.h>
36 #include <glibmm/pattern.h>
37 #include <glibmm/module.h>
38
39 #include "pbd/epa.h"
40 #include "pbd/file_utils.h"
41 #include "pbd/pthread_utils.h"
42 #include "pbd/stacktrace.h"
43 #include "pbd/unknown_type.h"
44
45 #include "midi++/port.h"
46 #include "midi++/mmc.h"
47
48 #include "ardour/async_midi_port.h"
49 #include "ardour/ardour.h"
50 #include "ardour/audio_port.h"
51 #include "ardour/audio_backend.h"
52 #include "ardour/audioengine.h"
53 #include "ardour/search_paths.h"
54 #include "ardour/buffer.h"
55 #include "ardour/cycle_timer.h"
56 #include "ardour/internal_send.h"
57 #include "ardour/meter.h"
58 #include "ardour/midi_port.h"
59 #include "ardour/midiport_manager.h"
60 #include "ardour/mididm.h"
61 #include "ardour/mtdm.h"
62 #include "ardour/port.h"
63 #include "ardour/process_thread.h"
64 #include "ardour/rc_configuration.h"
65 #include "ardour/session.h"
66 #include "ardour/transport_master_manager.h"
67
68 #include "pbd/i18n.h"
69
70 using namespace std;
71 using namespace ARDOUR;
72 using namespace PBD;
73
74 AudioEngine* AudioEngine::_instance = 0;
75
76 static gint audioengine_thread_cnt = 1;
77
78 #ifdef SILENCE_AFTER
79 #define SILENCE_AFTER_SECONDS 600
80 #endif
81
82 AudioEngine::AudioEngine ()
83         : session_remove_pending (false)
84         , session_removal_countdown (-1)
85         , _running (false)
86         , _freewheeling (false)
87         , monitor_check_interval (INT32_MAX)
88         , last_monitor_check (0)
89         , _processed_samples (-1)
90         , m_meter_thread (0)
91         , _main_thread (0)
92         , _mtdm (0)
93         , _mididm (0)
94         , _measuring_latency (MeasureNone)
95         , _latency_input_port (0)
96         , _latency_output_port (0)
97         , _latency_flush_samples (0)
98         , _latency_signal_latency (0)
99         , _stopped_for_latency (false)
100         , _started_for_latency (false)
101         , _in_destructor (false)
102         , _last_backend_error_string(AudioBackend::get_error_string((AudioBackend::ErrorCode)-1))
103         , _hw_reset_event_thread(0)
104         , _hw_reset_request_count(0)
105         , _stop_hw_reset_processing(0)
106         , _hw_devicelist_update_thread(0)
107         , _hw_devicelist_update_count(0)
108         , _stop_hw_devicelist_processing(0)
109         , _start_cnt (0)
110         , _init_countdown (0)
111 #ifdef SILENCE_AFTER_SECONDS
112         , _silence_countdown (0)
113         , _silence_hit_cnt (0)
114 #endif
115 {
116         reset_silence_countdown ();
117         start_hw_event_processing();
118         discover_backends ();
119 }
120
121 AudioEngine::~AudioEngine ()
122 {
123         _in_destructor = true;
124         stop_hw_event_processing();
125         drop_backend ();
126         for (BackendMap::const_iterator i = _backends.begin(); i != _backends.end(); ++i) {
127                 i->second->deinstantiate();
128         }
129         delete _main_thread;
130 }
131
132 AudioEngine*
133 AudioEngine::create ()
134 {
135         if (_instance) {
136                 return _instance;
137         }
138
139         _instance = new AudioEngine ();
140
141         return _instance;
142 }
143
144 void
145 AudioEngine::split_cycle (pframes_t offset)
146 {
147         /* caller must hold process lock */
148
149         Port::increment_global_port_buffer_offset (offset);
150
151         /* tell all Ports that we're going to start a new (split) cycle */
152
153         boost::shared_ptr<Ports> p = ports.reader();
154
155         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
156                 i->second->cycle_split ();
157         }
158 }
159
160 int
161 AudioEngine::sample_rate_change (pframes_t nframes)
162 {
163         /* check for monitor input change every 1/10th of second */
164
165         monitor_check_interval = nframes / 10;
166         last_monitor_check = 0;
167
168         if (_session) {
169                 _session->set_sample_rate (nframes);
170         }
171
172         SampleRateChanged (nframes); /* EMIT SIGNAL */
173
174 #ifdef SILENCE_AFTER_SECONDS
175         _silence_countdown = nframes * SILENCE_AFTER_SECONDS;
176 #endif
177
178         return 0;
179 }
180
181 int
182 AudioEngine::buffer_size_change (pframes_t bufsiz)
183 {
184         set_port_buffer_sizes (bufsiz);
185
186         if (_session) {
187                 _session->set_block_size (bufsiz);
188                 last_monitor_check = 0;
189         }
190
191         BufferSizeChanged (bufsiz); /* EMIT SIGNAL */
192
193         return 0;
194 }
195
196 /** Method called by our ::process_thread when there is work to be done.
197  *  @param nframes Number of samples to process.
198  */
199 #ifdef __clang__
200 __attribute__((annotate("realtime")))
201 #endif
202 int
203 AudioEngine::process_callback (pframes_t nframes)
204 {
205         Glib::Threads::Mutex::Lock tm (_process_lock, Glib::Threads::TRY_LOCK);
206         Port::set_speed_ratio (1.0);
207
208         PT_TIMING_REF;
209         PT_TIMING_CHECK (1);
210
211         /// The number of samples that will have been processed when we've finished
212         pframes_t next_processed_samples;
213
214         if (_processed_samples < 0) {
215                 _processed_samples = sample_time();
216                 cerr << "IIIIINIT PS to " << _processed_samples << endl;
217         }
218
219         /* handle wrap around of total samples counter */
220
221         if (max_samplepos - _processed_samples < nframes) {
222                 next_processed_samples = nframes - (max_samplepos - _processed_samples);
223         } else {
224                 next_processed_samples = _processed_samples + nframes;
225         }
226
227         if (!tm.locked()) {
228                 /* return having done nothing */
229                 if (_session) {
230                         Xrun();
231                 }
232                 /* really only JACK requires this
233                  * (other backends clear the output buffers
234                  * before the process_callback. it may even be
235                  * jack/alsa only). but better safe than sorry.
236                  */
237                 PortManager::silence_outputs (nframes);
238                 return 0;
239         }
240
241         /* The coreaudio-backend calls thread_init_callback() if
242          * the hardware changes or pthread_self() changes.
243          *
244          * However there are cases when neither holds true, yet
245          * the thread-pool changes: e.g. connect a headphone to
246          * a shared mic/headphone jack.
247          * It's probably related to, or caused by clocksource changes.
248          *
249          * For reasons yet unknown Glib::Threads::Private() can
250          * use a different thread-private in the same pthread
251          * (coreaudio render callback).
252          *
253          * Coreaudio must set something which influences
254          * pthread_key_t uniqness or reset the key using
255          * pthread_getspecific().
256          */
257         if (! SessionEvent::has_per_thread_pool ()) {
258                 thread_init_callback (NULL);
259         }
260
261         if (_session && _init_countdown > 0) {
262                 --_init_countdown;
263                 /* Warm up caches */
264                 PortManager::cycle_start (nframes);
265                 PortManager::silence (nframes);
266                 _session->process (nframes);
267                 PortManager::cycle_end (nframes);
268                 return 0;
269         }
270
271         bool return_after_remove_check = false;
272
273         if (_measuring_latency == MeasureAudio && _mtdm) {
274                 /* run a normal cycle from the perspective of the PortManager
275                    so that we get silence on all registered ports.
276
277                    we overwrite the silence on the two ports used for latency
278                    measurement.
279                 */
280
281                 PortManager::cycle_start (nframes);
282                 PortManager::silence (nframes);
283
284                 if (_latency_input_port && _latency_output_port) {
285                         PortEngine& pe (port_engine());
286
287                         Sample* in = (Sample*) pe.get_buffer (_latency_input_port, nframes);
288                         Sample* out = (Sample*) pe.get_buffer (_latency_output_port, nframes);
289
290                         _mtdm->process (nframes, in, out);
291                 }
292
293                 PortManager::cycle_end (nframes);
294                 return_after_remove_check = true;
295
296         } else if (_measuring_latency == MeasureMIDI && _mididm) {
297                 /* run a normal cycle from the perspective of the PortManager
298                    so that we get silence on all registered ports.
299
300                    we overwrite the silence on the two ports used for latency
301                    measurement.
302                 */
303
304                 PortManager::cycle_start (nframes);
305                 PortManager::silence (nframes);
306
307                 if (_latency_input_port && _latency_output_port) {
308                         PortEngine& pe (port_engine());
309
310                         _mididm->process (nframes, pe,
311                                         pe.get_buffer (_latency_input_port, nframes),
312                                         pe.get_buffer (_latency_output_port, nframes));
313                 }
314
315                 PortManager::cycle_end (nframes);
316                 return_after_remove_check = true;
317
318         } else if (_latency_flush_samples) {
319
320                 /* wait for the appropriate duration for the MTDM signal to
321                  * drain from the ports before we revert to normal behaviour.
322                  */
323
324                 PortManager::cycle_start (nframes);
325                 PortManager::silence (nframes);
326                 PortManager::cycle_end (nframes);
327
328                 if (_latency_flush_samples > nframes) {
329                         _latency_flush_samples -= nframes;
330                 } else {
331                         _latency_flush_samples = 0;
332                 }
333
334                 return_after_remove_check = true;
335         }
336
337         if (session_remove_pending) {
338
339                 /* perform the actual session removal */
340
341                 if (session_removal_countdown < 0) {
342
343                         /* fade out over 1 second */
344                         session_removal_countdown = sample_rate()/2;
345                         session_removal_gain = GAIN_COEFF_UNITY;
346                         session_removal_gain_step = 1.0/session_removal_countdown;
347
348                 } else if (session_removal_countdown > 0) {
349
350                         /* we'll be fading audio out.
351
352                            if this is the last time we do this as part
353                            of session removal, do a MIDI panic now
354                            to get MIDI stopped. This relies on the fact
355                            that "immediate data" (aka "out of band data") from
356                            MIDI tracks is *appended* after any other data,
357                            so that it emerges after any outbound note ons, etc.
358                         */
359
360                         if (session_removal_countdown <= nframes) {
361                                 assert (_session);
362                                 _session->midi_panic ();
363                         }
364
365                 } else {
366                         /* fade out done */
367                         _session = 0;
368                         session_removal_countdown = -1; // reset to "not in progress"
369                         session_remove_pending = false;
370                         session_removed.signal(); // wakes up thread that initiated session removal
371                 }
372         }
373
374         if (return_after_remove_check) {
375                 return 0;
376         }
377
378         TransportMasterManager& tmm (TransportMasterManager::instance());
379
380         /* make sure the TMM is up to date about the current session */
381
382         if (_session != tmm.session()) {
383                 tmm.set_session (_session);
384         }
385
386         if (_session == 0) {
387
388                 if (!_freewheeling) {
389                         PortManager::silence_outputs (nframes);
390                 }
391
392                 _processed_samples = next_processed_samples;
393
394                 return 0;
395         }
396
397         if (!_freewheeling || Freewheel.empty()) {
398                 const double engine_speed = tmm.pre_process_transport_masters (nframes, sample_time_at_cycle_start());
399                 Port::set_speed_ratio (engine_speed);
400                 DEBUG_TRACE (DEBUG::Slave, string_compose ("transport master (current=%1) gives speed %2 (ports using %3)\n", tmm.current() ? tmm.current()->name() : string("[]"), engine_speed, Port::speed_ratio()));
401         }
402
403         /* tell all relevant objects that we're starting a new cycle */
404
405         InternalSend::CycleStart (nframes);
406
407         /* tell all Ports that we're starting a new cycle */
408
409         PortManager::cycle_start (nframes, _session);
410
411         /* test if we are freewheeling and there are freewheel signals connected.
412          * ardour should act normally even when freewheeling unless /it/ is
413          * exporting (which is what Freewheel.empty() tests for).
414          */
415
416         if (_freewheeling && !Freewheel.empty()) {
417                 Freewheel (nframes);
418         } else {
419                 if (Port::cycle_nframes () <= nframes) {
420                         _session->process (Port::cycle_nframes ());
421                 } else {
422                         pframes_t remain = Port::cycle_nframes ();
423                         while (remain > 0) {
424                                 pframes_t nf = std::min (remain, nframes);
425                                 _session->process (nf);
426                                 remain -= nf;
427                                 if (remain > 0) {
428                                         split_cycle (nf);
429                                 }
430                         }
431                 }
432         }
433
434         if (_freewheeling) {
435                 PortManager::cycle_end (nframes, _session);
436                 return 0;
437         }
438
439         if (!_running) {
440                 _processed_samples = next_processed_samples;
441                 return 0;
442         }
443
444         if (last_monitor_check + monitor_check_interval < next_processed_samples) {
445
446                 PortManager::check_monitoring ();
447                 last_monitor_check = next_processed_samples;
448         }
449
450 #ifdef SILENCE_AFTER_SECONDS
451
452         bool was_silent = (_silence_countdown == 0);
453
454         if (_silence_countdown >= nframes) {
455                 _silence_countdown -= nframes;
456         } else {
457                 _silence_countdown = 0;
458         }
459
460         if (!was_silent && _silence_countdown == 0) {
461                 _silence_hit_cnt++;
462                 BecameSilent (); /* EMIT SIGNAL */
463         }
464
465         if (_silence_countdown == 0 || _session->silent()) {
466                 PortManager::silence (nframes);
467         }
468
469 #else
470         if (_session->silent()) {
471                 PortManager::silence (nframes, _session);
472         }
473 #endif
474
475         if (session_remove_pending && session_removal_countdown) {
476
477                 PortManager::cycle_end_fade_out (session_removal_gain, session_removal_gain_step, nframes, _session);
478
479                 if (session_removal_countdown > nframes) {
480                         session_removal_countdown -= nframes;
481                 } else {
482                         session_removal_countdown = 0;
483                 }
484
485                 session_removal_gain -= (nframes * session_removal_gain_step);
486         } else {
487                 PortManager::cycle_end (nframes, _session);
488         }
489
490         _processed_samples = next_processed_samples;
491
492         PT_TIMING_CHECK (2);
493
494         return 0;
495 }
496
497 void
498 AudioEngine::reset_silence_countdown ()
499 {
500 #ifdef SILENCE_AFTER_SECONDS
501         double sr = 48000; /* default in case there is no backend */
502
503         sr = sample_rate();
504
505         _silence_countdown = max (60 * sr, /* 60 seconds */
506                                   sr * (SILENCE_AFTER_SECONDS / ::pow (2.0, (double) _silence_hit_cnt)));
507
508 #endif
509 }
510
511 void
512 AudioEngine::launch_device_control_app()
513 {
514         if (_state_lock.trylock () ) {
515                 _backend->launch_control_app ();
516                 _state_lock.unlock ();
517         }
518 }
519
520
521 void
522 AudioEngine::request_backend_reset()
523 {
524         Glib::Threads::Mutex::Lock guard (_reset_request_lock);
525         g_atomic_int_inc (&_hw_reset_request_count);
526         _hw_reset_condition.signal ();
527 }
528
529 int
530 AudioEngine::backend_reset_requested()
531 {
532         return g_atomic_int_get (&_hw_reset_request_count);
533 }
534
535 void
536 AudioEngine::do_reset_backend()
537 {
538         SessionEvent::create_per_thread_pool (X_("Backend reset processing thread"), 1024);
539
540         Glib::Threads::Mutex::Lock guard (_reset_request_lock);
541
542         while (!_stop_hw_reset_processing) {
543
544                 if (g_atomic_int_get (&_hw_reset_request_count) != 0 && _backend) {
545
546                         _reset_request_lock.unlock();
547
548                         Glib::Threads::RecMutex::Lock pl (_state_lock);
549                         g_atomic_int_dec_and_test (&_hw_reset_request_count);
550
551                         std::cout << "AudioEngine::RESET::Reset request processing. Requests left: " << _hw_reset_request_count << std::endl;
552                         DeviceResetStarted(); // notify about device reset to be started
553
554                         // backup the device name
555                         std::string name = _backend->device_name ();
556
557                         std::cout << "AudioEngine::RESET::Reseting device..." << std::endl;
558                         if ( ( 0 == stop () ) &&
559                                         ( 0 == _backend->reset_device () ) &&
560                                         ( 0 == start () ) ) {
561
562                                 std::cout << "AudioEngine::RESET::Engine started..." << std::endl;
563
564                                 // inform about possible changes
565                                 BufferSizeChanged (_backend->buffer_size() );
566                                 DeviceResetFinished(); // notify about device reset finish
567
568                         } else {
569
570                                 DeviceResetFinished(); // notify about device reset finish
571                                 // we've got an error
572                                 DeviceError();
573                         }
574
575                         std::cout << "AudioEngine::RESET::Done." << std::endl;
576
577                         _reset_request_lock.lock();
578
579                 } else {
580
581                         _hw_reset_condition.wait (_reset_request_lock);
582
583                 }
584         }
585 }
586
587 void
588 AudioEngine::request_device_list_update()
589 {
590         Glib::Threads::Mutex::Lock guard (_devicelist_update_lock);
591         g_atomic_int_inc (&_hw_devicelist_update_count);
592         _hw_devicelist_update_condition.signal ();
593 }
594
595 void
596 AudioEngine::do_devicelist_update()
597 {
598         SessionEvent::create_per_thread_pool (X_("Device list update processing thread"), 512);
599
600         Glib::Threads::Mutex::Lock guard (_devicelist_update_lock);
601
602         while (!_stop_hw_devicelist_processing) {
603
604                 if (g_atomic_int_get (&_hw_devicelist_update_count)) {
605
606                         _devicelist_update_lock.unlock();
607
608                         Glib::Threads::RecMutex::Lock pl (_state_lock);
609
610                         g_atomic_int_dec_and_test (&_hw_devicelist_update_count);
611                         DeviceListChanged (); /* EMIT SIGNAL */
612
613                         _devicelist_update_lock.lock();
614
615                 } else {
616                         _hw_devicelist_update_condition.wait (_devicelist_update_lock);
617                 }
618         }
619 }
620
621
622 void
623 AudioEngine::start_hw_event_processing()
624 {
625         if (_hw_reset_event_thread == 0) {
626                 g_atomic_int_set(&_hw_reset_request_count, 0);
627                 g_atomic_int_set(&_stop_hw_reset_processing, 0);
628                 _hw_reset_event_thread = Glib::Threads::Thread::create (boost::bind (&AudioEngine::do_reset_backend, this));
629         }
630
631         if (_hw_devicelist_update_thread == 0) {
632                 g_atomic_int_set(&_hw_devicelist_update_count, 0);
633                 g_atomic_int_set(&_stop_hw_devicelist_processing, 0);
634                 _hw_devicelist_update_thread = Glib::Threads::Thread::create (boost::bind (&AudioEngine::do_devicelist_update, this));
635         }
636 }
637
638
639 void
640 AudioEngine::stop_hw_event_processing()
641 {
642         if (_hw_reset_event_thread) {
643                 g_atomic_int_set(&_stop_hw_reset_processing, 1);
644                 g_atomic_int_set(&_hw_reset_request_count, 0);
645                 _hw_reset_condition.signal ();
646                 _hw_reset_event_thread->join ();
647                 _hw_reset_event_thread = 0;
648         }
649
650         if (_hw_devicelist_update_thread) {
651                 g_atomic_int_set(&_stop_hw_devicelist_processing, 1);
652                 g_atomic_int_set(&_hw_devicelist_update_count, 0);
653                 _hw_devicelist_update_condition.signal ();
654                 _hw_devicelist_update_thread->join ();
655                 _hw_devicelist_update_thread = 0;
656         }
657 }
658
659 void
660 AudioEngine::set_session (Session *s)
661 {
662         Glib::Threads::Mutex::Lock pl (_process_lock);
663
664         SessionHandlePtr::set_session (s);
665
666         if (_session) {
667                 _init_countdown = 8;
668         }
669 }
670
671 void
672 AudioEngine::remove_session ()
673 {
674         Glib::Threads::Mutex::Lock lm (_process_lock);
675
676         if (_running) {
677
678                 if (_session) {
679                         session_remove_pending = true;
680                         /* signal the start of the fade out countdown */
681                         session_removal_countdown = -1;
682                         session_removed.wait(_process_lock);
683                 }
684
685         } else {
686                 SessionHandlePtr::set_session (0);
687         }
688
689         remove_all_ports ();
690 }
691
692 void
693 AudioEngine::died ()
694 {
695         /* called from a signal handler for SIGPIPE */
696         _running = false;
697 }
698
699 int
700 AudioEngine::reset_timebase ()
701 {
702         if (_session) {
703                 if (_session->config.get_jack_time_master()) {
704                         _backend->set_time_master (true);
705                 } else {
706                         _backend->set_time_master (false);
707                 }
708         }
709         return 0;
710 }
711
712
713 void
714 AudioEngine::destroy ()
715 {
716         delete _instance;
717         _instance = 0;
718 }
719
720 int
721 AudioEngine::discover_backends ()
722 {
723         vector<std::string> backend_modules;
724
725         _backends.clear ();
726
727         Glib::PatternSpec so_extension_pattern("*backend.so");
728         Glib::PatternSpec dylib_extension_pattern("*backend.dylib");
729
730 #if defined(PLATFORM_WINDOWS) && defined(DEBUGGABLE_BACKENDS)
731         #if defined(DEBUG) || defined(_DEBUG)
732                 Glib::PatternSpec dll_extension_pattern("*backendD.dll");
733         #else
734                 Glib::PatternSpec dll_extension_pattern("*backendRDC.dll");
735         #endif
736 #else
737         Glib::PatternSpec dll_extension_pattern("*backend.dll");
738 #endif
739
740         find_files_matching_pattern (backend_modules, backend_search_path (),
741                                      so_extension_pattern);
742
743         find_files_matching_pattern (backend_modules, backend_search_path (),
744                                      dylib_extension_pattern);
745
746         find_files_matching_pattern (backend_modules, backend_search_path (),
747                                      dll_extension_pattern);
748
749         DEBUG_TRACE (DEBUG::AudioEngine, string_compose ("looking for backends in %1\n", backend_search_path().to_string()));
750
751         for (vector<std::string>::iterator i = backend_modules.begin(); i != backend_modules.end(); ++i) {
752
753                 AudioBackendInfo* info;
754
755                 DEBUG_TRACE (DEBUG::AudioEngine, string_compose ("Checking possible backend in %1\n", *i));
756
757                 if ((info = backend_discover (*i)) != 0) {
758                         _backends.insert (make_pair (info->name, info));
759                 }
760         }
761
762         DEBUG_TRACE (DEBUG::AudioEngine, string_compose ("Found %1 backends\n", _backends.size()));
763
764         return _backends.size();
765 }
766
767 AudioBackendInfo*
768 AudioEngine::backend_discover (const string& path)
769 {
770 #ifdef PLATFORM_WINDOWS
771         // do not show popup dialog (e.g. missing libjack.dll)
772         // win7+ should use SetThreadErrorMode()
773         SetErrorMode(SEM_FAILCRITICALERRORS);
774 #endif
775         Glib::Module module (path);
776 #ifdef PLATFORM_WINDOWS
777         SetErrorMode(0); // reset to system default
778 #endif
779         AudioBackendInfo* info;
780         AudioBackendInfo* (*dfunc)(void);
781         void* func = 0;
782
783         if (!module) {
784                 error << string_compose(_("AudioEngine: cannot load module \"%1\" (%2)"), path,
785                                         Glib::Module::get_last_error()) << endmsg;
786                 return 0;
787         }
788
789         if (!module.get_symbol ("descriptor", func)) {
790                 error << string_compose(_("AudioEngine: backend at \"%1\" has no descriptor function."), path) << endmsg;
791                 error << Glib::Module::get_last_error() << endmsg;
792                 return 0;
793         }
794
795         dfunc = (AudioBackendInfo* (*)(void))func;
796         info = dfunc();
797         if (!info->available()) {
798                 return 0;
799         }
800
801         module.make_resident ();
802
803         return info;
804 }
805
806 #ifdef NDEBUG
807 static bool running_from_source_tree ()
808 {
809         // dup ARDOUR_UI_UTILS::running_from_source_tree ()
810         gchar const *x = g_getenv ("ARDOUR_THEMES_PATH");
811         return x && (string (x).find ("gtk2_ardour") != string::npos);
812 }
813 #endif
814
815 vector<const AudioBackendInfo*>
816 AudioEngine::available_backends() const
817 {
818         vector<const AudioBackendInfo*> r;
819
820         for (BackendMap::const_iterator i = _backends.begin(); i != _backends.end(); ++i) {
821 #ifdef NDEBUG
822                 if (i->first == "None (Dummy)" && !running_from_source_tree () && Config->get_hide_dummy_backend ()) {
823                         continue;
824                 }
825 #endif
826                 r.push_back (i->second);
827         }
828
829         return r;
830 }
831
832 string
833 AudioEngine::current_backend_name() const
834 {
835         if (_backend) {
836                 return _backend->name();
837         }
838         return string();
839 }
840
841 void
842 AudioEngine::drop_backend ()
843 {
844         if (_backend) {
845                 _backend->stop ();
846                 // Stopped is needed for Graph to explicitly terminate threads
847                 Stopped (); /* EMIT SIGNAL */
848                 _backend->drop_device ();
849                 _backend.reset ();
850                 _running = false;
851         }
852 }
853
854 boost::shared_ptr<AudioBackend>
855 AudioEngine::set_backend (const std::string& name, const std::string& arg1, const std::string& arg2)
856 {
857         BackendMap::iterator b = _backends.find (name);
858
859         if (b == _backends.end()) {
860                 return boost::shared_ptr<AudioBackend>();
861         }
862
863         drop_backend ();
864
865         try {
866                 if (b->second->instantiate (arg1, arg2)) {
867                         throw failed_constructor ();
868                 }
869
870                 _backend = b->second->factory (*this);
871
872         } catch (exception& e) {
873                 error << string_compose (_("Could not create backend for %1: %2"), name, e.what()) << endmsg;
874                 return boost::shared_ptr<AudioBackend>();
875         }
876
877         return _backend;
878 }
879
880 /* BACKEND PROXY WRAPPERS */
881
882 int
883 AudioEngine::start (bool for_latency)
884 {
885         if (!_backend) {
886                 return -1;
887         }
888
889         if (_running && _backend->can_change_systemic_latency_when_running()) {
890                 _started_for_latency = for_latency;
891         }
892
893         if (_running) {
894                 return 0;
895         }
896
897         _processed_samples = 0;
898         last_monitor_check = 0;
899
900         int error_code = _backend->start (for_latency);
901
902         if (error_code != 0) {
903                 _last_backend_error_string = AudioBackend::get_error_string((AudioBackend::ErrorCode) error_code);
904                 return -1;
905         }
906
907         _running = true;
908
909         if (_session) {
910                 _session->set_sample_rate (_backend->sample_rate());
911
912                 if (_session->config.get_jack_time_master()) {
913                         _backend->set_time_master (true);
914                 }
915
916         }
917
918         midi_info_dirty = true;
919
920         if (!for_latency) {
921                 /* Call the library-wide ::init_post_engine() before emitting
922                  * running to ensure that its tasks are complete before any
923                  * signal handlers execute. PBD::Signal does not ensure
924                  * ordering of signal handlers so even if ::init_post_engine()
925                  * is connected first, it may not run first.
926                  */
927
928                 ARDOUR::init_post_engine (_start_cnt);
929
930                 Running (_start_cnt); /* EMIT SIGNAL */
931
932                 /* latency start/stop cycles do not count as "starts" */
933
934                 _start_cnt++;
935         }
936
937
938         return 0;
939 }
940
941 int
942 AudioEngine::stop (bool for_latency)
943 {
944         bool stop_engine = true;
945
946         if (!_backend) {
947                 return 0;
948         }
949
950         Glib::Threads::Mutex::Lock pl (_process_lock, Glib::Threads::NOT_LOCK);
951
952         if (running()) {
953                 pl.acquire ();
954         }
955
956         if (for_latency && _backend->can_change_systemic_latency_when_running()) {
957                 stop_engine = false;
958                 if (_running && _started_for_latency) {
959                         _backend->start (false); // keep running, reload latencies
960                 }
961         } else {
962                 if (_backend->stop ()) {
963                         if (pl.locked ()) {
964                                 pl.release ();
965                         }
966                         return -1;
967                 }
968         }
969
970         if (pl.locked ()) {
971                 pl.release ();
972         }
973
974         const bool was_running_will_stop = (_running && stop_engine);
975
976         if (was_running_will_stop) {
977                 _running = false;
978         }
979
980         if (_session && was_running_will_stop && !_session->loading() && !_session->deletion_in_progress()) {
981                 // it's not a halt, but should be handled the same way:
982                 // disable record, stop transport and I/O processign but save the data.
983                 _session->engine_halted ();
984         }
985
986         if (was_running_will_stop) {
987                 if (!for_latency) {
988                         _started_for_latency = false;
989                 } else if (!_started_for_latency) {
990                         _stopped_for_latency = true;
991                 }
992         }
993         _processed_samples = 0;
994         _measuring_latency = MeasureNone;
995         _latency_output_port = 0;
996         _latency_input_port = 0;
997
998         if (stop_engine) {
999                 Port::PortDrop ();
1000         }
1001
1002         if (stop_engine) {
1003                 TransportMasterManager& tmm (TransportMasterManager::instance());
1004                 tmm.engine_stopped ();
1005                 Stopped (); /* EMIT SIGNAL */
1006         }
1007
1008         return 0;
1009 }
1010
1011 int
1012 AudioEngine::freewheel (bool start_stop)
1013 {
1014         if (!_backend) {
1015                 return -1;
1016         }
1017
1018         /* _freewheeling will be set when first Freewheel signal occurs */
1019
1020         return _backend->freewheel (start_stop);
1021 }
1022
1023 float
1024 AudioEngine::get_dsp_load() const
1025 {
1026         if (!_backend || !_running) {
1027                 return 0.0;
1028         }
1029         return _backend->dsp_load ();
1030 }
1031
1032 bool
1033 AudioEngine::is_realtime() const
1034 {
1035         if (!_backend) {
1036                 return false;
1037         }
1038
1039         return _backend->is_realtime();
1040 }
1041
1042 void
1043 AudioEngine::transport_start ()
1044 {
1045         if (!_backend) {
1046                 return;
1047         }
1048         return _backend->transport_start ();
1049 }
1050
1051 void
1052 AudioEngine::transport_stop ()
1053 {
1054         if (!_backend) {
1055                 return;
1056         }
1057         return _backend->transport_stop ();
1058 }
1059
1060 TransportState
1061 AudioEngine::transport_state ()
1062 {
1063         if (!_backend) {
1064                 return TransportStopped;
1065         }
1066         return _backend->transport_state ();
1067 }
1068
1069 void
1070 AudioEngine::transport_locate (samplepos_t pos)
1071 {
1072         if (!_backend) {
1073                 return;
1074         }
1075         return _backend->transport_locate (pos);
1076 }
1077
1078 samplepos_t
1079 AudioEngine::transport_sample()
1080 {
1081         if (!_backend) {
1082                 return 0;
1083         }
1084         return _backend->transport_sample ();
1085 }
1086
1087 samplecnt_t
1088 AudioEngine::sample_rate () const
1089 {
1090         if (!_backend) {
1091                 return 0;
1092         }
1093         return _backend->sample_rate ();
1094 }
1095
1096 pframes_t
1097 AudioEngine::samples_per_cycle () const
1098 {
1099         if (!_backend) {
1100                 return 0;
1101         }
1102         return _backend->buffer_size ();
1103 }
1104
1105 int
1106 AudioEngine::usecs_per_cycle () const
1107 {
1108         if (!_backend) {
1109                 return -1;
1110         }
1111         return _backend->usecs_per_cycle ();
1112 }
1113
1114 size_t
1115 AudioEngine::raw_buffer_size (DataType t)
1116 {
1117         if (!_backend) {
1118                 return -1;
1119         }
1120         return _backend->raw_buffer_size (t);
1121 }
1122
1123 samplepos_t
1124 AudioEngine::sample_time ()
1125 {
1126         if (!_backend) {
1127                 return 0;
1128         }
1129         return _backend->sample_time ();
1130 }
1131
1132 samplepos_t
1133 AudioEngine::sample_time_at_cycle_start ()
1134 {
1135         if (!_backend) {
1136                 return 0;
1137         }
1138         return _backend->sample_time_at_cycle_start ();
1139 }
1140
1141 pframes_t
1142 AudioEngine::samples_since_cycle_start ()
1143 {
1144         if (!_backend) {
1145                 return 0;
1146         }
1147         return _backend->samples_since_cycle_start ();
1148 }
1149
1150 bool
1151 AudioEngine::get_sync_offset (pframes_t& offset) const
1152 {
1153         if (!_backend) {
1154                 return false;
1155         }
1156         return _backend->get_sync_offset (offset);
1157 }
1158
1159 int
1160 AudioEngine::create_process_thread (boost::function<void()> func)
1161 {
1162         if (!_backend) {
1163                 return -1;
1164         }
1165         return _backend->create_process_thread (func);
1166 }
1167
1168 int
1169 AudioEngine::join_process_threads ()
1170 {
1171         if (!_backend) {
1172                 return -1;
1173         }
1174         return _backend->join_process_threads ();
1175 }
1176
1177 bool
1178 AudioEngine::in_process_thread ()
1179 {
1180         if (!_backend) {
1181                 return false;
1182         }
1183         return _backend->in_process_thread ();
1184 }
1185
1186 uint32_t
1187 AudioEngine::process_thread_count ()
1188 {
1189         if (!_backend) {
1190                 return 0;
1191         }
1192         return _backend->process_thread_count ();
1193 }
1194
1195 int
1196 AudioEngine::set_device_name (const std::string& name)
1197 {
1198         if (!_backend) {
1199                 return -1;
1200         }
1201         return _backend->set_device_name  (name);
1202 }
1203
1204 int
1205 AudioEngine::set_sample_rate (float sr)
1206 {
1207         if (!_backend) {
1208                 return -1;
1209         }
1210
1211         return _backend->set_sample_rate  (sr);
1212 }
1213
1214 int
1215 AudioEngine::set_buffer_size (uint32_t bufsiz)
1216 {
1217         if (!_backend) {
1218                 return -1;
1219         }
1220         return _backend->set_buffer_size  (bufsiz);
1221 }
1222
1223 int
1224 AudioEngine::set_interleaved (bool yn)
1225 {
1226         if (!_backend) {
1227                 return -1;
1228         }
1229         return _backend->set_interleaved  (yn);
1230 }
1231
1232 int
1233 AudioEngine::set_input_channels (uint32_t ic)
1234 {
1235         if (!_backend) {
1236                 return -1;
1237         }
1238         return _backend->set_input_channels  (ic);
1239 }
1240
1241 int
1242 AudioEngine::set_output_channels (uint32_t oc)
1243 {
1244         if (!_backend) {
1245                 return -1;
1246         }
1247         return _backend->set_output_channels (oc);
1248 }
1249
1250 int
1251 AudioEngine::set_systemic_input_latency (uint32_t il)
1252 {
1253         if (!_backend) {
1254                 return -1;
1255         }
1256         return _backend->set_systemic_input_latency  (il);
1257 }
1258
1259 int
1260 AudioEngine::set_systemic_output_latency (uint32_t ol)
1261 {
1262         if (!_backend) {
1263                 return -1;
1264         }
1265         return _backend->set_systemic_output_latency  (ol);
1266 }
1267
1268 bool
1269 AudioEngine::thread_initialised_for_audio_processing ()
1270 {
1271         return SessionEvent::has_per_thread_pool () && AsyncMIDIPort::is_process_thread();
1272 }
1273
1274 /* END OF BACKEND PROXY API */
1275
1276 void
1277 AudioEngine::thread_init_callback (void* arg)
1278 {
1279         /* make sure that anybody who needs to know about this thread
1280            knows about it.
1281         */
1282
1283         pthread_set_name (X_("audioengine"));
1284
1285         const int thread_num = g_atomic_int_add (&audioengine_thread_cnt, 1);
1286         const string thread_name = string_compose (X_("AudioEngine %1"), thread_num);
1287
1288         SessionEvent::create_per_thread_pool (thread_name, 512);
1289         PBD::notify_event_loops_about_thread_creation (pthread_self(), thread_name, 4096);
1290         AsyncMIDIPort::set_process_thread (pthread_self());
1291
1292         if (arg) {
1293                 delete AudioEngine::instance()->_main_thread;
1294                 /* the special thread created/managed by the backend */
1295                 AudioEngine::instance()->_main_thread = new ProcessThread;
1296         }
1297 }
1298
1299 int
1300 AudioEngine::sync_callback (TransportState state, samplepos_t position)
1301 {
1302         if (_session) {
1303                 return _session->backend_sync_callback (state, position);
1304         }
1305         return 0;
1306 }
1307
1308 void
1309 AudioEngine::freewheel_callback (bool onoff)
1310 {
1311         _freewheeling = onoff;
1312 }
1313
1314 void
1315 AudioEngine::latency_callback (bool for_playback)
1316 {
1317         if (_session) {
1318                 _session->update_latency (for_playback);
1319         }
1320 }
1321
1322 void
1323 AudioEngine::update_latencies ()
1324 {
1325         if (_backend) {
1326                 _backend->update_latencies ();
1327         }
1328 }
1329
1330 void
1331 AudioEngine::halted_callback (const char* why)
1332 {
1333         if (_in_destructor) {
1334                 /* everything is under control */
1335                 return;
1336         }
1337
1338         _running = false;
1339
1340         Port::PortDrop (); /* EMIT SIGNAL */
1341
1342         if (!_started_for_latency) {
1343                 Halted (why);      /* EMIT SIGNAL */
1344         }
1345 }
1346
1347 bool
1348 AudioEngine::setup_required () const
1349 {
1350         if (_backend) {
1351                 if (_backend->info().already_configured())
1352                         return false;
1353         } else {
1354                 if (_backends.size() == 1 && _backends.begin()->second->already_configured()) {
1355                         return false;
1356                 }
1357         }
1358
1359         return true;
1360 }
1361
1362 int
1363 AudioEngine::prepare_for_latency_measurement ()
1364 {
1365         if (!_backend) {
1366                 return -1;
1367         }
1368
1369         if (running() && _started_for_latency) {
1370                 return 0;
1371         }
1372
1373         if (_backend->can_change_systemic_latency_when_running()) {
1374                 if (_running) {
1375                         _backend->start (true); // zero latency reporting of running backend
1376                 } else if (start (true)) {
1377                         return -1;
1378                 }
1379                 _started_for_latency = true;
1380                 return 0;
1381         }
1382
1383         if (running()) {
1384                 stop (true);
1385         }
1386
1387         if (start (true)) {
1388                 return -1;
1389         }
1390         _started_for_latency = true;
1391         return 0;
1392 }
1393
1394 int
1395 AudioEngine::start_latency_detection (bool for_midi)
1396 {
1397         if (prepare_for_latency_measurement ()) {
1398                 return -1;
1399         }
1400
1401         PortEngine& pe (port_engine());
1402
1403         delete _mtdm;
1404         _mtdm = 0;
1405
1406         delete _mididm;
1407         _mididm = 0;
1408
1409         /* find the ports we will connect to */
1410
1411         PortEngine::PortHandle out = pe.get_port_by_name (_latency_output_name);
1412         PortEngine::PortHandle in = pe.get_port_by_name (_latency_input_name);
1413
1414         if (!out || !in) {
1415                 stop (true);
1416                 return -1;
1417         }
1418
1419         /* create the ports we will use to read/write data */
1420         if (for_midi) {
1421                 if ((_latency_output_port = pe.register_port ("latency_out", DataType::MIDI, IsOutput)) == 0) {
1422                         stop (true);
1423                         return -1;
1424                 }
1425                 if (pe.connect (_latency_output_port, _latency_output_name)) {
1426                         pe.unregister_port (_latency_output_port);
1427                         stop (true);
1428                         return -1;
1429                 }
1430
1431                 const string portname ("latency_in");
1432                 if ((_latency_input_port = pe.register_port (portname, DataType::MIDI, IsInput)) == 0) {
1433                         pe.unregister_port (_latency_input_port);
1434                         pe.unregister_port (_latency_output_port);
1435                         stop (true);
1436                         return -1;
1437                 }
1438                 if (pe.connect (_latency_input_name, make_port_name_non_relative (portname))) {
1439                         pe.unregister_port (_latency_input_port);
1440                         pe.unregister_port (_latency_output_port);
1441                         stop (true);
1442                         return -1;
1443                 }
1444
1445                 _mididm = new MIDIDM (sample_rate());
1446
1447         } else {
1448
1449                 if ((_latency_output_port = pe.register_port ("latency_out", DataType::AUDIO, IsOutput)) == 0) {
1450                         stop (true);
1451                         return -1;
1452                 }
1453                 if (pe.connect (_latency_output_port, _latency_output_name)) {
1454                         pe.unregister_port (_latency_output_port);
1455                         stop (true);
1456                         return -1;
1457                 }
1458
1459                 const string portname ("latency_in");
1460                 if ((_latency_input_port = pe.register_port (portname, DataType::AUDIO, IsInput)) == 0) {
1461                         pe.unregister_port (_latency_input_port);
1462                         pe.unregister_port (_latency_output_port);
1463                         stop (true);
1464                         return -1;
1465                 }
1466                 if (pe.connect (_latency_input_name, make_port_name_non_relative (portname))) {
1467                         pe.unregister_port (_latency_input_port);
1468                         pe.unregister_port (_latency_output_port);
1469                         stop (true);
1470                         return -1;
1471                 }
1472
1473                 _mtdm = new MTDM (sample_rate());
1474
1475         }
1476
1477         LatencyRange lr;
1478         _latency_signal_latency = 0;
1479         lr = pe.get_latency_range (in, false);
1480         _latency_signal_latency = lr.max;
1481         lr = pe.get_latency_range (out, true);
1482         _latency_signal_latency += lr.max;
1483
1484         /* all created and connected, lets go */
1485         _latency_flush_samples = samples_per_cycle();
1486         _measuring_latency = for_midi ? MeasureMIDI : MeasureAudio;
1487
1488         return 0;
1489 }
1490
1491 void
1492 AudioEngine::stop_latency_detection ()
1493 {
1494         _measuring_latency = MeasureNone;
1495
1496         if (_latency_output_port) {
1497                 port_engine().unregister_port (_latency_output_port);
1498                 _latency_output_port = 0;
1499         }
1500         if (_latency_input_port) {
1501                 port_engine().unregister_port (_latency_input_port);
1502                 _latency_input_port = 0;
1503         }
1504
1505         if (_running && _backend->can_change_systemic_latency_when_running()) {
1506                 if (_started_for_latency) {
1507                         _running = false; // force reload: reset latencies and emit Running()
1508                         start ();
1509                 }
1510         }
1511
1512         if (_running && !_started_for_latency) {
1513                 assert (!_stopped_for_latency);
1514                 return;
1515         }
1516
1517         if (!_backend->can_change_systemic_latency_when_running()) {
1518                 stop (true);
1519         }
1520
1521         if (_stopped_for_latency) {
1522                 start ();
1523         }
1524
1525         _stopped_for_latency = false;
1526         _started_for_latency = false;
1527 }
1528
1529 void
1530 AudioEngine::set_latency_output_port (const string& name)
1531 {
1532         _latency_output_name = name;
1533 }
1534
1535 void
1536 AudioEngine::set_latency_input_port (const string& name)
1537 {
1538         _latency_input_name = name;
1539 }
1540
1541 void
1542 AudioEngine::add_pending_port_deletion (Port* p)
1543 {
1544         if (_session) {
1545                 DEBUG_TRACE (DEBUG::Ports, string_compose ("adding %1 to pending port deletion list\n", p->name()));
1546                 if (_port_deletions_pending.write (&p, 1) != 1) {
1547                         error << string_compose (_("programming error: port %1 could not be placed on the pending deletion queue\n"), p->name()) << endmsg;
1548                 }
1549                 _session->auto_connect_thread_wakeup ();
1550         } else {
1551                 DEBUG_TRACE (DEBUG::Ports, string_compose ("Directly delete port %1\n", p->name()));
1552                 delete p;
1553         }
1554 }