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