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)
74 g_atomic_int_set (&m_meter_exit, 0);
76 Port::set_engine (this);
79 AudioEngine::~AudioEngine ()
81 config_connection.disconnect ();
84 Glib::Threads::Mutex::Lock tm (_process_lock);
85 session_removed.signal ();
86 stop_metering_thread ();
91 AudioEngine::create ()
96 return new AudioEngine;
100 AudioEngine::jack() const
106 _thread_init_callback (void * /*arg*/)
108 /* make sure that anybody who needs to know about this thread
112 pthread_set_name (X_("audioengine"));
114 PBD::notify_gui_about_thread_creation ("gui", pthread_self(), X_("Audioengine"), 4096);
115 PBD::notify_gui_about_thread_creation ("midiui", pthread_self(), X_("Audioengine"), 128);
117 SessionEvent::create_per_thread_pool (X_("Audioengine"), 512);
119 MIDI::JackMIDIPort::set_process_thread (pthread_self());
124 AudioEngine::start ()
126 GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
130 if (!jack_port_type_get_buffer_size) {
131 warning << _("This version of JACK is old - you should upgrade to a newer version that supports jack_port_type_get_buffer_size()") << endmsg;
135 BootMessage (_("Connect session to engine"));
136 _session->set_frame_rate (jack_get_sample_rate (_priv_jack));
139 /* a proxy for whether jack_activate() will definitely call the buffer size
140 * callback. with older versions of JACK, this function symbol will be null.
141 * this is reliable, but not clean.
144 if (!jack_port_type_get_buffer_size) {
145 jack_bufsize_callback (jack_get_buffer_size (_priv_jack));
148 _processed_frames = 0;
149 last_monitor_check = 0;
151 set_jack_callbacks ();
153 if (jack_activate (_priv_jack) == 0) {
156 Running(); /* EMIT SIGNAL */
158 // error << _("cannot activate JACK client") << endmsg;
162 return _running ? 0 : -1;
166 AudioEngine::stop (bool forever)
168 GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
172 disconnect_from_jack ();
174 jack_deactivate (_priv_jack);
175 MIDI::JackMIDIPort::JackHalted (); /* EMIT SIGNAL */
176 Stopped(); /* EMIT SIGNAL */
181 stop_metering_thread ();
184 return _running ? -1 : 0;
189 AudioEngine::split_cycle (pframes_t offset)
191 /* caller must hold process lock */
193 Port::increment_global_port_buffer_offset (offset);
195 /* tell all Ports that we're going to start a new (split) cycle */
197 boost::shared_ptr<Ports> p = ports.reader();
199 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
200 i->second->cycle_split ();
205 /** Method called by our ::process_thread when there is work to be done.
206 * @param nframes Number of frames to process.
209 AudioEngine::process_callback (pframes_t nframes)
211 GET_PRIVATE_JACK_POINTER_RET(_jack,0);
212 Glib::Threads::Mutex::Lock tm (_process_lock, Glib::Threads::TRY_LOCK);
217 /// The number of frames that will have been processed when we've finished
218 pframes_t next_processed_frames;
220 /* handle wrap around of total frames counter */
222 if (max_framepos - _processed_frames < nframes) {
223 next_processed_frames = nframes - (max_framepos - _processed_frames);
225 next_processed_frames = _processed_frames + nframes;
229 /* return having done nothing */
230 _processed_frames = next_processed_frames;
234 if (session_remove_pending) {
236 /* perform the actual session removal */
238 if (session_removal_countdown < 0) {
240 /* fade out over 1 second */
241 session_removal_countdown = _frame_rate/2;
242 session_removal_gain = 1.0;
243 session_removal_gain_step = 1.0/session_removal_countdown;
245 } else if (session_removal_countdown > 0) {
247 /* we'll be fading audio out.
249 if this is the last time we do this as part
250 of session removal, do a MIDI panic now
251 to get MIDI stopped. This relies on the fact
252 that "immediate data" (aka "out of band data") from
253 MIDI tracks is *appended* after any other data,
254 so that it emerges after any outbound note ons, etc.
257 if (session_removal_countdown <= nframes) {
258 _session->midi_panic ();
264 session_removal_countdown = -1; // reset to "not in progress"
265 session_remove_pending = false;
266 session_removed.signal(); // wakes up thread that initiated session removal
272 if (!_freewheeling) {
273 MIDI::Manager::instance()->cycle_start(nframes);
274 MIDI::Manager::instance()->cycle_end();
277 _processed_frames = next_processed_frames;
282 /* tell all relevant objects that we're starting a new cycle */
284 InternalSend::CycleStart (nframes);
285 Port::set_global_port_buffer_offset (0);
286 Port::set_cycle_framecnt (nframes);
288 /* tell all Ports that we're starting a new cycle */
290 boost::shared_ptr<Ports> p = ports.reader();
292 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
293 i->second->cycle_start (nframes);
296 /* test if we are freewheeling and there are freewheel signals connected.
297 ardour should act normally even when freewheeling unless /it/ is
301 if (_freewheeling && !Freewheel.empty()) {
306 MIDI::Manager::instance()->cycle_start(nframes);
309 _session->process (nframes);
312 MIDI::Manager::instance()->cycle_end();
320 _processed_frames = next_processed_frames;
324 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
326 boost::shared_ptr<Ports> p = ports.reader();
328 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
332 if (i->second->last_monitor() != (x = i->second->monitoring_input ())) {
333 i->second->set_last_monitor (x);
334 /* XXX I think this is dangerous, due to
335 a likely mutex in the signal handlers ...
337 i->second->MonitorInputChanged (x); /* EMIT SIGNAL */
340 last_monitor_check = next_processed_frames;
343 if (_session->silent()) {
345 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
347 if (i->second->sends_output()) {
348 i->second->get_buffer(nframes).silence(nframes);
353 if (session_remove_pending && session_removal_countdown) {
355 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
357 if (i->second->sends_output()) {
359 boost::shared_ptr<AudioPort> ap = boost::dynamic_pointer_cast<AudioPort> (i->second);
361 Sample* s = ap->engine_get_whole_audio_buffer ();
362 gain_t g = session_removal_gain;
364 for (pframes_t n = 0; n < nframes; ++n) {
366 g -= session_removal_gain_step;
372 if (session_removal_countdown > nframes) {
373 session_removal_countdown -= nframes;
375 session_removal_countdown = 0;
378 session_removal_gain -= (nframes * session_removal_gain_step);
383 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
384 i->second->cycle_end (nframes);
387 _processed_frames = next_processed_frames;
396 AudioEngine::stop_metering_thread ()
398 if (m_meter_thread) {
399 g_atomic_int_set (&m_meter_exit, 1);
400 m_meter_thread->join ();
406 AudioEngine::start_metering_thread ()
408 if (m_meter_thread == 0) {
409 g_atomic_int_set (&m_meter_exit, 0);
410 m_meter_thread = Glib::Threads::Thread::create (boost::bind (&AudioEngine::meter_thread, this));
415 AudioEngine::meter_thread ()
417 pthread_set_name (X_("meter"));
420 Glib::usleep (10000); /* 1/100th sec interval */
421 if (g_atomic_int_get(&m_meter_exit)) {
429 AudioEngine::set_session (Session *s)
431 Glib::Threads::Mutex::Lock pl (_process_lock);
433 SessionHandlePtr::set_session (s);
437 start_metering_thread ();
439 pframes_t blocksize = jack_get_buffer_size (_jack);
441 /* page in as much of the session process code as we
442 can before we really start running.
445 boost::shared_ptr<Ports> p = ports.reader();
447 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
448 i->second->cycle_start (blocksize);
451 _session->process (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);
460 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
461 i->second->cycle_end (blocksize);
467 AudioEngine::remove_session ()
469 Glib::Threads::Mutex::Lock lm (_process_lock);
473 stop_metering_thread ();
476 session_remove_pending = true;
477 session_removed.wait(_process_lock);
481 SessionHandlePtr::set_session (0);
488 AudioEngine::port_registration_failure (const std::string& portname)
490 GET_PRIVATE_JACK_POINTER (_jack);
491 string full_portname = jack_client_name;
492 full_portname += ':';
493 full_portname += portname;
496 jack_port_t* p = jack_port_by_name (_priv_jack, full_portname.c_str());
500 reason = string_compose (_("a port with the name \"%1\" already exists: check for duplicated track/bus names"), portname);
502 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);
505 throw PortRegistrationFailure (string_compose (_("AudioEngine: cannot register port \"%1\": %2"), portname, reason).c_str());
508 boost::shared_ptr<Port>
509 AudioEngine::register_port (DataType dtype, const string& portname, bool input)
511 boost::shared_ptr<Port> newport;
514 if (dtype == DataType::AUDIO) {
515 newport.reset (new AudioPort (portname, (input ? Port::IsInput : Port::IsOutput)));
516 } else if (dtype == DataType::MIDI) {
517 newport.reset (new MidiPort (portname, (input ? Port::IsInput : Port::IsOutput)));
519 throw PortRegistrationFailure("unable to create port (unknown type)");
522 RCUWriter<Ports> writer (ports);
523 boost::shared_ptr<Ports> ps = writer.get_copy ();
524 ps->insert (make_pair (make_port_name_relative (portname), newport));
526 /* writer goes out of scope, forces update */
531 catch (PortRegistrationFailure& err) {
533 } catch (std::exception& e) {
534 throw PortRegistrationFailure(string_compose(
535 _("unable to create port: %1"), e.what()).c_str());
537 throw PortRegistrationFailure("unable to create port (unknown error)");
541 boost::shared_ptr<Port>
542 AudioEngine::register_input_port (DataType type, const string& portname)
544 return register_port (type, portname, true);
547 boost::shared_ptr<Port>
548 AudioEngine::register_output_port (DataType type, const string& portname)
550 return register_port (type, portname, false);
554 AudioEngine::unregister_port (boost::shared_ptr<Port> port)
556 /* caller must hold process lock */
559 /* probably happening when the engine has been halted by JACK,
560 in which case, there is nothing we can do here.
566 RCUWriter<Ports> writer (ports);
567 boost::shared_ptr<Ports> ps = writer.get_copy ();
568 Ports::iterator x = ps->find (make_port_name_relative (port->name()));
570 if (x != ps->end()) {
574 /* writer goes out of scope, forces update */
583 AudioEngine::connect (const string& source, const string& destination)
589 fatal << _("connect called before engine was started") << endmsg;
596 string s = make_port_name_non_relative (source);
597 string d = make_port_name_non_relative (destination);
600 boost::shared_ptr<Port> src = get_port_by_name (s);
601 boost::shared_ptr<Port> dst = get_port_by_name (d);
604 ret = src->connect (d);
606 ret = dst->connect (s);
608 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
613 /* already exists - no error, no warning */
614 } else if (ret < 0) {
615 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
616 source, s, destination, d)
624 AudioEngine::disconnect (const string& source, const string& destination)
630 fatal << _("disconnect called before engine was started") << endmsg;
637 string s = make_port_name_non_relative (source);
638 string d = make_port_name_non_relative (destination);
640 boost::shared_ptr<Port> src = get_port_by_name (s);
641 boost::shared_ptr<Port> dst = get_port_by_name (d);
644 ret = src->disconnect (d);
646 ret = dst->disconnect (s);
648 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
655 AudioEngine::disconnect (boost::shared_ptr<Port> port)
657 GET_PRIVATE_JACK_POINTER_RET (_jack,-1);
661 fatal << _("disconnect called before engine was started") << endmsg;
668 return port->disconnect_all ();
672 AudioEngine::frame_rate () const
674 GET_PRIVATE_JACK_POINTER_RET (_jack, 0);
675 if (_frame_rate == 0) {
676 return (_frame_rate = jack_get_sample_rate (_priv_jack));
683 AudioEngine::raw_buffer_size (DataType t)
685 std::map<DataType,size_t>::const_iterator s = _raw_buffer_sizes.find(t);
686 return (s != _raw_buffer_sizes.end()) ? s->second : 0;
690 AudioEngine::frames_per_cycle () const
692 GET_PRIVATE_JACK_POINTER_RET (_jack,0);
693 if (_buffer_size == 0) {
694 return jack_get_buffer_size (_jack);
700 /** @param name Full or short name of port
701 * @return Corresponding Port or 0.
704 boost::shared_ptr<Port>
705 AudioEngine::get_port_by_name (const string& portname)
709 fatal << _("get_port_by_name() called before engine was started") << endmsg;
712 boost::shared_ptr<Port> ();
716 if (!port_is_mine (portname)) {
717 /* not an ardour port */
718 return boost::shared_ptr<Port> ();
721 boost::shared_ptr<Ports> pr = ports.reader();
722 std::string rel = make_port_name_relative (portname);
723 Ports::iterator x = pr->find (rel);
725 if (x != pr->end()) {
726 /* its possible that the port was renamed by some 3rd party and
727 we don't know about it. check for this (the check is quick
728 and cheap), and if so, rename the port (which will alter
729 the port map as a side effect).
731 const std::string check = make_port_name_relative (jack_port_name (x->second->jack_port()));
733 x->second->set_name (check);
738 return boost::shared_ptr<Port> ();
742 AudioEngine::port_renamed (const std::string& old_relative_name, const std::string& new_relative_name)
744 RCUWriter<Ports> writer (ports);
745 boost::shared_ptr<Ports> p = writer.get_copy();
746 Ports::iterator x = p->find (old_relative_name);
749 boost::shared_ptr<Port> port = x->second;
751 p->insert (make_pair (new_relative_name, port));
756 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
758 GET_PRIVATE_JACK_POINTER_RET (_jack,0);
761 fatal << _("get_ports called before engine was started") << endmsg;
767 return jack_get_ports (_priv_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
773 /* called from a signal handler for SIGPIPE */
775 stop_metering_thread ();
784 AudioEngine::can_request_hardware_monitoring ()
786 GET_PRIVATE_JACK_POINTER_RET (_jack,false);
789 if ((ports = jack_get_ports (_priv_jack, NULL, JACK_DEFAULT_AUDIO_TYPE, JackPortCanMonitor)) == 0) {
799 AudioEngine::n_physical (unsigned long flags) const
803 GET_PRIVATE_JACK_POINTER_RET (_jack, c);
805 const char ** ports = jack_get_ports (_priv_jack, NULL, NULL, JackPortIsPhysical | flags);
810 for (uint32_t i = 0; ports[i]; ++i) {
811 if (!strstr (ports[i], "Midi-Through")) {
812 DataType t (jack_port_type (jack_port_by_name (_jack, ports[i])));
813 c.set (t, c.get (t) + 1);
823 AudioEngine::n_physical_inputs () const
825 return n_physical (JackPortIsInput);
829 AudioEngine::n_physical_outputs () const
831 return n_physical (JackPortIsOutput);
835 AudioEngine::get_physical (DataType type, unsigned long flags, vector<string>& phy)
837 GET_PRIVATE_JACK_POINTER (_jack);
840 if ((ports = jack_get_ports (_priv_jack, NULL, type.to_jack_type(), JackPortIsPhysical | flags)) == 0) {
845 for (uint32_t i = 0; ports[i]; ++i) {
846 if (strstr (ports[i], "Midi-Through")) {
849 phy.push_back (ports[i]);
855 /** Get physical ports for which JackPortIsOutput is set; ie those that correspond to
856 * a physical input connector.
859 AudioEngine::get_physical_inputs (DataType type, vector<string>& ins)
861 get_physical (type, JackPortIsOutput, ins);
864 /** Get physical ports for which JackPortIsInput is set; ie those that correspond to
865 * a physical output connector.
868 AudioEngine::get_physical_outputs (DataType type, vector<string>& outs)
870 get_physical (type, JackPortIsInput, outs);
875 AudioEngine::reset_timebase ()
877 GET_PRIVATE_JACK_POINTER_RET (_jack, -1);
879 if (_session->config.get_jack_time_master()) {
880 _backend->set_time_master (true);
882 _backend->set_time_master (false);
889 AudioEngine::remove_all_ports ()
891 /* make sure that JACK callbacks that will be invoked as we cleanup
892 * ports know that they have nothing to do.
895 port_remove_in_progress = true;
897 /* process lock MUST be held by caller
901 RCUWriter<Ports> writer (ports);
902 boost::shared_ptr<Ports> ps = writer.get_copy ();
906 /* clear dead wood list in RCU */
910 port_remove_in_progress = false;
915 AudioEngine::make_port_name_relative (string portname) const
917 string::size_type len;
920 len = portname.length();
922 for (n = 0; n < len; ++n) {
923 if (portname[n] == ':') {
928 if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
929 return portname.substr (n+1);
936 AudioEngine::make_port_name_non_relative (string portname) const
940 if (portname.find_first_of (':') != string::npos) {
944 str = jack_client_name;
952 AudioEngine::port_is_mine (const string& portname) const
954 if (portname.find_first_of (':') != string::npos) {
955 if (portname.substr (0, jack_client_name.length ()) != jack_client_name) {
963 AudioEngine::port_is_physical (const std::string& portname) const
965 GET_PRIVATE_JACK_POINTER_RET(_jack, false);
967 jack_port_t *port = jack_port_by_name (_priv_jack, portname.c_str());
973 return jack_port_flags (port) & JackPortIsPhysical;
977 AudioEngine::destroy ()
984 AudioEngine::discover_backends ()
986 vector<std::string> backend_modules;
987 AudioBackend* backend;
989 Glib::PatternSpec so_extension_pattern("*.so");
990 Glib::PatternSpec dylib_extension_pattern("*.dylib");
992 find_matching_files_in_search_path (backend_search_path (),
993 so_extension_pattern, backend_modules);
995 find_matching_files_in_search_path (backend_search_path (),
996 dylib_extension_pattern, backend_modules);
998 DEBUG_TRACE (DEBUG::Panning, string_compose (_("looking for backends in %1"), backend_search_path().to_string()));
1000 for (vector<std::string>::iterator i = backend_modules.begin(); i != backend_modules.end(); ++i) {
1001 if ((backend = backend_discover (*i)) != 0) {
1002 _backends.insert (make_pair (backend->name(), backend));
1008 AudioEngine::backend_discover (string path)
1010 Glib::Module* module = new Glib::Module(path);
1011 AudioBackend* (*dfunc)(void);
1015 error << string_compose(_("AudioEngine: cannot load module \"%1\" (%2)"), path,
1016 Glib::Module::get_last_error()) << endmsg;
1021 if (!module->get_symbol("backend_factory", func)) {
1022 error << string_compose(_("AudioEngine: module \"%1\" has no factory function."), path) << endmsg;
1023 error << Glib::Module::get_last_error() << endmsg;
1028 dfunc = (AudioBackend* (*)(void))func;
1029 AudioBackend* backend = dfunc();