update engine to allow latency measurement w/o restart.
[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         bool stop_engine = true;
871
872         if (!_backend) {
873                 return 0;
874         }
875
876         Glib::Threads::Mutex::Lock pl (_process_lock, Glib::Threads::NOT_LOCK);
877
878         if (running()) {
879                 pl.acquire ();
880         }
881
882         if (for_latency && _backend->can_change_systemic_latency_when_running()) {
883                 stop_engine = false;
884         } else {
885                 if (_backend->stop ()) {
886                         pl.release ();
887                         return -1;
888                 }
889         }
890
891         if (pl.locked ()) {
892                 pl.release ();
893         }
894
895         if (_session && _running && stop_engine &&
896             (_session->state_of_the_state() & Session::Loading) == 0 &&
897             (_session->state_of_the_state() & Session::Deletion) == 0) {
898                 // it's not a halt, but should be handled the same way:
899                 // disable record, stop transport and I/O processign but save the data.
900                 _session->engine_halted ();
901         }
902
903         if (stop_engine) {
904                 _running = false;
905         }
906         _processed_frames = 0;
907         _measuring_latency = MeasureNone;
908         _latency_output_port = 0;
909         _latency_input_port = 0;
910         _started_for_latency = false;
911
912         if (stop_engine) {
913                 Port::PortDrop ();
914         }
915
916         if (!for_latency && stop_engine) {
917                 Stopped (); /* EMIT SIGNAL */
918         }
919
920         return 0;
921 }
922
923 int
924 AudioEngine::freewheel (bool start_stop)
925 {
926         if (!_backend) {
927                 return -1;
928         }
929
930         /* _freewheeling will be set when first Freewheel signal occurs */
931
932         return _backend->freewheel (start_stop);
933 }
934
935 float
936 AudioEngine::get_dsp_load() const
937 {
938         if (!_backend || !_running) {
939                 return 0.0;
940         }
941         return _backend->dsp_load ();
942 }
943
944 bool
945 AudioEngine::is_realtime() const
946 {
947         if (!_backend) {
948                 return false;
949         }
950
951         return _backend->is_realtime();
952 }
953
954 bool
955 AudioEngine::connected() const
956 {
957         if (!_backend) {
958                 return false;
959         }
960
961         return _backend->available();
962 }
963
964 void
965 AudioEngine::transport_start ()
966 {
967         if (!_backend) {
968                 return;
969         }
970         return _backend->transport_start ();
971 }
972
973 void
974 AudioEngine::transport_stop ()
975 {
976         if (!_backend) {
977                 return;
978         }
979         return _backend->transport_stop ();
980 }
981
982 TransportState
983 AudioEngine::transport_state ()
984 {
985         if (!_backend) {
986                 return TransportStopped;
987         }
988         return _backend->transport_state ();
989 }
990
991 void
992 AudioEngine::transport_locate (framepos_t pos)
993 {
994         if (!_backend) {
995                 return;
996         }
997         return _backend->transport_locate (pos);
998 }
999
1000 framepos_t
1001 AudioEngine::transport_frame()
1002 {
1003         if (!_backend) {
1004                 return 0;
1005         }
1006         return _backend->transport_frame ();
1007 }
1008
1009 framecnt_t
1010 AudioEngine::sample_rate () const
1011 {
1012         if (!_backend) {
1013                 return 0;
1014         }
1015         return _backend->sample_rate ();
1016 }
1017
1018 pframes_t
1019 AudioEngine::samples_per_cycle () const
1020 {
1021         if (!_backend) {
1022                 return 0;
1023         }
1024         return _backend->buffer_size ();
1025 }
1026
1027 int
1028 AudioEngine::usecs_per_cycle () const
1029 {
1030         if (!_backend) {
1031                 return -1;
1032         }
1033         return _backend->usecs_per_cycle ();
1034 }
1035
1036 size_t
1037 AudioEngine::raw_buffer_size (DataType t)
1038 {
1039         if (!_backend) {
1040                 return -1;
1041         }
1042         return _backend->raw_buffer_size (t);
1043 }
1044
1045 framepos_t
1046 AudioEngine::sample_time ()
1047 {
1048         if (!_backend) {
1049                 return 0;
1050         }
1051         return _backend->sample_time ();
1052 }
1053
1054 framepos_t
1055 AudioEngine::sample_time_at_cycle_start ()
1056 {
1057         if (!_backend) {
1058                 return 0;
1059         }
1060         return _backend->sample_time_at_cycle_start ();
1061 }
1062
1063 pframes_t
1064 AudioEngine::samples_since_cycle_start ()
1065 {
1066         if (!_backend) {
1067                 return 0;
1068         }
1069         return _backend->samples_since_cycle_start ();
1070 }
1071
1072 bool
1073 AudioEngine::get_sync_offset (pframes_t& offset) const
1074 {
1075         if (!_backend) {
1076                 return false;
1077         }
1078         return _backend->get_sync_offset (offset);
1079 }
1080
1081 int
1082 AudioEngine::create_process_thread (boost::function<void()> func)
1083 {
1084         if (!_backend) {
1085                 return -1;
1086         }
1087         return _backend->create_process_thread (func);
1088 }
1089
1090 int
1091 AudioEngine::join_process_threads ()
1092 {
1093         if (!_backend) {
1094                 return -1;
1095         }
1096         return _backend->join_process_threads ();
1097 }
1098
1099 bool
1100 AudioEngine::in_process_thread ()
1101 {
1102         if (!_backend) {
1103                 return false;
1104         }
1105         return _backend->in_process_thread ();
1106 }
1107
1108 uint32_t
1109 AudioEngine::process_thread_count ()
1110 {
1111         if (!_backend) {
1112                 return 0;
1113         }
1114         return _backend->process_thread_count ();
1115 }
1116
1117 int
1118 AudioEngine::set_device_name (const std::string& name)
1119 {
1120         if (!_backend) {
1121                 return -1;
1122         }
1123         return _backend->set_device_name  (name);
1124 }
1125
1126 int
1127 AudioEngine::set_sample_rate (float sr)
1128 {
1129         if (!_backend) {
1130                 return -1;
1131         }
1132
1133         return _backend->set_sample_rate  (sr);
1134 }
1135
1136 int
1137 AudioEngine::set_buffer_size (uint32_t bufsiz)
1138 {
1139         if (!_backend) {
1140                 return -1;
1141         }
1142         return _backend->set_buffer_size  (bufsiz);
1143 }
1144
1145 int
1146 AudioEngine::set_interleaved (bool yn)
1147 {
1148         if (!_backend) {
1149                 return -1;
1150         }
1151         return _backend->set_interleaved  (yn);
1152 }
1153
1154 int
1155 AudioEngine::set_input_channels (uint32_t ic)
1156 {
1157         if (!_backend) {
1158                 return -1;
1159         }
1160         return _backend->set_input_channels  (ic);
1161 }
1162
1163 int
1164 AudioEngine::set_output_channels (uint32_t oc)
1165 {
1166         if (!_backend) {
1167                 return -1;
1168         }
1169         return _backend->set_output_channels (oc);
1170 }
1171
1172 int
1173 AudioEngine::set_systemic_input_latency (uint32_t il)
1174 {
1175         if (!_backend) {
1176                 return -1;
1177         }
1178         return _backend->set_systemic_input_latency  (il);
1179 }
1180
1181 int
1182 AudioEngine::set_systemic_output_latency (uint32_t ol)
1183 {
1184         if (!_backend) {
1185                 return -1;
1186         }
1187         return _backend->set_systemic_output_latency  (ol);
1188 }
1189
1190 bool
1191 AudioEngine::thread_initialised_for_audio_processing ()
1192 {
1193     return SessionEvent::has_per_thread_pool () && AsyncMIDIPort::is_process_thread();
1194 }
1195
1196 /* END OF BACKEND PROXY API */
1197
1198 void
1199 AudioEngine::thread_init_callback (void* arg)
1200 {
1201         /* make sure that anybody who needs to know about this thread
1202            knows about it.
1203         */
1204
1205         pthread_set_name (X_("audioengine"));
1206
1207         SessionEvent::create_per_thread_pool (X_("AudioEngine"), 512);
1208
1209         PBD::notify_gui_about_thread_creation ("gui", pthread_self(), X_("AudioEngine"), 4096);
1210         PBD::notify_gui_about_thread_creation ("midiui", pthread_self(), X_("AudioEngine"), 128);
1211
1212         AsyncMIDIPort::set_process_thread (pthread_self());
1213
1214         if (arg) {
1215                 /* the special thread created/managed by the backend */
1216                 AudioEngine::instance()->_main_thread = new ProcessThread;
1217         }
1218 }
1219
1220 int
1221 AudioEngine::sync_callback (TransportState state, framepos_t position)
1222 {
1223         if (_session) {
1224                 return _session->backend_sync_callback (state, position);
1225         }
1226         return 0;
1227 }
1228
1229 void
1230 AudioEngine::freewheel_callback (bool onoff)
1231 {
1232         _freewheeling = onoff;
1233 }
1234
1235 void
1236 AudioEngine::latency_callback (bool for_playback)
1237 {
1238         if (_session) {
1239                 _session->update_latency (for_playback);
1240         }
1241 }
1242
1243 void
1244 AudioEngine::update_latencies ()
1245 {
1246         if (_backend) {
1247                 _backend->update_latencies ();
1248         }
1249 }
1250
1251 void
1252 AudioEngine::halted_callback (const char* why)
1253 {
1254         if (_in_destructor) {
1255                 /* everything is under control */
1256                 return;
1257         }
1258
1259         _running = false;
1260
1261         Port::PortDrop (); /* EMIT SIGNAL */
1262
1263         if (!_started_for_latency) {
1264                 Halted (why);      /* EMIT SIGNAL */
1265         }
1266 }
1267
1268 bool
1269 AudioEngine::setup_required () const
1270 {
1271         if (_backend) {
1272                 if (_backend->info().already_configured())
1273                         return false;
1274         } else {
1275                 if (_backends.size() == 1 && _backends.begin()->second->already_configured()) {
1276                         return false;
1277                 }
1278         }
1279
1280         return true;
1281 }
1282
1283 int
1284 AudioEngine::prepare_for_latency_measurement ()
1285 {
1286         if (!_backend) {
1287                 return -1;
1288         }
1289
1290         if (_backend->can_change_systemic_latency_when_running()) {
1291                 if (start()) {
1292                         return -1;
1293                 }
1294                 _backend->set_systemic_input_latency (0);
1295                 _backend->set_systemic_output_latency (0);
1296                 return 0;
1297         }
1298
1299         if (running()) {
1300                 _stopped_for_latency = true;
1301                 stop (true);
1302         }
1303
1304         if (start (true)) {
1305                 return -1;
1306         }
1307         _started_for_latency = true;
1308
1309         return 0;
1310 }
1311
1312 int
1313 AudioEngine::start_latency_detection (bool for_midi)
1314 {
1315         if (prepare_for_latency_measurement ()) {
1316                 return -1;
1317         }
1318
1319         PortEngine& pe (port_engine());
1320
1321         delete _mtdm;
1322         _mtdm = 0;
1323
1324         delete _mididm;
1325         _mididm = 0;
1326
1327         /* find the ports we will connect to */
1328
1329         PortEngine::PortHandle out = pe.get_port_by_name (_latency_output_name);
1330         PortEngine::PortHandle in = pe.get_port_by_name (_latency_input_name);
1331
1332         if (!out || !in) {
1333                 stop (true);
1334                 return -1;
1335         }
1336
1337         /* create the ports we will use to read/write data */
1338         if (for_midi) {
1339                 if ((_latency_output_port = pe.register_port ("latency_out", DataType::MIDI, IsOutput)) == 0) {
1340                         stop (true);
1341                         return -1;
1342                 }
1343                 if (pe.connect (_latency_output_port, _latency_output_name)) {
1344                         pe.unregister_port (_latency_output_port);
1345                         stop (true);
1346                         return -1;
1347                 }
1348
1349                 const string portname ("latency_in");
1350                 if ((_latency_input_port = pe.register_port (portname, DataType::MIDI, IsInput)) == 0) {
1351                         pe.unregister_port (_latency_input_port);
1352                         pe.unregister_port (_latency_output_port);
1353                         stop (true);
1354                         return -1;
1355                 }
1356                 if (pe.connect (_latency_input_name, make_port_name_non_relative (portname))) {
1357                         pe.unregister_port (_latency_input_port);
1358                         pe.unregister_port (_latency_output_port);
1359                         stop (true);
1360                         return -1;
1361                 }
1362
1363                 _mididm = new MIDIDM (sample_rate());
1364
1365         } else {
1366
1367                 if ((_latency_output_port = pe.register_port ("latency_out", DataType::AUDIO, IsOutput)) == 0) {
1368                         stop (true);
1369                         return -1;
1370                 }
1371                 if (pe.connect (_latency_output_port, _latency_output_name)) {
1372                         pe.unregister_port (_latency_output_port);
1373                         stop (true);
1374                         return -1;
1375                 }
1376
1377                 const string portname ("latency_in");
1378                 if ((_latency_input_port = pe.register_port (portname, DataType::AUDIO, IsInput)) == 0) {
1379                         pe.unregister_port (_latency_input_port);
1380                         pe.unregister_port (_latency_output_port);
1381                         stop (true);
1382                         return -1;
1383                 }
1384                 if (pe.connect (_latency_input_name, make_port_name_non_relative (portname))) {
1385                         pe.unregister_port (_latency_input_port);
1386                         pe.unregister_port (_latency_output_port);
1387                         stop (true);
1388                         return -1;
1389                 }
1390
1391                 _mtdm = new MTDM (sample_rate());
1392
1393         }
1394
1395         LatencyRange lr;
1396         _latency_signal_latency = 0;
1397         lr = pe.get_latency_range (in, false);
1398         _latency_signal_latency = lr.max;
1399         lr = pe.get_latency_range (out, true);
1400         _latency_signal_latency += lr.max;
1401
1402         /* all created and connected, lets go */
1403         _latency_flush_frames = samples_per_cycle();
1404         _measuring_latency = for_midi ? MeasureMIDI : MeasureAudio;
1405
1406         return 0;
1407 }
1408
1409 void
1410 AudioEngine::stop_latency_detection ()
1411 {
1412         _measuring_latency = MeasureNone;
1413
1414         if (_latency_output_port) {
1415                 port_engine().unregister_port (_latency_output_port);
1416                 _latency_output_port = 0;
1417         }
1418         if (_latency_input_port) {
1419                 port_engine().unregister_port (_latency_input_port);
1420                 _latency_input_port = 0;
1421         }
1422
1423         if (!_backend->can_change_systemic_latency_when_running()) {
1424                 stop (true);
1425         }
1426
1427         if (_stopped_for_latency) {
1428                 start ();
1429         }
1430
1431         _stopped_for_latency = false;
1432         _started_for_latency = false;
1433 }
1434
1435 void
1436 AudioEngine::set_latency_output_port (const string& name)
1437 {
1438         _latency_output_name = name;
1439 }
1440
1441 void
1442 AudioEngine::set_latency_input_port (const string& name)
1443 {
1444         _latency_input_name = name;
1445 }