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