convert cerr<< to DEBUG_TRACE
[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 "pbd/i18n.h"
59
60 using namespace std;
61 using namespace ARDOUR;
62 using namespace PBD;
63
64 AudioEngine* AudioEngine::_instance = 0;
65
66 static gint audioengine_thread_cnt = 1;
67
68 #ifdef SILENCE_AFTER
69 #define SILENCE_AFTER_SECONDS 600
70 #endif
71
72 AudioEngine::AudioEngine ()
73         : session_remove_pending (false)
74         , session_removal_countdown (-1)
75         , _running (false)
76         , _freewheeling (false)
77         , monitor_check_interval (INT32_MAX)
78         , last_monitor_check (0)
79         , _processed_frames (0)
80         , m_meter_thread (0)
81         , _main_thread (0)
82         , _mtdm (0)
83         , _mididm (0)
84         , _measuring_latency (MeasureNone)
85         , _latency_input_port (0)
86         , _latency_output_port (0)
87         , _latency_flush_frames (0)
88         , _latency_signal_latency (0)
89         , _stopped_for_latency (false)
90         , _started_for_latency (false)
91         , _in_destructor (false)
92         , _last_backend_error_string(AudioBackend::get_error_string((AudioBackend::ErrorCode)-1))
93     , _hw_reset_event_thread(0)
94     , _hw_reset_request_count(0)
95     , _stop_hw_reset_processing(0)
96     , _hw_devicelist_update_thread(0)
97     , _hw_devicelist_update_count(0)
98     , _stop_hw_devicelist_processing(0)
99 #ifdef SILENCE_AFTER_SECONDS
100         , _silence_countdown (0)
101         , _silence_hit_cnt (0)
102 #endif
103 {
104         reset_silence_countdown ();
105         start_hw_event_processing();
106         discover_backends ();
107 }
108
109 AudioEngine::~AudioEngine ()
110 {
111         _in_destructor = true;
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         delete _main_thread;
118 }
119
120 AudioEngine*
121 AudioEngine::create ()
122 {
123         if (_instance) {
124                 return _instance;
125         }
126
127         _instance = new AudioEngine ();
128
129         return _instance;
130 }
131
132 void
133 AudioEngine::split_cycle (pframes_t offset)
134 {
135         /* caller must hold process lock */
136
137         Port::increment_global_port_buffer_offset (offset);
138
139         /* tell all Ports that we're going to start a new (split) cycle */
140
141         boost::shared_ptr<Ports> p = ports.reader();
142
143         for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
144                 i->second->cycle_split ();
145         }
146 }
147
148 int
149 AudioEngine::sample_rate_change (pframes_t nframes)
150 {
151         /* check for monitor input change every 1/10th of second */
152
153         monitor_check_interval = nframes / 10;
154         last_monitor_check = 0;
155
156         if (_session) {
157                 _session->set_frame_rate (nframes);
158         }
159
160         SampleRateChanged (nframes); /* EMIT SIGNAL */
161
162 #ifdef SILENCE_AFTER_SECONDS
163         _silence_countdown = nframes * SILENCE_AFTER_SECONDS;
164 #endif
165
166         return 0;
167 }
168
169 int
170 AudioEngine::buffer_size_change (pframes_t bufsiz)
171 {
172         if (_session) {
173                 _session->set_block_size (bufsiz);
174                 last_monitor_check = 0;
175         }
176
177         BufferSizeChanged (bufsiz); /* EMIT SIGNAL */
178
179         return 0;
180 }
181
182 /** Method called by our ::process_thread when there is work to be done.
183  *  @param nframes Number of frames to process.
184  */
185 #ifdef __clang__
186 __attribute__((annotate("realtime")))
187 #endif
188 int
189 AudioEngine::process_callback (pframes_t nframes)
190 {
191         Glib::Threads::Mutex::Lock tm (_process_lock, Glib::Threads::TRY_LOCK);
192
193         PT_TIMING_REF;
194         PT_TIMING_CHECK (1);
195
196         /// The number of frames that will have been processed when we've finished
197         pframes_t next_processed_frames;
198
199         /* handle wrap around of total frames counter */
200
201         if (max_framepos - _processed_frames < nframes) {
202                 next_processed_frames = nframes - (max_framepos - _processed_frames);
203         } else {
204                 next_processed_frames = _processed_frames + nframes;
205         }
206
207         if (!tm.locked()) {
208                 /* return having done nothing */
209                 if (_session) {
210                         Xrun();
211                 }
212                 /* really only JACK requires this
213                  * (other backends clear the output buffers
214                  * before the process_callback. it may even be
215                  * jack/alsa only). but better safe than sorry.
216                  */
217                 PortManager::silence_outputs (nframes);
218                 return 0;
219         }
220
221         /* The coreaudio-backend calls thread_init_callback() if
222          * the hardware changes or pthread_self() changes.
223          *
224          * However there are cases when neither holds true, yet
225          * the thread-pool changes: e.g. connect a headphone to
226          * a shared mic/headphone jack.
227          * It's probably related to, or caused by clocksource changes.
228          *
229          * For reasons yet unknown Glib::Threads::Private() can
230          * use a different thread-private in the same pthread
231          * (coreaudio render callback).
232          *
233          * Coreaudio must set something which influences
234          * pthread_key_t uniqness or reset the key using
235          * pthread_getspecific().
236          */
237         if (! SessionEvent::has_per_thread_pool ()) {
238                 thread_init_callback (NULL);
239         }
240
241         bool return_after_remove_check = false;
242
243         if (_measuring_latency == MeasureAudio && _mtdm) {
244                 /* run a normal cycle from the perspective of the PortManager
245                    so that we get silence on all registered ports.
246
247                    we overwrite the silence on the two ports used for latency
248                    measurement.
249                 */
250
251                 PortManager::cycle_start (nframes);
252                 PortManager::silence (nframes);
253
254                 if (_latency_input_port && _latency_output_port) {
255                         PortEngine& pe (port_engine());
256
257                         Sample* in = (Sample*) pe.get_buffer (_latency_input_port, nframes);
258                         Sample* out = (Sample*) pe.get_buffer (_latency_output_port, nframes);
259
260                         _mtdm->process (nframes, in, out);
261                 }
262
263                 PortManager::cycle_end (nframes);
264                 return_after_remove_check = true;
265
266         } else if (_measuring_latency == MeasureMIDI && _mididm) {
267                 /* run a normal cycle from the perspective of the PortManager
268                    so that we get silence on all registered ports.
269
270                    we overwrite the silence on the two ports used for latency
271                    measurement.
272                 */
273
274                 PortManager::cycle_start (nframes);
275                 PortManager::silence (nframes);
276
277                 if (_latency_input_port && _latency_output_port) {
278                         PortEngine& pe (port_engine());
279
280                         _mididm->process (nframes, pe,
281                                         pe.get_buffer (_latency_input_port, nframes),
282                                         pe.get_buffer (_latency_output_port, nframes));
283                 }
284
285                 PortManager::cycle_end (nframes);
286                 return_after_remove_check = true;
287
288         } else if (_latency_flush_frames) {
289
290                 /* wait for the appropriate duration for the MTDM signal to
291                  * drain from the ports before we revert to normal behaviour.
292                  */
293
294                 PortManager::cycle_start (nframes);
295                 PortManager::silence (nframes);
296                 PortManager::cycle_end (nframes);
297
298                 if (_latency_flush_frames > nframes) {
299                         _latency_flush_frames -= nframes;
300                 } else {
301                         _latency_flush_frames = 0;
302                 }
303
304                 return_after_remove_check = true;
305         }
306
307         if (session_remove_pending) {
308
309                 /* perform the actual session removal */
310
311                 if (session_removal_countdown < 0) {
312
313                         /* fade out over 1 second */
314                         session_removal_countdown = sample_rate()/2;
315                         session_removal_gain = GAIN_COEFF_UNITY;
316                         session_removal_gain_step = 1.0/session_removal_countdown;
317
318                 } else if (session_removal_countdown > 0) {
319
320                         /* we'll be fading audio out.
321
322                            if this is the last time we do this as part
323                            of session removal, do a MIDI panic now
324                            to get MIDI stopped. This relies on the fact
325                            that "immediate data" (aka "out of band data") from
326                            MIDI tracks is *appended* after any other data,
327                            so that it emerges after any outbound note ons, etc.
328                         */
329
330                         if (session_removal_countdown <= nframes) {
331                                 _session->midi_panic ();
332                         }
333
334                 } else {
335                         /* fade out done */
336                         _session = 0;
337                         session_removal_countdown = -1; // reset to "not in progress"
338                         session_remove_pending = false;
339                         session_removed.signal(); // wakes up thread that initiated session removal
340                 }
341         }
342
343         if (return_after_remove_check) {
344                 return 0;
345         }
346
347         if (_session == 0) {
348
349                 if (!_freewheeling) {
350                         PortManager::cycle_start (nframes);
351                         PortManager::cycle_end (nframes);
352                 }
353
354                 _processed_frames = next_processed_frames;
355
356                 return 0;
357         }
358
359         /* tell all relevant objects that we're starting a new cycle */
360
361         InternalSend::CycleStart (nframes);
362
363         /* tell all Ports that we're starting a new cycle */
364
365         PortManager::cycle_start (nframes);
366
367         /* test if we are freewheeling and there are freewheel signals connected.
368            ardour should act normally even when freewheeling unless /it/ is
369            exporting (which is what Freewheel.empty() tests for).
370         */
371
372         if (_freewheeling && !Freewheel.empty()) {
373                 Freewheel (nframes);
374         } else {
375                 _session->process (nframes);
376         }
377
378         if (_freewheeling) {
379                 PortManager::cycle_end (nframes);
380                 return 0;
381         }
382
383         if (!_running) {
384                 _processed_frames = next_processed_frames;
385                 return 0;
386         }
387
388         if (last_monitor_check + monitor_check_interval < next_processed_frames) {
389
390                 PortManager::check_monitoring ();
391                 last_monitor_check = next_processed_frames;
392         }
393
394 #ifdef SILENCE_AFTER_SECONDS
395
396         bool was_silent = (_silence_countdown == 0);
397
398         if (_silence_countdown >= nframes) {
399                 _silence_countdown -= nframes;
400         } else {
401                 _silence_countdown = 0;
402         }
403
404         if (!was_silent && _silence_countdown == 0) {
405                 _silence_hit_cnt++;
406                 BecameSilent (); /* EMIT SIGNAL */
407         }
408
409         if (_silence_countdown == 0 || _session->silent()) {
410                 PortManager::silence (nframes);
411         }
412
413 #else
414         if (_session->silent()) {
415                 PortManager::silence (nframes, _session);
416         }
417 #endif
418
419         if (session_remove_pending && session_removal_countdown) {
420
421                 PortManager::fade_out (session_removal_gain, session_removal_gain_step, nframes);
422
423                 if (session_removal_countdown > nframes) {
424                         session_removal_countdown -= nframes;
425                 } else {
426                         session_removal_countdown = 0;
427                 }
428
429                 session_removal_gain -= (nframes * session_removal_gain_step);
430         }
431
432         PortManager::cycle_end (nframes);
433
434         _processed_frames = next_processed_frames;
435
436         PT_TIMING_CHECK (2);
437
438         return 0;
439 }
440
441 void
442 AudioEngine::reset_silence_countdown ()
443 {
444 #ifdef SILENCE_AFTER_SECONDS
445         double sr = 48000; /* default in case there is no backend */
446
447         sr = sample_rate();
448
449         _silence_countdown = max (60 * sr, /* 60 seconds */
450                                   sr * (SILENCE_AFTER_SECONDS / ::pow (2.0, (double) _silence_hit_cnt)));
451
452 #endif
453 }
454
455 void
456 AudioEngine::launch_device_control_app()
457 {
458         if (_state_lock.trylock () ) {
459                 _backend->launch_control_app ();
460                 _state_lock.unlock ();
461         }
462 }
463
464
465 void
466 AudioEngine::request_backend_reset()
467 {
468     Glib::Threads::Mutex::Lock guard (_reset_request_lock);
469     g_atomic_int_inc (&_hw_reset_request_count);
470     _hw_reset_condition.signal ();
471 }
472
473 int
474 AudioEngine::backend_reset_requested()
475 {
476         return g_atomic_int_get (&_hw_reset_request_count);
477 }
478
479 void
480 AudioEngine::do_reset_backend()
481 {
482         SessionEvent::create_per_thread_pool (X_("Backend reset processing thread"), 1024);
483
484         Glib::Threads::Mutex::Lock guard (_reset_request_lock);
485
486         while (!_stop_hw_reset_processing) {
487
488                 if (g_atomic_int_get (&_hw_reset_request_count) != 0 && _backend) {
489
490                         _reset_request_lock.unlock();
491
492                         Glib::Threads::RecMutex::Lock pl (_state_lock);
493                         g_atomic_int_dec_and_test (&_hw_reset_request_count);
494
495             std::cout << "AudioEngine::RESET::Reset request processing. Requests left: " << _hw_reset_request_count << std::endl;
496                         DeviceResetStarted(); // notify about device reset to be started
497
498                         // backup the device name
499                         std::string name = _backend->device_name ();
500
501             std::cout << "AudioEngine::RESET::Reseting device..." << std::endl;
502                         if ( ( 0 == stop () ) &&
503                  ( 0 == _backend->reset_device () ) &&
504                  ( 0 == start () ) ) {
505
506                                 std::cout << "AudioEngine::RESET::Engine started..." << std::endl;
507
508                                 // inform about possible changes
509                                 BufferSizeChanged (_backend->buffer_size() );
510                 DeviceResetFinished(); // notify about device reset finish
511
512             } else {
513
514                 DeviceResetFinished(); // notify about device reset finish
515                                 // we've got an error
516                 DeviceError();
517                         }
518
519                         std::cout << "AudioEngine::RESET::Done." << std::endl;
520
521                         _reset_request_lock.lock();
522
523                 } else {
524
525                         _hw_reset_condition.wait (_reset_request_lock);
526
527                 }
528         }
529 }
530 void
531 AudioEngine::request_device_list_update()
532 {
533     Glib::Threads::Mutex::Lock guard (_devicelist_update_lock);
534     g_atomic_int_inc (&_hw_devicelist_update_count);
535     _hw_devicelist_update_condition.signal ();
536 }
537
538
539 void
540 AudioEngine::do_devicelist_update()
541 {
542     SessionEvent::create_per_thread_pool (X_("Device list update processing thread"), 512);
543
544     Glib::Threads::Mutex::Lock guard (_devicelist_update_lock);
545
546     while (!_stop_hw_devicelist_processing) {
547
548         if (_hw_devicelist_update_count) {
549
550             _devicelist_update_lock.unlock();
551
552             Glib::Threads::RecMutex::Lock pl (_state_lock);
553
554             g_atomic_int_dec_and_test (&_hw_devicelist_update_count);
555             DeviceListChanged (); /* EMIT SIGNAL */
556
557             _devicelist_update_lock.lock();
558
559         } else {
560             _hw_devicelist_update_condition.wait (_devicelist_update_lock);
561         }
562     }
563 }
564
565
566 void
567 AudioEngine::start_hw_event_processing()
568 {
569     if (_hw_reset_event_thread == 0) {
570         g_atomic_int_set(&_hw_reset_request_count, 0);
571         g_atomic_int_set(&_stop_hw_reset_processing, 0);
572         _hw_reset_event_thread = Glib::Threads::Thread::create (boost::bind (&AudioEngine::do_reset_backend, this));
573     }
574
575     if (_hw_devicelist_update_thread == 0) {
576         g_atomic_int_set(&_hw_devicelist_update_count, 0);
577         g_atomic_int_set(&_stop_hw_devicelist_processing, 0);
578         _hw_devicelist_update_thread = Glib::Threads::Thread::create (boost::bind (&AudioEngine::do_devicelist_update, this));
579     }
580 }
581
582
583 void
584 AudioEngine::stop_hw_event_processing()
585 {
586     if (_hw_reset_event_thread) {
587         g_atomic_int_set(&_stop_hw_reset_processing, 1);
588         g_atomic_int_set(&_hw_reset_request_count, 0);
589         _hw_reset_condition.signal ();
590         _hw_reset_event_thread->join ();
591         _hw_reset_event_thread = 0;
592     }
593
594     if (_hw_devicelist_update_thread) {
595         g_atomic_int_set(&_stop_hw_devicelist_processing, 1);
596         g_atomic_int_set(&_hw_devicelist_update_count, 0);
597         _hw_devicelist_update_condition.signal ();
598         _hw_devicelist_update_thread->join ();
599         _hw_devicelist_update_thread = 0;
600     }
601
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                         /* signal the start of the fade out countdown */
641                         session_removal_countdown = -1;
642                         session_removed.wait(_process_lock);
643                 }
644
645         } else {
646                 SessionHandlePtr::set_session (0);
647         }
648
649         remove_all_ports ();
650 }
651
652
653 void
654 AudioEngine::reconnect_session_routes (bool reconnect_inputs, bool reconnect_outputs)
655 {
656 #ifdef USE_TRACKS_CODE_FEATURES
657         if (_session) {
658                 _session->reconnect_existing_routes(true, true, reconnect_inputs, reconnect_outputs);
659         }
660 #endif
661 }
662
663
664 void
665 AudioEngine::died ()
666 {
667         /* called from a signal handler for SIGPIPE */
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 static bool running_from_source_tree ()
779 {
780         // dup ARDOUR_UI_UTILS::running_from_source_tree ()
781         gchar const *x = g_getenv ("ARDOUR_THEMES_PATH");
782         return x && (string (x).find ("gtk2_ardour") != string::npos);
783 }
784
785 vector<const AudioBackendInfo*>
786 AudioEngine::available_backends() const
787 {
788         vector<const AudioBackendInfo*> r;
789
790         for (BackendMap::const_iterator i = _backends.begin(); i != _backends.end(); ++i) {
791 #ifdef NDEBUG
792                 if (i->first == "None (Dummy)" && !running_from_source_tree ()) {
793                         continue;
794                 }
795 #endif
796                 r.push_back (i->second);
797         }
798
799         return r;
800 }
801
802 string
803 AudioEngine::current_backend_name() const
804 {
805         if (_backend) {
806                 return _backend->name();
807         }
808         return string();
809 }
810
811 void
812 AudioEngine::drop_backend ()
813 {
814         if (_backend) {
815                 _backend->stop ();
816                 // Stopped is needed for Graph to explicitly terminate threads
817                 Stopped (); /* EMIT SIGNAL */
818                 _backend->drop_device ();
819                 _backend.reset ();
820                 _running = false;
821         }
822 }
823
824 boost::shared_ptr<AudioBackend>
825 AudioEngine::set_default_backend ()
826 {
827         if (_backends.empty()) {
828                 return boost::shared_ptr<AudioBackend>();
829         }
830
831         return set_backend (_backends.begin()->first, "", "");
832 }
833
834 boost::shared_ptr<AudioBackend>
835 AudioEngine::set_backend (const std::string& name, const std::string& arg1, const std::string& arg2)
836 {
837         BackendMap::iterator b = _backends.find (name);
838
839         if (b == _backends.end()) {
840                 return boost::shared_ptr<AudioBackend>();
841         }
842
843         drop_backend ();
844
845         try {
846                 if (b->second->instantiate (arg1, arg2)) {
847                         throw failed_constructor ();
848                 }
849
850                 _backend = b->second->factory (*this);
851
852         } catch (exception& e) {
853                 error << string_compose (_("Could not create backend for %1: %2"), name, e.what()) << endmsg;
854                 return boost::shared_ptr<AudioBackend>();
855         }
856
857         return _backend;
858 }
859
860 /* BACKEND PROXY WRAPPERS */
861
862 int
863 AudioEngine::start (bool for_latency)
864 {
865         if (!_backend) {
866                 return -1;
867         }
868
869         if (_running) {
870                 return 0;
871         }
872
873         _processed_frames = 0;
874         last_monitor_check = 0;
875
876         int error_code = _backend->start (for_latency);
877
878         if (error_code != 0) {
879                 _last_backend_error_string =
880                     AudioBackend::get_error_string((AudioBackend::ErrorCode)error_code);
881                 return -1;
882         }
883
884         _running = true;
885
886         if (_session) {
887                 _session->set_frame_rate (_backend->sample_rate());
888
889                 if (_session->config.get_jack_time_master()) {
890                         _backend->set_time_master (true);
891                 }
892
893         }
894
895         if (!for_latency) {
896                 Running(); /* EMIT SIGNAL */
897         }
898
899         return 0;
900 }
901
902 int
903 AudioEngine::stop (bool for_latency)
904 {
905         bool stop_engine = true;
906
907         if (!_backend) {
908                 return 0;
909         }
910
911         Glib::Threads::Mutex::Lock pl (_process_lock, Glib::Threads::NOT_LOCK);
912
913         if (running()) {
914                 pl.acquire ();
915         }
916
917         if (for_latency && _backend->can_change_systemic_latency_when_running()) {
918                 stop_engine = false;
919         } else {
920                 if (_backend->stop ()) {
921                         if (pl.locked ()) { 
922                             pl.release ();
923                         }
924                         return -1;
925                 }
926         }
927
928         if (pl.locked ()) {
929                 pl.release ();
930         }
931
932         if (_session && _running && stop_engine &&
933             (_session->state_of_the_state() & Session::Loading) == 0 &&
934             (_session->state_of_the_state() & Session::Deletion) == 0) {
935                 // it's not a halt, but should be handled the same way:
936                 // disable record, stop transport and I/O processign but save the data.
937                 _session->engine_halted ();
938         }
939
940         if (stop_engine) {
941                 _running = false;
942         }
943         _processed_frames = 0;
944         _measuring_latency = MeasureNone;
945         _latency_output_port = 0;
946         _latency_input_port = 0;
947         _started_for_latency = false;
948
949         if (stop_engine) {
950                 Port::PortDrop ();
951         }
952
953         if (!for_latency && stop_engine) {
954                 Stopped (); /* EMIT SIGNAL */
955         }
956
957         return 0;
958 }
959
960 int
961 AudioEngine::freewheel (bool start_stop)
962 {
963         if (!_backend) {
964                 return -1;
965         }
966
967         /* _freewheeling will be set when first Freewheel signal occurs */
968
969         return _backend->freewheel (start_stop);
970 }
971
972 float
973 AudioEngine::get_dsp_load() const
974 {
975         if (!_backend || !_running) {
976                 return 0.0;
977         }
978         return _backend->dsp_load ();
979 }
980
981 bool
982 AudioEngine::is_realtime() const
983 {
984         if (!_backend) {
985                 return false;
986         }
987
988         return _backend->is_realtime();
989 }
990
991 bool
992 AudioEngine::connected() const
993 {
994         if (!_backend) {
995                 return false;
996         }
997
998         return _backend->available();
999 }
1000
1001 void
1002 AudioEngine::transport_start ()
1003 {
1004         if (!_backend) {
1005                 return;
1006         }
1007         return _backend->transport_start ();
1008 }
1009
1010 void
1011 AudioEngine::transport_stop ()
1012 {
1013         if (!_backend) {
1014                 return;
1015         }
1016         return _backend->transport_stop ();
1017 }
1018
1019 TransportState
1020 AudioEngine::transport_state ()
1021 {
1022         if (!_backend) {
1023                 return TransportStopped;
1024         }
1025         return _backend->transport_state ();
1026 }
1027
1028 void
1029 AudioEngine::transport_locate (framepos_t pos)
1030 {
1031         if (!_backend) {
1032                 return;
1033         }
1034         return _backend->transport_locate (pos);
1035 }
1036
1037 framepos_t
1038 AudioEngine::transport_frame()
1039 {
1040         if (!_backend) {
1041                 return 0;
1042         }
1043         return _backend->transport_frame ();
1044 }
1045
1046 framecnt_t
1047 AudioEngine::sample_rate () const
1048 {
1049         if (!_backend) {
1050                 return 0;
1051         }
1052         return _backend->sample_rate ();
1053 }
1054
1055 pframes_t
1056 AudioEngine::samples_per_cycle () const
1057 {
1058         if (!_backend) {
1059                 return 0;
1060         }
1061         return _backend->buffer_size ();
1062 }
1063
1064 int
1065 AudioEngine::usecs_per_cycle () const
1066 {
1067         if (!_backend) {
1068                 return -1;
1069         }
1070         return _backend->usecs_per_cycle ();
1071 }
1072
1073 size_t
1074 AudioEngine::raw_buffer_size (DataType t)
1075 {
1076         if (!_backend) {
1077                 return -1;
1078         }
1079         return _backend->raw_buffer_size (t);
1080 }
1081
1082 framepos_t
1083 AudioEngine::sample_time ()
1084 {
1085         if (!_backend) {
1086                 return 0;
1087         }
1088         return _backend->sample_time ();
1089 }
1090
1091 framepos_t
1092 AudioEngine::sample_time_at_cycle_start ()
1093 {
1094         if (!_backend) {
1095                 return 0;
1096         }
1097         return _backend->sample_time_at_cycle_start ();
1098 }
1099
1100 pframes_t
1101 AudioEngine::samples_since_cycle_start ()
1102 {
1103         if (!_backend) {
1104                 return 0;
1105         }
1106         return _backend->samples_since_cycle_start ();
1107 }
1108
1109 bool
1110 AudioEngine::get_sync_offset (pframes_t& offset) const
1111 {
1112         if (!_backend) {
1113                 return false;
1114         }
1115         return _backend->get_sync_offset (offset);
1116 }
1117
1118 int
1119 AudioEngine::create_process_thread (boost::function<void()> func)
1120 {
1121         if (!_backend) {
1122                 return -1;
1123         }
1124         return _backend->create_process_thread (func);
1125 }
1126
1127 int
1128 AudioEngine::join_process_threads ()
1129 {
1130         if (!_backend) {
1131                 return -1;
1132         }
1133         return _backend->join_process_threads ();
1134 }
1135
1136 bool
1137 AudioEngine::in_process_thread ()
1138 {
1139         if (!_backend) {
1140                 return false;
1141         }
1142         return _backend->in_process_thread ();
1143 }
1144
1145 uint32_t
1146 AudioEngine::process_thread_count ()
1147 {
1148         if (!_backend) {
1149                 return 0;
1150         }
1151         return _backend->process_thread_count ();
1152 }
1153
1154 int
1155 AudioEngine::set_device_name (const std::string& name)
1156 {
1157         if (!_backend) {
1158                 return -1;
1159         }
1160         return _backend->set_device_name  (name);
1161 }
1162
1163 int
1164 AudioEngine::set_sample_rate (float sr)
1165 {
1166         if (!_backend) {
1167                 return -1;
1168         }
1169
1170         return _backend->set_sample_rate  (sr);
1171 }
1172
1173 int
1174 AudioEngine::set_buffer_size (uint32_t bufsiz)
1175 {
1176         if (!_backend) {
1177                 return -1;
1178         }
1179         return _backend->set_buffer_size  (bufsiz);
1180 }
1181
1182 int
1183 AudioEngine::set_interleaved (bool yn)
1184 {
1185         if (!_backend) {
1186                 return -1;
1187         }
1188         return _backend->set_interleaved  (yn);
1189 }
1190
1191 int
1192 AudioEngine::set_input_channels (uint32_t ic)
1193 {
1194         if (!_backend) {
1195                 return -1;
1196         }
1197         return _backend->set_input_channels  (ic);
1198 }
1199
1200 int
1201 AudioEngine::set_output_channels (uint32_t oc)
1202 {
1203         if (!_backend) {
1204                 return -1;
1205         }
1206         return _backend->set_output_channels (oc);
1207 }
1208
1209 int
1210 AudioEngine::set_systemic_input_latency (uint32_t il)
1211 {
1212         if (!_backend) {
1213                 return -1;
1214         }
1215         return _backend->set_systemic_input_latency  (il);
1216 }
1217
1218 int
1219 AudioEngine::set_systemic_output_latency (uint32_t ol)
1220 {
1221         if (!_backend) {
1222                 return -1;
1223         }
1224         return _backend->set_systemic_output_latency  (ol);
1225 }
1226
1227 bool
1228 AudioEngine::thread_initialised_for_audio_processing ()
1229 {
1230     return SessionEvent::has_per_thread_pool () && AsyncMIDIPort::is_process_thread();
1231 }
1232
1233 /* END OF BACKEND PROXY API */
1234
1235 void
1236 AudioEngine::thread_init_callback (void* arg)
1237 {
1238         /* make sure that anybody who needs to know about this thread
1239            knows about it.
1240         */
1241
1242         pthread_set_name (X_("audioengine"));
1243
1244         const int thread_num = g_atomic_int_add (&audioengine_thread_cnt, 1);
1245         const string thread_name = string_compose (X_("AudioEngine %1"), thread_num);
1246
1247         SessionEvent::create_per_thread_pool (thread_name, 512);
1248         PBD::notify_event_loops_about_thread_creation (pthread_self(), thread_name, 4096);
1249         AsyncMIDIPort::set_process_thread (pthread_self());
1250
1251         if (arg) {
1252                 delete AudioEngine::instance()->_main_thread;
1253                 /* the special thread created/managed by the backend */
1254                 AudioEngine::instance()->_main_thread = new ProcessThread;
1255         }
1256 }
1257
1258 int
1259 AudioEngine::sync_callback (TransportState state, framepos_t position)
1260 {
1261         if (_session) {
1262                 return _session->backend_sync_callback (state, position);
1263         }
1264         return 0;
1265 }
1266
1267 void
1268 AudioEngine::freewheel_callback (bool onoff)
1269 {
1270         _freewheeling = onoff;
1271 }
1272
1273 void
1274 AudioEngine::latency_callback (bool for_playback)
1275 {
1276         if (_session) {
1277                 _session->update_latency (for_playback);
1278         }
1279 }
1280
1281 void
1282 AudioEngine::update_latencies ()
1283 {
1284         if (_backend) {
1285                 _backend->update_latencies ();
1286         }
1287 }
1288
1289 void
1290 AudioEngine::halted_callback (const char* why)
1291 {
1292         if (_in_destructor) {
1293                 /* everything is under control */
1294                 return;
1295         }
1296
1297         _running = false;
1298
1299         Port::PortDrop (); /* EMIT SIGNAL */
1300
1301         if (!_started_for_latency) {
1302                 Halted (why);      /* EMIT SIGNAL */
1303         }
1304 }
1305
1306 bool
1307 AudioEngine::setup_required () const
1308 {
1309         if (_backend) {
1310                 if (_backend->info().already_configured())
1311                         return false;
1312         } else {
1313                 if (_backends.size() == 1 && _backends.begin()->second->already_configured()) {
1314                         return false;
1315                 }
1316         }
1317
1318         return true;
1319 }
1320
1321 int
1322 AudioEngine::prepare_for_latency_measurement ()
1323 {
1324         if (!_backend) {
1325                 return -1;
1326         }
1327
1328         if (_backend->can_change_systemic_latency_when_running()) {
1329                 if (start()) {
1330                         return -1;
1331                 }
1332                 _backend->set_systemic_input_latency (0);
1333                 _backend->set_systemic_output_latency (0);
1334                 return 0;
1335         }
1336
1337         if (running()) {
1338                 _stopped_for_latency = true;
1339                 stop (true);
1340         }
1341
1342         if (start (true)) {
1343                 return -1;
1344         }
1345         _started_for_latency = true;
1346
1347         return 0;
1348 }
1349
1350 int
1351 AudioEngine::start_latency_detection (bool for_midi)
1352 {
1353         if (prepare_for_latency_measurement ()) {
1354                 return -1;
1355         }
1356
1357         PortEngine& pe (port_engine());
1358
1359         delete _mtdm;
1360         _mtdm = 0;
1361
1362         delete _mididm;
1363         _mididm = 0;
1364
1365         /* find the ports we will connect to */
1366
1367         PortEngine::PortHandle out = pe.get_port_by_name (_latency_output_name);
1368         PortEngine::PortHandle in = pe.get_port_by_name (_latency_input_name);
1369
1370         if (!out || !in) {
1371                 stop (true);
1372                 return -1;
1373         }
1374
1375         /* create the ports we will use to read/write data */
1376         if (for_midi) {
1377                 if ((_latency_output_port = pe.register_port ("latency_out", DataType::MIDI, IsOutput)) == 0) {
1378                         stop (true);
1379                         return -1;
1380                 }
1381                 if (pe.connect (_latency_output_port, _latency_output_name)) {
1382                         pe.unregister_port (_latency_output_port);
1383                         stop (true);
1384                         return -1;
1385                 }
1386
1387                 const string portname ("latency_in");
1388                 if ((_latency_input_port = pe.register_port (portname, DataType::MIDI, IsInput)) == 0) {
1389                         pe.unregister_port (_latency_input_port);
1390                         pe.unregister_port (_latency_output_port);
1391                         stop (true);
1392                         return -1;
1393                 }
1394                 if (pe.connect (_latency_input_name, make_port_name_non_relative (portname))) {
1395                         pe.unregister_port (_latency_input_port);
1396                         pe.unregister_port (_latency_output_port);
1397                         stop (true);
1398                         return -1;
1399                 }
1400
1401                 _mididm = new MIDIDM (sample_rate());
1402
1403         } else {
1404
1405                 if ((_latency_output_port = pe.register_port ("latency_out", DataType::AUDIO, IsOutput)) == 0) {
1406                         stop (true);
1407                         return -1;
1408                 }
1409                 if (pe.connect (_latency_output_port, _latency_output_name)) {
1410                         pe.unregister_port (_latency_output_port);
1411                         stop (true);
1412                         return -1;
1413                 }
1414
1415                 const string portname ("latency_in");
1416                 if ((_latency_input_port = pe.register_port (portname, DataType::AUDIO, IsInput)) == 0) {
1417                         pe.unregister_port (_latency_input_port);
1418                         pe.unregister_port (_latency_output_port);
1419                         stop (true);
1420                         return -1;
1421                 }
1422                 if (pe.connect (_latency_input_name, make_port_name_non_relative (portname))) {
1423                         pe.unregister_port (_latency_input_port);
1424                         pe.unregister_port (_latency_output_port);
1425                         stop (true);
1426                         return -1;
1427                 }
1428
1429                 _mtdm = new MTDM (sample_rate());
1430
1431         }
1432
1433         LatencyRange lr;
1434         _latency_signal_latency = 0;
1435         lr = pe.get_latency_range (in, false);
1436         _latency_signal_latency = lr.max;
1437         lr = pe.get_latency_range (out, true);
1438         _latency_signal_latency += lr.max;
1439
1440         /* all created and connected, lets go */
1441         _latency_flush_frames = samples_per_cycle();
1442         _measuring_latency = for_midi ? MeasureMIDI : MeasureAudio;
1443
1444         return 0;
1445 }
1446
1447 void
1448 AudioEngine::stop_latency_detection ()
1449 {
1450         _measuring_latency = MeasureNone;
1451
1452         if (_latency_output_port) {
1453                 port_engine().unregister_port (_latency_output_port);
1454                 _latency_output_port = 0;
1455         }
1456         if (_latency_input_port) {
1457                 port_engine().unregister_port (_latency_input_port);
1458                 _latency_input_port = 0;
1459         }
1460
1461         if (!_backend->can_change_systemic_latency_when_running()) {
1462                 stop (true);
1463         }
1464
1465         if (_stopped_for_latency) {
1466                 start ();
1467         }
1468
1469         _stopped_for_latency = false;
1470         _started_for_latency = false;
1471 }
1472
1473 void
1474 AudioEngine::set_latency_output_port (const string& name)
1475 {
1476         _latency_output_name = name;
1477 }
1478
1479 void
1480 AudioEngine::set_latency_input_port (const string& name)
1481 {
1482         _latency_input_name = name;
1483 }
1484
1485 void
1486 AudioEngine::add_pending_port_deletion (Port* p)
1487 {
1488         if (_session) {
1489                 DEBUG_TRACE (DEBUG::Ports, string_compose ("adding %1 to pending port deletion list\n", p->name()));
1490                 if (_port_deletions_pending.write (&p, 1) != 1) {
1491                         error << string_compose (_("programming error: port %1 could not be placed on the pending deletion queue\n"), p->name()) << endmsg;
1492                 }
1493                 _session->auto_connect_thread_wakeup ();
1494         } else {
1495                 DEBUG_TRACE (DEBUG::Ports, string_compose ("Directly delete port %1\n", p->name()));
1496                 delete p;
1497         }
1498 }
1499