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.
26 #include <glibmm/timer.h>
27 #include <pbd/pthread_utils.h>
28 #include <pbd/stacktrace.h>
29 #include <pbd/unknown_type.h>
31 #include <ardour/audioengine.h>
32 #include <ardour/buffer.h>
33 #include <ardour/port.h>
34 #include <ardour/jack_audio_port.h>
35 #include <ardour/jack_midi_port.h>
36 #include <ardour/audio_port.h>
37 #include <ardour/session.h>
38 #include <ardour/cycle_timer.h>
39 #include <ardour/utils.h>
44 #include <ardour/timestamps.h>
49 using namespace ARDOUR;
52 gint AudioEngine::m_meter_exit;
55 ardour_jack_error (const char* msg)
57 error << "JACK: " << msg << endmsg;
60 AudioEngine::AudioEngine (string client_name)
64 session_remove_pending = false;
67 last_monitor_check = 0;
68 monitor_check_interval = max_frames;
69 _processed_frames = 0;
70 _freewheeling = false;
75 _freewheeling = false;
76 _freewheel_thread_registered = false;
79 g_atomic_int_set (&m_meter_exit, 0);
81 if (connect_to_jack (client_name)) {
82 throw NoBackendAvailable ();
85 start_metering_thread();
87 Port::set_engine (this);
90 AudioEngine::~AudioEngine ()
93 Glib::Mutex::Lock tm (_process_lock);
94 session_removed.signal ();
97 jack_client_close (_jack);
100 stop_metering_thread ();
105 AudioEngine::jack() const
111 _thread_init_callback (void *arg)
113 /* make sure that anybody who needs to know about this thread
117 PBD::ThreadCreatedWithRequestSize (pthread_self(), X_("Audioengine"), 4096);
121 AudioEngine::start ()
126 nframes_t blocksize = jack_get_buffer_size (_jack);
128 session->set_block_size (blocksize);
129 session->set_frame_rate (jack_get_sample_rate (_jack));
131 /* page in as much of the session process code as we
132 can before we really start running.
135 session->process (blocksize);
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);
145 _processed_frames = 0;
146 last_monitor_check = 0;
148 jack_on_shutdown (_jack, halted, this);
149 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
150 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
151 jack_set_process_callback (_jack, _process_callback, this);
152 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
153 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
154 jack_set_xrun_callback (_jack, _xrun_callback, this);
155 jack_set_sync_callback (_jack, _jack_sync_callback, this);
156 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
158 if (Config->get_jack_time_master()) {
159 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
162 if (jack_activate (_jack) == 0) {
165 Running(); /* EMIT SIGNAL */
167 // error << _("cannot activate JACK client") << endmsg;
171 return _running ? 0 : -1;
175 AudioEngine::stop (bool forever)
180 jack_client_t* foo = _jack;
182 jack_client_close (foo);
183 stop_metering_thread ();
185 jack_deactivate (_jack);
187 Stopped(); /* EMIT SIGNAL */
190 return _running ? -1 : 0;
195 AudioEngine::get_sync_offset (nframes_t& offset) const
198 #ifdef HAVE_JACK_VIDEO_SUPPORT
202 (void) jack_transport_query (_jack, &pos);
204 if (pos.valid & JackVideoFrameOffset) {
205 offset = pos.video_offset;
215 AudioEngine::_jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
216 jack_position_t* pos, int new_position, void *arg)
218 static_cast<AudioEngine*> (arg)->jack_timebase_callback (state, nframes, pos, new_position);
222 AudioEngine::jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
223 jack_position_t* pos, int new_position)
225 if (_jack && session && session->synced_to_jack()) {
226 session->jack_timebase_callback (state, nframes, pos, new_position);
231 AudioEngine::_jack_sync_callback (jack_transport_state_t state, jack_position_t* pos, void* arg)
233 return static_cast<AudioEngine*> (arg)->jack_sync_callback (state, pos);
237 AudioEngine::jack_sync_callback (jack_transport_state_t state, jack_position_t* pos)
239 if (_jack && session) {
240 return session->jack_sync_callback (state, pos);
247 AudioEngine::_xrun_callback (void *arg)
249 AudioEngine* ae = static_cast<AudioEngine*> (arg);
251 ae->Xrun (); /* EMIT SIGNAL */
257 AudioEngine::_graph_order_callback (void *arg)
259 AudioEngine* ae = static_cast<AudioEngine*> (arg);
261 ae->GraphReordered (); /* EMIT SIGNAL */
266 /** Wrapped which is called by JACK as its process callback. It is just
267 * here to get us back into C++ land by calling AudioEngine::process_callback()
268 * @param nframes Number of frames passed by JACK.
269 * @param arg User argument passed by JACK, which will be the AudioEngine*.
272 AudioEngine::_process_callback (nframes_t nframes, void *arg)
274 return static_cast<AudioEngine *> (arg)->process_callback (nframes);
278 AudioEngine::_freewheel_callback (int onoff, void *arg)
280 static_cast<AudioEngine*>(arg)->_freewheeling = onoff;
283 /** Method called by JACK (via _process_callback) which says that there
284 * is work to be done.
285 * @param nframes Number of frames to process.
288 AudioEngine::process_callback (nframes_t nframes)
290 // CycleTimer ct ("AudioEngine::process");
291 Glib::Mutex::Lock tm (_process_lock, Glib::TRY_LOCK);
293 /// The number of frames that will have been processed when we've finished
294 nframes_t next_processed_frames;
296 /* handle wrap around of total frames counter */
298 if (max_frames - _processed_frames < nframes) {
299 next_processed_frames = nframes - (max_frames - _processed_frames);
301 next_processed_frames = _processed_frames + nframes;
304 if (!tm.locked() || session == 0) {
305 /* return having done nothing */
306 _processed_frames = next_processed_frames;
310 if (session_remove_pending) {
311 /* perform the actual session removal */
313 session_remove_pending = false;
314 session_removed.signal();
315 _processed_frames = next_processed_frames;
320 /* emit the Freewheel signal and stop freewheeling in the event of trouble */
321 if (Freewheel (nframes)) {
322 cerr << "Freewheeling returned non-zero!\n";
323 _freewheeling = false;
324 jack_set_freewheel (_jack, false);
329 boost::shared_ptr<Ports> p = ports.reader();
331 // Prepare ports (ie read data if necessary)
332 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
333 (*i)->cycle_start (nframes, 0);
337 session->process (nframes);
341 _processed_frames = next_processed_frames;
345 // Finalize ports (ie write data if necessary)
347 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
348 (*i)->cycle_end (nframes, 0);
351 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
353 boost::shared_ptr<Ports> p = ports.reader();
355 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
360 if (port->_last_monitor != (x = port->monitoring_input ())) {
361 port->_last_monitor = x;
362 /* XXX I think this is dangerous, due to
363 a likely mutex in the signal handlers ...
365 port->MonitorInputChanged (x); /* EMIT SIGNAL */
368 last_monitor_check = next_processed_frames;
371 _processed_frames = next_processed_frames;
376 AudioEngine::_sample_rate_callback (nframes_t nframes, void *arg)
378 return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
382 AudioEngine::jack_sample_rate_callback (nframes_t nframes)
384 _frame_rate = nframes;
385 _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
387 /* check for monitor input change every 1/10th of second */
389 monitor_check_interval = nframes / 10;
390 last_monitor_check = 0;
393 session->set_frame_rate (nframes);
396 SampleRateChanged (nframes); /* EMIT SIGNAL */
402 AudioEngine::_bufsize_callback (nframes_t nframes, void *arg)
404 return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
408 AudioEngine::jack_bufsize_callback (nframes_t nframes)
410 _buffer_size = nframes;
411 _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
412 last_monitor_check = 0;
414 boost::shared_ptr<Ports> p = ports.reader();
416 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
421 session->set_block_size (_buffer_size);
428 AudioEngine::stop_metering_thread ()
430 if (m_meter_thread) {
431 g_atomic_int_set (&m_meter_exit, 1);
432 m_meter_thread->join ();
438 AudioEngine::start_metering_thread ()
440 if (m_meter_thread == 0) {
441 m_meter_thread = Glib::Thread::create (sigc::mem_fun(this, &AudioEngine::meter_thread),
442 500000, true, true, Glib::THREAD_PRIORITY_NORMAL);
447 AudioEngine::meter_thread ()
450 Glib::usleep (10000); /* 1/100th sec interval */
451 if (g_atomic_int_get(&m_meter_exit)) {
454 IO::update_meters ();
459 AudioEngine::set_session (Session *s)
461 Glib::Mutex::Lock pl (_process_lock);
467 nframes_t blocksize = jack_get_buffer_size (_jack);
469 /* page in as much of the session process code as we
470 can before we really start running.
473 boost::shared_ptr<Ports> p = ports.reader();
475 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
476 (*i)->cycle_start (blocksize, 0);
479 s->process (blocksize);
480 s->process (blocksize);
481 s->process (blocksize);
482 s->process (blocksize);
483 s->process (blocksize);
484 s->process (blocksize);
485 s->process (blocksize);
486 s->process (blocksize);
488 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
489 (*i)->cycle_end (blocksize, 0);
495 AudioEngine::remove_session ()
497 Glib::Mutex::Lock lm (_process_lock);
502 session_remove_pending = true;
503 session_removed.wait(_process_lock);
514 AudioEngine::register_port (DataType dtype, const string& portname, bool input, bool publish)
519 if (dtype == DataType::AUDIO) {
520 newport = new AudioPort (portname, (input ? Port::IsInput : Port::IsOutput), publish, frames_per_cycle());
521 } else if (dtype == DataType::MIDI) {
522 newport = new MidiPort (portname, (input ? Port::IsInput : Port::IsOutput), publish, frames_per_cycle());
524 throw unknown_type();
527 RCUWriter<Ports> writer (ports);
528 boost::shared_ptr<Ports> ps = writer.get_copy ();
529 ps->insert (ps->begin(), newport);
530 /* writer goes out of scope, forces update */
536 throw PortRegistrationFailure();
541 AudioEngine::get_port (const std::string& full_name)
543 boost::shared_ptr<Ports> p = ports.reader();
545 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
546 if ((*i)->name() == full_name) {
555 AudioEngine::register_input_port (DataType type, const string& portname, bool publish)
557 return register_port (type, portname, true, publish);
561 AudioEngine::register_output_port (DataType type, const string& portname, bool publish)
563 return register_port (type, portname, false, publish);
567 AudioEngine::unregister_port (Port& port)
569 /* caller must hold process lock */
572 /* probably happening when the engine has been halted by JACK,
573 in which case, there is nothing we can do here.
580 RCUWriter<Ports> writer (ports);
581 boost::shared_ptr<Ports> ps = writer.get_copy ();
583 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
591 /* writer goes out of scope, forces update */
598 AudioEngine::connect (const string& source, const string& destination)
604 fatal << _("connect called before engine was started") << endmsg;
611 string s = make_port_name_non_relative (source);
612 string d = make_port_name_non_relative (destination);
614 Port* src = get_port (s);
615 Port* dst = get_port (d);
619 /* both ports are known to us, so do the internal connect stuff */
621 if ((ret = src->connect (*dst)) == 0) {
622 ret = dst->connect (*src);
625 } else if (src || dst) {
627 /* one port is known to us, try to connect it to something external */
629 PortConnectableByName* pcn;
633 pcn = dynamic_cast<PortConnectableByName*>(src);
636 pcn = dynamic_cast<PortConnectableByName*>(dst);
641 ret = pcn->connect (other);
648 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
655 error << string_compose(_("AudioEngine: connection already exists: %1 (%2) to %3 (%4)"),
656 source, s, destination, d)
658 } else if (ret < 0) {
659 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
660 source, s, destination, d)
668 AudioEngine::disconnect (const string& source, const string& destination)
674 fatal << _("disconnect called before engine was started") << endmsg;
681 string s = make_port_name_non_relative (source);
682 string d = make_port_name_non_relative (destination);
684 Port* src = get_port (s);
685 Port* dst = get_port (d);
689 /* both ports are known to us, so do the internal connect stuff */
691 if ((ret = src->disconnect (*dst)) == 0) {
692 ret = dst->disconnect (*src);
695 } else if (src || dst) {
697 /* one port is known to us, try to connect it to something external */
700 PortConnectableByName* pcn;
704 pcn = dynamic_cast<PortConnectableByName*>(src);
707 pcn = dynamic_cast<PortConnectableByName*>(dst);
712 ret = pcn->disconnect (other);
719 /* neither port is known to us, and this API isn't intended for use as a general patch bay */
729 AudioEngine::disconnect (Port& port)
733 fatal << _("disconnect called before engine was started") << endmsg;
740 return port.disconnect_all ();
744 AudioEngine::frame_rate ()
747 if (_frame_rate == 0) {
748 return (_frame_rate = jack_get_sample_rate (_jack));
753 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
761 AudioEngine::frames_per_cycle ()
764 if (_buffer_size == 0) {
765 return (_buffer_size = jack_get_buffer_size (_jack));
770 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
777 /** Get a port by name.
778 * Note this can return NULL, it will NOT create a port if it is not found (any more).
781 AudioEngine::get_port_by_name (const string& portname, bool keep) const
783 Glib::Mutex::Lock lm (_process_lock);
787 fatal << _("get_port_by_name() called before engine was started") << endmsg;
794 boost::shared_ptr<Ports> pr = ports.reader();
796 for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
797 if (portname == (*i)->name()) {
806 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
810 fatal << _("get_ports called before engine was started") << endmsg;
816 return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
820 AudioEngine::halted (void *arg)
822 AudioEngine* ae = static_cast<AudioEngine *> (arg);
824 ae->_running = false;
825 ae->_buffer_size = 0;
829 ae->Halted(); /* EMIT SIGNAL */
833 AudioEngine::n_physical_outputs () const
842 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
847 for (i = 0; ports[i]; ++i);
854 AudioEngine::n_physical_inputs () const
863 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
868 for (i = 0; ports[i]; ++i);
875 AudioEngine::get_physical_inputs (vector<string>& ins)
884 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
889 for (i = 0; ports[i]; ++i) {
890 ins.push_back (ports[i]);
897 AudioEngine::get_physical_outputs (vector<string>& outs)
906 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
911 for (i = 0; ports[i]; ++i) {
912 outs.push_back (ports[i]);
919 AudioEngine::get_nth_physical (DataType type, uint32_t n, int flag)
925 assert(type != DataType::NIL);
927 if (!_running || !_jack) {
929 fatal << _("get_nth_physical called before engine was started") << endmsg;
936 ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|flag);
942 for (i = 0; i < n && ports[i]; ++i);
948 free ((char *) ports);
954 AudioEngine::get_port_total_latency (const Port& port)
956 return port.total_latency ();
960 AudioEngine::update_total_latency (const Port& port)
963 fatal << _("update_total_latency() called with no JACK client connection") << endmsg;
969 fatal << _("update_total_latency() called before engine was started") << endmsg;
974 port.recompute_total_latency ();
978 AudioEngine::transport_stop ()
980 // cerr << "tell JACK to stop\n";
982 jack_transport_stop (_jack);
987 AudioEngine::transport_start ()
989 // cerr << "tell JACK to start\n";
991 jack_transport_start (_jack);
996 AudioEngine::transport_locate (nframes_t where)
998 // cerr << "tell JACK to locate to " << where << endl;
1000 jack_transport_locate (_jack, where);
1004 AudioEngine::TransportState
1005 AudioEngine::transport_state ()
1008 jack_position_t pos;
1009 return (TransportState) jack_transport_query (_jack, &pos);
1011 return (TransportState) JackTransportStopped;
1016 AudioEngine::reset_timebase ()
1019 if (Config->get_jack_time_master()) {
1020 return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1022 return jack_release_timebase (_jack);
1030 AudioEngine::freewheel (bool onoff)
1035 _freewheel_thread_registered = false;
1038 return jack_set_freewheel (_jack, onoff);
1046 AudioEngine::remove_all_ports ()
1048 /* process lock MUST be held */
1051 RCUWriter<Ports> writer (ports);
1052 boost::shared_ptr<Ports> ps = writer.get_copy ();
1058 #ifdef HAVE_JACK_CLIENT_OPEN
1061 AudioEngine::connect_to_jack (string client_name)
1063 jack_options_t options = JackNullOption;
1064 jack_status_t status;
1065 const char *server_name = NULL;
1067 jack_client_name = client_name; /* might be reset below */
1069 _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
1071 if (_jack == NULL) {
1073 if (status & JackServerFailed) {
1074 error << _("Unable to connect to JACK server") << endmsg;
1077 // error message is not useful here
1081 if (status & JackServerStarted) {
1082 info << _("JACK server started") << endmsg;
1085 if (status & JackNameNotUnique) {
1086 jack_client_name = jack_get_client_name (_jack);
1089 jack_set_error_function (ardour_jack_error);
1097 AudioEngine::connect_to_jack (string client_name)
1099 jack_client_name = client_name;
1101 if ((_jack = jack_client_new (client_name.c_str())) == NULL) {
1108 #endif /* HAVE_JACK_CLIENT_OPEN */
1111 AudioEngine::disconnect_from_jack ()
1117 jack_client_close (_jack);
1124 Stopped(); /* EMIT SIGNAL */
1132 AudioEngine::reconnect_to_jack ()
1135 disconnect_from_jack ();
1136 /* XXX give jackd a chance */
1137 Glib::usleep (250000);
1140 if (connect_to_jack (jack_client_name)) {
1141 error << _("failed to connect to JACK") << endmsg;
1147 boost::shared_ptr<Ports> p = ports.reader ();
1149 for (i = p->begin(); i != p->end(); ++i) {
1150 if ((*i)->reestablish ()) {
1155 if (i != p->end()) {
1157 remove_all_ports ();
1163 session->reset_jack_connection (_jack);
1164 nframes_t blocksize = jack_get_buffer_size (_jack);
1165 session->set_block_size (blocksize);
1166 session->set_frame_rate (jack_get_sample_rate (_jack));
1169 last_monitor_check = 0;
1171 jack_on_shutdown (_jack, halted, this);
1172 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
1173 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1174 jack_set_process_callback (_jack, _process_callback, this);
1175 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1176 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1177 jack_set_xrun_callback (_jack, _xrun_callback, this);
1178 jack_set_sync_callback (_jack, _jack_sync_callback, this);
1179 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1181 if (Config->get_jack_time_master()) {
1182 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1185 if (jack_activate (_jack) == 0) {
1192 /* re-establish connections */
1194 for (i = p->begin(); i != p->end(); ++i) {
1198 Running (); /* EMIT SIGNAL*/
1204 AudioEngine::request_buffer_size (nframes_t nframes)
1208 if (nframes == jack_get_buffer_size (_jack)) {
1212 return jack_set_buffer_size (_jack, nframes);
1220 AudioEngine::update_total_latencies ()
1222 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1223 jack_recompute_total_latencies (_jack);
1228 AudioEngine::make_port_name_relative (string portname)
1230 string::size_type len;
1231 string::size_type n;
1233 len = portname.length();
1235 for (n = 0; n < len; ++n) {
1236 if (portname[n] == ':') {
1241 if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1242 return portname.substr (n+1);
1249 AudioEngine::make_port_name_non_relative (string portname)
1253 if (portname.find_first_of (':') != string::npos) {
1257 str = jack_client_name;
1265 AudioEngine::is_realtime () const
1268 return jack_is_realtime (_jack);