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