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 <pbd/pthread_utils.h>
29 #include <pbd/stacktrace.h>
30 #include <pbd/unknown_type.h>
32 #include <ardour/audioengine.h>
33 #include <ardour/buffer.h>
34 #include <ardour/port.h>
35 #include <ardour/jack_audio_port.h>
36 #include <ardour/jack_midi_port.h>
37 #include <ardour/audio_port.h>
38 #include <ardour/session.h>
39 #include <ardour/cycle_timer.h>
40 #include <ardour/utils.h>
45 #include <ardour/timestamps.h>
50 using namespace ARDOUR;
53 gint AudioEngine::m_meter_exit;
56 ardour_jack_error (const char* msg)
58 error << "JACK: " << msg << endmsg;
61 AudioEngine::AudioEngine (string client_name)
65 session_remove_pending = false;
68 last_monitor_check = 0;
69 monitor_check_interval = max_frames;
70 _processed_frames = 0;
71 _freewheeling = false;
76 _freewheeling = false;
77 _freewheel_thread_registered = false;
80 g_atomic_int_set (&m_meter_exit, 0);
82 if (connect_to_jack (client_name)) {
83 throw NoBackendAvailable ();
86 start_metering_thread();
88 Port::set_engine (this);
91 AudioEngine::~AudioEngine ()
94 Glib::Mutex::Lock tm (_process_lock);
95 session_removed.signal ();
98 jack_client_close (_jack);
101 stop_metering_thread ();
106 AudioEngine::jack() const
112 _thread_init_callback (void *arg)
114 /* make sure that anybody who needs to know about this thread
118 PBD::ThreadCreatedWithRequestSize (pthread_self(), X_("Audioengine"), 4096);
122 AudioEngine::start ()
127 nframes_t blocksize = jack_get_buffer_size (_jack);
129 session->set_block_size (blocksize);
130 session->set_frame_rate (jack_get_sample_rate (_jack));
132 /* page in as much of the session process code as we
133 can before we really start running.
136 session->process (blocksize);
137 session->process (blocksize);
138 session->process (blocksize);
139 session->process (blocksize);
140 session->process (blocksize);
141 session->process (blocksize);
142 session->process (blocksize);
143 session->process (blocksize);
146 _processed_frames = 0;
147 last_monitor_check = 0;
149 jack_on_shutdown (_jack, halted, this);
150 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
151 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
152 jack_set_process_callback (_jack, _process_callback, this);
153 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
154 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
155 jack_set_xrun_callback (_jack, _xrun_callback, this);
156 jack_set_sync_callback (_jack, _jack_sync_callback, this);
157 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
159 if (Config->get_jack_time_master()) {
160 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
163 if (jack_activate (_jack) == 0) {
166 Running(); /* EMIT SIGNAL */
168 // error << _("cannot activate JACK client") << endmsg;
172 return _running ? 0 : -1;
176 AudioEngine::stop (bool forever)
181 jack_client_t* foo = _jack;
183 jack_client_close (foo);
184 stop_metering_thread ();
186 jack_deactivate (_jack);
188 Stopped(); /* EMIT SIGNAL */
191 return _running ? -1 : 0;
196 AudioEngine::get_sync_offset (nframes_t& offset) const
199 #ifdef HAVE_JACK_VIDEO_SUPPORT
203 (void) jack_transport_query (_jack, &pos);
205 if (pos.valid & JackVideoFrameOffset) {
206 offset = pos.video_offset;
216 AudioEngine::_jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
217 jack_position_t* pos, int new_position, void *arg)
219 static_cast<AudioEngine*> (arg)->jack_timebase_callback (state, nframes, pos, new_position);
223 AudioEngine::jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
224 jack_position_t* pos, int new_position)
226 if (_jack && session && session->synced_to_jack()) {
227 session->jack_timebase_callback (state, nframes, pos, new_position);
232 AudioEngine::_jack_sync_callback (jack_transport_state_t state, jack_position_t* pos, void* arg)
234 return static_cast<AudioEngine*> (arg)->jack_sync_callback (state, pos);
238 AudioEngine::jack_sync_callback (jack_transport_state_t state, jack_position_t* pos)
240 if (_jack && session) {
241 return session->jack_sync_callback (state, pos);
248 AudioEngine::_xrun_callback (void *arg)
250 AudioEngine* ae = static_cast<AudioEngine*> (arg);
252 ae->Xrun (); /* EMIT SIGNAL */
258 AudioEngine::_graph_order_callback (void *arg)
260 AudioEngine* ae = static_cast<AudioEngine*> (arg);
262 ae->GraphReordered (); /* EMIT SIGNAL */
267 /** Wrapped which is called by JACK as its process callback. It is just
268 * here to get us back into C++ land by calling AudioEngine::process_callback()
269 * @param nframes Number of frames passed by JACK.
270 * @param arg User argument passed by JACK, which will be the AudioEngine*.
273 AudioEngine::_process_callback (nframes_t nframes, void *arg)
275 return static_cast<AudioEngine *> (arg)->process_callback (nframes);
279 AudioEngine::_freewheel_callback (int onoff, void *arg)
281 static_cast<AudioEngine*>(arg)->_freewheeling = onoff;
284 /** Method called by JACK (via _process_callback) which says that there
285 * is work to be done.
286 * @param nframes Number of frames to process.
289 AudioEngine::process_callback (nframes_t nframes)
291 // CycleTimer ct ("AudioEngine::process");
292 Glib::Mutex::Lock tm (_process_lock, Glib::TRY_LOCK);
294 /// The number of frames that will have been processed when we've finished
295 nframes_t next_processed_frames;
297 /* handle wrap around of total frames counter */
299 if (max_frames - _processed_frames < nframes) {
300 next_processed_frames = nframes - (max_frames - _processed_frames);
302 next_processed_frames = _processed_frames + nframes;
305 if (!tm.locked() || session == 0) {
306 /* return having done nothing */
307 _processed_frames = next_processed_frames;
311 if (session_remove_pending) {
312 /* perform the actual session removal */
314 session_remove_pending = false;
315 session_removed.signal();
316 _processed_frames = next_processed_frames;
321 /* emit the Freewheel signal and stop freewheeling in the event of trouble */
322 if (Freewheel (nframes)) {
323 cerr << "Freewheeling returned non-zero!\n";
324 _freewheeling = false;
325 jack_set_freewheel (_jack, false);
330 boost::shared_ptr<Ports> p = ports.reader();
332 // Prepare ports (ie read data if necessary)
333 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
334 (*i)->cycle_start (nframes, 0);
338 session->process (nframes);
341 // Finalize ports (ie write data if necessary)
343 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
344 (*i)->cycle_end (nframes, 0);
348 _processed_frames = next_processed_frames;
352 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
354 boost::shared_ptr<Ports> p = ports.reader();
356 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
361 if (port->_last_monitor != (x = port->monitoring_input ())) {
362 port->_last_monitor = x;
363 /* XXX I think this is dangerous, due to
364 a likely mutex in the signal handlers ...
366 port->MonitorInputChanged (x); /* EMIT SIGNAL */
369 last_monitor_check = next_processed_frames;
372 if (session->silent()) {
374 boost::shared_ptr<Ports> p = ports.reader();
376 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
380 if (port->sends_output()) {
381 port->get_buffer().silence(nframes);
386 _processed_frames = next_processed_frames;
391 AudioEngine::_sample_rate_callback (nframes_t nframes, void *arg)
393 return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
397 AudioEngine::jack_sample_rate_callback (nframes_t nframes)
399 _frame_rate = nframes;
400 _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
402 /* check for monitor input change every 1/10th of second */
404 monitor_check_interval = nframes / 10;
405 last_monitor_check = 0;
408 session->set_frame_rate (nframes);
411 SampleRateChanged (nframes); /* EMIT SIGNAL */
417 AudioEngine::_bufsize_callback (nframes_t nframes, void *arg)
419 return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
423 AudioEngine::jack_bufsize_callback (nframes_t nframes)
425 _buffer_size = nframes;
426 _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
427 last_monitor_check = 0;
429 boost::shared_ptr<Ports> p = ports.reader();
431 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
436 session->set_block_size (_buffer_size);
443 AudioEngine::stop_metering_thread ()
445 if (m_meter_thread) {
446 g_atomic_int_set (&m_meter_exit, 1);
447 m_meter_thread->join ();
453 AudioEngine::start_metering_thread ()
455 if (m_meter_thread == 0) {
456 m_meter_thread = Glib::Thread::create (sigc::mem_fun(this, &AudioEngine::meter_thread),
457 500000, true, true, Glib::THREAD_PRIORITY_NORMAL);
462 AudioEngine::meter_thread ()
465 Glib::usleep (10000); /* 1/100th sec interval */
466 if (g_atomic_int_get(&m_meter_exit)) {
469 IO::update_meters ();
474 AudioEngine::set_session (Session *s)
476 Glib::Mutex::Lock pl (_process_lock);
482 nframes_t blocksize = jack_get_buffer_size (_jack);
484 /* page in as much of the session process code as we
485 can before we really start running.
488 boost::shared_ptr<Ports> p = ports.reader();
490 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
491 (*i)->cycle_start (blocksize, 0);
494 s->process (blocksize);
495 s->process (blocksize);
496 s->process (blocksize);
497 s->process (blocksize);
498 s->process (blocksize);
499 s->process (blocksize);
500 s->process (blocksize);
501 s->process (blocksize);
503 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
504 (*i)->cycle_end (blocksize, 0);
510 AudioEngine::remove_session ()
512 Glib::Mutex::Lock lm (_process_lock);
517 session_remove_pending = true;
518 session_removed.wait(_process_lock);
529 AudioEngine::port_registration_failure (const std::string& portname)
531 string full_portname = jack_client_name;
532 full_portname += ':';
533 full_portname += portname;
536 jack_port_t* p = jack_port_by_name (_jack, full_portname.c_str());
540 reason = _("a port with this name already exists: check for duplicated track/bus names");
542 reason = _("unknown error");
545 throw PortRegistrationFailure (string_compose (_("AudioEngine: cannot register port \"%1\": %2"), portname, reason).c_str());
549 AudioEngine::register_port (DataType dtype, const string& portname, bool input, bool publish)
554 if (dtype == DataType::AUDIO) {
555 newport = new AudioPort (portname, (input ? Port::IsInput : Port::IsOutput), publish, frames_per_cycle());
556 } else if (dtype == DataType::MIDI) {
557 newport = new MidiPort (portname, (input ? Port::IsInput : Port::IsOutput), publish, frames_per_cycle());
559 throw unknown_type();
562 RCUWriter<Ports> writer (ports);
563 boost::shared_ptr<Ports> ps = writer.get_copy ();
564 ps->insert (ps->begin(), newport);
565 /* writer goes out of scope, forces update */
571 throw PortRegistrationFailure("unable to create port (unknown type?)");
576 AudioEngine::get_port (const std::string& full_name)
578 boost::shared_ptr<Ports> p = ports.reader();
580 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
581 if ((*i)->name() == full_name) {
590 AudioEngine::register_input_port (DataType type, const string& portname, bool publish)
592 return register_port (type, portname, true, publish);
596 AudioEngine::register_output_port (DataType type, const string& portname, bool publish)
598 return register_port (type, portname, false, publish);
602 AudioEngine::unregister_port (Port& port)
604 /* caller must hold process lock */
607 /* probably happening when the engine has been halted by JACK,
608 in which case, there is nothing we can do here.
615 RCUWriter<Ports> writer (ports);
616 boost::shared_ptr<Ports> ps = writer.get_copy ();
618 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
626 /* writer goes out of scope, forces update */
629 remove_connections_for (port);
635 AudioEngine::connect (const string& source, const string& destination)
641 fatal << _("connect called before engine was started") << endmsg;
648 string s = make_port_name_non_relative (source);
649 string d = make_port_name_non_relative (destination);
651 Port* src = get_port (s);
652 Port* dst = get_port (d);
656 /* both ports are known to us, so do the internal connect stuff */
658 if ((ret = src->connect (*dst)) == 0) {
659 ret = dst->connect (*src);
662 } else if (src || dst) {
664 /* one port is known to us, try to connect it to something external */
666 PortConnectableByName* pcn;
670 pcn = dynamic_cast<PortConnectableByName*>(src);
673 pcn = dynamic_cast<PortConnectableByName*>(dst);
678 ret = pcn->connect (other);
685 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
692 error << string_compose(_("AudioEngine: connection already exists: %1 (%2) to %3 (%4)"),
693 source, s, destination, d)
695 } else if (ret < 0) {
696 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
697 source, s, destination, d)
705 AudioEngine::disconnect (const string& source, const string& destination)
711 fatal << _("disconnect called before engine was started") << endmsg;
718 string s = make_port_name_non_relative (source);
719 string d = make_port_name_non_relative (destination);
721 Port* src = get_port (s);
722 Port* dst = get_port (d);
726 /* both ports are known to us, so do the internal connect stuff */
728 if ((ret = src->disconnect (*dst)) == 0) {
729 ret = dst->disconnect (*src);
732 } else if (src || dst) {
734 /* one port is known to us, try to connect it to something external */
737 PortConnectableByName* pcn;
741 pcn = dynamic_cast<PortConnectableByName*>(src);
744 pcn = dynamic_cast<PortConnectableByName*>(dst);
749 ret = pcn->disconnect (other);
756 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
766 AudioEngine::disconnect (Port& port)
770 fatal << _("disconnect called before engine was started") << endmsg;
777 return port.disconnect_all ();
781 AudioEngine::frame_rate ()
784 if (_frame_rate == 0) {
785 return (_frame_rate = jack_get_sample_rate (_jack));
790 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
798 AudioEngine::frames_per_cycle ()
801 if (_buffer_size == 0) {
802 return (_buffer_size = jack_get_buffer_size (_jack));
807 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
814 /** Get a port by name.
815 * Note this can return NULL, it will NOT create a port if it is not found (any more).
818 AudioEngine::get_port_by_name (const string& portname, bool keep) const
820 Glib::Mutex::Lock lm (_process_lock);
824 fatal << _("get_port_by_name() called before engine was started") << endmsg;
831 boost::shared_ptr<Ports> pr = ports.reader();
833 for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
834 if (portname == (*i)->name()) {
843 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
847 fatal << _("get_ports called before engine was started") << endmsg;
853 return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
857 AudioEngine::halted (void *arg)
859 AudioEngine* ae = static_cast<AudioEngine *> (arg);
860 bool was_running = ae->_running;
862 ae->_running = false;
863 ae->_buffer_size = 0;
868 ae->Halted(); /* EMIT SIGNAL */
873 AudioEngine::n_physical_outputs () const
882 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
887 for (i = 0; ports[i]; ++i);
894 AudioEngine::n_physical_inputs () const
903 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
908 for (i = 0; ports[i]; ++i);
915 AudioEngine::get_physical_inputs (vector<string>& ins)
924 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
929 for (i = 0; ports[i]; ++i) {
930 ins.push_back (ports[i]);
937 AudioEngine::get_physical_outputs (vector<string>& outs)
946 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
951 for (i = 0; ports[i]; ++i) {
952 outs.push_back (ports[i]);
959 AudioEngine::get_nth_physical (DataType type, uint32_t n, int flag)
965 assert(type != DataType::NIL);
967 if (!_running || !_jack) {
969 fatal << _("get_nth_physical called before engine was started") << endmsg;
976 ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|flag);
982 for (i = 0; i < n && ports[i]; ++i);
988 free ((char *) ports);
994 AudioEngine::get_port_total_latency (const Port& port)
996 return port.total_latency ();
1000 AudioEngine::update_total_latency (const Port& port)
1003 fatal << _("update_total_latency() called with no JACK client connection") << endmsg;
1009 fatal << _("update_total_latency() called before engine was started") << endmsg;
1014 port.recompute_total_latency ();
1018 AudioEngine::transport_stop ()
1020 // cerr << "tell JACK to stop\n";
1022 jack_transport_stop (_jack);
1027 AudioEngine::transport_start ()
1029 // cerr << "tell JACK to start\n";
1031 jack_transport_start (_jack);
1036 AudioEngine::transport_locate (nframes_t where)
1038 // cerr << "tell JACK to locate to " << where << endl;
1040 jack_transport_locate (_jack, where);
1044 AudioEngine::TransportState
1045 AudioEngine::transport_state ()
1048 jack_position_t pos;
1049 return (TransportState) jack_transport_query (_jack, &pos);
1051 return (TransportState) JackTransportStopped;
1056 AudioEngine::reset_timebase ()
1059 if (Config->get_jack_time_master()) {
1060 return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1062 return jack_release_timebase (_jack);
1070 AudioEngine::freewheel (bool onoff)
1075 _freewheel_thread_registered = false;
1078 return jack_set_freewheel (_jack, onoff);
1086 AudioEngine::remove_all_ports ()
1088 /* process lock MUST be held */
1091 RCUWriter<Ports> writer (ports);
1092 boost::shared_ptr<Ports> ps = writer.get_copy ();
1098 AudioEngine::remove_connections_for (Port& port)
1100 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ) {
1101 PortConnections::iterator tmp;
1106 if ((*i).first == port.name()) {
1107 port_connections.erase (i);
1115 #ifdef HAVE_JACK_CLIENT_OPEN
1118 AudioEngine::connect_to_jack (string client_name)
1120 jack_options_t options = JackNullOption;
1121 jack_status_t status;
1122 const char *server_name = NULL;
1124 jack_client_name = client_name; /* might be reset below */
1125 _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
1127 if (_jack == NULL) {
1129 if (status & JackServerFailed) {
1130 error << _("Unable to connect to JACK server") << endmsg;
1133 // error message is not useful here
1137 if (status & JackServerStarted) {
1138 info << _("JACK server started") << endmsg;
1141 if (status & JackNameNotUnique) {
1142 jack_client_name = jack_get_client_name (_jack);
1145 jack_set_error_function (ardour_jack_error);
1153 AudioEngine::connect_to_jack (string client_name)
1155 jack_client_name = client_name;
1157 if ((_jack = jack_client_new (client_name.c_str())) == NULL) {
1164 #endif /* HAVE_JACK_CLIENT_OPEN */
1167 AudioEngine::disconnect_from_jack ()
1173 jack_client_close (_jack);
1180 Stopped(); /* EMIT SIGNAL */
1188 AudioEngine::reconnect_to_jack ()
1191 disconnect_from_jack ();
1192 /* XXX give jackd a chance */
1193 Glib::usleep (250000);
1196 if (connect_to_jack (jack_client_name)) {
1197 error << _("failed to connect to JACK") << endmsg;
1203 boost::shared_ptr<Ports> p = ports.reader ();
1205 for (i = p->begin(); i != p->end(); ++i) {
1206 if ((*i)->reestablish ()) {
1211 if (i != p->end()) {
1213 remove_all_ports ();
1219 session->reset_jack_connection (_jack);
1220 nframes_t blocksize = jack_get_buffer_size (_jack);
1221 session->set_block_size (blocksize);
1222 session->set_frame_rate (jack_get_sample_rate (_jack));
1225 last_monitor_check = 0;
1227 jack_on_shutdown (_jack, halted, this);
1228 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
1229 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1230 jack_set_process_callback (_jack, _process_callback, this);
1231 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1232 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1233 jack_set_xrun_callback (_jack, _xrun_callback, this);
1234 jack_set_sync_callback (_jack, _jack_sync_callback, this);
1235 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1237 if (Config->get_jack_time_master()) {
1238 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1241 if (jack_activate (_jack) == 0) {
1248 /* re-establish connections */
1250 for (i = p->begin(); i != p->end(); ++i) {
1254 Running (); /* EMIT SIGNAL*/
1260 AudioEngine::request_buffer_size (nframes_t nframes)
1264 if (nframes == jack_get_buffer_size (_jack)) {
1268 return jack_set_buffer_size (_jack, nframes);
1276 AudioEngine::update_total_latencies ()
1278 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1279 jack_recompute_total_latencies (_jack);
1284 AudioEngine::make_port_name_relative (string portname)
1286 string::size_type len;
1287 string::size_type n;
1289 len = portname.length();
1291 for (n = 0; n < len; ++n) {
1292 if (portname[n] == ':') {
1297 if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1298 return portname.substr (n+1);
1305 AudioEngine::make_port_name_non_relative (string portname)
1309 if (portname.find_first_of (':') != string::npos) {
1313 str = jack_client_name;
1321 AudioEngine::is_realtime () const
1324 return jack_is_realtime (_jack);