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 <jack/weakjack.h>
39 #include "midi++/port.h"
40 #include "midi++/jack_midi_port.h"
41 #include "midi++/mmc.h"
42 #include "midi++/manager.h"
44 #include "ardour/audio_port.h"
45 #include "ardour/audio_backend.h"
46 #include "ardour/audioengine.h"
47 #include "ardour/backend_search_path.h"
48 #include "ardour/buffer.h"
49 #include "ardour/cycle_timer.h"
50 #include "ardour/internal_send.h"
51 #include "ardour/meter.h"
52 #include "ardour/midi_port.h"
53 #include "ardour/port.h"
54 #include "ardour/process_thread.h"
55 #include "ardour/session.h"
60 using namespace ARDOUR;
63 gint AudioEngine::m_meter_exit;
64 AudioEngine* AudioEngine::_instance = 0;
66 AudioEngine::AudioEngine ()
67 : session_remove_pending (false)
68 , session_removal_countdown (-1)
69 , monitor_check_interval (INT32_MAX)
70 , last_monitor_check (0)
71 , _processed_frames (0)
72 , _freewheeling (false)
73 , _pre_freewheel_mmc_enabled (false)
74 , _usecs_per_cycle (0)
75 , port_remove_in_progress (false)
79 g_atomic_int_set (&m_meter_exit, 0);
83 AudioEngine::~AudioEngine ()
87 config_connection.disconnect ();
90 Glib::Threads::Mutex::Lock tm (_process_lock);
91 session_removed.signal ();
92 stop_metering_thread ();
97 AudioEngine::create ()
103 _instance = new AudioEngine ();
109 _thread_init_callback (void * /*arg*/)
111 /* make sure that anybody who needs to know about this thread
115 pthread_set_name (X_("audioengine"));
117 PBD::notify_gui_about_thread_creation ("gui", pthread_self(), X_("Audioengine"), 4096);
118 PBD::notify_gui_about_thread_creation ("midiui", pthread_self(), X_("Audioengine"), 128);
120 SessionEvent::create_per_thread_pool (X_("Audioengine"), 512);
122 MIDI::JackMIDIPort::set_process_thread (pthread_self());
126 AudioEngine::split_cycle (pframes_t offset)
128 /* caller must hold process lock */
130 Port::increment_global_port_buffer_offset (offset);
132 /* tell all Ports that we're going to start a new (split) cycle */
134 boost::shared_ptr<Ports> p = ports.reader();
136 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
137 i->second->cycle_split ();
142 AudioEngine::sample_rate_change (pframes_t nframes)
144 /* check for monitor input change every 1/10th of second */
146 monitor_check_interval = nframes / 10;
147 last_monitor_check = 0;
150 _session->set_frame_rate (nframes);
153 SampleRateChanged (nframes); /* EMIT SIGNAL */
159 AudioEngine::buffer_size_change (pframes_t bufsiz)
162 _session->set_block_size (bufsiz);
163 last_monitor_check = 0;
169 /** Method called by our ::process_thread when there is work to be done.
170 * @param nframes Number of frames to process.
173 AudioEngine::process_callback (pframes_t nframes)
175 Glib::Threads::Mutex::Lock tm (_process_lock, Glib::Threads::TRY_LOCK);
180 /// The number of frames that will have been processed when we've finished
181 pframes_t next_processed_frames;
183 /* handle wrap around of total frames counter */
185 if (max_framepos - _processed_frames < nframes) {
186 next_processed_frames = nframes - (max_framepos - _processed_frames);
188 next_processed_frames = _processed_frames + nframes;
192 /* return having done nothing */
193 _processed_frames = next_processed_frames;
197 if (session_remove_pending) {
199 /* perform the actual session removal */
201 if (session_removal_countdown < 0) {
203 /* fade out over 1 second */
204 session_removal_countdown = _frame_rate/2;
205 session_removal_gain = 1.0;
206 session_removal_gain_step = 1.0/session_removal_countdown;
208 } else if (session_removal_countdown > 0) {
210 /* we'll be fading audio out.
212 if this is the last time we do this as part
213 of session removal, do a MIDI panic now
214 to get MIDI stopped. This relies on the fact
215 that "immediate data" (aka "out of band data") from
216 MIDI tracks is *appended* after any other data,
217 so that it emerges after any outbound note ons, etc.
220 if (session_removal_countdown <= nframes) {
221 _session->midi_panic ();
227 session_removal_countdown = -1; // reset to "not in progress"
228 session_remove_pending = false;
229 session_removed.signal(); // wakes up thread that initiated session removal
235 if (!_freewheeling) {
236 MIDI::Manager::instance()->cycle_start(nframes);
237 MIDI::Manager::instance()->cycle_end();
240 _processed_frames = next_processed_frames;
245 /* tell all relevant objects that we're starting a new cycle */
247 InternalSend::CycleStart (nframes);
248 Port::set_global_port_buffer_offset (0);
249 Port::set_cycle_framecnt (nframes);
251 /* tell all Ports that we're starting a new cycle */
253 boost::shared_ptr<Ports> p = ports.reader();
255 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
256 i->second->cycle_start (nframes);
259 /* test if we are freewheeling and there are freewheel signals connected.
260 ardour should act normally even when freewheeling unless /it/ is
264 if (_freewheeling && !Freewheel.empty()) {
269 MIDI::Manager::instance()->cycle_start(nframes);
272 _session->process (nframes);
275 MIDI::Manager::instance()->cycle_end();
283 _processed_frames = next_processed_frames;
287 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
289 boost::shared_ptr<Ports> p = ports.reader();
291 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
295 if (i->second->last_monitor() != (x = i->second->monitoring_input ())) {
296 i->second->set_last_monitor (x);
297 /* XXX I think this is dangerous, due to
298 a likely mutex in the signal handlers ...
300 i->second->MonitorInputChanged (x); /* EMIT SIGNAL */
303 last_monitor_check = next_processed_frames;
306 if (_session->silent()) {
308 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
310 if (i->second->sends_output()) {
311 i->second->get_buffer(nframes).silence(nframes);
316 if (session_remove_pending && session_removal_countdown) {
318 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
320 if (i->second->sends_output()) {
322 boost::shared_ptr<AudioPort> ap = boost::dynamic_pointer_cast<AudioPort> (i->second);
324 Sample* s = ap->engine_get_whole_audio_buffer ();
325 gain_t g = session_removal_gain;
327 for (pframes_t n = 0; n < nframes; ++n) {
329 g -= session_removal_gain_step;
335 if (session_removal_countdown > nframes) {
336 session_removal_countdown -= nframes;
338 session_removal_countdown = 0;
341 session_removal_gain -= (nframes * session_removal_gain_step);
346 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
347 i->second->cycle_end (nframes);
350 _processed_frames = next_processed_frames;
359 AudioEngine::stop_metering_thread ()
361 if (m_meter_thread) {
362 g_atomic_int_set (&m_meter_exit, 1);
363 m_meter_thread->join ();
369 AudioEngine::start_metering_thread ()
371 if (m_meter_thread == 0) {
372 g_atomic_int_set (&m_meter_exit, 0);
373 m_meter_thread = Glib::Threads::Thread::create (boost::bind (&AudioEngine::meter_thread, this));
378 AudioEngine::meter_thread ()
380 pthread_set_name (X_("meter"));
383 Glib::usleep (10000); /* 1/100th sec interval */
384 if (g_atomic_int_get(&m_meter_exit)) {
392 AudioEngine::set_session (Session *s)
394 Glib::Threads::Mutex::Lock pl (_process_lock);
396 SessionHandlePtr::set_session (s);
400 start_metering_thread ();
402 pframes_t blocksize = _backend->buffer_size ();
404 /* page in as much of the session process code as we
405 can before we really start running.
408 boost::shared_ptr<Ports> p = ports.reader();
410 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
411 i->second->cycle_start (blocksize);
414 _session->process (blocksize);
415 _session->process (blocksize);
416 _session->process (blocksize);
417 _session->process (blocksize);
418 _session->process (blocksize);
419 _session->process (blocksize);
420 _session->process (blocksize);
421 _session->process (blocksize);
423 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
424 i->second->cycle_end (blocksize);
430 AudioEngine::remove_session ()
432 Glib::Threads::Mutex::Lock lm (_process_lock);
436 stop_metering_thread ();
439 session_remove_pending = true;
440 session_removed.wait(_process_lock);
444 SessionHandlePtr::set_session (0);
454 /* called from a signal handler for SIGPIPE */
456 stop_metering_thread ();
464 AudioEngine::reset_timebase ()
467 if (_session->config.get_jack_time_master()) {
468 _backend->set_time_master (true);
470 _backend->set_time_master (false);
478 AudioEngine::destroy ()
485 AudioEngine::discover_backends ()
487 vector<std::string> backend_modules;
491 Glib::PatternSpec so_extension_pattern("*backend.so");
492 Glib::PatternSpec dylib_extension_pattern("*backend.dylib");
494 find_matching_files_in_search_path (backend_search_path (),
495 so_extension_pattern, backend_modules);
497 find_matching_files_in_search_path (backend_search_path (),
498 dylib_extension_pattern, backend_modules);
500 DEBUG_TRACE (DEBUG::Panning, string_compose (_("looking for backends in %1\n"), backend_search_path().to_string()));
502 for (vector<std::string>::iterator i = backend_modules.begin(); i != backend_modules.end(); ++i) {
504 AudioBackendInfo* info;
506 if ((info = backend_discover (*i)) != 0) {
507 _backends.insert (make_pair (info->name, info));
511 return _backends.size();
515 AudioEngine::backend_discover (const string& path)
517 Glib::Module module (path);
518 AudioBackendInfo* info;
522 error << string_compose(_("AudioEngine: cannot load module \"%1\" (%2)"), path,
523 Glib::Module::get_last_error()) << endmsg;
527 if (!module.get_symbol ("descriptor", sym)) {
528 error << string_compose(_("AudioEngine: backend at \"%1\" has no descriptor."), path) << endmsg;
529 error << Glib::Module::get_last_error() << endmsg;
533 module.make_resident ();
535 info = (AudioBackendInfo*) sym;
540 vector<const AudioBackendInfo*>
541 AudioEngine::available_backends() const
543 vector<const AudioBackendInfo*> r;
545 for (BackendMap::const_iterator i = _backends.begin(); i != _backends.end(); ++i) {
546 r.push_back (i->second);
553 AudioEngine::current_backend_name() const
556 return _backend->name();
562 AudioEngine::drop_backend ()
568 BackendRemoved(); /* EMIT SIGNAL */
573 AudioEngine::set_backend (const std::string& name, const std::string& arg1, const std::string& arg2)
575 BackendMap::iterator b = _backends.find (name);
577 if (b == _backends.end()) {
584 cerr << "Instantiate " << b->second->name << " with " << arg1 << " + " << arg2 << endl;
586 if (b->second->instantiate (arg1, arg2)) {
587 cerr << "i failed\n";
588 throw failed_constructor ();
592 _backend = b->second->backend_factory (*this);
594 _impl = b->second->portengine_factory (*this);
597 } catch (exception& e) {
598 error << string_compose (_("Could not create backend for %1: %2"), name, e.what()) << endmsg;
602 BackendAvailable (); /* EMIT SIGNAL */
607 /* BACKEND PROXY WRAPPERS */
610 AudioEngine::start ()
619 BootMessage (_("Connect session to engine"));
620 _session->set_frame_rate (_backend->sample_rate());
623 _processed_frames = 0;
624 last_monitor_check = 0;
626 if (_backend->start() == 0) {
629 last_monitor_check = 0;
631 if (_session && _session->config.get_jack_time_master()) {
632 _backend->set_time_master (true);
635 Running(); /* EMIT SIGNAL */
637 /* should report error? */
641 return _running ? 0 : -1;
651 Glib::Threads::Mutex::Lock lm (_process_lock);
653 if (_backend->stop () == 0) {
655 stop_metering_thread ();
657 Stopped (); /* EMIT SIGNAL */
666 AudioEngine::pause ()
672 if (_backend->pause () == 0) {
674 Stopped(); /* EMIT SIGNAL */
682 AudioEngine::freewheel (bool start_stop)
688 /* _freewheeling will be set when first Freewheel signal occurs */
690 return _backend->freewheel (start_stop);
694 AudioEngine::get_cpu_load() const
699 return _backend->cpu_load ();
703 AudioEngine::is_realtime() const
709 return _backend->is_realtime();
713 AudioEngine::connected() const
719 return _backend->connected();
723 AudioEngine::transport_start ()
728 return _backend->transport_start ();
732 AudioEngine::transport_stop ()
737 return _backend->transport_stop ();
741 AudioEngine::transport_state ()
744 return TransportStopped;
746 return _backend->transport_state ();
750 AudioEngine::transport_locate (framepos_t pos)
755 return _backend->transport_locate (pos);
759 AudioEngine::transport_frame()
764 return _backend->transport_frame ();
768 AudioEngine::sample_rate () const
773 return _backend->sample_rate ();
777 AudioEngine::samples_per_cycle () const
782 return _backend->buffer_size ();
786 AudioEngine::usecs_per_cycle () const
791 return _backend->usecs_per_cycle ();
795 AudioEngine::raw_buffer_size (DataType t)
800 return _backend->raw_buffer_size (t);
804 AudioEngine::sample_time ()
809 return _backend->sample_time ();
813 AudioEngine::sample_time_at_cycle_start ()
818 return _backend->sample_time_at_cycle_start ();
822 AudioEngine::samples_since_cycle_start ()
827 return _backend->samples_since_cycle_start ();
831 AudioEngine::get_sync_offset (pframes_t& offset) const
836 return _backend->get_sync_offset (offset);
840 AudioEngine::create_process_thread (boost::function<void()> func, pthread_t* thr, size_t stacksize)
845 return _backend->create_process_thread (func, thr, stacksize);
850 AudioEngine::set_device_name (const std::string& name)
855 return _backend->set_device_name (name);
859 AudioEngine::set_sample_rate (float sr)
864 return _backend->set_sample_rate (sr);
868 AudioEngine::set_buffer_size (uint32_t bufsiz)
873 return _backend->set_buffer_size (bufsiz);
877 AudioEngine::set_sample_format (SampleFormat sf)
882 return _backend->set_sample_format (sf);
886 AudioEngine::set_interleaved (bool yn)
891 return _backend->set_interleaved (yn);
895 AudioEngine::set_input_channels (uint32_t ic)
900 return _backend->set_input_channels (ic);
904 AudioEngine::set_output_channels (uint32_t oc)
909 return _backend->set_output_channels (oc);
913 AudioEngine::set_systemic_input_latency (uint32_t il)
918 return _backend->set_systemic_input_latency (il);
922 AudioEngine::set_systemic_output_latency (uint32_t ol)
927 return _backend->set_systemic_output_latency (ol);
930 /* END OF BACKEND PROXY API */
933 AudioEngine::thread_init_callback (void* arg)
935 /* make sure that anybody who needs to know about this thread
939 pthread_set_name (X_("audioengine"));
941 PBD::notify_gui_about_thread_creation ("gui", pthread_self(), X_("AudioEngine"), 4096);
942 PBD::notify_gui_about_thread_creation ("midiui", pthread_self(), X_("AudioEngine"), 128);
944 SessionEvent::create_per_thread_pool (X_("AudioEngine"), 512);
946 MIDI::JackMIDIPort::set_process_thread (pthread_self());
949 AudioEngine* ae = static_cast<AudioEngine*> (arg);
950 /* the special thread created/managed by the backend */
951 ae->_main_thread = new ProcessThread;
957 AudioEngine::timebase_callback (TransportState state, pframes_t nframes, jack_position_t pos, int new_position)
959 if (_session && _session->synced_to_jack()) {
960 // _session->timebase_callback (state, nframes, pos, new_position);
966 AudioEngine::sync_callback (TransportState state, framepos_t position)
969 return _session->jack_sync_callback (state, position);
975 AudioEngine::freewheel_callback (bool onoff)
978 _pre_freewheel_mmc_enabled = MIDI::Manager::instance()->mmc()->send_enabled ();
979 MIDI::Manager::instance()->mmc()->enable_send (false);
981 MIDI::Manager::instance()->mmc()->enable_send (_pre_freewheel_mmc_enabled);
986 AudioEngine::latency_callback (bool for_playback)
989 _session->update_latency (for_playback);
994 AudioEngine::update_latencies ()
997 _backend->update_latencies ();
1002 AudioEngine::halted_callback (const char* why)
1004 stop_metering_thread ();
1006 MIDI::JackMIDIPort::EngineHalted (); /* EMIT SIGNAL */
1007 Halted (why); /* EMIT SIGNAL */