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