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)
77 g_atomic_int_set (&m_meter_exit, 0);
81 AudioEngine::~AudioEngine ()
85 config_connection.disconnect ();
88 Glib::Threads::Mutex::Lock tm (_process_lock);
89 session_removed.signal ();
90 stop_metering_thread ();
95 AudioEngine::create ()
101 _instance = new AudioEngine ();
107 _thread_init_callback (void * /*arg*/)
109 /* make sure that anybody who needs to know about this thread
113 pthread_set_name (X_("audioengine"));
115 PBD::notify_gui_about_thread_creation ("gui", pthread_self(), X_("Audioengine"), 4096);
116 PBD::notify_gui_about_thread_creation ("midiui", pthread_self(), X_("Audioengine"), 128);
118 SessionEvent::create_per_thread_pool (X_("Audioengine"), 512);
120 MIDI::JackMIDIPort::set_process_thread (pthread_self());
124 AudioEngine::split_cycle (pframes_t offset)
126 /* caller must hold process lock */
128 Port::increment_global_port_buffer_offset (offset);
130 /* tell all Ports that we're going to start a new (split) cycle */
132 boost::shared_ptr<Ports> p = ports.reader();
134 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
135 i->second->cycle_split ();
140 AudioEngine::sample_rate_change (pframes_t nframes)
142 /* check for monitor input change every 1/10th of second */
144 monitor_check_interval = nframes / 10;
145 last_monitor_check = 0;
148 _session->set_frame_rate (nframes);
151 SampleRateChanged (nframes); /* EMIT SIGNAL */
157 AudioEngine::buffer_size_change (pframes_t bufsiz)
160 _session->set_block_size (bufsiz);
161 last_monitor_check = 0;
167 /** Method called by our ::process_thread when there is work to be done.
168 * @param nframes Number of frames to process.
171 AudioEngine::process_callback (pframes_t nframes)
173 Glib::Threads::Mutex::Lock tm (_process_lock, Glib::Threads::TRY_LOCK);
178 /// The number of frames that will have been processed when we've finished
179 pframes_t next_processed_frames;
181 /* handle wrap around of total frames counter */
183 if (max_framepos - _processed_frames < nframes) {
184 next_processed_frames = nframes - (max_framepos - _processed_frames);
186 next_processed_frames = _processed_frames + nframes;
190 /* return having done nothing */
191 _processed_frames = next_processed_frames;
195 if (session_remove_pending) {
197 /* perform the actual session removal */
199 if (session_removal_countdown < 0) {
201 /* fade out over 1 second */
202 session_removal_countdown = sample_rate()/2;
203 session_removal_gain = 1.0;
204 session_removal_gain_step = 1.0/session_removal_countdown;
206 } else if (session_removal_countdown > 0) {
208 /* we'll be fading audio out.
210 if this is the last time we do this as part
211 of session removal, do a MIDI panic now
212 to get MIDI stopped. This relies on the fact
213 that "immediate data" (aka "out of band data") from
214 MIDI tracks is *appended* after any other data,
215 so that it emerges after any outbound note ons, etc.
218 if (session_removal_countdown <= nframes) {
219 _session->midi_panic ();
225 session_removal_countdown = -1; // reset to "not in progress"
226 session_remove_pending = false;
227 session_removed.signal(); // wakes up thread that initiated session removal
233 if (!_freewheeling) {
234 MIDI::Manager::instance()->cycle_start(nframes);
235 MIDI::Manager::instance()->cycle_end();
238 _processed_frames = next_processed_frames;
243 /* tell all relevant objects that we're starting a new cycle */
245 InternalSend::CycleStart (nframes);
246 Port::set_global_port_buffer_offset (0);
247 Port::set_cycle_framecnt (nframes);
249 /* tell all Ports that we're starting a new cycle */
251 boost::shared_ptr<Ports> p = ports.reader();
253 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
254 i->second->cycle_start (nframes);
257 /* test if we are freewheeling and there are freewheel signals connected.
258 ardour should act normally even when freewheeling unless /it/ is
262 if (_freewheeling && !Freewheel.empty()) {
267 MIDI::Manager::instance()->cycle_start(nframes);
270 _session->process (nframes);
273 MIDI::Manager::instance()->cycle_end();
281 _processed_frames = next_processed_frames;
285 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
287 boost::shared_ptr<Ports> p = ports.reader();
289 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
293 if (i->second->last_monitor() != (x = i->second->monitoring_input ())) {
294 i->second->set_last_monitor (x);
295 /* XXX I think this is dangerous, due to
296 a likely mutex in the signal handlers ...
298 i->second->MonitorInputChanged (x); /* EMIT SIGNAL */
301 last_monitor_check = next_processed_frames;
304 if (_session->silent()) {
306 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
308 if (i->second->sends_output()) {
309 i->second->get_buffer(nframes).silence(nframes);
314 if (session_remove_pending && session_removal_countdown) {
316 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
318 if (i->second->sends_output()) {
320 boost::shared_ptr<AudioPort> ap = boost::dynamic_pointer_cast<AudioPort> (i->second);
322 Sample* s = ap->engine_get_whole_audio_buffer ();
323 gain_t g = session_removal_gain;
325 for (pframes_t n = 0; n < nframes; ++n) {
327 g -= session_removal_gain_step;
333 if (session_removal_countdown > nframes) {
334 session_removal_countdown -= nframes;
336 session_removal_countdown = 0;
339 session_removal_gain -= (nframes * session_removal_gain_step);
344 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
345 i->second->cycle_end (nframes);
348 _processed_frames = next_processed_frames;
357 AudioEngine::stop_metering_thread ()
359 if (m_meter_thread) {
360 g_atomic_int_set (&m_meter_exit, 1);
361 m_meter_thread->join ();
367 AudioEngine::start_metering_thread ()
369 if (m_meter_thread == 0) {
370 g_atomic_int_set (&m_meter_exit, 0);
371 m_meter_thread = Glib::Threads::Thread::create (boost::bind (&AudioEngine::meter_thread, this));
376 AudioEngine::meter_thread ()
378 pthread_set_name (X_("meter"));
381 Glib::usleep (10000); /* 1/100th sec interval */
382 if (g_atomic_int_get(&m_meter_exit)) {
390 AudioEngine::set_session (Session *s)
392 Glib::Threads::Mutex::Lock pl (_process_lock);
394 SessionHandlePtr::set_session (s);
398 start_metering_thread ();
400 pframes_t blocksize = _backend->buffer_size ();
402 /* page in as much of the session process code as we
403 can before we really start running.
406 boost::shared_ptr<Ports> p = ports.reader();
408 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
409 i->second->cycle_start (blocksize);
412 _session->process (blocksize);
413 _session->process (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);
421 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
422 i->second->cycle_end (blocksize);
428 AudioEngine::remove_session ()
430 Glib::Threads::Mutex::Lock lm (_process_lock);
434 stop_metering_thread ();
437 session_remove_pending = true;
438 session_removal_countdown = 0;
439 session_removed.wait(_process_lock);
443 SessionHandlePtr::set_session (0);
453 /* called from a signal handler for SIGPIPE */
455 stop_metering_thread ();
461 AudioEngine::reset_timebase ()
464 if (_session->config.get_jack_time_master()) {
465 _backend->set_time_master (true);
467 _backend->set_time_master (false);
475 AudioEngine::destroy ()
482 AudioEngine::discover_backends ()
484 vector<std::string> backend_modules;
488 Glib::PatternSpec so_extension_pattern("*backend.so");
489 Glib::PatternSpec dylib_extension_pattern("*backend.dylib");
491 find_matching_files_in_search_path (backend_search_path (),
492 so_extension_pattern, backend_modules);
494 find_matching_files_in_search_path (backend_search_path (),
495 dylib_extension_pattern, backend_modules);
497 DEBUG_TRACE (DEBUG::Panning, string_compose (_("looking for backends in %1\n"), backend_search_path().to_string()));
499 for (vector<std::string>::iterator i = backend_modules.begin(); i != backend_modules.end(); ++i) {
501 AudioBackendInfo* info;
503 if ((info = backend_discover (*i)) != 0) {
504 _backends.insert (make_pair (info->name, info));
508 return _backends.size();
512 AudioEngine::backend_discover (const string& path)
514 Glib::Module module (path);
515 AudioBackendInfo* info;
519 error << string_compose(_("AudioEngine: cannot load module \"%1\" (%2)"), path,
520 Glib::Module::get_last_error()) << endmsg;
524 if (!module.get_symbol ("descriptor", sym)) {
525 error << string_compose(_("AudioEngine: backend at \"%1\" has no descriptor."), path) << endmsg;
526 error << Glib::Module::get_last_error() << endmsg;
530 module.make_resident ();
532 info = (AudioBackendInfo*) sym;
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_backend (const std::string& name, const std::string& arg1, const std::string& arg2)
570 BackendMap::iterator b = _backends.find (name);
572 if (b == _backends.end()) {
573 return boost::shared_ptr<AudioBackend>();
579 cerr << "Instantiate " << b->second->name << " with " << arg1 << " + " << arg2 << endl;
581 if (b->second->instantiate (arg1, arg2)) {
582 cerr << "i failed\n";
583 throw failed_constructor ();
586 _backend = b->second->backend_factory (*this);
587 _impl = b->second->portengine_factory (*this);
589 } catch (exception& e) {
590 error << string_compose (_("Could not create backend for %1: %2"), name, e.what()) << endmsg;
591 return boost::shared_ptr<AudioBackend>();
597 /* BACKEND PROXY WRAPPERS */
600 AudioEngine::start ()
609 BootMessage (_("Connect session to engine"));
610 _session->set_frame_rate (_backend->sample_rate());
613 _processed_frames = 0;
614 last_monitor_check = 0;
616 if (_backend->start() == 0) {
618 last_monitor_check = 0;
620 if (_session && _session->config.get_jack_time_master()) {
621 _backend->set_time_master (true);
624 Running(); /* EMIT SIGNAL */
626 /* should report error? */
630 return _running ? 0 : -1;
640 Glib::Threads::Mutex::Lock lm (_process_lock);
642 if (_backend->stop () == 0) {
644 stop_metering_thread ();
646 Stopped (); /* EMIT SIGNAL */
655 AudioEngine::pause ()
661 if (_backend->pause () == 0) {
663 Stopped(); /* EMIT SIGNAL */
671 AudioEngine::freewheel (bool start_stop)
677 /* _freewheeling will be set when first Freewheel signal occurs */
679 return _backend->freewheel (start_stop);
683 AudioEngine::get_cpu_load() const
688 return _backend->cpu_load ();
692 AudioEngine::is_realtime() const
698 return _backend->is_realtime();
702 AudioEngine::connected() const
708 return _backend->connected();
712 AudioEngine::transport_start ()
717 return _backend->transport_start ();
721 AudioEngine::transport_stop ()
726 return _backend->transport_stop ();
730 AudioEngine::transport_state ()
733 return TransportStopped;
735 return _backend->transport_state ();
739 AudioEngine::transport_locate (framepos_t pos)
744 return _backend->transport_locate (pos);
748 AudioEngine::transport_frame()
753 return _backend->transport_frame ();
757 AudioEngine::sample_rate () const
762 return _backend->sample_rate ();
766 AudioEngine::samples_per_cycle () const
771 return _backend->buffer_size ();
775 AudioEngine::usecs_per_cycle () const
780 return _backend->usecs_per_cycle ();
784 AudioEngine::raw_buffer_size (DataType t)
789 return _backend->raw_buffer_size (t);
793 AudioEngine::sample_time ()
798 return _backend->sample_time ();
802 AudioEngine::sample_time_at_cycle_start ()
807 return _backend->sample_time_at_cycle_start ();
811 AudioEngine::samples_since_cycle_start ()
816 return _backend->samples_since_cycle_start ();
820 AudioEngine::get_sync_offset (pframes_t& offset) const
825 return _backend->get_sync_offset (offset);
829 AudioEngine::create_process_thread (boost::function<void()> func, pthread_t* thr, size_t stacksize)
834 return _backend->create_process_thread (func, thr, stacksize);
839 AudioEngine::set_device_name (const std::string& name)
844 return _backend->set_device_name (name);
848 AudioEngine::set_sample_rate (float sr)
853 return _backend->set_sample_rate (sr);
857 AudioEngine::set_buffer_size (uint32_t bufsiz)
862 return _backend->set_buffer_size (bufsiz);
866 AudioEngine::set_sample_format (SampleFormat sf)
871 return _backend->set_sample_format (sf);
875 AudioEngine::set_interleaved (bool yn)
880 return _backend->set_interleaved (yn);
884 AudioEngine::set_input_channels (uint32_t ic)
889 return _backend->set_input_channels (ic);
893 AudioEngine::set_output_channels (uint32_t oc)
898 return _backend->set_output_channels (oc);
902 AudioEngine::set_systemic_input_latency (uint32_t il)
907 return _backend->set_systemic_input_latency (il);
911 AudioEngine::set_systemic_output_latency (uint32_t ol)
916 return _backend->set_systemic_output_latency (ol);
919 /* END OF BACKEND PROXY API */
922 AudioEngine::thread_init_callback (void* arg)
924 /* make sure that anybody who needs to know about this thread
928 pthread_set_name (X_("audioengine"));
930 PBD::notify_gui_about_thread_creation ("gui", pthread_self(), X_("AudioEngine"), 4096);
931 PBD::notify_gui_about_thread_creation ("midiui", pthread_self(), X_("AudioEngine"), 128);
933 SessionEvent::create_per_thread_pool (X_("AudioEngine"), 512);
935 MIDI::JackMIDIPort::set_process_thread (pthread_self());
938 AudioEngine* ae = static_cast<AudioEngine*> (arg);
939 /* the special thread created/managed by the backend */
940 ae->_main_thread = new ProcessThread;
946 AudioEngine::timebase_callback (TransportState state, pframes_t nframes, jack_position_t pos, int new_position)
948 if (_session && _session->synced_to_jack()) {
949 // _session->timebase_callback (state, nframes, pos, new_position);
955 AudioEngine::sync_callback (TransportState state, framepos_t position)
958 return _session->jack_sync_callback (state, position);
964 AudioEngine::freewheel_callback (bool onoff)
967 _pre_freewheel_mmc_enabled = MIDI::Manager::instance()->mmc()->send_enabled ();
968 MIDI::Manager::instance()->mmc()->enable_send (false);
970 MIDI::Manager::instance()->mmc()->enable_send (_pre_freewheel_mmc_enabled);
975 AudioEngine::latency_callback (bool for_playback)
978 _session->update_latency (for_playback);
983 AudioEngine::update_latencies ()
986 _backend->update_latencies ();
991 AudioEngine::halted_callback (const char* why)
993 stop_metering_thread ();
995 MIDI::JackMIDIPort::EngineHalted (); /* EMIT SIGNAL */
996 Halted (why); /* EMIT SIGNAL */
1000 AudioEngine::setup_required () const
1002 if (_backends.size() == 1 && _backends.begin()->second->already_configured()) {