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