7fe9bebed117a6a9e91498b3cfb51df525edc48b
[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
693 void
694 AudioEngine::reconnect_session_routes (bool reconnect_inputs, bool reconnect_outputs)
695 {
696 #ifdef USE_TRACKS_CODE_FEATURES
697         if (_session) {
698                 _session->reconnect_existing_routes(true, true, reconnect_inputs, reconnect_outputs);
699         }
700 #endif
701 }
702
703
704 void
705 AudioEngine::died ()
706 {
707         /* called from a signal handler for SIGPIPE */
708         _running = false;
709 }
710
711 int
712 AudioEngine::reset_timebase ()
713 {
714         if (_session) {
715                 if (_session->config.get_jack_time_master()) {
716                         _backend->set_time_master (true);
717                 } else {
718                         _backend->set_time_master (false);
719                 }
720         }
721         return 0;
722 }
723
724
725 void
726 AudioEngine::destroy ()
727 {
728         delete _instance;
729         _instance = 0;
730 }
731
732 int
733 AudioEngine::discover_backends ()
734 {
735         vector<std::string> backend_modules;
736
737         _backends.clear ();
738
739         Glib::PatternSpec so_extension_pattern("*backend.so");
740         Glib::PatternSpec dylib_extension_pattern("*backend.dylib");
741
742 #if defined(PLATFORM_WINDOWS) && defined(DEBUGGABLE_BACKENDS)
743         #if defined(DEBUG) || defined(_DEBUG)
744                 Glib::PatternSpec dll_extension_pattern("*backendD.dll");
745         #else
746                 Glib::PatternSpec dll_extension_pattern("*backendRDC.dll");
747         #endif
748 #else
749         Glib::PatternSpec dll_extension_pattern("*backend.dll");
750 #endif
751
752         find_files_matching_pattern (backend_modules, backend_search_path (),
753                                      so_extension_pattern);
754
755         find_files_matching_pattern (backend_modules, backend_search_path (),
756                                      dylib_extension_pattern);
757
758         find_files_matching_pattern (backend_modules, backend_search_path (),
759                                      dll_extension_pattern);
760
761         DEBUG_TRACE (DEBUG::AudioEngine, string_compose ("looking for backends in %1\n", backend_search_path().to_string()));
762
763         for (vector<std::string>::iterator i = backend_modules.begin(); i != backend_modules.end(); ++i) {
764
765                 AudioBackendInfo* info;
766
767                 DEBUG_TRACE (DEBUG::AudioEngine, string_compose ("Checking possible backend in %1\n", *i));
768
769                 if ((info = backend_discover (*i)) != 0) {
770                         _backends.insert (make_pair (info->name, info));
771                 }
772         }
773
774         DEBUG_TRACE (DEBUG::AudioEngine, string_compose ("Found %1 backends\n", _backends.size()));
775
776         return _backends.size();
777 }
778
779 AudioBackendInfo*
780 AudioEngine::backend_discover (const string& path)
781 {
782 #ifdef PLATFORM_WINDOWS
783         // do not show popup dialog (e.g. missing libjack.dll)
784         // win7+ should use SetThreadErrorMode()
785         SetErrorMode(SEM_FAILCRITICALERRORS);
786 #endif
787         Glib::Module module (path);
788 #ifdef PLATFORM_WINDOWS
789         SetErrorMode(0); // reset to system default
790 #endif
791         AudioBackendInfo* info;
792         AudioBackendInfo* (*dfunc)(void);
793         void* func = 0;
794
795         if (!module) {
796                 error << string_compose(_("AudioEngine: cannot load module \"%1\" (%2)"), path,
797                                         Glib::Module::get_last_error()) << endmsg;
798                 return 0;
799         }
800
801         if (!module.get_symbol ("descriptor", func)) {
802                 error << string_compose(_("AudioEngine: backend at \"%1\" has no descriptor function."), path) << endmsg;
803                 error << Glib::Module::get_last_error() << endmsg;
804                 return 0;
805         }
806
807         dfunc = (AudioBackendInfo* (*)(void))func;
808         info = dfunc();
809         if (!info->available()) {
810                 return 0;
811         }
812
813         module.make_resident ();
814
815         return info;
816 }
817
818 #ifdef NDEBUG
819 static bool running_from_source_tree ()
820 {
821         // dup ARDOUR_UI_UTILS::running_from_source_tree ()
822         gchar const *x = g_getenv ("ARDOUR_THEMES_PATH");
823         return x && (string (x).find ("gtk2_ardour") != string::npos);
824 }
825 #endif
826
827 vector<const AudioBackendInfo*>
828 AudioEngine::available_backends() const
829 {
830         vector<const AudioBackendInfo*> r;
831
832         for (BackendMap::const_iterator i = _backends.begin(); i != _backends.end(); ++i) {
833 #ifdef NDEBUG
834                 if (i->first == "None (Dummy)" && !running_from_source_tree () && Config->get_hide_dummy_backend ()) {
835                         continue;
836                 }
837 #endif
838                 r.push_back (i->second);
839         }
840
841         return r;
842 }
843
844 string
845 AudioEngine::current_backend_name() const
846 {
847         if (_backend) {
848                 return _backend->name();
849         }
850         return string();
851 }
852
853 void
854 AudioEngine::drop_backend ()
855 {
856         if (_backend) {
857                 _backend->stop ();
858                 // Stopped is needed for Graph to explicitly terminate threads
859                 Stopped (); /* EMIT SIGNAL */
860                 _backend->drop_device ();
861                 _backend.reset ();
862                 _running = false;
863         }
864 }
865
866 boost::shared_ptr<AudioBackend>
867 AudioEngine::set_backend (const std::string& name, const std::string& arg1, const std::string& arg2)
868 {
869         BackendMap::iterator b = _backends.find (name);
870
871         if (b == _backends.end()) {
872                 return boost::shared_ptr<AudioBackend>();
873         }
874
875         drop_backend ();
876
877         try {
878                 if (b->second->instantiate (arg1, arg2)) {
879                         throw failed_constructor ();
880                 }
881
882                 _backend = b->second->factory (*this);
883
884         } catch (exception& e) {
885                 error << string_compose (_("Could not create backend for %1: %2"), name, e.what()) << endmsg;
886                 return boost::shared_ptr<AudioBackend>();
887         }
888
889         return _backend;
890 }
891
892 /* BACKEND PROXY WRAPPERS */
893
894 int
895 AudioEngine::start (bool for_latency)
896 {
897         if (!_backend) {
898                 return -1;
899         }
900
901         if (_running && _backend->can_change_systemic_latency_when_running()) {
902                 _started_for_latency = for_latency;
903         }
904
905         if (_running) {
906                 return 0;
907         }
908
909         _processed_samples = 0;
910         last_monitor_check = 0;
911
912         int error_code = _backend->start (for_latency);
913
914         if (error_code != 0) {
915                 _last_backend_error_string = AudioBackend::get_error_string((AudioBackend::ErrorCode) error_code);
916                 return -1;
917         }
918
919         _running = true;
920
921         if (_session) {
922                 _session->set_sample_rate (_backend->sample_rate());
923
924                 if (_session->config.get_jack_time_master()) {
925                         _backend->set_time_master (true);
926                 }
927
928         }
929
930         midi_info_dirty = true;
931
932         if (!for_latency) {
933                 /* Call the library-wide ::init_post_engine() before emitting
934                  * running to ensure that its tasks are complete before any
935                  * signal handlers execute. PBD::Signal does not ensure
936                  * ordering of signal handlers so even if ::init_post_engine()
937                  * is connected first, it may not run first.
938                  */
939
940                 ARDOUR::init_post_engine (_start_cnt);
941
942                 Running (_start_cnt); /* EMIT SIGNAL */
943
944                 /* latency start/stop cycles do not count as "starts" */
945
946                 _start_cnt++;
947         }
948
949
950         return 0;
951 }
952
953 int
954 AudioEngine::stop (bool for_latency)
955 {
956         bool stop_engine = true;
957
958         if (!_backend) {
959                 return 0;
960         }
961
962         Glib::Threads::Mutex::Lock pl (_process_lock, Glib::Threads::NOT_LOCK);
963
964         if (running()) {
965                 pl.acquire ();
966         }
967
968         if (for_latency && _backend->can_change_systemic_latency_when_running()) {
969                 stop_engine = false;
970                 if (_running && _started_for_latency) {
971                         _backend->start (false); // keep running, reload latencies
972                 }
973         } else {
974                 if (_backend->stop ()) {
975                         if (pl.locked ()) {
976                                 pl.release ();
977                         }
978                         return -1;
979                 }
980         }
981
982         if (pl.locked ()) {
983                 pl.release ();
984         }
985
986         const bool was_running_will_stop = (_running && stop_engine);
987
988         if (was_running_will_stop) {
989                 _running = false;
990         }
991
992         if (_session && was_running_will_stop && !_session->loading() && !_session->deletion_in_progress()) {
993                 // it's not a halt, but should be handled the same way:
994                 // disable record, stop transport and I/O processign but save the data.
995                 _session->engine_halted ();
996         }
997
998         if (was_running_will_stop) {
999                 if (!for_latency) {
1000                         _started_for_latency = false;
1001                 } else if (!_started_for_latency) {
1002                         _stopped_for_latency = true;
1003                 }
1004         }
1005         _processed_samples = 0;
1006         _measuring_latency = MeasureNone;
1007         _latency_output_port = 0;
1008         _latency_input_port = 0;
1009
1010         if (stop_engine) {
1011                 Port::PortDrop ();
1012         }
1013
1014         if (stop_engine) {
1015                 TransportMasterManager& tmm (TransportMasterManager::instance());
1016                 tmm.engine_stopped ();
1017                 Stopped (); /* EMIT SIGNAL */
1018         }
1019
1020         return 0;
1021 }
1022
1023 int
1024 AudioEngine::freewheel (bool start_stop)
1025 {
1026         if (!_backend) {
1027                 return -1;
1028         }
1029
1030         /* _freewheeling will be set when first Freewheel signal occurs */
1031
1032         return _backend->freewheel (start_stop);
1033 }
1034
1035 float
1036 AudioEngine::get_dsp_load() const
1037 {
1038         if (!_backend || !_running) {
1039                 return 0.0;
1040         }
1041         return _backend->dsp_load ();
1042 }
1043
1044 bool
1045 AudioEngine::is_realtime() const
1046 {
1047         if (!_backend) {
1048                 return false;
1049         }
1050
1051         return _backend->is_realtime();
1052 }
1053
1054 void
1055 AudioEngine::transport_start ()
1056 {
1057         if (!_backend) {
1058                 return;
1059         }
1060         return _backend->transport_start ();
1061 }
1062
1063 void
1064 AudioEngine::transport_stop ()
1065 {
1066         if (!_backend) {
1067                 return;
1068         }
1069         return _backend->transport_stop ();
1070 }
1071
1072 TransportState
1073 AudioEngine::transport_state ()
1074 {
1075         if (!_backend) {
1076                 return TransportStopped;
1077         }
1078         return _backend->transport_state ();
1079 }
1080
1081 void
1082 AudioEngine::transport_locate (samplepos_t pos)
1083 {
1084         if (!_backend) {
1085                 return;
1086         }
1087         return _backend->transport_locate (pos);
1088 }
1089
1090 samplepos_t
1091 AudioEngine::transport_sample()
1092 {
1093         if (!_backend) {
1094                 return 0;
1095         }
1096         return _backend->transport_sample ();
1097 }
1098
1099 samplecnt_t
1100 AudioEngine::sample_rate () const
1101 {
1102         if (!_backend) {
1103                 return 0;
1104         }
1105         return _backend->sample_rate ();
1106 }
1107
1108 pframes_t
1109 AudioEngine::samples_per_cycle () const
1110 {
1111         if (!_backend) {
1112                 return 0;
1113         }
1114         return _backend->buffer_size ();
1115 }
1116
1117 int
1118 AudioEngine::usecs_per_cycle () const
1119 {
1120         if (!_backend) {
1121                 return -1;
1122         }
1123         return _backend->usecs_per_cycle ();
1124 }
1125
1126 size_t
1127 AudioEngine::raw_buffer_size (DataType t)
1128 {
1129         if (!_backend) {
1130                 return -1;
1131         }
1132         return _backend->raw_buffer_size (t);
1133 }
1134
1135 samplepos_t
1136 AudioEngine::sample_time ()
1137 {
1138         if (!_backend) {
1139                 return 0;
1140         }
1141         return _backend->sample_time ();
1142 }
1143
1144 samplepos_t
1145 AudioEngine::sample_time_at_cycle_start ()
1146 {
1147         if (!_backend) {
1148                 return 0;
1149         }
1150         return _backend->sample_time_at_cycle_start ();
1151 }
1152
1153 pframes_t
1154 AudioEngine::samples_since_cycle_start ()
1155 {
1156         if (!_backend) {
1157                 return 0;
1158         }
1159         return _backend->samples_since_cycle_start ();
1160 }
1161
1162 bool
1163 AudioEngine::get_sync_offset (pframes_t& offset) const
1164 {
1165         if (!_backend) {
1166                 return false;
1167         }
1168         return _backend->get_sync_offset (offset);
1169 }
1170
1171 int
1172 AudioEngine::create_process_thread (boost::function<void()> func)
1173 {
1174         if (!_backend) {
1175                 return -1;
1176         }
1177         return _backend->create_process_thread (func);
1178 }
1179
1180 int
1181 AudioEngine::join_process_threads ()
1182 {
1183         if (!_backend) {
1184                 return -1;
1185         }
1186         return _backend->join_process_threads ();
1187 }
1188
1189 bool
1190 AudioEngine::in_process_thread ()
1191 {
1192         if (!_backend) {
1193                 return false;
1194         }
1195         return _backend->in_process_thread ();
1196 }
1197
1198 uint32_t
1199 AudioEngine::process_thread_count ()
1200 {
1201         if (!_backend) {
1202                 return 0;
1203         }
1204         return _backend->process_thread_count ();
1205 }
1206
1207 int
1208 AudioEngine::set_device_name (const std::string& name)
1209 {
1210         if (!_backend) {
1211                 return -1;
1212         }
1213         return _backend->set_device_name  (name);
1214 }
1215
1216 int
1217 AudioEngine::set_sample_rate (float sr)
1218 {
1219         if (!_backend) {
1220                 return -1;
1221         }
1222
1223         return _backend->set_sample_rate  (sr);
1224 }
1225
1226 int
1227 AudioEngine::set_buffer_size (uint32_t bufsiz)
1228 {
1229         if (!_backend) {
1230                 return -1;
1231         }
1232         return _backend->set_buffer_size  (bufsiz);
1233 }
1234
1235 int
1236 AudioEngine::set_interleaved (bool yn)
1237 {
1238         if (!_backend) {
1239                 return -1;
1240         }
1241         return _backend->set_interleaved  (yn);
1242 }
1243
1244 int
1245 AudioEngine::set_input_channels (uint32_t ic)
1246 {
1247         if (!_backend) {
1248                 return -1;
1249         }
1250         return _backend->set_input_channels  (ic);
1251 }
1252
1253 int
1254 AudioEngine::set_output_channels (uint32_t oc)
1255 {
1256         if (!_backend) {
1257                 return -1;
1258         }
1259         return _backend->set_output_channels (oc);
1260 }
1261
1262 int
1263 AudioEngine::set_systemic_input_latency (uint32_t il)
1264 {
1265         if (!_backend) {
1266                 return -1;
1267         }
1268         return _backend->set_systemic_input_latency  (il);
1269 }
1270
1271 int
1272 AudioEngine::set_systemic_output_latency (uint32_t ol)
1273 {
1274         if (!_backend) {
1275                 return -1;
1276         }
1277         return _backend->set_systemic_output_latency  (ol);
1278 }
1279
1280 bool
1281 AudioEngine::thread_initialised_for_audio_processing ()
1282 {
1283         return SessionEvent::has_per_thread_pool () && AsyncMIDIPort::is_process_thread();
1284 }
1285
1286 /* END OF BACKEND PROXY API */
1287
1288 void
1289 AudioEngine::thread_init_callback (void* arg)
1290 {
1291         /* make sure that anybody who needs to know about this thread
1292            knows about it.
1293         */
1294
1295         pthread_set_name (X_("audioengine"));
1296
1297         const int thread_num = g_atomic_int_add (&audioengine_thread_cnt, 1);
1298         const string thread_name = string_compose (X_("AudioEngine %1"), thread_num);
1299
1300         SessionEvent::create_per_thread_pool (thread_name, 512);
1301         PBD::notify_event_loops_about_thread_creation (pthread_self(), thread_name, 4096);
1302         AsyncMIDIPort::set_process_thread (pthread_self());
1303
1304         if (arg) {
1305                 delete AudioEngine::instance()->_main_thread;
1306                 /* the special thread created/managed by the backend */
1307                 AudioEngine::instance()->_main_thread = new ProcessThread;
1308         }
1309 }
1310
1311 int
1312 AudioEngine::sync_callback (TransportState state, samplepos_t position)
1313 {
1314         if (_session) {
1315                 return _session->backend_sync_callback (state, position);
1316         }
1317         return 0;
1318 }
1319
1320 void
1321 AudioEngine::freewheel_callback (bool onoff)
1322 {
1323         _freewheeling = onoff;
1324 }
1325
1326 void
1327 AudioEngine::latency_callback (bool for_playback)
1328 {
1329         if (_session) {
1330                 _session->update_latency (for_playback);
1331         }
1332 }
1333
1334 void
1335 AudioEngine::update_latencies ()
1336 {
1337         if (_backend) {
1338                 _backend->update_latencies ();
1339         }
1340 }
1341
1342 void
1343 AudioEngine::halted_callback (const char* why)
1344 {
1345         if (_in_destructor) {
1346                 /* everything is under control */
1347                 return;
1348         }
1349
1350         _running = false;
1351
1352         Port::PortDrop (); /* EMIT SIGNAL */
1353
1354         if (!_started_for_latency) {
1355                 Halted (why);      /* EMIT SIGNAL */
1356         }
1357 }
1358
1359 bool
1360 AudioEngine::setup_required () const
1361 {
1362         if (_backend) {
1363                 if (_backend->info().already_configured())
1364                         return false;
1365         } else {
1366                 if (_backends.size() == 1 && _backends.begin()->second->already_configured()) {
1367                         return false;
1368                 }
1369         }
1370
1371         return true;
1372 }
1373
1374 int
1375 AudioEngine::prepare_for_latency_measurement ()
1376 {
1377         if (!_backend) {
1378                 return -1;
1379         }
1380
1381         if (running() && _started_for_latency) {
1382                 return 0;
1383         }
1384
1385         if (_backend->can_change_systemic_latency_when_running()) {
1386                 if (_running) {
1387                         _backend->start (true); // zero latency reporting of running backend
1388                 } else if (start (true)) {
1389                         return -1;
1390                 }
1391                 _started_for_latency = true;
1392                 return 0;
1393         }
1394
1395         if (running()) {
1396                 stop (true);
1397         }
1398
1399         if (start (true)) {
1400                 return -1;
1401         }
1402         _started_for_latency = true;
1403         return 0;
1404 }
1405
1406 int
1407 AudioEngine::start_latency_detection (bool for_midi)
1408 {
1409         if (prepare_for_latency_measurement ()) {
1410                 return -1;
1411         }
1412
1413         PortEngine& pe (port_engine());
1414
1415         delete _mtdm;
1416         _mtdm = 0;
1417
1418         delete _mididm;
1419         _mididm = 0;
1420
1421         /* find the ports we will connect to */
1422
1423         PortEngine::PortHandle out = pe.get_port_by_name (_latency_output_name);
1424         PortEngine::PortHandle in = pe.get_port_by_name (_latency_input_name);
1425
1426         if (!out || !in) {
1427                 stop (true);
1428                 return -1;
1429         }
1430
1431         /* create the ports we will use to read/write data */
1432         if (for_midi) {
1433                 if ((_latency_output_port = pe.register_port ("latency_out", DataType::MIDI, IsOutput)) == 0) {
1434                         stop (true);
1435                         return -1;
1436                 }
1437                 if (pe.connect (_latency_output_port, _latency_output_name)) {
1438                         pe.unregister_port (_latency_output_port);
1439                         stop (true);
1440                         return -1;
1441                 }
1442
1443                 const string portname ("latency_in");
1444                 if ((_latency_input_port = pe.register_port (portname, DataType::MIDI, IsInput)) == 0) {
1445                         pe.unregister_port (_latency_input_port);
1446                         pe.unregister_port (_latency_output_port);
1447                         stop (true);
1448                         return -1;
1449                 }
1450                 if (pe.connect (_latency_input_name, make_port_name_non_relative (portname))) {
1451                         pe.unregister_port (_latency_input_port);
1452                         pe.unregister_port (_latency_output_port);
1453                         stop (true);
1454                         return -1;
1455                 }
1456
1457                 _mididm = new MIDIDM (sample_rate());
1458
1459         } else {
1460
1461                 if ((_latency_output_port = pe.register_port ("latency_out", DataType::AUDIO, IsOutput)) == 0) {
1462                         stop (true);
1463                         return -1;
1464                 }
1465                 if (pe.connect (_latency_output_port, _latency_output_name)) {
1466                         pe.unregister_port (_latency_output_port);
1467                         stop (true);
1468                         return -1;
1469                 }
1470
1471                 const string portname ("latency_in");
1472                 if ((_latency_input_port = pe.register_port (portname, DataType::AUDIO, IsInput)) == 0) {
1473                         pe.unregister_port (_latency_input_port);
1474                         pe.unregister_port (_latency_output_port);
1475                         stop (true);
1476                         return -1;
1477                 }
1478                 if (pe.connect (_latency_input_name, make_port_name_non_relative (portname))) {
1479                         pe.unregister_port (_latency_input_port);
1480                         pe.unregister_port (_latency_output_port);
1481                         stop (true);
1482                         return -1;
1483                 }
1484
1485                 _mtdm = new MTDM (sample_rate());
1486
1487         }
1488
1489         LatencyRange lr;
1490         _latency_signal_latency = 0;
1491         lr = pe.get_latency_range (in, false);
1492         _latency_signal_latency = lr.max;
1493         lr = pe.get_latency_range (out, true);
1494         _latency_signal_latency += lr.max;
1495
1496         /* all created and connected, lets go */
1497         _latency_flush_samples = samples_per_cycle();
1498         _measuring_latency = for_midi ? MeasureMIDI : MeasureAudio;
1499
1500         return 0;
1501 }
1502
1503 void
1504 AudioEngine::stop_latency_detection ()
1505 {
1506         _measuring_latency = MeasureNone;
1507
1508         if (_latency_output_port) {
1509                 port_engine().unregister_port (_latency_output_port);
1510                 _latency_output_port = 0;
1511         }
1512         if (_latency_input_port) {
1513                 port_engine().unregister_port (_latency_input_port);
1514                 _latency_input_port = 0;
1515         }
1516
1517         if (_running && _backend->can_change_systemic_latency_when_running()) {
1518                 if (_started_for_latency) {
1519                         _running = false; // force reload: reset latencies and emit Running()
1520                         start ();
1521                 }
1522         }
1523
1524         if (_running && !_started_for_latency) {
1525                 assert (!_stopped_for_latency);
1526                 return;
1527         }
1528
1529         if (!_backend->can_change_systemic_latency_when_running()) {
1530                 stop (true);
1531         }
1532
1533         if (_stopped_for_latency) {
1534                 start ();
1535         }
1536
1537         _stopped_for_latency = false;
1538         _started_for_latency = false;
1539 }
1540
1541 void
1542 AudioEngine::set_latency_output_port (const string& name)
1543 {
1544         _latency_output_name = name;
1545 }
1546
1547 void
1548 AudioEngine::set_latency_input_port (const string& name)
1549 {
1550         _latency_input_name = name;
1551 }
1552
1553 void
1554 AudioEngine::add_pending_port_deletion (Port* p)
1555 {
1556         if (_session) {
1557                 DEBUG_TRACE (DEBUG::Ports, string_compose ("adding %1 to pending port deletion list\n", p->name()));
1558                 if (_port_deletions_pending.write (&p, 1) != 1) {
1559                         error << string_compose (_("programming error: port %1 could not be placed on the pending deletion queue\n"), p->name()) << endmsg;
1560                 }
1561                 _session->auto_connect_thread_wakeup ();
1562         } else {
1563                 DEBUG_TRACE (DEBUG::Ports, string_compose ("Directly delete port %1\n", p->name()));
1564                 delete p;
1565         }
1566 }