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