b18d5e1af26834ee2d6325b2d6c16abf66b3f7a7
[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     , _hw_reset_event_thread(0)
91     , _hw_reset_request_count(0)
92     , _stop_hw_reset_processing(0)
93     , _hw_devicelist_update_thread(0)
94     , _hw_devicelist_update_count(0)
95     , _stop_hw_devicelist_processing(0)
96 #ifdef SILENCE_AFTER_SECONDS
97         , _silence_countdown (0)
98         , _silence_hit_cnt (0)
99 #endif
100 {
101         reset_silence_countdown ();
102         start_hw_event_processing();
103         discover_backends ();
104 }
105
106 AudioEngine::~AudioEngine ()
107 {
108         _in_destructor = true;
109         stop_hw_event_processing();
110         drop_backend ();
111         for (BackendMap::const_iterator i = _backends.begin(); i != _backends.end(); ++i) {
112                 i->second->deinstantiate();
113         }
114 }
115
116 AudioEngine*
117 AudioEngine::create ()
118 {
119         if (_instance) {
120                 return _instance;
121         }
122
123         _instance = new AudioEngine ();
124         
125         return _instance;
126 }
127
128 void
129 AudioEngine::split_cycle (pframes_t offset)
130 {
131         /* caller must hold process lock */
132
133         Port::increment_global_port_buffer_offset (offset);
134
135         /* tell all Ports that we're going to start a new (split) cycle */
136
137         boost::shared_ptr<Ports> p = ports.reader();
138
139         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
140                 i->second->cycle_split ();
141         }
142 }
143
144 int
145 AudioEngine::sample_rate_change (pframes_t nframes)
146 {
147         /* check for monitor input change every 1/10th of second */
148
149         monitor_check_interval = nframes / 10;
150         last_monitor_check = 0;
151
152         if (_session) {
153                 _session->set_frame_rate (nframes);
154         }
155
156         SampleRateChanged (nframes); /* EMIT SIGNAL */
157
158 #ifdef SILENCE_AFTER_SECONDS
159         _silence_countdown = nframes * SILENCE_AFTER_SECONDS;
160 #endif
161         
162         return 0;
163 }
164
165 int 
166 AudioEngine::buffer_size_change (pframes_t bufsiz)
167 {
168         if (_session) {
169                 _session->set_block_size (bufsiz);
170                 last_monitor_check = 0;
171         }
172
173         BufferSizeChanged (bufsiz); /* EMIT SIGNAL */
174
175         return 0;
176 }
177
178 /** Method called by our ::process_thread when there is work to be done.
179  *  @param nframes Number of frames to process.
180  */
181 #ifdef __clang__
182 __attribute__((annotate("realtime")))
183 #endif
184 int
185 AudioEngine::process_callback (pframes_t nframes)
186 {
187         Glib::Threads::Mutex::Lock tm (_process_lock, Glib::Threads::TRY_LOCK);
188
189         PT_TIMING_REF;
190         PT_TIMING_CHECK (1);
191
192         /// The number of frames that will have been processed when we've finished
193         pframes_t next_processed_frames;
194
195         /* handle wrap around of total frames counter */
196
197         if (max_framepos - _processed_frames < nframes) {
198                 next_processed_frames = nframes - (max_framepos - _processed_frames);
199         } else {
200                 next_processed_frames = _processed_frames + nframes;
201         }
202
203         if (!tm.locked()) {
204                 /* return having done nothing */
205                 if (_session) {
206                         Xrun();
207                 }
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 void
572 AudioEngine::set_session (Session *s)
573 {
574         Glib::Threads::Mutex::Lock pl (_process_lock);
575
576         SessionHandlePtr::set_session (s);
577
578         if (_session) {
579
580                 pframes_t blocksize = samples_per_cycle ();
581
582                 PortManager::cycle_start (blocksize);
583
584                 _session->process (blocksize);
585                 _session->process (blocksize);
586                 _session->process (blocksize);
587                 _session->process (blocksize);
588                 _session->process (blocksize);
589                 _session->process (blocksize);
590                 _session->process (blocksize);
591                 _session->process (blocksize);
592
593                 PortManager::cycle_end (blocksize);
594         }
595 }
596
597 void
598 AudioEngine::remove_session ()
599 {
600         Glib::Threads::Mutex::Lock lm (_process_lock);
601
602         if (_running) {
603
604                 if (_session) {
605                         session_remove_pending = true;
606                         session_removal_countdown = 0;
607                         session_removed.wait(_process_lock);
608                 }
609
610         } else {
611                 SessionHandlePtr::set_session (0);
612         }
613
614         remove_all_ports ();
615 }
616
617
618 void
619 AudioEngine::reconnect_session_routes (bool reconnect_inputs, bool reconnect_outputs)
620 {
621     if (_session) {
622         _session->reconnect_existing_routes(true, true, reconnect_inputs, reconnect_outputs);
623     }
624 }
625
626
627 void
628 AudioEngine::died ()
629 {
630         /* called from a signal handler for SIGPIPE */
631         _running = false;
632 }
633
634 int
635 AudioEngine::reset_timebase ()
636 {
637         if (_session) {
638                 if (_session->config.get_jack_time_master()) {
639                         _backend->set_time_master (true);
640                 } else {
641                         _backend->set_time_master (false);
642                 }
643         }
644         return 0;
645 }
646
647
648 void
649 AudioEngine::destroy ()
650 {
651         delete _instance;
652         _instance = 0;
653 }
654
655 int
656 AudioEngine::discover_backends ()
657 {
658         vector<std::string> backend_modules;
659
660         _backends.clear ();
661
662         Glib::PatternSpec so_extension_pattern("*backend.so");
663         Glib::PatternSpec dylib_extension_pattern("*backend.dylib");
664
665 #if defined(PLATFORM_WINDOWS) && defined(DEBUGGABLE_BACKENDS)
666         #if defined(DEBUG) || defined(_DEBUG)
667                 Glib::PatternSpec dll_extension_pattern("*backendD.dll");
668         #else
669                 Glib::PatternSpec dll_extension_pattern("*backendRDC.dll");
670         #endif
671 #else
672         Glib::PatternSpec dll_extension_pattern("*backend.dll");
673 #endif
674
675         find_files_matching_pattern (backend_modules, backend_search_path (),
676                                      so_extension_pattern);
677
678         find_files_matching_pattern (backend_modules, backend_search_path (),
679                                      dylib_extension_pattern);
680
681         find_files_matching_pattern (backend_modules, backend_search_path (),
682                                      dll_extension_pattern);
683
684         DEBUG_TRACE (DEBUG::AudioEngine, string_compose ("looking for backends in %1\n", backend_search_path().to_string()));
685
686         for (vector<std::string>::iterator i = backend_modules.begin(); i != backend_modules.end(); ++i) {
687
688                 AudioBackendInfo* info;
689
690                 DEBUG_TRACE (DEBUG::AudioEngine, string_compose ("Checking possible backend in %1\n", *i));
691
692                 if ((info = backend_discover (*i)) != 0) {
693                         _backends.insert (make_pair (info->name, info));
694                 }
695         }
696
697         DEBUG_TRACE (DEBUG::AudioEngine, string_compose ("Found %1 backends\n", _backends.size()));
698
699         return _backends.size();
700 }
701
702 AudioBackendInfo*
703 AudioEngine::backend_discover (const string& path)
704 {
705 #ifdef PLATFORM_WINDOWS
706         // do not show popup dialog (e.g. missing libjack.dll)
707         // win7+ should use SetThreadErrorMode()
708         SetErrorMode(SEM_FAILCRITICALERRORS);
709 #endif
710         Glib::Module module (path);
711 #ifdef PLATFORM_WINDOWS
712         SetErrorMode(0); // reset to system default
713 #endif
714         AudioBackendInfo* info;
715         AudioBackendInfo* (*dfunc)(void);
716         void* func = 0;
717
718         if (!module) {
719                 error << string_compose(_("AudioEngine: cannot load module \"%1\" (%2)"), path,
720                                         Glib::Module::get_last_error()) << endmsg;
721                 return 0;
722         }
723         
724         if (!module.get_symbol ("descriptor", func)) {
725                 error << string_compose(_("AudioEngine: backend at \"%1\" has no descriptor function."), path) << endmsg;
726                 error << Glib::Module::get_last_error() << endmsg;
727                 return 0;
728         }
729         
730         dfunc = (AudioBackendInfo* (*)(void))func;
731         info = dfunc();
732         if (!info->available()) {
733                 return 0;
734         }
735
736         module.make_resident ();
737         
738         return info;
739 }
740
741 vector<const AudioBackendInfo*>
742 AudioEngine::available_backends() const
743 {
744         vector<const AudioBackendInfo*> r;
745         
746         for (BackendMap::const_iterator i = _backends.begin(); i != _backends.end(); ++i) {
747                 r.push_back (i->second);
748         }
749
750         return r;
751 }
752
753 string
754 AudioEngine::current_backend_name() const
755 {
756         if (_backend) {
757                 return _backend->name();
758         } 
759         return string();
760 }
761
762 void
763 AudioEngine::drop_backend ()
764 {
765         if (_backend) {
766                 stop(false);
767                 _backend->drop_device ();
768                 _backend.reset ();
769                 _running = false;
770         }
771 }
772
773 boost::shared_ptr<AudioBackend>
774 AudioEngine::set_default_backend ()
775 {
776         if (_backends.empty()) {
777                 return boost::shared_ptr<AudioBackend>();
778         }
779
780         return set_backend (_backends.begin()->first, "", "");
781 }
782
783 boost::shared_ptr<AudioBackend>
784 AudioEngine::set_backend (const std::string& name, const std::string& arg1, const std::string& arg2)
785 {
786         BackendMap::iterator b = _backends.find (name);
787
788         if (b == _backends.end()) {
789                 return boost::shared_ptr<AudioBackend>();
790         }
791
792         drop_backend ();
793         
794         try {
795                 if (b->second->instantiate (arg1, arg2)) {
796                         throw failed_constructor ();
797                 }
798                 
799                 _backend = b->second->factory (*this);
800
801         } catch (exception& e) {
802                 error << string_compose (_("Could not create backend for %1: %2"), name, e.what()) << endmsg;
803                 return boost::shared_ptr<AudioBackend>();
804         }
805
806         return _backend;
807 }
808
809 /* BACKEND PROXY WRAPPERS */
810
811 int
812 AudioEngine::start (bool for_latency)
813 {
814         if (!_backend) {
815                 return -1;
816         }
817
818         if (_running) {
819                 return 0;
820         }
821
822         _processed_frames = 0;
823         last_monitor_check = 0;
824         
825         if (_backend->start (for_latency)) {
826                 return -1;
827         }
828
829         _running = true;
830         
831         if (_session) {
832                 _session->set_frame_rate (_backend->sample_rate());
833                 
834                 if (_session->config.get_jack_time_master()) {
835                         _backend->set_time_master (true);
836                 }
837
838         }
839         
840         if (!for_latency) {
841                 Running(); /* EMIT SIGNAL */
842         }
843         
844         return 0;
845 }
846
847 int
848 AudioEngine::stop (bool for_latency)
849 {
850         if (!_backend) {
851                 return 0;
852         }
853
854         if (_session && _running) {
855                 // it's not a halt, but should be handled the same way:
856                 // disable record, stop transport and I/O processign but save the data.
857                 _session->engine_halted ();
858         }
859
860         Glib::Threads::Mutex::Lock lm (_process_lock);
861
862         if (_backend->stop ()) {
863                 return -1;
864         }
865         
866         _running = false;
867         _processed_frames = 0;
868         _measuring_latency = MeasureNone;
869         _latency_output_port = 0;
870         _latency_input_port = 0;
871         _started_for_latency = false;
872         
873         Port::PortDrop ();
874
875         if (!for_latency) {
876                 Stopped (); /* EMIT SIGNAL */
877         }
878         
879         return 0;
880 }
881
882 int
883 AudioEngine::freewheel (bool start_stop)
884 {
885         if (!_backend) {
886                 return -1;
887         }
888
889         /* _freewheeling will be set when first Freewheel signal occurs */
890
891         return _backend->freewheel (start_stop);
892 }
893
894 float
895 AudioEngine::get_dsp_load() const 
896 {
897         if (!_backend) {
898                 return 0.0;
899         }
900         return _backend->dsp_load ();
901 }
902
903 bool
904 AudioEngine::is_realtime() const 
905 {
906         if (!_backend) {
907                 return false;
908         }
909
910         return _backend->is_realtime();
911 }
912
913 bool
914 AudioEngine::connected() const 
915 {
916         if (!_backend) {
917                 return false;
918         }
919
920         return _backend->available();
921 }
922
923 void
924 AudioEngine::transport_start ()
925 {
926         if (!_backend) {
927                 return;
928         }
929         return _backend->transport_start ();
930 }
931
932 void
933 AudioEngine::transport_stop ()
934 {
935         if (!_backend) {
936                 return;
937         }
938         return _backend->transport_stop ();
939 }
940
941 TransportState
942 AudioEngine::transport_state ()
943 {
944         if (!_backend) {
945                 return TransportStopped;
946         }
947         return _backend->transport_state ();
948 }
949
950 void
951 AudioEngine::transport_locate (framepos_t pos)
952 {
953         if (!_backend) {
954                 return;
955         }
956         return _backend->transport_locate (pos);
957 }
958
959 framepos_t
960 AudioEngine::transport_frame()
961 {
962         if (!_backend) {
963                 return 0;
964         }
965         return _backend->transport_frame ();
966 }
967
968 framecnt_t
969 AudioEngine::sample_rate () const
970 {
971         if (!_backend) {
972                 return 0;
973         }
974         return _backend->sample_rate ();
975 }
976
977 pframes_t
978 AudioEngine::samples_per_cycle () const
979 {
980         if (!_backend) {
981                 return 0;
982         }
983         return _backend->buffer_size ();
984 }
985
986 int
987 AudioEngine::usecs_per_cycle () const
988 {
989         if (!_backend) {
990                 return -1;
991         }
992         return _backend->usecs_per_cycle ();
993 }
994
995 size_t
996 AudioEngine::raw_buffer_size (DataType t)
997 {
998         if (!_backend) {
999                 return -1;
1000         }
1001         return _backend->raw_buffer_size (t);
1002 }
1003
1004 framepos_t
1005 AudioEngine::sample_time ()
1006 {
1007         if (!_backend) {
1008                 return 0;
1009         }
1010         return _backend->sample_time ();
1011 }
1012
1013 framepos_t
1014 AudioEngine::sample_time_at_cycle_start ()
1015 {
1016         if (!_backend) {
1017                 return 0;
1018         }
1019         return _backend->sample_time_at_cycle_start ();
1020 }
1021
1022 pframes_t
1023 AudioEngine::samples_since_cycle_start ()
1024 {
1025         if (!_backend) {
1026                 return 0;
1027         }
1028         return _backend->samples_since_cycle_start ();
1029 }
1030
1031 bool
1032 AudioEngine::get_sync_offset (pframes_t& offset) const
1033 {
1034         if (!_backend) {
1035                 return false;
1036         }
1037         return _backend->get_sync_offset (offset);
1038 }
1039
1040 int
1041 AudioEngine::create_process_thread (boost::function<void()> func)
1042 {
1043         if (!_backend) {
1044                 return -1;
1045         }
1046         return _backend->create_process_thread (func);
1047 }
1048
1049 int
1050 AudioEngine::join_process_threads ()
1051 {
1052         if (!_backend) {
1053                 return -1;
1054         }
1055         return _backend->join_process_threads ();
1056 }
1057
1058 bool
1059 AudioEngine::in_process_thread ()
1060 {
1061         if (!_backend) {
1062                 return false;
1063         }
1064         return _backend->in_process_thread ();
1065 }
1066
1067 uint32_t
1068 AudioEngine::process_thread_count ()
1069 {
1070         if (!_backend) {
1071                 return 0;
1072         }
1073         return _backend->process_thread_count ();
1074 }
1075
1076 int
1077 AudioEngine::set_device_name (const std::string& name)
1078 {
1079         if (!_backend) {
1080                 return -1;
1081         }
1082         return _backend->set_device_name  (name);
1083 }
1084
1085 int
1086 AudioEngine::set_sample_rate (float sr)
1087 {
1088         if (!_backend) {
1089                 return -1;
1090         }
1091
1092         return _backend->set_sample_rate  (sr);
1093 }
1094
1095 int
1096 AudioEngine::set_buffer_size (uint32_t bufsiz)
1097 {
1098         if (!_backend) {
1099                 return -1;
1100         }
1101         return _backend->set_buffer_size  (bufsiz);
1102 }
1103
1104 int
1105 AudioEngine::set_interleaved (bool yn)
1106 {
1107         if (!_backend) {
1108                 return -1;
1109         }
1110         return _backend->set_interleaved  (yn);
1111 }
1112
1113 int
1114 AudioEngine::set_input_channels (uint32_t ic)
1115 {
1116         if (!_backend) {
1117                 return -1;
1118         }
1119         return _backend->set_input_channels  (ic);
1120 }
1121
1122 int
1123 AudioEngine::set_output_channels (uint32_t oc)
1124 {
1125         if (!_backend) {
1126                 return -1;
1127         }
1128         return _backend->set_output_channels (oc);
1129 }
1130
1131 int
1132 AudioEngine::set_systemic_input_latency (uint32_t il)
1133 {
1134         if (!_backend) {
1135                 return -1;
1136         }
1137         return _backend->set_systemic_input_latency  (il);
1138 }
1139
1140 int
1141 AudioEngine::set_systemic_output_latency (uint32_t ol)
1142 {
1143         if (!_backend) {
1144                 return -1;
1145         }
1146         return _backend->set_systemic_output_latency  (ol);
1147 }
1148
1149 /* END OF BACKEND PROXY API */
1150
1151 void
1152 AudioEngine::thread_init_callback (void* arg)
1153 {
1154         /* make sure that anybody who needs to know about this thread
1155            knows about it.
1156         */
1157
1158         pthread_set_name (X_("audioengine"));
1159
1160         SessionEvent::create_per_thread_pool (X_("AudioEngine"), 512);
1161
1162         PBD::notify_gui_about_thread_creation ("gui", pthread_self(), X_("AudioEngine"), 4096);
1163         PBD::notify_gui_about_thread_creation ("midiui", pthread_self(), X_("AudioEngine"), 128);
1164
1165         AsyncMIDIPort::set_process_thread (pthread_self());
1166
1167         if (arg) {
1168                 /* the special thread created/managed by the backend */
1169                 AudioEngine::instance()->_main_thread = new ProcessThread;
1170         }
1171 }
1172
1173 int
1174 AudioEngine::sync_callback (TransportState state, framepos_t position)
1175 {
1176         if (_session) {
1177                 return _session->backend_sync_callback (state, position);
1178         }
1179         return 0;
1180 }
1181
1182 void
1183 AudioEngine::freewheel_callback (bool onoff)
1184 {
1185         _freewheeling = onoff;
1186 }
1187
1188 void
1189 AudioEngine::latency_callback (bool for_playback)
1190 {
1191         if (_session) {
1192                 _session->update_latency (for_playback);
1193         }
1194 }
1195
1196 void
1197 AudioEngine::update_latencies ()
1198 {
1199         if (_backend) {
1200                 _backend->update_latencies ();
1201         }
1202 }
1203
1204 void
1205 AudioEngine::halted_callback (const char* why)
1206 {
1207         if (_in_destructor) {
1208                 /* everything is under control */
1209                 return;
1210         }
1211
1212         _running = false;
1213
1214         Port::PortDrop (); /* EMIT SIGNAL */
1215
1216         if (!_started_for_latency) {
1217                 Halted (why);      /* EMIT SIGNAL */
1218         }
1219 }
1220
1221 bool
1222 AudioEngine::setup_required () const
1223 {
1224         if (_backend) {
1225                 if (_backend->info().already_configured())
1226                         return false;
1227         } else {
1228                 if (_backends.size() == 1 && _backends.begin()->second->already_configured()) {
1229                         return false;
1230                 }
1231         }
1232         
1233         return true;
1234 }
1235
1236 int
1237 AudioEngine::prepare_for_latency_measurement ()
1238 {
1239         if (running()) {
1240                 _stopped_for_latency = true;
1241                 stop (true);
1242         }
1243
1244         if (start (true)) {
1245                 _started_for_latency = true;
1246                 return -1;
1247         }
1248
1249         return 0;
1250 }
1251
1252 int
1253 AudioEngine::start_latency_detection (bool for_midi)
1254 {
1255         if (!running()) {
1256                 if (prepare_for_latency_measurement ()) {
1257                         return -1;
1258                 }
1259         }
1260
1261         PortEngine& pe (port_engine());
1262
1263         delete _mtdm;
1264         _mtdm = 0;
1265
1266         delete _mididm;
1267         _mididm = 0;
1268
1269         /* find the ports we will connect to */
1270
1271         PortEngine::PortHandle out = pe.get_port_by_name (_latency_output_name);
1272         PortEngine::PortHandle in = pe.get_port_by_name (_latency_input_name);
1273
1274         if (!out || !in) {
1275                 stop (true);
1276                 return -1;
1277         }
1278
1279         /* create the ports we will use to read/write data */
1280         if (for_midi) {
1281                 if ((_latency_output_port = pe.register_port ("latency_out", DataType::MIDI, IsOutput)) == 0) {
1282                         stop (true);
1283                         return -1;
1284                 }
1285                 if (pe.connect (_latency_output_port, _latency_output_name)) {
1286                         pe.unregister_port (_latency_output_port);
1287                         stop (true);
1288                         return -1;
1289                 }
1290
1291                 const string portname ("latency_in");
1292                 if ((_latency_input_port = pe.register_port (portname, DataType::MIDI, IsInput)) == 0) {
1293                         pe.unregister_port (_latency_input_port);
1294                         pe.unregister_port (_latency_output_port);
1295                         stop (true);
1296                         return -1;
1297                 }
1298                 if (pe.connect (_latency_input_name, make_port_name_non_relative (portname))) {
1299                         pe.unregister_port (_latency_input_port);
1300                         pe.unregister_port (_latency_output_port);
1301                         stop (true);
1302                         return -1;
1303                 }
1304
1305                 _mididm = new MIDIDM (sample_rate());
1306
1307         } else {
1308
1309                 if ((_latency_output_port = pe.register_port ("latency_out", DataType::AUDIO, IsOutput)) == 0) {
1310                         stop (true);
1311                         return -1;
1312                 }
1313                 if (pe.connect (_latency_output_port, _latency_output_name)) {
1314                         pe.unregister_port (_latency_output_port);
1315                         stop (true);
1316                         return -1;
1317                 }
1318
1319                 const string portname ("latency_in");
1320                 if ((_latency_input_port = pe.register_port (portname, DataType::AUDIO, IsInput)) == 0) {
1321                         pe.unregister_port (_latency_input_port);
1322                         pe.unregister_port (_latency_output_port);
1323                         stop (true);
1324                         return -1;
1325                 }
1326                 if (pe.connect (_latency_input_name, make_port_name_non_relative (portname))) {
1327                         pe.unregister_port (_latency_input_port);
1328                         pe.unregister_port (_latency_output_port);
1329                         stop (true);
1330                         return -1;
1331                 }
1332
1333                 _mtdm = new MTDM (sample_rate());
1334
1335         }
1336
1337         LatencyRange lr;
1338         _latency_signal_latency = 0;
1339         lr = pe.get_latency_range (in, false);
1340         _latency_signal_latency = lr.max;
1341         lr = pe.get_latency_range (out, true);
1342         _latency_signal_latency += lr.max;
1343
1344         /* all created and connected, lets go */
1345         _latency_flush_frames = samples_per_cycle();
1346         _measuring_latency = for_midi ? MeasureMIDI : MeasureAudio;
1347
1348         return 0;
1349 }
1350
1351 void
1352 AudioEngine::stop_latency_detection ()
1353 {
1354         _measuring_latency = MeasureNone;
1355
1356         if (_latency_output_port) {
1357                 port_engine().unregister_port (_latency_output_port);
1358                 _latency_output_port = 0;
1359         }
1360         if (_latency_input_port) {
1361                 port_engine().unregister_port (_latency_input_port);
1362                 _latency_input_port = 0;
1363         }
1364
1365         stop (true);
1366
1367         if (_stopped_for_latency) {
1368                 start ();
1369         }
1370
1371         _stopped_for_latency = false;
1372         _started_for_latency = false;
1373 }
1374
1375 void
1376 AudioEngine::set_latency_output_port (const string& name)
1377 {
1378         _latency_output_name = name;
1379 }
1380
1381 void
1382 AudioEngine::set_latency_input_port (const string& name)
1383 {
1384         _latency_input_name = name;
1385 }