bump default silent-after-seconds duration to 10 minutes
[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 gint AudioEngine::m_meter_exit;
65 AudioEngine* AudioEngine::_instance = 0;
66
67 #ifdef SILENCE_AFTER
68 #define SILENCE_AFTER_SECONDS 600
69 #endif
70
71 AudioEngine::AudioEngine ()
72         : session_remove_pending (false)
73         , session_removal_countdown (-1)
74         , _running (false)
75         , _freewheeling (false)
76         , monitor_check_interval (INT32_MAX)
77         , last_monitor_check (0)
78         , _processed_frames (0)
79         , m_meter_thread (0)
80         , _main_thread (0)
81         , _mtdm (0)
82         , _mididm (0)
83         , _measuring_latency (MeasureNone)
84         , _latency_input_port (0)
85         , _latency_output_port (0)
86         , _latency_flush_frames (0)
87         , _latency_signal_latency (0)
88         , _stopped_for_latency (false)
89         , _started_for_latency (false)
90         , _in_destructor (false)
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         g_atomic_int_set (&m_meter_exit, 0);
103         reset_silence_countdown ();
104         start_hw_event_processing();
105         discover_backends ();
106 }
107
108 AudioEngine::~AudioEngine ()
109 {
110         _in_destructor = true;
111         stop_metering_thread ();
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                 _processed_frames = next_processed_frames;
209                 return 0;
210         }
211
212         bool return_after_remove_check = false;
213
214         if (_measuring_latency == MeasureAudio && _mtdm) {
215                 /* run a normal cycle from the perspective of the PortManager
216                    so that we get silence on all registered ports.
217                    
218                    we overwrite the silence on the two ports used for latency
219                    measurement.
220                 */
221                 
222                 PortManager::cycle_start (nframes);
223                 PortManager::silence (nframes);
224
225                 if (_latency_input_port && _latency_output_port) {
226                         PortEngine& pe (port_engine());
227
228                         Sample* in = (Sample*) pe.get_buffer (_latency_input_port, nframes);
229                         Sample* out = (Sample*) pe.get_buffer (_latency_output_port, nframes);
230
231                         _mtdm->process (nframes, in, out);
232                 }
233
234                 PortManager::cycle_end (nframes);
235                 return_after_remove_check = true;
236
237         } else if (_measuring_latency == MeasureMIDI && _mididm) {
238                 /* run a normal cycle from the perspective of the PortManager
239                    so that we get silence on all registered ports.
240
241                    we overwrite the silence on the two ports used for latency
242                    measurement.
243                 */
244
245                 PortManager::cycle_start (nframes);
246                 PortManager::silence (nframes);
247
248                 if (_latency_input_port && _latency_output_port) {
249                         PortEngine& pe (port_engine());
250
251                         _mididm->process (nframes, pe,
252                                         pe.get_buffer (_latency_input_port, nframes),
253                                         pe.get_buffer (_latency_output_port, nframes));
254                 }
255
256                 PortManager::cycle_end (nframes);
257                 return_after_remove_check = true;
258
259         } else if (_latency_flush_frames) {
260                 
261                 /* wait for the appropriate duration for the MTDM signal to
262                  * drain from the ports before we revert to normal behaviour.
263                  */
264
265                 PortManager::cycle_start (nframes);
266                 PortManager::silence (nframes);
267                 PortManager::cycle_end (nframes);
268                 
269                 if (_latency_flush_frames > nframes) {
270                         _latency_flush_frames -= nframes;
271                 } else {
272                         _latency_flush_frames = 0;
273                 }
274
275                 return_after_remove_check = true;
276         }
277
278         if (session_remove_pending) {
279
280                 /* perform the actual session removal */
281
282                 if (session_removal_countdown < 0) {
283
284                         /* fade out over 1 second */
285                         session_removal_countdown = sample_rate()/2;
286                         session_removal_gain = 1.0;
287                         session_removal_gain_step = 1.0/session_removal_countdown;
288
289                 } else if (session_removal_countdown > 0) {
290
291                         /* we'll be fading audio out.
292                            
293                            if this is the last time we do this as part 
294                            of session removal, do a MIDI panic now
295                            to get MIDI stopped. This relies on the fact
296                            that "immediate data" (aka "out of band data") from
297                            MIDI tracks is *appended* after any other data, 
298                            so that it emerges after any outbound note ons, etc.
299                         */
300
301                         if (session_removal_countdown <= nframes) {
302                                 _session->midi_panic ();
303                         }
304
305                 } else {
306                         /* fade out done */
307                         _session = 0;
308                         session_removal_countdown = -1; // reset to "not in progress"
309                         session_remove_pending = false;
310                         session_removed.signal(); // wakes up thread that initiated session removal
311                 }
312         }
313
314         if (return_after_remove_check) {
315                 return 0;
316         }
317
318         if (_session == 0) {
319
320                 if (!_freewheeling) {
321                         PortManager::cycle_start (nframes);
322                         PortManager::cycle_end (nframes);
323                 }
324
325                 _processed_frames = next_processed_frames;
326
327                 return 0;
328         }
329
330         /* tell all relevant objects that we're starting a new cycle */
331
332         InternalSend::CycleStart (nframes);
333
334         /* tell all Ports that we're starting a new cycle */
335
336         PortManager::cycle_start (nframes);
337
338         /* test if we are freewheeling and there are freewheel signals connected.
339            ardour should act normally even when freewheeling unless /it/ is
340            exporting (which is what Freewheel.empty() tests for).
341         */
342
343         if (_freewheeling && !Freewheel.empty()) {
344                 Freewheel (nframes);
345         } else {
346                 _session->process (nframes);
347         }
348
349         if (_freewheeling) {
350                 PortManager::cycle_end (nframes);
351                 return 0;
352         }
353
354         if (!_running) {
355                 PortManager::cycle_end (nframes);
356                 _processed_frames = next_processed_frames;
357                 return 0;
358         }
359
360         if (last_monitor_check + monitor_check_interval < next_processed_frames) {
361                 
362                 PortManager::check_monitoring ();
363                 last_monitor_check = next_processed_frames;
364         }
365
366 #ifdef SILENCE_AFTER_SECONDS
367
368         bool was_silent = (_silence_countdown == 0);
369         
370         if (_silence_countdown >= nframes) {
371                 _silence_countdown -= nframes;
372         } else {
373                 _silence_countdown = 0;
374         }
375
376         if (!was_silent && _silence_countdown == 0) {
377                 _silence_hit_cnt++;
378                 BecameSilent (); /* EMIT SIGNAL */
379         }
380
381         if (_silence_countdown == 0 || _session->silent()) {
382                 PortManager::silence (nframes);
383         }
384         
385 #else   
386         if (_session->silent()) {
387                 PortManager::silence (nframes);
388         }
389 #endif
390         
391         if (session_remove_pending && session_removal_countdown) {
392
393                 PortManager::fade_out (session_removal_gain, session_removal_gain_step, nframes);
394                 
395                 if (session_removal_countdown > nframes) {
396                         session_removal_countdown -= nframes;
397                 } else {
398                         session_removal_countdown = 0;
399                 }
400
401                 session_removal_gain -= (nframes * session_removal_gain_step);
402         }
403
404         PortManager::cycle_end (nframes);
405
406         _processed_frames = next_processed_frames;
407
408         PT_TIMING_CHECK (2);
409         
410         return 0;
411 }
412
413 void
414 AudioEngine::reset_silence_countdown ()
415 {
416 #ifdef SILENCE_AFTER_SECONDS
417         double sr = 48000; /* default in case there is no backend */
418
419         sr = sample_rate();
420
421         _silence_countdown = max (60 * sr, /* 60 seconds */
422                                   sr * (SILENCE_AFTER_SECONDS / pow (2, _silence_hit_cnt)));
423
424 #endif
425 }
426
427 void
428 AudioEngine::launch_device_control_app()
429 {
430         if (_state_lock.trylock () ) {
431                 _backend->launch_control_app ();
432                 _state_lock.unlock ();
433         }
434 }
435
436
437 void
438 AudioEngine::request_backend_reset()
439 {
440     Glib::Threads::Mutex::Lock guard (_reset_request_lock);
441     g_atomic_int_inc (&_hw_reset_request_count);
442     _hw_reset_condition.signal ();
443 }
444
445 int
446 AudioEngine::backend_reset_requested()
447 {
448         return g_atomic_int_get (&_hw_reset_request_count);
449 }
450
451 void
452 AudioEngine::do_reset_backend()
453 {
454         SessionEvent::create_per_thread_pool (X_("Backend reset processing thread"), 512);
455     
456         Glib::Threads::Mutex::Lock guard (_reset_request_lock);
457     
458         while (!_stop_hw_reset_processing) {
459         
460                 if (g_atomic_int_get (&_hw_reset_request_count) != 0 && _backend) {
461                 
462                         _reset_request_lock.unlock();
463                 
464                         Glib::Threads::RecMutex::Lock pl (_state_lock);
465                         g_atomic_int_dec_and_test (&_hw_reset_request_count);
466                 
467                         std::cout << "AudioEngine::RESET::Reset request processing. Requests left: " << _hw_reset_request_count << std::endl;
468                         DeviceResetStarted(); // notify about device reset to be started
469                 
470                         // backup the device name
471                         std::string name = _backend->device_name ();
472                 
473                         std::cout << "AudioEngine::RESET::Stoping engine..." << std::endl;
474                         stop();
475                 
476                         std::cout << "AudioEngine::RESET::Reseting device..." << std::endl;
477                         if ( 0 == _backend->reset_device () ) {
478                         
479                                 std::cout << "AudioEngine::RESET::Starting engine..." << std::endl;
480                                 start ();
481                         
482                                 // inform about possible changes
483                                 BufferSizeChanged (_backend->buffer_size() );
484                         } else {
485                                 DeviceError();
486                         }
487                         
488                         std::cout << "AudioEngine::RESET::Done." << std::endl;
489
490                         _reset_request_lock.lock();
491             
492                 } else {
493             
494                         _hw_reset_condition.wait (_reset_request_lock);
495             
496                 }
497         }
498 }
499 void
500 AudioEngine::request_device_list_update()
501 {
502     Glib::Threads::Mutex::Lock guard (_devicelist_update_lock);
503     g_atomic_int_inc (&_hw_devicelist_update_count);
504     _hw_devicelist_update_condition.signal ();
505 }
506
507
508 void
509 AudioEngine::do_devicelist_update()
510 {
511     SessionEvent::create_per_thread_pool (X_("Device list update processing thread"), 512);
512     
513     Glib::Threads::Mutex::Lock guard (_devicelist_update_lock);
514     
515     while (!_stop_hw_devicelist_processing) {
516         
517         if (_hw_devicelist_update_count) {
518
519             _devicelist_update_lock.unlock();
520             
521             g_atomic_int_dec_and_test (&_hw_devicelist_update_count);
522             DeviceListChanged (); /* EMIT SIGNAL */
523         
524             _devicelist_update_lock.lock();
525             
526         } else {
527             _hw_devicelist_update_condition.wait (_devicelist_update_lock);
528         }
529     }
530 }
531
532
533 void
534 AudioEngine::start_hw_event_processing()
535 {   
536     if (_hw_reset_event_thread == 0) {
537         g_atomic_int_set(&_hw_reset_request_count, 0);
538         g_atomic_int_set(&_stop_hw_reset_processing, 0);
539         _hw_reset_event_thread = Glib::Threads::Thread::create (boost::bind (&AudioEngine::do_reset_backend, this));
540     }
541     
542     if (_hw_devicelist_update_thread == 0) {
543         g_atomic_int_set(&_hw_devicelist_update_count, 0);
544         g_atomic_int_set(&_stop_hw_devicelist_processing, 0);
545         _hw_devicelist_update_thread = Glib::Threads::Thread::create (boost::bind (&AudioEngine::do_devicelist_update, this));
546     }
547 }
548
549
550 void
551 AudioEngine::stop_hw_event_processing()
552 {
553     if (_hw_reset_event_thread) {
554         g_atomic_int_set(&_stop_hw_reset_processing, 1);
555         g_atomic_int_set(&_hw_reset_request_count, 0);
556         _hw_reset_condition.signal ();
557         _hw_reset_event_thread->join ();
558         _hw_reset_event_thread = 0;
559     }
560     
561     if (_hw_devicelist_update_thread) {
562         g_atomic_int_set(&_stop_hw_devicelist_processing, 1);
563         g_atomic_int_set(&_hw_devicelist_update_count, 0);
564         _hw_devicelist_update_condition.signal ();
565         _hw_devicelist_update_thread->join ();
566         _hw_devicelist_update_thread = 0;
567     }
568         
569 }
570
571
572
573 void
574 AudioEngine::stop_metering_thread ()
575 {
576         if (m_meter_thread) {
577                 g_atomic_int_set (&m_meter_exit, 1);
578                 m_meter_thread->join ();
579                 m_meter_thread = 0;
580         }
581 }
582
583 void
584 AudioEngine::start_metering_thread ()
585 {
586         if (m_meter_thread == 0) {
587                 g_atomic_int_set (&m_meter_exit, 0);
588                 m_meter_thread = Glib::Threads::Thread::create (boost::bind (&AudioEngine::meter_thread, this));
589         }
590 }
591
592 void
593 AudioEngine::meter_thread ()
594 {
595         pthread_set_name (X_("meter"));
596
597         while (true) {
598                 Glib::usleep (10000); /* 1/100th sec interval */
599                 if (g_atomic_int_get(&m_meter_exit)) {
600                         break;
601                 }
602                 Metering::Meter ();
603         }
604 }
605
606 void
607 AudioEngine::set_session (Session *s)
608 {
609         Glib::Threads::Mutex::Lock pl (_process_lock);
610
611         SessionHandlePtr::set_session (s);
612
613         if (_session) {
614
615                 pframes_t blocksize = samples_per_cycle ();
616
617                 PortManager::cycle_start (blocksize);
618
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                 _session->process (blocksize);
626                 _session->process (blocksize);
627
628                 PortManager::cycle_end (blocksize);
629         }
630 }
631
632 void
633 AudioEngine::remove_session ()
634 {
635         Glib::Threads::Mutex::Lock lm (_process_lock);
636
637         if (_running) {
638
639                 if (_session) {
640                         session_remove_pending = true;
641                         session_removal_countdown = 0;
642                         session_removed.wait(_process_lock);
643                 }
644
645         } else {
646                 SessionHandlePtr::set_session (0);
647         }
648
649         remove_all_ports ();
650 }
651
652
653 void
654 AudioEngine::reconnect_session_routes (bool reconnect_inputs, bool reconnect_outputs)
655 {
656     if (_session) {
657         _session->reconnect_existing_routes(true, true, reconnect_inputs, reconnect_outputs);
658     }
659 }
660
661
662 void
663 AudioEngine::died ()
664 {
665         /* called from a signal handler for SIGPIPE */
666
667         stop_metering_thread ();
668
669     _running = false;
670 }
671
672 int
673 AudioEngine::reset_timebase ()
674 {
675         if (_session) {
676                 if (_session->config.get_jack_time_master()) {
677                         _backend->set_time_master (true);
678                 } else {
679                         _backend->set_time_master (false);
680                 }
681         }
682         return 0;
683 }
684
685
686 void
687 AudioEngine::destroy ()
688 {
689         delete _instance;
690         _instance = 0;
691 }
692
693 int
694 AudioEngine::discover_backends ()
695 {
696         vector<std::string> backend_modules;
697
698         _backends.clear ();
699
700         Glib::PatternSpec so_extension_pattern("*backend.so");
701         Glib::PatternSpec dylib_extension_pattern("*backend.dylib");
702
703 #if defined(PLATFORM_WINDOWS) && defined(DEBUGGABLE_BACKENDS)
704         #if defined(DEBUG) || defined(_DEBUG)
705                 Glib::PatternSpec dll_extension_pattern("*backendD.dll");
706         #else
707                 Glib::PatternSpec dll_extension_pattern("*backendRDC.dll");
708         #endif
709 #else
710         Glib::PatternSpec dll_extension_pattern("*backend.dll");
711 #endif
712
713         find_files_matching_pattern (backend_modules, backend_search_path (),
714                                      so_extension_pattern);
715
716         find_files_matching_pattern (backend_modules, backend_search_path (),
717                                      dylib_extension_pattern);
718
719         find_files_matching_pattern (backend_modules, backend_search_path (),
720                                      dll_extension_pattern);
721
722         DEBUG_TRACE (DEBUG::AudioEngine, string_compose ("looking for backends in %1\n", backend_search_path().to_string()));
723
724         for (vector<std::string>::iterator i = backend_modules.begin(); i != backend_modules.end(); ++i) {
725
726                 AudioBackendInfo* info;
727
728                 DEBUG_TRACE (DEBUG::AudioEngine, string_compose ("Checking possible backend in %1\n", *i));
729
730                 if ((info = backend_discover (*i)) != 0) {
731                         _backends.insert (make_pair (info->name, info));
732                 }
733         }
734
735         DEBUG_TRACE (DEBUG::AudioEngine, string_compose ("Found %1 backends\n", _backends.size()));
736
737         return _backends.size();
738 }
739
740 AudioBackendInfo*
741 AudioEngine::backend_discover (const string& path)
742 {
743 #ifdef PLATFORM_WINDOWS
744         // do not show popup dialog (e.g. missing libjack.dll)
745         // win7+ should use SetThreadErrorMode()
746         SetErrorMode(SEM_FAILCRITICALERRORS);
747 #endif
748         Glib::Module module (path);
749 #ifdef PLATFORM_WINDOWS
750         SetErrorMode(0); // reset to system default
751 #endif
752         AudioBackendInfo* info;
753         AudioBackendInfo* (*dfunc)(void);
754         void* func = 0;
755
756         if (!module) {
757                 error << string_compose(_("AudioEngine: cannot load module \"%1\" (%2)"), path,
758                                         Glib::Module::get_last_error()) << endmsg;
759                 return 0;
760         }
761         
762         if (!module.get_symbol ("descriptor", func)) {
763                 error << string_compose(_("AudioEngine: backend at \"%1\" has no descriptor function."), path) << endmsg;
764                 error << Glib::Module::get_last_error() << endmsg;
765                 return 0;
766         }
767         
768         dfunc = (AudioBackendInfo* (*)(void))func;
769         info = dfunc();
770         if (!info->available()) {
771                 return 0;
772         }
773
774         module.make_resident ();
775         
776         return info;
777 }
778
779 vector<const AudioBackendInfo*>
780 AudioEngine::available_backends() const
781 {
782         vector<const AudioBackendInfo*> r;
783         
784         for (BackendMap::const_iterator i = _backends.begin(); i != _backends.end(); ++i) {
785                 r.push_back (i->second);
786         }
787
788         return r;
789 }
790
791 string
792 AudioEngine::current_backend_name() const
793 {
794         if (_backend) {
795                 return _backend->name();
796         } 
797         return string();
798 }
799
800 void
801 AudioEngine::drop_backend ()
802 {
803         if (_backend) {
804                 stop(false);
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         if (_backend->start (for_latency)) {
864                 return -1;
865         }
866
867         _running = true;
868         
869         if (_session) {
870                 _session->set_frame_rate (_backend->sample_rate());
871                 
872                 if (_session->config.get_jack_time_master()) {
873                         _backend->set_time_master (true);
874                 }
875
876         }
877         
878         start_metering_thread ();
879         
880         if (!for_latency) {
881                 Running(); /* EMIT SIGNAL */
882         }
883         
884         return 0;
885 }
886
887 int
888 AudioEngine::stop (bool for_latency)
889 {
890         if (!_backend) {
891                 return 0;
892         }
893
894         if (_session && _running) {
895                 // it's not a halt, but should be handled the same way:
896                 // disable record, stop transport and I/O processign but save the data.
897                 _session->engine_halted ();
898         }
899
900         Glib::Threads::Mutex::Lock lm (_process_lock);
901
902         if (_backend->stop ()) {
903                 return -1;
904         }
905         
906         _running = false;
907         _processed_frames = 0;
908         _measuring_latency = MeasureNone;
909         _latency_output_port = 0;
910         _latency_input_port = 0;
911         _started_for_latency = false;
912         stop_metering_thread ();
913         
914         Port::PortDrop ();
915
916         if (!for_latency) {
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) {
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 /* END OF BACKEND PROXY API */
1191
1192 void
1193 AudioEngine::thread_init_callback (void* arg)
1194 {
1195         /* make sure that anybody who needs to know about this thread
1196            knows about it.
1197         */
1198
1199         pthread_set_name (X_("audioengine"));
1200
1201         SessionEvent::create_per_thread_pool (X_("AudioEngine"), 512);
1202
1203         PBD::notify_gui_about_thread_creation ("gui", pthread_self(), X_("AudioEngine"), 4096);
1204         PBD::notify_gui_about_thread_creation ("midiui", pthread_self(), X_("AudioEngine"), 128);
1205
1206         AsyncMIDIPort::set_process_thread (pthread_self());
1207
1208         if (arg) {
1209                 /* the special thread created/managed by the backend */
1210                 AudioEngine::instance()->_main_thread = new ProcessThread;
1211         }
1212 }
1213
1214 int
1215 AudioEngine::sync_callback (TransportState state, framepos_t position)
1216 {
1217         if (_session) {
1218                 return _session->backend_sync_callback (state, position);
1219         }
1220         return 0;
1221 }
1222
1223 void
1224 AudioEngine::freewheel_callback (bool onoff)
1225 {
1226         _freewheeling = onoff;
1227 }
1228
1229 void
1230 AudioEngine::latency_callback (bool for_playback)
1231 {
1232         if (_session) {
1233                 _session->update_latency (for_playback);
1234         }
1235 }
1236
1237 void
1238 AudioEngine::update_latencies ()
1239 {
1240         if (_backend) {
1241                 _backend->update_latencies ();
1242         }
1243 }
1244
1245 void
1246 AudioEngine::halted_callback (const char* why)
1247 {
1248         if (_in_destructor) {
1249                 /* everything is under control */
1250                 return;
1251         }
1252
1253     stop_metering_thread ();
1254         _running = false;
1255
1256         Port::PortDrop (); /* EMIT SIGNAL */
1257
1258         if (!_started_for_latency) {
1259                 Halted (why);      /* EMIT SIGNAL */
1260         }
1261 }
1262
1263 bool
1264 AudioEngine::setup_required () const
1265 {
1266         if (_backend) {
1267                 if (_backend->info().already_configured())
1268                         return false;
1269         } else {
1270                 if (_backends.size() == 1 && _backends.begin()->second->already_configured()) {
1271                         return false;
1272                 }
1273         }
1274         
1275         return true;
1276 }
1277
1278 int
1279 AudioEngine::prepare_for_latency_measurement ()
1280 {
1281         if (running()) {
1282                 _stopped_for_latency = true;
1283                 stop (true);
1284         }
1285
1286         if (start (true)) {
1287                 _started_for_latency = true;
1288                 return -1;
1289         }
1290
1291         return 0;
1292 }
1293
1294 int
1295 AudioEngine::start_latency_detection (bool for_midi)
1296 {
1297         if (!running()) {
1298                 if (prepare_for_latency_measurement ()) {
1299                         return -1;
1300                 }
1301         }
1302
1303         PortEngine& pe (port_engine());
1304
1305         delete _mtdm;
1306         _mtdm = 0;
1307
1308         delete _mididm;
1309         _mididm = 0;
1310
1311         /* find the ports we will connect to */
1312
1313         PortEngine::PortHandle out = pe.get_port_by_name (_latency_output_name);
1314         PortEngine::PortHandle in = pe.get_port_by_name (_latency_input_name);
1315
1316         if (!out || !in) {
1317                 stop (true);
1318                 return -1;
1319         }
1320
1321         /* create the ports we will use to read/write data */
1322         if (for_midi) {
1323                 if ((_latency_output_port = pe.register_port ("latency_out", DataType::MIDI, IsOutput)) == 0) {
1324                         stop (true);
1325                         return -1;
1326                 }
1327                 if (pe.connect (_latency_output_port, _latency_output_name)) {
1328                         pe.unregister_port (_latency_output_port);
1329                         stop (true);
1330                         return -1;
1331                 }
1332
1333                 const string portname ("latency_in");
1334                 if ((_latency_input_port = pe.register_port (portname, DataType::MIDI, IsInput)) == 0) {
1335                         pe.unregister_port (_latency_input_port);
1336                         pe.unregister_port (_latency_output_port);
1337                         stop (true);
1338                         return -1;
1339                 }
1340                 if (pe.connect (_latency_input_name, make_port_name_non_relative (portname))) {
1341                         pe.unregister_port (_latency_input_port);
1342                         pe.unregister_port (_latency_output_port);
1343                         stop (true);
1344                         return -1;
1345                 }
1346
1347                 _mididm = new MIDIDM (sample_rate());
1348
1349         } else {
1350
1351                 if ((_latency_output_port = pe.register_port ("latency_out", DataType::AUDIO, IsOutput)) == 0) {
1352                         stop (true);
1353                         return -1;
1354                 }
1355                 if (pe.connect (_latency_output_port, _latency_output_name)) {
1356                         pe.unregister_port (_latency_output_port);
1357                         stop (true);
1358                         return -1;
1359                 }
1360
1361                 const string portname ("latency_in");
1362                 if ((_latency_input_port = pe.register_port (portname, DataType::AUDIO, IsInput)) == 0) {
1363                         pe.unregister_port (_latency_input_port);
1364                         pe.unregister_port (_latency_output_port);
1365                         stop (true);
1366                         return -1;
1367                 }
1368                 if (pe.connect (_latency_input_name, make_port_name_non_relative (portname))) {
1369                         pe.unregister_port (_latency_input_port);
1370                         pe.unregister_port (_latency_output_port);
1371                         stop (true);
1372                         return -1;
1373                 }
1374
1375                 _mtdm = new MTDM (sample_rate());
1376
1377         }
1378
1379         LatencyRange lr;
1380         _latency_signal_latency = 0;
1381         lr = pe.get_latency_range (in, false);
1382         _latency_signal_latency = lr.max;
1383         lr = pe.get_latency_range (out, true);
1384         _latency_signal_latency += lr.max;
1385
1386         /* all created and connected, lets go */
1387         _latency_flush_frames = samples_per_cycle();
1388         _measuring_latency = for_midi ? MeasureMIDI : MeasureAudio;
1389
1390         return 0;
1391 }
1392
1393 void
1394 AudioEngine::stop_latency_detection ()
1395 {
1396         _measuring_latency = MeasureNone;
1397
1398         if (_latency_output_port) {
1399                 port_engine().unregister_port (_latency_output_port);
1400                 _latency_output_port = 0;
1401         }
1402         if (_latency_input_port) {
1403                 port_engine().unregister_port (_latency_input_port);
1404                 _latency_input_port = 0;
1405         }
1406
1407         stop (true);
1408
1409         if (_stopped_for_latency) {
1410                 start ();
1411         }
1412
1413         _stopped_for_latency = false;
1414         _started_for_latency = false;
1415 }
1416
1417 void
1418 AudioEngine::set_latency_output_port (const string& name)
1419 {
1420         _latency_output_name = name;
1421 }
1422
1423 void
1424 AudioEngine::set_latency_input_port (const string& name)
1425 {
1426         _latency_input_name = name;
1427 }