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