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