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