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>
29 #include "pbd/pthread_utils.h"
30 #include "pbd/stacktrace.h"
31 #include "pbd/unknown_type.h"
34 #include <jack/weakjack.h>
36 #include "midi++/port.h"
37 #include "midi++/jack_midi_port.h"
38 #include "midi++/mmc.h"
39 #include "midi++/manager.h"
41 #include "ardour/audio_port.h"
42 #include "ardour/audioengine.h"
43 #include "ardour/buffer.h"
44 #include "ardour/cycle_timer.h"
45 #include "ardour/internal_send.h"
46 #include "ardour/meter.h"
47 #include "ardour/midi_port.h"
48 #include "ardour/port.h"
49 #include "ardour/process_thread.h"
50 #include "ardour/session.h"
55 using namespace ARDOUR;
58 gint AudioEngine::m_meter_exit;
59 AudioEngine* AudioEngine::_instance = 0;
61 AudioEngine::AudioEngine ()
62 : session_remove_pending (false)
63 , session_removal_countdown (-1)
64 , monitor_check_interval (INT32_MAX)
65 , last_monitor_check (0)
66 , _processed_frames (0)
67 , _freewheeling (false)
68 , _pre_freewheel_mmc_enabled (false)
69 , _usecs_per_cycle (0)
70 , port_remove_in_progress (false)
75 g_atomic_int_set (&m_meter_exit, 0);
77 Port::set_engine (this);
80 AudioEngine::~AudioEngine ()
82 config_connection.disconnect ();
85 Glib::Threads::Mutex::Lock tm (_process_lock);
86 session_removed.signal ();
87 stop_metering_thread ();
92 AudioEngine::create ()
97 return new AudioEngine;
101 AudioEngine::jack() const
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());
125 AudioEngine::start ()
127 GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
131 if (!jack_port_type_get_buffer_size) {
132 warning << _("This version of JACK is old - you should upgrade to a newer version that supports jack_port_type_get_buffer_size()") << endmsg;
136 BootMessage (_("Connect session to engine"));
137 _session->set_frame_rate (jack_get_sample_rate (_priv_jack));
140 /* a proxy for whether jack_activate() will definitely call the buffer size
141 * callback. with older versions of JACK, this function symbol will be null.
142 * this is reliable, but not clean.
145 if (!jack_port_type_get_buffer_size) {
146 jack_bufsize_callback (jack_get_buffer_size (_priv_jack));
149 _processed_frames = 0;
150 last_monitor_check = 0;
152 set_jack_callbacks ();
154 if (jack_activate (_priv_jack) == 0) {
157 Running(); /* EMIT SIGNAL */
159 // error << _("cannot activate JACK client") << endmsg;
163 return _running ? 0 : -1;
167 AudioEngine::stop (bool forever)
169 GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
173 disconnect_from_jack ();
175 jack_deactivate (_priv_jack);
176 MIDI::JackMIDIPort::JackHalted (); /* EMIT SIGNAL */
177 Stopped(); /* EMIT SIGNAL */
182 stop_metering_thread ();
185 return _running ? -1 : 0;
190 AudioEngine::split_cycle (pframes_t offset)
192 /* caller must hold process lock */
194 Port::increment_global_port_buffer_offset (offset);
196 /* tell all Ports that we're going to start a new (split) cycle */
198 boost::shared_ptr<Ports> p = ports.reader();
200 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
201 i->second->cycle_split ();
206 /** Method called by our ::process_thread when there is work to be done.
207 * @param nframes Number of frames to process.
210 AudioEngine::process_callback (pframes_t nframes)
212 GET_PRIVATE_JACK_POINTER_RET(_jack,0);
213 Glib::Threads::Mutex::Lock tm (_process_lock, Glib::Threads::TRY_LOCK);
218 /// The number of frames that will have been processed when we've finished
219 pframes_t next_processed_frames;
221 /* handle wrap around of total frames counter */
223 if (max_framepos - _processed_frames < nframes) {
224 next_processed_frames = nframes - (max_framepos - _processed_frames);
226 next_processed_frames = _processed_frames + nframes;
230 /* return having done nothing */
231 _processed_frames = next_processed_frames;
235 if (session_remove_pending) {
237 /* perform the actual session removal */
239 if (session_removal_countdown < 0) {
241 /* fade out over 1 second */
242 session_removal_countdown = _frame_rate/2;
243 session_removal_gain = 1.0;
244 session_removal_gain_step = 1.0/session_removal_countdown;
246 } else if (session_removal_countdown > 0) {
248 /* we'll be fading audio out.
250 if this is the last time we do this as part
251 of session removal, do a MIDI panic now
252 to get MIDI stopped. This relies on the fact
253 that "immediate data" (aka "out of band data") from
254 MIDI tracks is *appended* after any other data,
255 so that it emerges after any outbound note ons, etc.
258 if (session_removal_countdown <= nframes) {
259 _session->midi_panic ();
265 session_removal_countdown = -1; // reset to "not in progress"
266 session_remove_pending = false;
267 session_removed.signal(); // wakes up thread that initiated session removal
273 if (!_freewheeling) {
274 MIDI::Manager::instance()->cycle_start(nframes);
275 MIDI::Manager::instance()->cycle_end();
278 _processed_frames = next_processed_frames;
283 /* tell all relevant objects that we're starting a new cycle */
285 InternalSend::CycleStart (nframes);
286 Port::set_global_port_buffer_offset (0);
287 Port::set_cycle_framecnt (nframes);
289 /* tell all Ports that we're starting a new cycle */
291 boost::shared_ptr<Ports> p = ports.reader();
293 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
294 i->second->cycle_start (nframes);
297 /* test if we are freewheeling and there are freewheel signals connected.
298 ardour should act normally even when freewheeling unless /it/ is
302 if (_freewheeling && !Freewheel.empty()) {
307 MIDI::Manager::instance()->cycle_start(nframes);
310 _session->process (nframes);
313 MIDI::Manager::instance()->cycle_end();
321 _processed_frames = next_processed_frames;
325 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
327 boost::shared_ptr<Ports> p = ports.reader();
329 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
333 if (i->second->last_monitor() != (x = i->second->jack_monitoring_input ())) {
334 i->second->set_last_monitor (x);
335 /* XXX I think this is dangerous, due to
336 a likely mutex in the signal handlers ...
338 i->second->MonitorInputChanged (x); /* EMIT SIGNAL */
341 last_monitor_check = next_processed_frames;
344 if (_session->silent()) {
346 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
348 if (i->second->sends_output()) {
349 i->second->get_buffer(nframes).silence(nframes);
354 if (session_remove_pending && session_removal_countdown) {
356 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
358 if (i->second->sends_output()) {
360 boost::shared_ptr<AudioPort> ap = boost::dynamic_pointer_cast<AudioPort> (i->second);
362 Sample* s = ap->engine_get_whole_audio_buffer ();
363 gain_t g = session_removal_gain;
365 for (pframes_t n = 0; n < nframes; ++n) {
367 g -= session_removal_gain_step;
373 if (session_removal_countdown > nframes) {
374 session_removal_countdown -= nframes;
376 session_removal_countdown = 0;
379 session_removal_gain -= (nframes * session_removal_gain_step);
384 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
385 i->second->cycle_end (nframes);
388 _processed_frames = next_processed_frames;
397 AudioEngine::stop_metering_thread ()
399 if (m_meter_thread) {
400 g_atomic_int_set (&m_meter_exit, 1);
401 m_meter_thread->join ();
407 AudioEngine::start_metering_thread ()
409 if (m_meter_thread == 0) {
410 g_atomic_int_set (&m_meter_exit, 0);
411 m_meter_thread = Glib::Threads::Thread::create (boost::bind (&AudioEngine::meter_thread, this));
416 AudioEngine::meter_thread ()
418 pthread_set_name (X_("meter"));
421 Glib::usleep (10000); /* 1/100th sec interval */
422 if (g_atomic_int_get(&m_meter_exit)) {
430 AudioEngine::set_session (Session *s)
432 Glib::Threads::Mutex::Lock pl (_process_lock);
434 SessionHandlePtr::set_session (s);
438 start_metering_thread ();
440 pframes_t blocksize = jack_get_buffer_size (_jack);
442 /* page in as much of the session process code as we
443 can before we really start running.
446 boost::shared_ptr<Ports> p = ports.reader();
448 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
449 i->second->cycle_start (blocksize);
452 _session->process (blocksize);
453 _session->process (blocksize);
454 _session->process (blocksize);
455 _session->process (blocksize);
456 _session->process (blocksize);
457 _session->process (blocksize);
458 _session->process (blocksize);
459 _session->process (blocksize);
461 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
462 i->second->cycle_end (blocksize);
468 AudioEngine::remove_session ()
470 Glib::Threads::Mutex::Lock lm (_process_lock);
474 stop_metering_thread ();
477 session_remove_pending = true;
478 session_removed.wait(_process_lock);
482 SessionHandlePtr::set_session (0);
489 AudioEngine::port_registration_failure (const std::string& portname)
491 GET_PRIVATE_JACK_POINTER (_jack);
492 string full_portname = jack_client_name;
493 full_portname += ':';
494 full_portname += portname;
497 jack_port_t* p = jack_port_by_name (_priv_jack, full_portname.c_str());
501 reason = string_compose (_("a port with the name \"%1\" already exists: check for duplicated track/bus names"), portname);
503 reason = string_compose (_("No more JACK ports are available. You will need to stop %1 and restart JACK with more ports if you need this many tracks."), PROGRAM_NAME);
506 throw PortRegistrationFailure (string_compose (_("AudioEngine: cannot register port \"%1\": %2"), portname, reason).c_str());
509 boost::shared_ptr<Port>
510 AudioEngine::register_port (DataType dtype, const string& portname, bool input)
512 boost::shared_ptr<Port> newport;
515 if (dtype == DataType::AUDIO) {
516 newport.reset (new AudioPort (portname, (input ? Port::IsInput : Port::IsOutput)));
517 } else if (dtype == DataType::MIDI) {
518 newport.reset (new MidiPort (portname, (input ? Port::IsInput : Port::IsOutput)));
520 throw PortRegistrationFailure("unable to create port (unknown type)");
523 RCUWriter<Ports> writer (ports);
524 boost::shared_ptr<Ports> ps = writer.get_copy ();
525 ps->insert (make_pair (make_port_name_relative (portname), newport));
527 /* writer goes out of scope, forces update */
532 catch (PortRegistrationFailure& err) {
534 } catch (std::exception& e) {
535 throw PortRegistrationFailure(string_compose(
536 _("unable to create port: %1"), e.what()).c_str());
538 throw PortRegistrationFailure("unable to create port (unknown error)");
542 boost::shared_ptr<Port>
543 AudioEngine::register_input_port (DataType type, const string& portname)
545 return register_port (type, portname, true);
548 boost::shared_ptr<Port>
549 AudioEngine::register_output_port (DataType type, const string& portname)
551 return register_port (type, portname, false);
555 AudioEngine::unregister_port (boost::shared_ptr<Port> port)
557 /* caller must hold process lock */
560 /* probably happening when the engine has been halted by JACK,
561 in which case, there is nothing we can do here.
567 RCUWriter<Ports> writer (ports);
568 boost::shared_ptr<Ports> ps = writer.get_copy ();
569 Ports::iterator x = ps->find (make_port_name_relative (port->name()));
571 if (x != ps->end()) {
575 /* writer goes out of scope, forces update */
584 AudioEngine::connect (const string& source, const string& destination)
590 fatal << _("connect called before engine was started") << endmsg;
597 string s = make_port_name_non_relative (source);
598 string d = make_port_name_non_relative (destination);
601 boost::shared_ptr<Port> src = get_port_by_name (s);
602 boost::shared_ptr<Port> dst = get_port_by_name (d);
605 ret = src->connect (d);
607 ret = dst->connect (s);
609 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
614 /* already exists - no error, no warning */
615 } else if (ret < 0) {
616 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
617 source, s, destination, d)
625 AudioEngine::disconnect (const string& source, const string& destination)
631 fatal << _("disconnect called before engine was started") << endmsg;
638 string s = make_port_name_non_relative (source);
639 string d = make_port_name_non_relative (destination);
641 boost::shared_ptr<Port> src = get_port_by_name (s);
642 boost::shared_ptr<Port> dst = get_port_by_name (d);
645 ret = src->disconnect (d);
647 ret = dst->disconnect (s);
649 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
656 AudioEngine::disconnect (boost::shared_ptr<Port> port)
658 GET_PRIVATE_JACK_POINTER_RET (_jack,-1);
662 fatal << _("disconnect called before engine was started") << endmsg;
669 return port->disconnect_all ();
673 AudioEngine::frame_rate () const
675 GET_PRIVATE_JACK_POINTER_RET (_jack, 0);
676 if (_frame_rate == 0) {
677 return (_frame_rate = jack_get_sample_rate (_priv_jack));
684 AudioEngine::raw_buffer_size (DataType t)
686 std::map<DataType,size_t>::const_iterator s = _raw_buffer_sizes.find(t);
687 return (s != _raw_buffer_sizes.end()) ? s->second : 0;
691 AudioEngine::frames_per_cycle () const
693 GET_PRIVATE_JACK_POINTER_RET (_jack,0);
694 if (_buffer_size == 0) {
695 return jack_get_buffer_size (_jack);
701 /** @param name Full or short name of port
702 * @return Corresponding Port or 0.
705 boost::shared_ptr<Port>
706 AudioEngine::get_port_by_name (const string& portname)
710 fatal << _("get_port_by_name() called before engine was started") << endmsg;
713 boost::shared_ptr<Port> ();
717 if (!port_is_mine (portname)) {
718 /* not an ardour port */
719 return boost::shared_ptr<Port> ();
722 boost::shared_ptr<Ports> pr = ports.reader();
723 std::string rel = make_port_name_relative (portname);
724 Ports::iterator x = pr->find (rel);
726 if (x != pr->end()) {
727 /* its possible that the port was renamed by some 3rd party and
728 we don't know about it. check for this (the check is quick
729 and cheap), and if so, rename the port (which will alter
730 the port map as a side effect).
732 const std::string check = make_port_name_relative (jack_port_name (x->second->jack_port()));
734 x->second->set_name (check);
739 return boost::shared_ptr<Port> ();
743 AudioEngine::port_renamed (const std::string& old_relative_name, const std::string& new_relative_name)
745 RCUWriter<Ports> writer (ports);
746 boost::shared_ptr<Ports> p = writer.get_copy();
747 Ports::iterator x = p->find (old_relative_name);
750 boost::shared_ptr<Port> port = x->second;
752 p->insert (make_pair (new_relative_name, port));
757 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
759 GET_PRIVATE_JACK_POINTER_RET (_jack,0);
762 fatal << _("get_ports called before engine was started") << endmsg;
768 return jack_get_ports (_priv_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
774 /* called from a signal handler for SIGPIPE */
776 stop_metering_thread ();
785 AudioEngine::can_request_hardware_monitoring ()
787 GET_PRIVATE_JACK_POINTER_RET (_jack,false);
790 if ((ports = jack_get_ports (_priv_jack, NULL, JACK_DEFAULT_AUDIO_TYPE, JackPortCanMonitor)) == 0) {
800 AudioEngine::n_physical (unsigned long flags) const
804 GET_PRIVATE_JACK_POINTER_RET (_jack, c);
806 const char ** ports = jack_get_ports (_priv_jack, NULL, NULL, JackPortIsPhysical | flags);
811 for (uint32_t i = 0; ports[i]; ++i) {
812 if (!strstr (ports[i], "Midi-Through")) {
813 DataType t (jack_port_type (jack_port_by_name (_jack, ports[i])));
814 c.set (t, c.get (t) + 1);
824 AudioEngine::n_physical_inputs () const
826 return n_physical (JackPortIsInput);
830 AudioEngine::n_physical_outputs () const
832 return n_physical (JackPortIsOutput);
836 AudioEngine::get_physical (DataType type, unsigned long flags, vector<string>& phy)
838 GET_PRIVATE_JACK_POINTER (_jack);
841 if ((ports = jack_get_ports (_priv_jack, NULL, type.to_jack_type(), JackPortIsPhysical | flags)) == 0) {
846 for (uint32_t i = 0; ports[i]; ++i) {
847 if (strstr (ports[i], "Midi-Through")) {
850 phy.push_back (ports[i]);
856 /** Get physical ports for which JackPortIsOutput is set; ie those that correspond to
857 * a physical input connector.
860 AudioEngine::get_physical_inputs (DataType type, vector<string>& ins)
862 get_physical (type, JackPortIsOutput, ins);
865 /** Get physical ports for which JackPortIsInput is set; ie those that correspond to
866 * a physical output connector.
869 AudioEngine::get_physical_outputs (DataType type, vector<string>& outs)
871 get_physical (type, JackPortIsInput, outs);
876 AudioEngine::reset_timebase ()
878 GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
880 if (_session->config.get_jack_time_master()) {
881 return jack_set_timebase_callback (_priv_jack, 0, _jack_timebase_callback, this);
883 return jack_release_timebase (_jack);
890 AudioEngine::remove_all_ports ()
892 /* make sure that JACK callbacks that will be invoked as we cleanup
893 * ports know that they have nothing to do.
896 port_remove_in_progress = true;
898 /* process lock MUST be held by caller
902 RCUWriter<Ports> writer (ports);
903 boost::shared_ptr<Ports> ps = writer.get_copy ();
907 /* clear dead wood list in RCU */
911 port_remove_in_progress = false;
916 AudioEngine::make_port_name_relative (string portname) const
918 string::size_type len;
921 len = portname.length();
923 for (n = 0; n < len; ++n) {
924 if (portname[n] == ':') {
929 if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
930 return portname.substr (n+1);
937 AudioEngine::make_port_name_non_relative (string portname) const
941 if (portname.find_first_of (':') != string::npos) {
945 str = jack_client_name;
953 AudioEngine::port_is_mine (const string& portname) const
955 if (portname.find_first_of (':') != string::npos) {
956 if (portname.substr (0, jack_client_name.length ()) != jack_client_name) {
964 AudioEngine::port_is_physical (const std::string& portname) const
966 GET_PRIVATE_JACK_POINTER_RET(_jack, false);
968 jack_port_t *port = jack_port_by_name (_priv_jack, portname.c_str());
974 return jack_port_flags (port) & JackPortIsPhysical;
978 AudioEngine::destroy ()
985 AudioEngine::discover_backends ()
987 vector<std::string> backend_modules;
988 AudioBackend* backend;
990 Glib::PatternSpec so_extension_pattern("*.so");
991 Glib::PatternSpec dylib_extension_pattern("*.dylib");
993 find_matching_files_in_search_path (backend_search_path (),
994 so_extension_pattern, backend_modules);
996 find_matching_files_in_search_path (backend_search_path (),
997 dylib_extension_pattern, backend_modules);
999 DEBUG_TRACE (DEBUG::Panning, string_compose (_("looking for backends in %1"), backend_search_path().to_string()));
1001 for (vector<std::string>::iterator i = backend_modules.begin(); i != backend_modules.end(); ++i) {
1002 if ((backend = backend_discover (*i)) != 0) {
1003 _backends.insert (make_pair (backend->name(), backend));
1009 AudioEngine::backend_discover (string path)
1011 Glib::Module* module = new Glib::Module(path);
1012 AudioBackend* (*dfunc)(void);
1016 error << string_compose(_("AudioEngine: cannot load module \"%1\" (%2)"), path,
1017 Glib::Module::get_last_error()) << endmsg;
1022 if (!module->get_symbol("backend_factory", func)) {
1023 error << string_compose(_("AudioEngine: module \"%1\" has no factory function."), path) << endmsg;
1024 error << Glib::Module::get_last_error() << endmsg;
1029 dfunc = (AudioBackend* (*)(void))func;
1030 AudioBackend* backend = dfunc();