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