Fix crash when switching backends.
[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 = GAIN_COEFF_UNITY;
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                 _processed_frames = next_processed_frames;
356                 return 0;
357         }
358
359         if (last_monitor_check + monitor_check_interval < next_processed_frames) {
360                 
361                 PortManager::check_monitoring ();
362                 last_monitor_check = next_processed_frames;
363         }
364
365 #ifdef SILENCE_AFTER_SECONDS
366
367         bool was_silent = (_silence_countdown == 0);
368         
369         if (_silence_countdown >= nframes) {
370                 _silence_countdown -= nframes;
371         } else {
372                 _silence_countdown = 0;
373         }
374
375         if (!was_silent && _silence_countdown == 0) {
376                 _silence_hit_cnt++;
377                 BecameSilent (); /* EMIT SIGNAL */
378         }
379
380         if (_silence_countdown == 0 || _session->silent()) {
381                 PortManager::silence (nframes);
382         }
383         
384 #else   
385         if (_session->silent()) {
386                 PortManager::silence (nframes);
387         }
388 #endif
389         
390         if (session_remove_pending && session_removal_countdown) {
391
392                 PortManager::fade_out (session_removal_gain, session_removal_gain_step, nframes);
393                 
394                 if (session_removal_countdown > nframes) {
395                         session_removal_countdown -= nframes;
396                 } else {
397                         session_removal_countdown = 0;
398                 }
399
400                 session_removal_gain -= (nframes * session_removal_gain_step);
401         }
402
403         PortManager::cycle_end (nframes);
404
405         _processed_frames = next_processed_frames;
406
407         PT_TIMING_CHECK (2);
408         
409         return 0;
410 }
411
412 void
413 AudioEngine::reset_silence_countdown ()
414 {
415 #ifdef SILENCE_AFTER_SECONDS
416         double sr = 48000; /* default in case there is no backend */
417
418         sr = sample_rate();
419
420         _silence_countdown = max (60 * sr, /* 60 seconds */
421                                   sr * (SILENCE_AFTER_SECONDS / ::pow (2.0, (double) _silence_hit_cnt)));
422
423 #endif
424 }
425
426 void
427 AudioEngine::launch_device_control_app()
428 {
429         if (_state_lock.trylock () ) {
430                 _backend->launch_control_app ();
431                 _state_lock.unlock ();
432         }
433 }
434
435
436 void
437 AudioEngine::request_backend_reset()
438 {
439     Glib::Threads::Mutex::Lock guard (_reset_request_lock);
440     g_atomic_int_inc (&_hw_reset_request_count);
441     _hw_reset_condition.signal ();
442 }
443
444 int
445 AudioEngine::backend_reset_requested()
446 {
447         return g_atomic_int_get (&_hw_reset_request_count);
448 }
449
450 void
451 AudioEngine::do_reset_backend()
452 {
453         SessionEvent::create_per_thread_pool (X_("Backend reset processing thread"), 512);
454     
455         Glib::Threads::Mutex::Lock guard (_reset_request_lock);
456     
457         while (!_stop_hw_reset_processing) {
458         
459                 if (g_atomic_int_get (&_hw_reset_request_count) != 0 && _backend) {
460                 
461                         _reset_request_lock.unlock();
462                 
463                         Glib::Threads::RecMutex::Lock pl (_state_lock);
464                         g_atomic_int_dec_and_test (&_hw_reset_request_count);
465                 
466                         std::cout << "AudioEngine::RESET::Reset request processing. Requests left: " << _hw_reset_request_count << std::endl;
467                         DeviceResetStarted(); // notify about device reset to be started
468                 
469                         // backup the device name
470                         std::string name = _backend->device_name ();
471                 
472                         std::cout << "AudioEngine::RESET::Stoping engine..." << std::endl;
473                         stop();
474                 
475                         std::cout << "AudioEngine::RESET::Reseting device..." << std::endl;
476                         if ( 0 == _backend->reset_device () ) {
477                         
478                                 std::cout << "AudioEngine::RESET::Starting engine..." << std::endl;
479                                 start ();
480                         
481                                 // inform about possible changes
482                                 BufferSizeChanged (_backend->buffer_size() );
483                         } else {
484                                 DeviceError();
485                         }
486                         
487                         std::cout << "AudioEngine::RESET::Done." << std::endl;
488
489                         _reset_request_lock.lock();
490             
491                 } else {
492             
493                         _hw_reset_condition.wait (_reset_request_lock);
494             
495                 }
496         }
497 }
498 void
499 AudioEngine::request_device_list_update()
500 {
501     Glib::Threads::Mutex::Lock guard (_devicelist_update_lock);
502     g_atomic_int_inc (&_hw_devicelist_update_count);
503     _hw_devicelist_update_condition.signal ();
504 }
505
506
507 void
508 AudioEngine::do_devicelist_update()
509 {
510     SessionEvent::create_per_thread_pool (X_("Device list update processing thread"), 512);
511     
512     Glib::Threads::Mutex::Lock guard (_devicelist_update_lock);
513     
514     while (!_stop_hw_devicelist_processing) {
515         
516         if (_hw_devicelist_update_count) {
517
518             _devicelist_update_lock.unlock();
519             
520             g_atomic_int_dec_and_test (&_hw_devicelist_update_count);
521             DeviceListChanged (); /* EMIT SIGNAL */
522         
523             _devicelist_update_lock.lock();
524             
525         } else {
526             _hw_devicelist_update_condition.wait (_devicelist_update_lock);
527         }
528     }
529 }
530
531
532 void
533 AudioEngine::start_hw_event_processing()
534 {   
535     if (_hw_reset_event_thread == 0) {
536         g_atomic_int_set(&_hw_reset_request_count, 0);
537         g_atomic_int_set(&_stop_hw_reset_processing, 0);
538         _hw_reset_event_thread = Glib::Threads::Thread::create (boost::bind (&AudioEngine::do_reset_backend, this));
539     }
540     
541     if (_hw_devicelist_update_thread == 0) {
542         g_atomic_int_set(&_hw_devicelist_update_count, 0);
543         g_atomic_int_set(&_stop_hw_devicelist_processing, 0);
544         _hw_devicelist_update_thread = Glib::Threads::Thread::create (boost::bind (&AudioEngine::do_devicelist_update, this));
545     }
546 }
547
548
549 void
550 AudioEngine::stop_hw_event_processing()
551 {
552     if (_hw_reset_event_thread) {
553         g_atomic_int_set(&_stop_hw_reset_processing, 1);
554         g_atomic_int_set(&_hw_reset_request_count, 0);
555         _hw_reset_condition.signal ();
556         _hw_reset_event_thread->join ();
557         _hw_reset_event_thread = 0;
558     }
559     
560     if (_hw_devicelist_update_thread) {
561         g_atomic_int_set(&_stop_hw_devicelist_processing, 1);
562         g_atomic_int_set(&_hw_devicelist_update_count, 0);
563         _hw_devicelist_update_condition.signal ();
564         _hw_devicelist_update_thread->join ();
565         _hw_devicelist_update_thread = 0;
566     }
567         
568 }
569
570
571
572 void
573 AudioEngine::stop_metering_thread ()
574 {
575         if (m_meter_thread) {
576                 g_atomic_int_set (&m_meter_exit, 1);
577                 m_meter_thread->join ();
578                 m_meter_thread = 0;
579         }
580 }
581
582 void
583 AudioEngine::start_metering_thread ()
584 {
585         if (m_meter_thread == 0) {
586                 g_atomic_int_set (&m_meter_exit, 0);
587                 m_meter_thread = Glib::Threads::Thread::create (boost::bind (&AudioEngine::meter_thread, this));
588         }
589 }
590
591 void
592 AudioEngine::meter_thread ()
593 {
594         pthread_set_name (X_("meter"));
595
596         while (true) {
597                 Glib::usleep (10000); /* 1/100th sec interval */
598                 if (g_atomic_int_get(&m_meter_exit)) {
599                         break;
600                 }
601                 Metering::Meter ();
602         }
603 }
604
605 void
606 AudioEngine::set_session (Session *s)
607 {
608         Glib::Threads::Mutex::Lock pl (_process_lock);
609
610         SessionHandlePtr::set_session (s);
611
612         if (_session) {
613
614                 pframes_t blocksize = samples_per_cycle ();
615
616                 PortManager::cycle_start (blocksize);
617
618                 _session->process (blocksize);
619                 _session->process (blocksize);
620                 _session->process (blocksize);
621                 _session->process (blocksize);
622                 _session->process (blocksize);
623                 _session->process (blocksize);
624                 _session->process (blocksize);
625                 _session->process (blocksize);
626
627                 PortManager::cycle_end (blocksize);
628         }
629 }
630
631 void
632 AudioEngine::remove_session ()
633 {
634         Glib::Threads::Mutex::Lock lm (_process_lock);
635
636         if (_running) {
637
638                 if (_session) {
639                         session_remove_pending = true;
640                         session_removal_countdown = 0;
641                         session_removed.wait(_process_lock);
642                 }
643
644         } else {
645                 SessionHandlePtr::set_session (0);
646         }
647
648         remove_all_ports ();
649 }
650
651
652 void
653 AudioEngine::reconnect_session_routes (bool reconnect_inputs, bool reconnect_outputs)
654 {
655     if (_session) {
656         _session->reconnect_existing_routes(true, true, reconnect_inputs, reconnect_outputs);
657     }
658 }
659
660
661 void
662 AudioEngine::died ()
663 {
664         /* called from a signal handler for SIGPIPE */
665
666         stop_metering_thread ();
667
668     _running = false;
669 }
670
671 int
672 AudioEngine::reset_timebase ()
673 {
674         if (_session) {
675                 if (_session->config.get_jack_time_master()) {
676                         _backend->set_time_master (true);
677                 } else {
678                         _backend->set_time_master (false);
679                 }
680         }
681         return 0;
682 }
683
684
685 void
686 AudioEngine::destroy ()
687 {
688         delete _instance;
689         _instance = 0;
690 }
691
692 int
693 AudioEngine::discover_backends ()
694 {
695         vector<std::string> backend_modules;
696
697         _backends.clear ();
698
699         Glib::PatternSpec so_extension_pattern("*backend.so");
700         Glib::PatternSpec dylib_extension_pattern("*backend.dylib");
701
702 #if defined(PLATFORM_WINDOWS) && defined(DEBUGGABLE_BACKENDS)
703         #if defined(DEBUG) || defined(_DEBUG)
704                 Glib::PatternSpec dll_extension_pattern("*backendD.dll");
705         #else
706                 Glib::PatternSpec dll_extension_pattern("*backendRDC.dll");
707         #endif
708 #else
709         Glib::PatternSpec dll_extension_pattern("*backend.dll");
710 #endif
711
712         find_files_matching_pattern (backend_modules, backend_search_path (),
713                                      so_extension_pattern);
714
715         find_files_matching_pattern (backend_modules, backend_search_path (),
716                                      dylib_extension_pattern);
717
718         find_files_matching_pattern (backend_modules, backend_search_path (),
719                                      dll_extension_pattern);
720
721         DEBUG_TRACE (DEBUG::AudioEngine, string_compose ("looking for backends in %1\n", backend_search_path().to_string()));
722
723         for (vector<std::string>::iterator i = backend_modules.begin(); i != backend_modules.end(); ++i) {
724
725                 AudioBackendInfo* info;
726
727                 DEBUG_TRACE (DEBUG::AudioEngine, string_compose ("Checking possible backend in %1\n", *i));
728
729                 if ((info = backend_discover (*i)) != 0) {
730                         _backends.insert (make_pair (info->name, info));
731                 }
732         }
733
734         DEBUG_TRACE (DEBUG::AudioEngine, string_compose ("Found %1 backends\n", _backends.size()));
735
736         return _backends.size();
737 }
738
739 AudioBackendInfo*
740 AudioEngine::backend_discover (const string& path)
741 {
742 #ifdef PLATFORM_WINDOWS
743         // do not show popup dialog (e.g. missing libjack.dll)
744         // win7+ should use SetThreadErrorMode()
745         SetErrorMode(SEM_FAILCRITICALERRORS);
746 #endif
747         Glib::Module module (path);
748 #ifdef PLATFORM_WINDOWS
749         SetErrorMode(0); // reset to system default
750 #endif
751         AudioBackendInfo* info;
752         AudioBackendInfo* (*dfunc)(void);
753         void* func = 0;
754
755         if (!module) {
756                 error << string_compose(_("AudioEngine: cannot load module \"%1\" (%2)"), path,
757                                         Glib::Module::get_last_error()) << endmsg;
758                 return 0;
759         }
760         
761         if (!module.get_symbol ("descriptor", func)) {
762                 error << string_compose(_("AudioEngine: backend at \"%1\" has no descriptor function."), path) << endmsg;
763                 error << Glib::Module::get_last_error() << endmsg;
764                 return 0;
765         }
766         
767         dfunc = (AudioBackendInfo* (*)(void))func;
768         info = dfunc();
769         if (!info->available()) {
770                 return 0;
771         }
772
773         module.make_resident ();
774         
775         return info;
776 }
777
778 vector<const AudioBackendInfo*>
779 AudioEngine::available_backends() const
780 {
781         vector<const AudioBackendInfo*> r;
782         
783         for (BackendMap::const_iterator i = _backends.begin(); i != _backends.end(); ++i) {
784                 r.push_back (i->second);
785         }
786
787         return r;
788 }
789
790 string
791 AudioEngine::current_backend_name() const
792 {
793         if (_backend) {
794                 return _backend->name();
795         } 
796         return string();
797 }
798
799 void
800 AudioEngine::drop_backend ()
801 {
802         if (_backend) {
803                 stop(false);
804                 _backend->drop_device ();
805                 _backend.reset ();
806                 _running = false;
807         }
808 }
809
810 boost::shared_ptr<AudioBackend>
811 AudioEngine::set_default_backend ()
812 {
813         if (_backends.empty()) {
814                 return boost::shared_ptr<AudioBackend>();
815         }
816
817         return set_backend (_backends.begin()->first, "", "");
818 }
819
820 boost::shared_ptr<AudioBackend>
821 AudioEngine::set_backend (const std::string& name, const std::string& arg1, const std::string& arg2)
822 {
823         BackendMap::iterator b = _backends.find (name);
824
825         if (b == _backends.end()) {
826                 return boost::shared_ptr<AudioBackend>();
827         }
828
829         drop_backend ();
830         
831         try {
832                 if (b->second->instantiate (arg1, arg2)) {
833                         throw failed_constructor ();
834                 }
835                 
836                 _backend = b->second->factory (*this);
837
838         } catch (exception& e) {
839                 error << string_compose (_("Could not create backend for %1: %2"), name, e.what()) << endmsg;
840                 return boost::shared_ptr<AudioBackend>();
841         }
842
843         return _backend;
844 }
845
846 /* BACKEND PROXY WRAPPERS */
847
848 int
849 AudioEngine::start (bool for_latency)
850 {
851         if (!_backend) {
852                 return -1;
853         }
854
855         if (_running) {
856                 return 0;
857         }
858
859         _processed_frames = 0;
860         last_monitor_check = 0;
861         
862         if (_backend->start (for_latency)) {
863                 return -1;
864         }
865
866         _running = true;
867         
868         if (_session) {
869                 _session->set_frame_rate (_backend->sample_rate());
870                 
871                 if (_session->config.get_jack_time_master()) {
872                         _backend->set_time_master (true);
873                 }
874
875         }
876         
877         start_metering_thread ();
878         
879         if (!for_latency) {
880                 Running(); /* EMIT SIGNAL */
881         }
882         
883         return 0;
884 }
885
886 int
887 AudioEngine::stop (bool for_latency)
888 {
889         if (!_backend) {
890                 return 0;
891         }
892
893         if (_session && _running) {
894                 // it's not a halt, but should be handled the same way:
895                 // disable record, stop transport and I/O processign but save the data.
896                 _session->engine_halted ();
897         }
898
899         Glib::Threads::Mutex::Lock lm (_process_lock);
900
901         if (_backend->stop ()) {
902                 return -1;
903         }
904         
905         _running = false;
906         _processed_frames = 0;
907         _measuring_latency = MeasureNone;
908         _latency_output_port = 0;
909         _latency_input_port = 0;
910         _started_for_latency = false;
911         stop_metering_thread ();
912         
913         Port::PortDrop ();
914
915         if (!for_latency) {
916                 Stopped (); /* EMIT SIGNAL */
917         }
918         
919         return 0;
920 }
921
922 int
923 AudioEngine::freewheel (bool start_stop)
924 {
925         if (!_backend) {
926                 return -1;
927         }
928
929         /* _freewheeling will be set when first Freewheel signal occurs */
930
931         return _backend->freewheel (start_stop);
932 }
933
934 float
935 AudioEngine::get_dsp_load() const 
936 {
937         if (!_backend) {
938                 return 0.0;
939         }
940         return _backend->dsp_load ();
941 }
942
943 bool
944 AudioEngine::is_realtime() const 
945 {
946         if (!_backend) {
947                 return false;
948         }
949
950         return _backend->is_realtime();
951 }
952
953 bool
954 AudioEngine::connected() const 
955 {
956         if (!_backend) {
957                 return false;
958         }
959
960         return _backend->available();
961 }
962
963 void
964 AudioEngine::transport_start ()
965 {
966         if (!_backend) {
967                 return;
968         }
969         return _backend->transport_start ();
970 }
971
972 void
973 AudioEngine::transport_stop ()
974 {
975         if (!_backend) {
976                 return;
977         }
978         return _backend->transport_stop ();
979 }
980
981 TransportState
982 AudioEngine::transport_state ()
983 {
984         if (!_backend) {
985                 return TransportStopped;
986         }
987         return _backend->transport_state ();
988 }
989
990 void
991 AudioEngine::transport_locate (framepos_t pos)
992 {
993         if (!_backend) {
994                 return;
995         }
996         return _backend->transport_locate (pos);
997 }
998
999 framepos_t
1000 AudioEngine::transport_frame()
1001 {
1002         if (!_backend) {
1003                 return 0;
1004         }
1005         return _backend->transport_frame ();
1006 }
1007
1008 framecnt_t
1009 AudioEngine::sample_rate () const
1010 {
1011         if (!_backend) {
1012                 return 0;
1013         }
1014         return _backend->sample_rate ();
1015 }
1016
1017 pframes_t
1018 AudioEngine::samples_per_cycle () const
1019 {
1020         if (!_backend) {
1021                 return 0;
1022         }
1023         return _backend->buffer_size ();
1024 }
1025
1026 int
1027 AudioEngine::usecs_per_cycle () const
1028 {
1029         if (!_backend) {
1030                 return -1;
1031         }
1032         return _backend->usecs_per_cycle ();
1033 }
1034
1035 size_t
1036 AudioEngine::raw_buffer_size (DataType t)
1037 {
1038         if (!_backend) {
1039                 return -1;
1040         }
1041         return _backend->raw_buffer_size (t);
1042 }
1043
1044 framepos_t
1045 AudioEngine::sample_time ()
1046 {
1047         if (!_backend) {
1048                 return 0;
1049         }
1050         return _backend->sample_time ();
1051 }
1052
1053 framepos_t
1054 AudioEngine::sample_time_at_cycle_start ()
1055 {
1056         if (!_backend) {
1057                 return 0;
1058         }
1059         return _backend->sample_time_at_cycle_start ();
1060 }
1061
1062 pframes_t
1063 AudioEngine::samples_since_cycle_start ()
1064 {
1065         if (!_backend) {
1066                 return 0;
1067         }
1068         return _backend->samples_since_cycle_start ();
1069 }
1070
1071 bool
1072 AudioEngine::get_sync_offset (pframes_t& offset) const
1073 {
1074         if (!_backend) {
1075                 return false;
1076         }
1077         return _backend->get_sync_offset (offset);
1078 }
1079
1080 int
1081 AudioEngine::create_process_thread (boost::function<void()> func)
1082 {
1083         if (!_backend) {
1084                 return -1;
1085         }
1086         return _backend->create_process_thread (func);
1087 }
1088
1089 int
1090 AudioEngine::join_process_threads ()
1091 {
1092         if (!_backend) {
1093                 return -1;
1094         }
1095         return _backend->join_process_threads ();
1096 }
1097
1098 bool
1099 AudioEngine::in_process_thread ()
1100 {
1101         if (!_backend) {
1102                 return false;
1103         }
1104         return _backend->in_process_thread ();
1105 }
1106
1107 uint32_t
1108 AudioEngine::process_thread_count ()
1109 {
1110         if (!_backend) {
1111                 return 0;
1112         }
1113         return _backend->process_thread_count ();
1114 }
1115
1116 int
1117 AudioEngine::set_device_name (const std::string& name)
1118 {
1119         if (!_backend) {
1120                 return -1;
1121         }
1122         return _backend->set_device_name  (name);
1123 }
1124
1125 int
1126 AudioEngine::set_sample_rate (float sr)
1127 {
1128         if (!_backend) {
1129                 return -1;
1130         }
1131
1132         return _backend->set_sample_rate  (sr);
1133 }
1134
1135 int
1136 AudioEngine::set_buffer_size (uint32_t bufsiz)
1137 {
1138         if (!_backend) {
1139                 return -1;
1140         }
1141         return _backend->set_buffer_size  (bufsiz);
1142 }
1143
1144 int
1145 AudioEngine::set_interleaved (bool yn)
1146 {
1147         if (!_backend) {
1148                 return -1;
1149         }
1150         return _backend->set_interleaved  (yn);
1151 }
1152
1153 int
1154 AudioEngine::set_input_channels (uint32_t ic)
1155 {
1156         if (!_backend) {
1157                 return -1;
1158         }
1159         return _backend->set_input_channels  (ic);
1160 }
1161
1162 int
1163 AudioEngine::set_output_channels (uint32_t oc)
1164 {
1165         if (!_backend) {
1166                 return -1;
1167         }
1168         return _backend->set_output_channels (oc);
1169 }
1170
1171 int
1172 AudioEngine::set_systemic_input_latency (uint32_t il)
1173 {
1174         if (!_backend) {
1175                 return -1;
1176         }
1177         return _backend->set_systemic_input_latency  (il);
1178 }
1179
1180 int
1181 AudioEngine::set_systemic_output_latency (uint32_t ol)
1182 {
1183         if (!_backend) {
1184                 return -1;
1185         }
1186         return _backend->set_systemic_output_latency  (ol);
1187 }
1188
1189 /* END OF BACKEND PROXY API */
1190
1191 void
1192 AudioEngine::thread_init_callback (void* arg)
1193 {
1194         /* make sure that anybody who needs to know about this thread
1195            knows about it.
1196         */
1197
1198         pthread_set_name (X_("audioengine"));
1199
1200         SessionEvent::create_per_thread_pool (X_("AudioEngine"), 512);
1201
1202         PBD::notify_gui_about_thread_creation ("gui", pthread_self(), X_("AudioEngine"), 4096);
1203         PBD::notify_gui_about_thread_creation ("midiui", pthread_self(), X_("AudioEngine"), 128);
1204
1205         AsyncMIDIPort::set_process_thread (pthread_self());
1206
1207         if (arg) {
1208                 /* the special thread created/managed by the backend */
1209                 AudioEngine::instance()->_main_thread = new ProcessThread;
1210         }
1211 }
1212
1213 int
1214 AudioEngine::sync_callback (TransportState state, framepos_t position)
1215 {
1216         if (_session) {
1217                 return _session->backend_sync_callback (state, position);
1218         }
1219         return 0;
1220 }
1221
1222 void
1223 AudioEngine::freewheel_callback (bool onoff)
1224 {
1225         _freewheeling = onoff;
1226 }
1227
1228 void
1229 AudioEngine::latency_callback (bool for_playback)
1230 {
1231         if (_session) {
1232                 _session->update_latency (for_playback);
1233         }
1234 }
1235
1236 void
1237 AudioEngine::update_latencies ()
1238 {
1239         if (_backend) {
1240                 _backend->update_latencies ();
1241         }
1242 }
1243
1244 void
1245 AudioEngine::halted_callback (const char* why)
1246 {
1247         if (_in_destructor) {
1248                 /* everything is under control */
1249                 return;
1250         }
1251
1252     stop_metering_thread ();
1253         _running = false;
1254
1255         Port::PortDrop (); /* EMIT SIGNAL */
1256
1257         if (!_started_for_latency) {
1258                 Halted (why);      /* EMIT SIGNAL */
1259         }
1260 }
1261
1262 bool
1263 AudioEngine::setup_required () const
1264 {
1265         if (_backend) {
1266                 if (_backend->info().already_configured())
1267                         return false;
1268         } else {
1269                 if (_backends.size() == 1 && _backends.begin()->second->already_configured()) {
1270                         return false;
1271                 }
1272         }
1273         
1274         return true;
1275 }
1276
1277 int
1278 AudioEngine::prepare_for_latency_measurement ()
1279 {
1280         if (running()) {
1281                 _stopped_for_latency = true;
1282                 stop (true);
1283         }
1284
1285         if (start (true)) {
1286                 _started_for_latency = true;
1287                 return -1;
1288         }
1289
1290         return 0;
1291 }
1292
1293 int
1294 AudioEngine::start_latency_detection (bool for_midi)
1295 {
1296         if (!running()) {
1297                 if (prepare_for_latency_measurement ()) {
1298                         return -1;
1299                 }
1300         }
1301
1302         PortEngine& pe (port_engine());
1303
1304         delete _mtdm;
1305         _mtdm = 0;
1306
1307         delete _mididm;
1308         _mididm = 0;
1309
1310         /* find the ports we will connect to */
1311
1312         PortEngine::PortHandle out = pe.get_port_by_name (_latency_output_name);
1313         PortEngine::PortHandle in = pe.get_port_by_name (_latency_input_name);
1314
1315         if (!out || !in) {
1316                 stop (true);
1317                 return -1;
1318         }
1319
1320         /* create the ports we will use to read/write data */
1321         if (for_midi) {
1322                 if ((_latency_output_port = pe.register_port ("latency_out", DataType::MIDI, IsOutput)) == 0) {
1323                         stop (true);
1324                         return -1;
1325                 }
1326                 if (pe.connect (_latency_output_port, _latency_output_name)) {
1327                         pe.unregister_port (_latency_output_port);
1328                         stop (true);
1329                         return -1;
1330                 }
1331
1332                 const string portname ("latency_in");
1333                 if ((_latency_input_port = pe.register_port (portname, DataType::MIDI, IsInput)) == 0) {
1334                         pe.unregister_port (_latency_input_port);
1335                         pe.unregister_port (_latency_output_port);
1336                         stop (true);
1337                         return -1;
1338                 }
1339                 if (pe.connect (_latency_input_name, make_port_name_non_relative (portname))) {
1340                         pe.unregister_port (_latency_input_port);
1341                         pe.unregister_port (_latency_output_port);
1342                         stop (true);
1343                         return -1;
1344                 }
1345
1346                 _mididm = new MIDIDM (sample_rate());
1347
1348         } else {
1349
1350                 if ((_latency_output_port = pe.register_port ("latency_out", DataType::AUDIO, IsOutput)) == 0) {
1351                         stop (true);
1352                         return -1;
1353                 }
1354                 if (pe.connect (_latency_output_port, _latency_output_name)) {
1355                         pe.unregister_port (_latency_output_port);
1356                         stop (true);
1357                         return -1;
1358                 }
1359
1360                 const string portname ("latency_in");
1361                 if ((_latency_input_port = pe.register_port (portname, DataType::AUDIO, IsInput)) == 0) {
1362                         pe.unregister_port (_latency_input_port);
1363                         pe.unregister_port (_latency_output_port);
1364                         stop (true);
1365                         return -1;
1366                 }
1367                 if (pe.connect (_latency_input_name, make_port_name_non_relative (portname))) {
1368                         pe.unregister_port (_latency_input_port);
1369                         pe.unregister_port (_latency_output_port);
1370                         stop (true);
1371                         return -1;
1372                 }
1373
1374                 _mtdm = new MTDM (sample_rate());
1375
1376         }
1377
1378         LatencyRange lr;
1379         _latency_signal_latency = 0;
1380         lr = pe.get_latency_range (in, false);
1381         _latency_signal_latency = lr.max;
1382         lr = pe.get_latency_range (out, true);
1383         _latency_signal_latency += lr.max;
1384
1385         /* all created and connected, lets go */
1386         _latency_flush_frames = samples_per_cycle();
1387         _measuring_latency = for_midi ? MeasureMIDI : MeasureAudio;
1388
1389         return 0;
1390 }
1391
1392 void
1393 AudioEngine::stop_latency_detection ()
1394 {
1395         _measuring_latency = MeasureNone;
1396
1397         if (_latency_output_port) {
1398                 port_engine().unregister_port (_latency_output_port);
1399                 _latency_output_port = 0;
1400         }
1401         if (_latency_input_port) {
1402                 port_engine().unregister_port (_latency_input_port);
1403                 _latency_input_port = 0;
1404         }
1405
1406         stop (true);
1407
1408         if (_stopped_for_latency) {
1409                 start ();
1410         }
1411
1412         _stopped_for_latency = false;
1413         _started_for_latency = false;
1414 }
1415
1416 void
1417 AudioEngine::set_latency_output_port (const string& name)
1418 {
1419         _latency_output_name = name;
1420 }
1421
1422 void
1423 AudioEngine::set_latency_input_port (const string& name)
1424 {
1425         _latency_input_name = name;
1426 }