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/session.h>
37 #include <ardour/cycle_timer.h>
38 #include <ardour/utils.h>
43 #include <ardour/timestamps.h>
48 using namespace ARDOUR;
51 gint AudioEngine::m_meter_exit;
54 ardour_jack_error (const char* msg)
56 error << "JACK: " << msg << endmsg;
59 AudioEngine::AudioEngine (string client_name)
63 session_remove_pending = false;
66 last_monitor_check = 0;
67 monitor_check_interval = max_frames;
68 _processed_frames = 0;
69 _freewheeling = false;
74 _freewheeling = false;
75 _freewheel_thread_registered = false;
78 g_atomic_int_set (&m_meter_exit, 0);
80 if (connect_to_jack (client_name)) {
81 throw NoBackendAvailable ();
84 start_metering_thread();
86 JackPort::set_engine (this);
89 AudioEngine::~AudioEngine ()
92 Glib::Mutex::Lock tm (_process_lock);
93 session_removed.signal ();
96 jack_client_close (_jack);
99 stop_metering_thread ();
104 AudioEngine::jack() const
110 _thread_init_callback (void *arg)
112 /* make sure that anybody who needs to know about this thread
116 PBD::ThreadCreatedWithRequestSize (pthread_self(), X_("Audioengine"), 4096);
120 AudioEngine::start ()
125 nframes_t blocksize = jack_get_buffer_size (_jack);
127 session->set_block_size (blocksize);
128 session->set_frame_rate (jack_get_sample_rate (_jack));
130 /* page in as much of the session process code as we
131 can before we really start running.
134 session->process (blocksize);
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);
144 _processed_frames = 0;
145 last_monitor_check = 0;
147 jack_on_shutdown (_jack, halted, this);
148 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
149 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
150 jack_set_process_callback (_jack, _process_callback, this);
151 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
152 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
153 jack_set_xrun_callback (_jack, _xrun_callback, this);
154 jack_set_sync_callback (_jack, _jack_sync_callback, this);
155 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
157 if (Config->get_jack_time_master()) {
158 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
161 if (jack_activate (_jack) == 0) {
164 Running(); /* EMIT SIGNAL */
166 // error << _("cannot activate JACK client") << endmsg;
170 return _running ? 0 : -1;
174 AudioEngine::stop (bool forever)
179 jack_client_t* foo = _jack;
181 jack_client_close (foo);
182 stop_metering_thread ();
184 jack_deactivate (_jack);
186 Stopped(); /* EMIT SIGNAL */
189 return _running ? -1 : 0;
194 AudioEngine::get_sync_offset (nframes_t& offset) const
197 #ifdef HAVE_JACK_VIDEO_SUPPORT
201 (void) jack_transport_query (_jack, &pos);
203 if (pos.valid & JackVideoFrameOffset) {
204 offset = pos.video_offset;
214 AudioEngine::_jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
215 jack_position_t* pos, int new_position, void *arg)
217 static_cast<AudioEngine*> (arg)->jack_timebase_callback (state, nframes, pos, new_position);
221 AudioEngine::jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
222 jack_position_t* pos, int new_position)
224 if (_jack && session && session->synced_to_jack()) {
225 session->jack_timebase_callback (state, nframes, pos, new_position);
230 AudioEngine::_jack_sync_callback (jack_transport_state_t state, jack_position_t* pos, void* arg)
232 return static_cast<AudioEngine*> (arg)->jack_sync_callback (state, pos);
236 AudioEngine::jack_sync_callback (jack_transport_state_t state, jack_position_t* pos)
238 if (_jack && session) {
239 return session->jack_sync_callback (state, pos);
246 AudioEngine::_xrun_callback (void *arg)
248 AudioEngine* ae = static_cast<AudioEngine*> (arg);
250 ae->Xrun (); /* EMIT SIGNAL */
256 AudioEngine::_graph_order_callback (void *arg)
258 AudioEngine* ae = static_cast<AudioEngine*> (arg);
260 ae->GraphReordered (); /* EMIT SIGNAL */
265 /** Wrapped which is called by JACK as its process callback. It is just
266 * here to get us back into C++ land by calling AudioEngine::process_callback()
267 * @param nframes Number of frames passed by JACK.
268 * @param arg User argument passed by JACK, which will be the AudioEngine*.
271 AudioEngine::_process_callback (nframes_t nframes, void *arg)
273 return static_cast<AudioEngine *> (arg)->process_callback (nframes);
277 AudioEngine::_freewheel_callback (int onoff, void *arg)
279 static_cast<AudioEngine*>(arg)->_freewheeling = onoff;
282 /** Method called by JACK (via _process_callback) which says that there
283 * is work to be done.
284 * @param nframes Number of frames to process.
287 AudioEngine::process_callback (nframes_t nframes)
289 // CycleTimer ct ("AudioEngine::process");
290 Glib::Mutex::Lock tm (_process_lock, Glib::TRY_LOCK);
292 /// The number of frames that will have been processed when we've finished
293 nframes_t next_processed_frames;
295 /* handle wrap around of total frames counter */
297 if (max_frames - _processed_frames < nframes) {
298 next_processed_frames = nframes - (max_frames - _processed_frames);
300 next_processed_frames = _processed_frames + nframes;
303 if (!tm.locked() || session == 0) {
304 /* return having done nothing */
305 _processed_frames = next_processed_frames;
309 if (session_remove_pending) {
310 /* perform the actual session removal */
312 session_remove_pending = false;
313 session_removed.signal();
314 _processed_frames = next_processed_frames;
319 /* emit the Freewheel signal and stop freewheeling in the event of trouble */
320 if (Freewheel (nframes)) {
321 cerr << "Freewheeling returned non-zero!\n";
322 _freewheeling = false;
323 jack_set_freewheel (_jack, false);
328 boost::shared_ptr<Ports> p = ports.reader();
330 // Prepare ports (ie read data if necessary)
331 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
332 (*i)->cycle_start (nframes);
336 session->process (nframes);
340 _processed_frames = next_processed_frames;
344 // Finalize ports (ie write data if necessary)
345 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
349 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
351 boost::shared_ptr<Ports> p = ports.reader();
353 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
358 if (port->_last_monitor != (x = port->monitoring_input ())) {
359 port->_last_monitor = x;
360 /* XXX I think this is dangerous, due to
361 a likely mutex in the signal handlers ...
363 port->MonitorInputChanged (x); /* EMIT SIGNAL */
366 last_monitor_check = next_processed_frames;
369 _processed_frames = next_processed_frames;
374 AudioEngine::_sample_rate_callback (nframes_t nframes, void *arg)
376 return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
380 AudioEngine::jack_sample_rate_callback (nframes_t nframes)
382 _frame_rate = nframes;
383 _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
385 /* check for monitor input change every 1/10th of second */
387 monitor_check_interval = nframes / 10;
388 last_monitor_check = 0;
391 session->set_frame_rate (nframes);
394 SampleRateChanged (nframes); /* EMIT SIGNAL */
400 AudioEngine::_bufsize_callback (nframes_t nframes, void *arg)
402 return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
406 AudioEngine::jack_bufsize_callback (nframes_t nframes)
408 _buffer_size = nframes;
409 _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
410 last_monitor_check = 0;
412 boost::shared_ptr<Ports> p = ports.reader();
414 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
419 session->set_block_size (_buffer_size);
426 AudioEngine::stop_metering_thread ()
428 if (m_meter_thread) {
429 g_atomic_int_set (&m_meter_exit, 1);
430 m_meter_thread->join ();
436 AudioEngine::start_metering_thread ()
438 if (m_meter_thread == 0) {
439 m_meter_thread = Glib::Thread::create (sigc::mem_fun(this, &AudioEngine::meter_thread),
440 500000, true, true, Glib::THREAD_PRIORITY_NORMAL);
445 AudioEngine::meter_thread ()
448 Glib::usleep (10000); /* 1/100th sec interval */
449 if (g_atomic_int_get(&m_meter_exit)) {
452 IO::update_meters ();
457 AudioEngine::set_session (Session *s)
459 Glib::Mutex::Lock pl (_process_lock);
465 nframes_t blocksize = jack_get_buffer_size (_jack);
467 /* page in as much of the session process code as we
468 can before we really start running.
471 boost::shared_ptr<Ports> p = ports.reader();
473 for (Ports::iterator i = p->begin(); i != p->end(); ++i)
474 (*i)->cycle_start (blocksize);
476 s->process (blocksize);
477 s->process (blocksize);
478 s->process (blocksize);
479 s->process (blocksize);
480 s->process (blocksize);
481 s->process (blocksize);
482 s->process (blocksize);
483 s->process (blocksize);
485 for (Ports::iterator i = p->begin(); i != p->end(); ++i)
492 AudioEngine::remove_session ()
494 Glib::Mutex::Lock lm (_process_lock);
499 session_remove_pending = true;
500 session_removed.wait(_process_lock);
511 AudioEngine::register_port (DataType type, const string& portname, bool input)
516 if (type == DataType::AUDIO)
517 newport = new JackAudioPort (portname, (input ? Port::IsInput : Port::IsOutput));
518 else if (type == DataType::MIDI)
519 newport = new JackMidiPort (portname, (input ? Port::IsInput : Port::IsOutput));
521 throw unknown_type();
524 RCUWriter<Ports> writer (ports);
525 boost::shared_ptr<Ports> ps = writer.get_copy ();
526 ps->insert (ps->begin(), newport);
527 /* writer goes out of scope, forces update */
534 throw PortRegistrationFailure();
539 AudioEngine::register_input_port (DataType type, const string& portname)
541 return register_port (type, portname, true);
545 AudioEngine::register_output_port (DataType type, const string& portname)
547 return register_port (type, portname, false);
551 AudioEngine::unregister_port (Port& port)
554 /* probably happening when the engine has been halted by JACK,
555 in which case, there is nothing we can do here.
562 RCUWriter<Ports> writer (ports);
563 boost::shared_ptr<Ports> ps = writer.get_copy ();
565 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
567 remove_connections_for (port);
568 cerr << "eraseing " << (*i)->name() << endl;
575 /* writer goes out of scope, forces update */
582 AudioEngine::connect (const string& source, const string& destination)
586 fatal << _("connect called before engine was started") << endmsg;
593 string s = make_port_name_non_relative (source);
594 string d = make_port_name_non_relative (destination);
596 int ret = jack_connect (_jack, s.c_str(), d.c_str());
599 pair<string,string> c (s, d);
600 port_connections.push_back (c);
601 } else if (ret == EEXIST) {
602 error << string_compose(_("AudioEngine: connection already exists: %1 (%2) to %3 (%4)"),
603 source, s, destination, d)
606 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
607 source, s, destination, d)
615 AudioEngine::disconnect (const string& source, const string& destination)
619 fatal << _("disconnect called before engine was started") << endmsg;
626 string s = make_port_name_non_relative (source);
627 string d = make_port_name_non_relative (destination);
629 int ret = jack_disconnect (_jack, s.c_str(), d.c_str());
632 pair<string,string> c (s, d);
633 PortConnections::iterator i;
635 if ((i = find (port_connections.begin(), port_connections.end(), c)) != port_connections.end()) {
636 port_connections.erase (i);
644 AudioEngine::disconnect (Port& port)
648 fatal << _("disconnect called before engine was started") << endmsg;
655 int ret = port.disconnect ();
658 remove_connections_for (port);
666 AudioEngine::frame_rate ()
669 if (_frame_rate == 0) {
670 return (_frame_rate = jack_get_sample_rate (_jack));
675 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
683 AudioEngine::frames_per_cycle ()
686 if (_buffer_size == 0) {
687 return (_buffer_size = jack_get_buffer_size (_jack));
692 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
699 /** Get a port by name.
700 * Note this can return NULL, it will NOT create a port if it is not found (any more).
703 AudioEngine::get_port_by_name (const string& portname, bool keep)
705 Glib::Mutex::Lock lm (_process_lock);
709 fatal << _("get_port_by_name() called before engine was started") << endmsg;
716 boost::shared_ptr<Ports> pr = ports.reader();
718 for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
719 if (portname == (*i)->name()) {
728 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
732 fatal << _("get_ports called before engine was started") << endmsg;
738 return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
742 AudioEngine::halted (void *arg)
744 AudioEngine* ae = static_cast<AudioEngine *> (arg);
746 ae->_running = false;
747 ae->_buffer_size = 0;
751 ae->Halted(); /* EMIT SIGNAL */
755 AudioEngine::n_physical_outputs () const
764 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
769 for (i = 0; ports[i]; ++i);
776 AudioEngine::n_physical_inputs () const
785 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
790 for (i = 0; ports[i]; ++i);
797 AudioEngine::get_physical_inputs (vector<string>& ins)
806 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
811 for (i = 0; ports[i]; ++i) {
812 ins.push_back (ports[i]);
819 AudioEngine::get_physical_outputs (vector<string>& outs)
828 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
833 for (i = 0; ports[i]; ++i) {
834 outs.push_back (ports[i]);
841 AudioEngine::get_nth_physical (DataType type, uint32_t n, int flag)
847 assert(type != DataType::NIL);
849 if (!_running || !_jack) {
851 fatal << _("get_nth_physical called before engine was started") << endmsg;
858 ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|flag);
864 for (i = 0; i < n && ports[i]; ++i);
870 free ((char *) ports);
876 AudioEngine::get_port_total_latency (const Port& port)
878 return port.total_latency ();
882 AudioEngine::update_total_latency (const Port& port)
885 fatal << _("update_total_latency() called with no JACK client connection") << endmsg;
891 fatal << _("update_total_latency() called before engine was started") << endmsg;
896 port.recompute_total_latency ();
900 AudioEngine::transport_stop ()
902 // cerr << "tell JACK to stop\n";
904 jack_transport_stop (_jack);
909 AudioEngine::transport_start ()
911 // cerr << "tell JACK to start\n";
913 jack_transport_start (_jack);
918 AudioEngine::transport_locate (nframes_t where)
920 // cerr << "tell JACK to locate to " << where << endl;
922 jack_transport_locate (_jack, where);
926 AudioEngine::TransportState
927 AudioEngine::transport_state ()
931 return (TransportState) jack_transport_query (_jack, &pos);
933 return (TransportState) JackTransportStopped;
938 AudioEngine::reset_timebase ()
941 if (Config->get_jack_time_master()) {
942 return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
944 return jack_release_timebase (_jack);
952 AudioEngine::freewheel (bool onoff)
957 _freewheel_thread_registered = false;
960 return jack_set_freewheel (_jack, onoff);
968 AudioEngine::remove_all_ports ()
970 /* process lock MUST be held */
973 RCUWriter<Ports> writer (ports);
974 boost::shared_ptr<Ports> ps = writer.get_copy ();
978 port_connections.clear ();
982 AudioEngine::remove_connections_for (Port& port)
984 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ) {
985 PortConnections::iterator tmp;
990 if ((*i).first == port.name()) {
991 port_connections.erase (i);
998 #ifdef HAVE_JACK_CLIENT_OPEN
1001 AudioEngine::connect_to_jack (string client_name)
1003 jack_options_t options = JackNullOption;
1004 jack_status_t status;
1005 const char *server_name = NULL;
1007 jack_client_name = client_name; /* might be reset below */
1009 _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
1011 if (_jack == NULL) {
1013 if (status & JackServerFailed) {
1014 error << _("Unable to connect to JACK server") << endmsg;
1017 // error message is not useful here
1021 if (status & JackServerStarted) {
1022 info << _("JACK server started") << endmsg;
1025 if (status & JackNameNotUnique) {
1026 jack_client_name = jack_get_client_name (_jack);
1029 jack_set_error_function (ardour_jack_error);
1037 AudioEngine::connect_to_jack (string client_name)
1039 jack_client_name = client_name;
1041 if ((_jack = jack_client_new (client_name.c_str())) == NULL) {
1048 #endif /* HAVE_JACK_CLIENT_OPEN */
1051 AudioEngine::disconnect_from_jack ()
1057 jack_client_close (_jack);
1064 Stopped(); /* EMIT SIGNAL */
1072 AudioEngine::reconnect_to_jack ()
1075 disconnect_from_jack ();
1076 /* XXX give jackd a chance */
1077 Glib::usleep (250000);
1080 if (connect_to_jack (jack_client_name)) {
1081 error << _("failed to connect to JACK") << endmsg;
1087 boost::shared_ptr<Ports> p = ports.reader ();
1089 for (i = p->begin(); i != p->end(); ++i) {
1091 if ((*i)->reestablish ()) {
1096 if (i != p->end()) {
1098 remove_all_ports ();
1104 session->reset_jack_connection (_jack);
1105 nframes_t blocksize = jack_get_buffer_size (_jack);
1106 session->set_block_size (blocksize);
1107 session->set_frame_rate (jack_get_sample_rate (_jack));
1110 last_monitor_check = 0;
1112 jack_on_shutdown (_jack, halted, this);
1113 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
1114 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1115 jack_set_process_callback (_jack, _process_callback, this);
1116 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1117 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1118 jack_set_xrun_callback (_jack, _xrun_callback, this);
1119 jack_set_sync_callback (_jack, _jack_sync_callback, this);
1120 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1122 if (Config->get_jack_time_master()) {
1123 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1126 if (jack_activate (_jack) == 0) {
1133 /* re-establish connections */
1135 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ++i) {
1139 if ((err = jack_connect (_jack, (*i).first.c_str(), (*i).second.c_str())) != 0) {
1140 if (err != EEXIST) {
1141 error << string_compose (_("could not reconnect %1 and %2 (err = %3)"),
1142 (*i).first, (*i).second, err)
1148 Running (); /* EMIT SIGNAL*/
1154 AudioEngine::request_buffer_size (nframes_t nframes)
1158 if (nframes == jack_get_buffer_size (_jack)) {
1162 return jack_set_buffer_size (_jack, nframes);
1170 AudioEngine::update_total_latencies ()
1172 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1173 jack_recompute_total_latencies (_jack);
1178 AudioEngine::make_port_name_relative (string portname)
1180 string::size_type len;
1181 string::size_type n;
1183 len = portname.length();
1185 for (n = 0; n < len; ++n) {
1186 if (portname[n] == ':') {
1191 if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1192 return portname.substr (n+1);
1199 AudioEngine::make_port_name_non_relative (string portname)
1203 if (portname.find_first_of (':') != string::npos) {
1207 str = jack_client_name;
1215 AudioEngine::is_realtime () const
1218 return jack_is_realtime (_jack);