fix error introduced in MTC transport master
[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 (_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         if (_session && _running && stop_engine &&
972             (_session->state_of_the_state() & Session::Loading) == 0 &&
973             (_session->state_of_the_state() & Session::Deletion) == 0) {
974                 // it's not a halt, but should be handled the same way:
975                 // disable record, stop transport and I/O processign but save the data.
976                 _session->engine_halted ();
977         }
978
979         if (stop_engine && _running) {
980                 _running = false;
981                 if (!for_latency) {
982                         _started_for_latency = false;
983                 } else if (!_started_for_latency) {
984                         _stopped_for_latency = true;
985                 }
986         }
987         _processed_samples = 0;
988         _measuring_latency = MeasureNone;
989         _latency_output_port = 0;
990         _latency_input_port = 0;
991
992         if (stop_engine) {
993                 Port::PortDrop ();
994         }
995
996         if (stop_engine) {
997                 Stopped (); /* EMIT SIGNAL */
998         }
999
1000         return 0;
1001 }
1002
1003 int
1004 AudioEngine::freewheel (bool start_stop)
1005 {
1006         if (!_backend) {
1007                 return -1;
1008         }
1009
1010         /* _freewheeling will be set when first Freewheel signal occurs */
1011
1012         return _backend->freewheel (start_stop);
1013 }
1014
1015 float
1016 AudioEngine::get_dsp_load() const
1017 {
1018         if (!_backend || !_running) {
1019                 return 0.0;
1020         }
1021         return _backend->dsp_load ();
1022 }
1023
1024 bool
1025 AudioEngine::is_realtime() const
1026 {
1027         if (!_backend) {
1028                 return false;
1029         }
1030
1031         return _backend->is_realtime();
1032 }
1033
1034 bool
1035 AudioEngine::connected() const
1036 {
1037         if (!_backend) {
1038                 return false;
1039         }
1040
1041         return _backend->available();
1042 }
1043
1044 void
1045 AudioEngine::transport_start ()
1046 {
1047         if (!_backend) {
1048                 return;
1049         }
1050         return _backend->transport_start ();
1051 }
1052
1053 void
1054 AudioEngine::transport_stop ()
1055 {
1056         if (!_backend) {
1057                 return;
1058         }
1059         return _backend->transport_stop ();
1060 }
1061
1062 TransportState
1063 AudioEngine::transport_state ()
1064 {
1065         if (!_backend) {
1066                 return TransportStopped;
1067         }
1068         return _backend->transport_state ();
1069 }
1070
1071 void
1072 AudioEngine::transport_locate (samplepos_t pos)
1073 {
1074         if (!_backend) {
1075                 return;
1076         }
1077         return _backend->transport_locate (pos);
1078 }
1079
1080 samplepos_t
1081 AudioEngine::transport_sample()
1082 {
1083         if (!_backend) {
1084                 return 0;
1085         }
1086         return _backend->transport_sample ();
1087 }
1088
1089 samplecnt_t
1090 AudioEngine::sample_rate () const
1091 {
1092         if (!_backend) {
1093                 return 0;
1094         }
1095         return _backend->sample_rate ();
1096 }
1097
1098 pframes_t
1099 AudioEngine::samples_per_cycle () const
1100 {
1101         if (!_backend) {
1102                 return 0;
1103         }
1104         return _backend->buffer_size ();
1105 }
1106
1107 int
1108 AudioEngine::usecs_per_cycle () const
1109 {
1110         if (!_backend) {
1111                 return -1;
1112         }
1113         return _backend->usecs_per_cycle ();
1114 }
1115
1116 size_t
1117 AudioEngine::raw_buffer_size (DataType t)
1118 {
1119         if (!_backend) {
1120                 return -1;
1121         }
1122         return _backend->raw_buffer_size (t);
1123 }
1124
1125 samplepos_t
1126 AudioEngine::sample_time ()
1127 {
1128         if (!_backend) {
1129                 return 0;
1130         }
1131         return _backend->sample_time ();
1132 }
1133
1134 samplepos_t
1135 AudioEngine::sample_time_at_cycle_start ()
1136 {
1137         if (!_backend) {
1138                 return 0;
1139         }
1140         return _backend->sample_time_at_cycle_start ();
1141 }
1142
1143 pframes_t
1144 AudioEngine::samples_since_cycle_start ()
1145 {
1146         if (!_backend) {
1147                 return 0;
1148         }
1149         return _backend->samples_since_cycle_start ();
1150 }
1151
1152 bool
1153 AudioEngine::get_sync_offset (pframes_t& offset) const
1154 {
1155         if (!_backend) {
1156                 return false;
1157         }
1158         return _backend->get_sync_offset (offset);
1159 }
1160
1161 int
1162 AudioEngine::create_process_thread (boost::function<void()> func)
1163 {
1164         if (!_backend) {
1165                 return -1;
1166         }
1167         return _backend->create_process_thread (func);
1168 }
1169
1170 int
1171 AudioEngine::join_process_threads ()
1172 {
1173         if (!_backend) {
1174                 return -1;
1175         }
1176         return _backend->join_process_threads ();
1177 }
1178
1179 bool
1180 AudioEngine::in_process_thread ()
1181 {
1182         if (!_backend) {
1183                 return false;
1184         }
1185         return _backend->in_process_thread ();
1186 }
1187
1188 uint32_t
1189 AudioEngine::process_thread_count ()
1190 {
1191         if (!_backend) {
1192                 return 0;
1193         }
1194         return _backend->process_thread_count ();
1195 }
1196
1197 int
1198 AudioEngine::set_device_name (const std::string& name)
1199 {
1200         if (!_backend) {
1201                 return -1;
1202         }
1203         return _backend->set_device_name  (name);
1204 }
1205
1206 int
1207 AudioEngine::set_sample_rate (float sr)
1208 {
1209         if (!_backend) {
1210                 return -1;
1211         }
1212
1213         return _backend->set_sample_rate  (sr);
1214 }
1215
1216 int
1217 AudioEngine::set_buffer_size (uint32_t bufsiz)
1218 {
1219         if (!_backend) {
1220                 return -1;
1221         }
1222         return _backend->set_buffer_size  (bufsiz);
1223 }
1224
1225 int
1226 AudioEngine::set_interleaved (bool yn)
1227 {
1228         if (!_backend) {
1229                 return -1;
1230         }
1231         return _backend->set_interleaved  (yn);
1232 }
1233
1234 int
1235 AudioEngine::set_input_channels (uint32_t ic)
1236 {
1237         if (!_backend) {
1238                 return -1;
1239         }
1240         return _backend->set_input_channels  (ic);
1241 }
1242
1243 int
1244 AudioEngine::set_output_channels (uint32_t oc)
1245 {
1246         if (!_backend) {
1247                 return -1;
1248         }
1249         return _backend->set_output_channels (oc);
1250 }
1251
1252 int
1253 AudioEngine::set_systemic_input_latency (uint32_t il)
1254 {
1255         if (!_backend) {
1256                 return -1;
1257         }
1258         return _backend->set_systemic_input_latency  (il);
1259 }
1260
1261 int
1262 AudioEngine::set_systemic_output_latency (uint32_t ol)
1263 {
1264         if (!_backend) {
1265                 return -1;
1266         }
1267         return _backend->set_systemic_output_latency  (ol);
1268 }
1269
1270 bool
1271 AudioEngine::thread_initialised_for_audio_processing ()
1272 {
1273         return SessionEvent::has_per_thread_pool () && AsyncMIDIPort::is_process_thread();
1274 }
1275
1276 /* END OF BACKEND PROXY API */
1277
1278 void
1279 AudioEngine::thread_init_callback (void* arg)
1280 {
1281         /* make sure that anybody who needs to know about this thread
1282            knows about it.
1283         */
1284
1285         pthread_set_name (X_("audioengine"));
1286
1287         const int thread_num = g_atomic_int_add (&audioengine_thread_cnt, 1);
1288         const string thread_name = string_compose (X_("AudioEngine %1"), thread_num);
1289
1290         SessionEvent::create_per_thread_pool (thread_name, 512);
1291         PBD::notify_event_loops_about_thread_creation (pthread_self(), thread_name, 4096);
1292         AsyncMIDIPort::set_process_thread (pthread_self());
1293
1294         if (arg) {
1295                 delete AudioEngine::instance()->_main_thread;
1296                 /* the special thread created/managed by the backend */
1297                 AudioEngine::instance()->_main_thread = new ProcessThread;
1298         }
1299 }
1300
1301 int
1302 AudioEngine::sync_callback (TransportState state, samplepos_t position)
1303 {
1304         if (_session) {
1305                 return _session->backend_sync_callback (state, position);
1306         }
1307         return 0;
1308 }
1309
1310 void
1311 AudioEngine::freewheel_callback (bool onoff)
1312 {
1313         _freewheeling = onoff;
1314 }
1315
1316 void
1317 AudioEngine::latency_callback (bool for_playback)
1318 {
1319         if (_session) {
1320                 _session->update_latency (for_playback);
1321         }
1322 }
1323
1324 void
1325 AudioEngine::update_latencies ()
1326 {
1327         if (_backend) {
1328                 _backend->update_latencies ();
1329         }
1330 }
1331
1332 void
1333 AudioEngine::halted_callback (const char* why)
1334 {
1335         if (_in_destructor) {
1336                 /* everything is under control */
1337                 return;
1338         }
1339
1340         _running = false;
1341
1342         Port::PortDrop (); /* EMIT SIGNAL */
1343
1344         if (!_started_for_latency) {
1345                 Halted (why);      /* EMIT SIGNAL */
1346         }
1347 }
1348
1349 bool
1350 AudioEngine::setup_required () const
1351 {
1352         if (_backend) {
1353                 if (_backend->info().already_configured())
1354                         return false;
1355         } else {
1356                 if (_backends.size() == 1 && _backends.begin()->second->already_configured()) {
1357                         return false;
1358                 }
1359         }
1360
1361         return true;
1362 }
1363
1364 int
1365 AudioEngine::prepare_for_latency_measurement ()
1366 {
1367         if (!_backend) {
1368                 return -1;
1369         }
1370
1371         if (running() && _started_for_latency) {
1372                 return 0;
1373         }
1374
1375         if (_backend->can_change_systemic_latency_when_running()) {
1376                 if (_running) {
1377                         _backend->start (true); // zero latency reporting of running backend
1378                 } else if (start (true)) {
1379                         return -1;
1380                 }
1381                 _started_for_latency = true;
1382                 return 0;
1383         }
1384
1385         if (running()) {
1386                 stop (true);
1387         }
1388
1389         if (start (true)) {
1390                 return -1;
1391         }
1392         _started_for_latency = true;
1393         return 0;
1394 }
1395
1396 int
1397 AudioEngine::start_latency_detection (bool for_midi)
1398 {
1399         if (prepare_for_latency_measurement ()) {
1400                 return -1;
1401         }
1402
1403         PortEngine& pe (port_engine());
1404
1405         delete _mtdm;
1406         _mtdm = 0;
1407
1408         delete _mididm;
1409         _mididm = 0;
1410
1411         /* find the ports we will connect to */
1412
1413         PortEngine::PortHandle out = pe.get_port_by_name (_latency_output_name);
1414         PortEngine::PortHandle in = pe.get_port_by_name (_latency_input_name);
1415
1416         if (!out || !in) {
1417                 stop (true);
1418                 return -1;
1419         }
1420
1421         /* create the ports we will use to read/write data */
1422         if (for_midi) {
1423                 if ((_latency_output_port = pe.register_port ("latency_out", DataType::MIDI, IsOutput)) == 0) {
1424                         stop (true);
1425                         return -1;
1426                 }
1427                 if (pe.connect (_latency_output_port, _latency_output_name)) {
1428                         pe.unregister_port (_latency_output_port);
1429                         stop (true);
1430                         return -1;
1431                 }
1432
1433                 const string portname ("latency_in");
1434                 if ((_latency_input_port = pe.register_port (portname, DataType::MIDI, IsInput)) == 0) {
1435                         pe.unregister_port (_latency_input_port);
1436                         pe.unregister_port (_latency_output_port);
1437                         stop (true);
1438                         return -1;
1439                 }
1440                 if (pe.connect (_latency_input_name, make_port_name_non_relative (portname))) {
1441                         pe.unregister_port (_latency_input_port);
1442                         pe.unregister_port (_latency_output_port);
1443                         stop (true);
1444                         return -1;
1445                 }
1446
1447                 _mididm = new MIDIDM (sample_rate());
1448
1449         } else {
1450
1451                 if ((_latency_output_port = pe.register_port ("latency_out", DataType::AUDIO, IsOutput)) == 0) {
1452                         stop (true);
1453                         return -1;
1454                 }
1455                 if (pe.connect (_latency_output_port, _latency_output_name)) {
1456                         pe.unregister_port (_latency_output_port);
1457                         stop (true);
1458                         return -1;
1459                 }
1460
1461                 const string portname ("latency_in");
1462                 if ((_latency_input_port = pe.register_port (portname, DataType::AUDIO, IsInput)) == 0) {
1463                         pe.unregister_port (_latency_input_port);
1464                         pe.unregister_port (_latency_output_port);
1465                         stop (true);
1466                         return -1;
1467                 }
1468                 if (pe.connect (_latency_input_name, make_port_name_non_relative (portname))) {
1469                         pe.unregister_port (_latency_input_port);
1470                         pe.unregister_port (_latency_output_port);
1471                         stop (true);
1472                         return -1;
1473                 }
1474
1475                 _mtdm = new MTDM (sample_rate());
1476
1477         }
1478
1479         LatencyRange lr;
1480         _latency_signal_latency = 0;
1481         lr = pe.get_latency_range (in, false);
1482         _latency_signal_latency = lr.max;
1483         lr = pe.get_latency_range (out, true);
1484         _latency_signal_latency += lr.max;
1485
1486         /* all created and connected, lets go */
1487         _latency_flush_samples = samples_per_cycle();
1488         _measuring_latency = for_midi ? MeasureMIDI : MeasureAudio;
1489
1490         return 0;
1491 }
1492
1493 void
1494 AudioEngine::stop_latency_detection ()
1495 {
1496         _measuring_latency = MeasureNone;
1497
1498         if (_latency_output_port) {
1499                 port_engine().unregister_port (_latency_output_port);
1500                 _latency_output_port = 0;
1501         }
1502         if (_latency_input_port) {
1503                 port_engine().unregister_port (_latency_input_port);
1504                 _latency_input_port = 0;
1505         }
1506
1507         if (_running && _backend->can_change_systemic_latency_when_running()) {
1508                 if (_started_for_latency) {
1509                         _running = false; // force reload: reset latencies and emit Running()
1510                         start ();
1511                 }
1512         }
1513
1514         if (_running && !_started_for_latency) {
1515                 assert (!_stopped_for_latency);
1516                 return;
1517         }
1518
1519         if (!_backend->can_change_systemic_latency_when_running()) {
1520                 stop (true);
1521         }
1522
1523         if (_stopped_for_latency) {
1524                 start ();
1525         }
1526
1527         _stopped_for_latency = false;
1528         _started_for_latency = false;
1529 }
1530
1531 void
1532 AudioEngine::set_latency_output_port (const string& name)
1533 {
1534         _latency_output_name = name;
1535 }
1536
1537 void
1538 AudioEngine::set_latency_input_port (const string& name)
1539 {
1540         _latency_input_name = name;
1541 }
1542
1543 void
1544 AudioEngine::add_pending_port_deletion (Port* p)
1545 {
1546         if (_session) {
1547                 DEBUG_TRACE (DEBUG::Ports, string_compose ("adding %1 to pending port deletion list\n", p->name()));
1548                 if (_port_deletions_pending.write (&p, 1) != 1) {
1549                         error << string_compose (_("programming error: port %1 could not be placed on the pending deletion queue\n"), p->name()) << endmsg;
1550                 }
1551                 _session->auto_connect_thread_wakeup ();
1552         } else {
1553                 DEBUG_TRACE (DEBUG::Ports, string_compose ("Directly delete port %1\n", p->name()));
1554                 delete p;
1555         }
1556 }