2 Copyright (C) 2002 Paul Davis
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.
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.
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.
27 #include <glibmm/timer.h>
28 #include <glibmm/pattern.h>
29 #include <glibmm/module.h>
32 #include "pbd/file_utils.h"
33 #include "pbd/pthread_utils.h"
34 #include "pbd/stacktrace.h"
35 #include "pbd/unknown_type.h"
37 #include "midi++/port.h"
38 #include "midi++/mmc.h"
40 #include "ardour/async_midi_port.h"
41 #include "ardour/audio_port.h"
42 #include "ardour/audio_backend.h"
43 #include "ardour/audioengine.h"
44 #include "ardour/backend_search_path.h"
45 #include "ardour/buffer.h"
46 #include "ardour/cycle_timer.h"
47 #include "ardour/internal_send.h"
48 #include "ardour/meter.h"
49 #include "ardour/midi_port.h"
50 #include "ardour/midiport_manager.h"
51 #include "ardour/mtdm.h"
52 #include "ardour/port.h"
53 #include "ardour/process_thread.h"
54 #include "ardour/session.h"
59 using namespace ARDOUR;
62 gint AudioEngine::m_meter_exit;
63 AudioEngine* AudioEngine::_instance = 0;
65 AudioEngine::AudioEngine ()
66 : session_remove_pending (false)
67 , session_removal_countdown (-1)
69 , _freewheeling (false)
70 , monitor_check_interval (INT32_MAX)
71 , last_monitor_check (0)
72 , _processed_frames (0)
76 , _measuring_latency (false)
77 , _latency_input_port (0)
78 , _latency_output_port (0)
79 , _latency_flush_frames (0)
80 , _latency_signal_latency (0)
81 , _stopped_for_latency (false)
82 , _in_destructor (false)
84 g_atomic_int_set (&m_meter_exit, 0);
88 AudioEngine::~AudioEngine ()
90 _in_destructor = true;
91 stop_metering_thread ();
96 AudioEngine::create ()
102 _instance = new AudioEngine ();
108 _thread_init_callback (void * /*arg*/)
110 /* make sure that anybody who needs to know about this thread
114 pthread_set_name (X_("audioengine"));
116 PBD::notify_gui_about_thread_creation ("gui", pthread_self(), X_("Audioengine"), 4096);
117 PBD::notify_gui_about_thread_creation ("midiui", pthread_self(), X_("Audioengine"), 128);
119 SessionEvent::create_per_thread_pool (X_("Audioengine"), 512);
121 AsyncMIDIPort::set_process_thread (pthread_self());
125 AudioEngine::split_cycle (pframes_t offset)
127 /* caller must hold process lock */
129 Port::increment_global_port_buffer_offset (offset);
131 /* tell all Ports that we're going to start a new (split) cycle */
133 boost::shared_ptr<Ports> p = ports.reader();
135 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
136 i->second->cycle_split ();
141 AudioEngine::sample_rate_change (pframes_t nframes)
143 /* check for monitor input change every 1/10th of second */
145 monitor_check_interval = nframes / 10;
146 last_monitor_check = 0;
149 _session->set_frame_rate (nframes);
152 SampleRateChanged (nframes); /* EMIT SIGNAL */
158 AudioEngine::buffer_size_change (pframes_t bufsiz)
161 _session->set_block_size (bufsiz);
162 last_monitor_check = 0;
168 /** Method called by our ::process_thread when there is work to be done.
169 * @param nframes Number of frames to process.
172 AudioEngine::process_callback (pframes_t nframes)
174 Glib::Threads::Mutex::Lock tm (_process_lock, Glib::Threads::TRY_LOCK);
179 /// The number of frames that will have been processed when we've finished
180 pframes_t next_processed_frames;
182 /* handle wrap around of total frames counter */
184 if (max_framepos - _processed_frames < nframes) {
185 next_processed_frames = nframes - (max_framepos - _processed_frames);
187 next_processed_frames = _processed_frames + nframes;
191 /* return having done nothing */
192 _processed_frames = next_processed_frames;
196 bool return_after_remove_check = false;
198 if (_measuring_latency && _mtdm) {
199 /* run a normal cycle from the perspective of the PortManager
200 so that we get silence on all registered ports.
202 we overwrite the silence on the two ports used for latency
206 PortManager::cycle_start (nframes);
207 PortManager::silence (nframes);
209 if (_latency_input_port && _latency_output_port) {
210 PortEngine& pe (port_engine());
212 Sample* in = (Sample*) pe.get_buffer (_latency_input_port, nframes);
213 Sample* out = (Sample*) pe.get_buffer (_latency_output_port, nframes);
215 _mtdm->process (nframes, in, out);
218 PortManager::cycle_end (nframes);
219 return_after_remove_check = true;
221 } else if (_latency_flush_frames) {
223 /* wait for the appropriate duration for the MTDM signal to
224 * drain from the ports before we revert to normal behaviour.
227 PortManager::cycle_start (nframes);
228 PortManager::silence (nframes);
229 PortManager::cycle_end (nframes);
231 if (_latency_flush_frames > nframes) {
232 _latency_flush_frames -= nframes;
234 _latency_flush_frames = 0;
237 return_after_remove_check = true;
240 if (session_remove_pending) {
242 /* perform the actual session removal */
244 if (session_removal_countdown < 0) {
246 /* fade out over 1 second */
247 session_removal_countdown = sample_rate()/2;
248 session_removal_gain = 1.0;
249 session_removal_gain_step = 1.0/session_removal_countdown;
251 } else if (session_removal_countdown > 0) {
253 /* we'll be fading audio out.
255 if this is the last time we do this as part
256 of session removal, do a MIDI panic now
257 to get MIDI stopped. This relies on the fact
258 that "immediate data" (aka "out of band data") from
259 MIDI tracks is *appended* after any other data,
260 so that it emerges after any outbound note ons, etc.
263 if (session_removal_countdown <= nframes) {
264 _session->midi_panic ();
270 session_removal_countdown = -1; // reset to "not in progress"
271 session_remove_pending = false;
272 session_removed.signal(); // wakes up thread that initiated session removal
276 if (return_after_remove_check) {
282 if (!_freewheeling) {
283 PortManager::cycle_start (nframes);
284 PortManager::cycle_end (nframes);
287 _processed_frames = next_processed_frames;
292 /* tell all relevant objects that we're starting a new cycle */
294 InternalSend::CycleStart (nframes);
296 /* tell all Ports that we're starting a new cycle */
298 PortManager::cycle_start (nframes);
300 /* test if we are freewheeling and there are freewheel signals connected.
301 ardour should act normally even when freewheeling unless /it/ is
302 exporting (which is what Freewheel.empty() tests for).
305 if (_freewheeling && !Freewheel.empty()) {
309 _session->process (nframes);
318 _processed_frames = next_processed_frames;
322 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
324 PortManager::check_monitoring ();
325 last_monitor_check = next_processed_frames;
328 if (_session->silent()) {
329 PortManager::silence (nframes);
332 if (session_remove_pending && session_removal_countdown) {
334 PortManager::fade_out (session_removal_gain, session_removal_gain_step, nframes);
336 if (session_removal_countdown > nframes) {
337 session_removal_countdown -= nframes;
339 session_removal_countdown = 0;
342 session_removal_gain -= (nframes * session_removal_gain_step);
345 PortManager::cycle_end (nframes);
347 _processed_frames = next_processed_frames;
356 AudioEngine::stop_metering_thread ()
358 if (m_meter_thread) {
359 g_atomic_int_set (&m_meter_exit, 1);
360 m_meter_thread->join ();
366 AudioEngine::start_metering_thread ()
368 if (m_meter_thread == 0) {
369 g_atomic_int_set (&m_meter_exit, 0);
370 m_meter_thread = Glib::Threads::Thread::create (boost::bind (&AudioEngine::meter_thread, this));
375 AudioEngine::meter_thread ()
377 pthread_set_name (X_("meter"));
380 Glib::usleep (10000); /* 1/100th sec interval */
381 if (g_atomic_int_get(&m_meter_exit)) {
389 AudioEngine::set_session (Session *s)
391 Glib::Threads::Mutex::Lock pl (_process_lock);
393 SessionHandlePtr::set_session (s);
397 pframes_t blocksize = samples_per_cycle ();
399 PortManager::cycle_start (blocksize);
401 _session->process (blocksize);
402 _session->process (blocksize);
403 _session->process (blocksize);
404 _session->process (blocksize);
405 _session->process (blocksize);
406 _session->process (blocksize);
407 _session->process (blocksize);
408 _session->process (blocksize);
410 PortManager::cycle_end (blocksize);
415 AudioEngine::remove_session ()
417 Glib::Threads::Mutex::Lock lm (_process_lock);
422 session_remove_pending = true;
423 session_removal_countdown = 0;
424 session_removed.wait(_process_lock);
428 SessionHandlePtr::set_session (0);
438 /* called from a signal handler for SIGPIPE */
440 stop_metering_thread ();
446 AudioEngine::reset_timebase ()
449 if (_session->config.get_jack_time_master()) {
450 _backend->set_time_master (true);
452 _backend->set_time_master (false);
460 AudioEngine::destroy ()
467 AudioEngine::discover_backends ()
469 vector<std::string> backend_modules;
473 Glib::PatternSpec so_extension_pattern("*backend.so");
474 Glib::PatternSpec dylib_extension_pattern("*backend.dylib");
476 #if defined(PLATFORM_WINDOWS) && defined(DEBUGGABLE_BACKENDS)
477 #if defined(DEBUG) || defined(_DEBUG)
478 Glib::PatternSpec dll_extension_pattern("*backendD.dll");
480 Glib::PatternSpec dll_extension_pattern("*backendRDC.dll");
483 Glib::PatternSpec dll_extension_pattern("*backend.dll");
486 find_matching_files_in_search_path (backend_search_path (),
487 so_extension_pattern, backend_modules);
489 find_matching_files_in_search_path (backend_search_path (),
490 dylib_extension_pattern, backend_modules);
492 find_matching_files_in_search_path (backend_search_path (),
493 dll_extension_pattern, backend_modules);
495 DEBUG_TRACE (DEBUG::Panning, string_compose (_("looking for backends in %1\n"), backend_search_path().to_string()));
497 for (vector<std::string>::iterator i = backend_modules.begin(); i != backend_modules.end(); ++i) {
499 AudioBackendInfo* info;
501 if ((info = backend_discover (*i)) != 0) {
502 _backends.insert (make_pair (info->name, info));
506 return _backends.size();
510 AudioEngine::backend_discover (const string& path)
512 Glib::Module module (path);
513 AudioBackendInfo* info;
514 AudioBackendInfo* (*dfunc)(void);
518 error << string_compose(_("AudioEngine: cannot load module \"%1\" (%2)"), path,
519 Glib::Module::get_last_error()) << endmsg;
523 if (!module.get_symbol ("descriptor", func)) {
524 error << string_compose(_("AudioEngine: backend at \"%1\" has no descriptor function."), path) << endmsg;
525 error << Glib::Module::get_last_error() << endmsg;
529 module.make_resident ();
531 dfunc = (AudioBackendInfo* (*)(void))func;
537 vector<const AudioBackendInfo*>
538 AudioEngine::available_backends() const
540 vector<const AudioBackendInfo*> r;
542 for (BackendMap::const_iterator i = _backends.begin(); i != _backends.end(); ++i) {
543 r.push_back (i->second);
550 AudioEngine::current_backend_name() const
553 return _backend->name();
559 AudioEngine::drop_backend ()
567 boost::shared_ptr<AudioBackend>
568 AudioEngine::set_default_backend ()
570 if (_backends.empty()) {
571 return boost::shared_ptr<AudioBackend>();
574 return set_backend (_backends.begin()->first, "", "");
577 boost::shared_ptr<AudioBackend>
578 AudioEngine::set_backend (const std::string& name, const std::string& arg1, const std::string& arg2)
580 BackendMap::iterator b = _backends.find (name);
582 if (b == _backends.end()) {
583 return boost::shared_ptr<AudioBackend>();
589 if (b->second->instantiate (arg1, arg2)) {
590 throw failed_constructor ();
593 _backend = b->second->factory (*this);
595 } catch (exception& e) {
596 error << string_compose (_("Could not create backend for %1: %2"), name, e.what()) << endmsg;
597 return boost::shared_ptr<AudioBackend>();
603 /* BACKEND PROXY WRAPPERS */
606 AudioEngine::start (bool for_latency)
616 _processed_frames = 0;
617 last_monitor_check = 0;
619 if (_backend->start (for_latency)) {
626 _session->set_frame_rate (_backend->sample_rate());
628 if (_session->config.get_jack_time_master()) {
629 _backend->set_time_master (true);
633 start_metering_thread ();
636 Running(); /* EMIT SIGNAL */
643 AudioEngine::stop (bool for_latency)
649 Glib::Threads::Mutex::Lock lm (_process_lock);
651 if (_backend->stop ()) {
656 _processed_frames = 0;
657 _measuring_latency = false;
658 _latency_output_port = 0;
659 _latency_input_port = 0;
660 _started_for_latency = false;
661 stop_metering_thread ();
666 Stopped (); /* EMIT SIGNAL */
673 AudioEngine::pause ()
679 if (_backend->pause ()) {
685 Stopped(); /* EMIT SIGNAL */
690 AudioEngine::freewheel (bool start_stop)
696 /* _freewheeling will be set when first Freewheel signal occurs */
698 return _backend->freewheel (start_stop);
702 AudioEngine::get_cpu_load() const
707 return _backend->cpu_load ();
711 AudioEngine::is_realtime() const
717 return _backend->is_realtime();
721 AudioEngine::connected() const
727 return _backend->available();
731 AudioEngine::transport_start ()
736 return _backend->transport_start ();
740 AudioEngine::transport_stop ()
745 return _backend->transport_stop ();
749 AudioEngine::transport_state ()
752 return TransportStopped;
754 return _backend->transport_state ();
758 AudioEngine::transport_locate (framepos_t pos)
763 return _backend->transport_locate (pos);
767 AudioEngine::transport_frame()
772 return _backend->transport_frame ();
776 AudioEngine::sample_rate () const
781 return _backend->sample_rate ();
785 AudioEngine::samples_per_cycle () const
790 return _backend->buffer_size ();
794 AudioEngine::usecs_per_cycle () const
799 return _backend->usecs_per_cycle ();
803 AudioEngine::raw_buffer_size (DataType t)
808 return _backend->raw_buffer_size (t);
812 AudioEngine::sample_time ()
817 return _backend->sample_time ();
821 AudioEngine::sample_time_at_cycle_start ()
826 return _backend->sample_time_at_cycle_start ();
830 AudioEngine::samples_since_cycle_start ()
835 return _backend->samples_since_cycle_start ();
839 AudioEngine::get_sync_offset (pframes_t& offset) const
844 return _backend->get_sync_offset (offset);
848 AudioEngine::create_process_thread (boost::function<void()> func)
853 return _backend->create_process_thread (func);
857 AudioEngine::join_process_threads ()
862 return _backend->join_process_threads ();
866 AudioEngine::in_process_thread ()
871 return _backend->in_process_thread ();
875 AudioEngine::process_thread_count ()
880 return _backend->process_thread_count ();
884 AudioEngine::set_device_name (const std::string& name)
889 return _backend->set_device_name (name);
893 AudioEngine::set_sample_rate (float sr)
898 return _backend->set_sample_rate (sr);
902 AudioEngine::set_buffer_size (uint32_t bufsiz)
907 return _backend->set_buffer_size (bufsiz);
911 AudioEngine::set_sample_format (SampleFormat sf)
916 return _backend->set_sample_format (sf);
920 AudioEngine::set_interleaved (bool yn)
925 return _backend->set_interleaved (yn);
929 AudioEngine::set_input_channels (uint32_t ic)
934 return _backend->set_input_channels (ic);
938 AudioEngine::set_output_channels (uint32_t oc)
943 return _backend->set_output_channels (oc);
947 AudioEngine::set_systemic_input_latency (uint32_t il)
952 return _backend->set_systemic_input_latency (il);
956 AudioEngine::set_systemic_output_latency (uint32_t ol)
961 return _backend->set_systemic_output_latency (ol);
964 /* END OF BACKEND PROXY API */
967 AudioEngine::thread_init_callback (void* arg)
969 /* make sure that anybody who needs to know about this thread
973 pthread_set_name (X_("audioengine"));
975 PBD::notify_gui_about_thread_creation ("gui", pthread_self(), X_("AudioEngine"), 4096);
976 PBD::notify_gui_about_thread_creation ("midiui", pthread_self(), X_("AudioEngine"), 128);
978 SessionEvent::create_per_thread_pool (X_("AudioEngine"), 512);
980 AsyncMIDIPort::set_process_thread (pthread_self());
983 /* the special thread created/managed by the backend */
984 AudioEngine::instance()->_main_thread = new ProcessThread;
989 AudioEngine::sync_callback (TransportState state, framepos_t position)
992 return _session->backend_sync_callback (state, position);
998 AudioEngine::freewheel_callback (bool onoff)
1000 _freewheeling = onoff;
1004 AudioEngine::latency_callback (bool for_playback)
1007 _session->update_latency (for_playback);
1012 AudioEngine::update_latencies ()
1015 _backend->update_latencies ();
1020 AudioEngine::halted_callback (const char* why)
1022 if (_in_destructor) {
1023 /* everything is under control */
1027 stop_metering_thread ();
1030 Port::PortDrop (); /* EMIT SIGNAL */
1032 if (!_started_for_latency) {
1033 Halted (why); /* EMIT SIGNAL */
1038 AudioEngine::setup_required () const
1040 /* If there is only a single backend and it claims to be configured
1041 * already there is no setup to be done.
1043 * Primarily for a case where there is only a JACK backend and
1044 * JACK is already running.
1047 if (_backends.size() == 1 && _backends.begin()->second->already_configured()) {
1061 AudioEngine::prepare_for_latency_measurement ()
1064 _stopped_for_latency = true;
1069 _started_for_latency = true;
1077 AudioEngine::start_latency_detection ()
1080 if (prepare_for_latency_measurement ()) {
1085 PortEngine& pe (port_engine());
1090 /* find the ports we will connect to */
1092 PortEngine::PortHandle* out = pe.get_port_by_name (_latency_output_name);
1093 PortEngine::PortHandle* in = pe.get_port_by_name (_latency_input_name);
1100 /* create the ports we will use to read/write data */
1102 if ((_latency_output_port = pe.register_port ("latency_out", DataType::AUDIO, IsOutput)) == 0) {
1106 if (pe.connect (_latency_output_port, _latency_output_name)) {
1107 pe.unregister_port (_latency_output_port);
1112 const string portname ("latency_in");
1113 if ((_latency_input_port = pe.register_port (portname, DataType::AUDIO, IsInput)) == 0) {
1114 pe.unregister_port (_latency_output_port);
1118 if (pe.connect (_latency_input_name, make_port_name_non_relative (portname))) {
1119 pe.unregister_port (_latency_output_port);
1125 _latency_signal_latency = 0;
1126 lr = pe.get_latency_range (in, false);
1127 _latency_signal_latency = lr.max;
1128 lr = pe.get_latency_range (out, true);
1129 _latency_signal_latency += lr.max;
1131 /* all created and connected, lets go */
1133 _mtdm = new MTDM (sample_rate());
1134 _measuring_latency = true;
1135 _latency_flush_frames = samples_per_cycle();
1141 AudioEngine::stop_latency_detection ()
1143 _measuring_latency = false;
1145 if (_latency_output_port) {
1146 port_engine().unregister_port (_latency_output_port);
1147 _latency_output_port = 0;
1149 if (_latency_input_port) {
1150 port_engine().unregister_port (_latency_input_port);
1151 _latency_input_port = 0;
1156 if (_stopped_for_latency) {
1160 _stopped_for_latency = false;
1161 _started_for_latency = false;
1165 AudioEngine::set_latency_output_port (const string& name)
1167 _latency_output_name = name;
1171 AudioEngine::set_latency_input_port (const string& name)
1173 _latency_input_name = name;