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/internal_audio_port.h>
36 #include <ardour/jack_midi_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 JackPort::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);
337 session->process (nframes);
341 _processed_frames = next_processed_frames;
345 // Finalize ports (ie write data if necessary)
346 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
350 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
352 boost::shared_ptr<Ports> p = ports.reader();
354 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
359 if (port->_last_monitor != (x = port->monitoring_input ())) {
360 port->_last_monitor = x;
361 /* XXX I think this is dangerous, due to
362 a likely mutex in the signal handlers ...
364 port->MonitorInputChanged (x); /* EMIT SIGNAL */
367 last_monitor_check = next_processed_frames;
370 _processed_frames = next_processed_frames;
375 AudioEngine::_sample_rate_callback (nframes_t nframes, void *arg)
377 return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
381 AudioEngine::jack_sample_rate_callback (nframes_t nframes)
383 _frame_rate = nframes;
384 _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
386 /* check for monitor input change every 1/10th of second */
388 monitor_check_interval = nframes / 10;
389 last_monitor_check = 0;
392 session->set_frame_rate (nframes);
395 SampleRateChanged (nframes); /* EMIT SIGNAL */
401 AudioEngine::_bufsize_callback (nframes_t nframes, void *arg)
403 return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
407 AudioEngine::jack_bufsize_callback (nframes_t nframes)
409 _buffer_size = nframes;
410 _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
411 last_monitor_check = 0;
413 boost::shared_ptr<Ports> p = ports.reader();
415 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
420 session->set_block_size (_buffer_size);
427 AudioEngine::stop_metering_thread ()
429 if (m_meter_thread) {
430 g_atomic_int_set (&m_meter_exit, 1);
431 m_meter_thread->join ();
437 AudioEngine::start_metering_thread ()
439 if (m_meter_thread == 0) {
440 m_meter_thread = Glib::Thread::create (sigc::mem_fun(this, &AudioEngine::meter_thread),
441 500000, true, true, Glib::THREAD_PRIORITY_NORMAL);
446 AudioEngine::meter_thread ()
449 Glib::usleep (10000); /* 1/100th sec interval */
450 if (g_atomic_int_get(&m_meter_exit)) {
453 IO::update_meters ();
458 AudioEngine::set_session (Session *s)
460 Glib::Mutex::Lock pl (_process_lock);
466 nframes_t blocksize = jack_get_buffer_size (_jack);
468 /* page in as much of the session process code as we
469 can before we really start running.
472 boost::shared_ptr<Ports> p = ports.reader();
474 for (Ports::iterator i = p->begin(); i != p->end(); ++i)
475 (*i)->cycle_start (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);
484 s->process (blocksize);
486 for (Ports::iterator i = p->begin(); i != p->end(); ++i)
493 AudioEngine::remove_session ()
495 Glib::Mutex::Lock lm (_process_lock);
500 session_remove_pending = true;
501 session_removed.wait(_process_lock);
512 AudioEngine::register_port (PortType ptype, DataType dtype, const string& portname, bool input)
519 if (dtype == DataType::AUDIO) {
520 newport = new JackAudioPort (portname, (input ? Port::IsInput : Port::IsOutput));
521 } else if (dtype == DataType::MIDI) {
522 newport = new JackMidiPort (portname, (input ? Port::IsInput : Port::IsOutput));
524 throw unknown_type();
529 if (dtype == DataType::AUDIO) {
530 newport = new InternalAudioPort (portname, (input ? Port::IsInput : Port::IsOutput));
531 } else if (dtype == DataType::MIDI) {
532 error << _("Internal MIDI ports are not implemented yet!") << endmsg;
533 throw unknown_type();
535 throw unknown_type();
541 RCUWriter<Ports> writer (ports);
542 boost::shared_ptr<Ports> ps = writer.get_copy ();
543 ps->insert (ps->begin(), newport);
544 /* writer goes out of scope, forces update */
551 throw PortRegistrationFailure();
556 AudioEngine::get_internal_port (const std::string& short_name)
558 boost::shared_ptr<Ports> p = ports.reader();
560 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
561 if ((*i)->short_name() == short_name) {
562 return dynamic_cast<InternalPort*> (*i);
570 AudioEngine::register_input_port (PortType ptype, DataType type, const string& portname)
572 return register_port (ptype, type, portname, true);
576 AudioEngine::register_output_port (PortType ptype, DataType type, const string& portname)
578 return register_port (ptype, type, portname, false);
582 AudioEngine::unregister_port (Port& port)
585 /* probably happening when the engine has been halted by JACK,
586 in which case, there is nothing we can do here.
593 RCUWriter<Ports> writer (ports);
594 boost::shared_ptr<Ports> ps = writer.get_copy ();
596 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
598 remove_connections_for (port);
605 /* writer goes out of scope, forces update */
612 AudioEngine::connect (const string& source, const string& destination)
618 fatal << _("connect called before engine was started") << endmsg;
625 string s = make_port_name_non_relative (source);
626 string d = make_port_name_non_relative (destination);
628 if (source.substr (0, 9) == "internal:") {
629 if (destination.substr (0, 9) == "internal:") {
630 InternalPort* src = get_internal_port (source);
631 InternalPort* dst = get_internal_port (destination);
633 InternalPort::connect (*src, *dst);
642 ret = jack_connect (_jack, s.c_str(), d.c_str());
646 pair<string,string> c (s, d);
647 port_connections.push_back (c);
648 } else if (ret == EEXIST) {
649 error << string_compose(_("AudioEngine: connection already exists: %1 (%2) to %3 (%4)"),
650 source, s, destination, d)
653 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
654 source, s, destination, d)
662 AudioEngine::disconnect (const string& source, const string& destination)
668 fatal << _("disconnect called before engine was started") << endmsg;
675 string s = make_port_name_non_relative (source);
676 string d = make_port_name_non_relative (destination);
678 if (source.substr (0, 9) == "internal:") {
679 if (destination.substr (0, 9) == "internal:") {
680 InternalPort* src = get_internal_port (source);
681 InternalPort* dst = get_internal_port (destination);
683 InternalPort::disconnect (*src, *dst);
691 ret = jack_disconnect (_jack, s.c_str(), d.c_str());
695 pair<string,string> c (s, d);
696 PortConnections::iterator i;
698 if ((i = find (port_connections.begin(), port_connections.end(), c)) != port_connections.end()) {
699 port_connections.erase (i);
707 AudioEngine::disconnect (Port& port)
711 fatal << _("disconnect called before engine was started") << endmsg;
718 int ret = port.disconnect ();
721 remove_connections_for (port);
729 AudioEngine::frame_rate ()
732 if (_frame_rate == 0) {
733 return (_frame_rate = jack_get_sample_rate (_jack));
738 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
746 AudioEngine::frames_per_cycle ()
749 if (_buffer_size == 0) {
750 return (_buffer_size = jack_get_buffer_size (_jack));
755 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
762 /** Get a port by name.
763 * Note this can return NULL, it will NOT create a port if it is not found (any more).
766 AudioEngine::get_port_by_name (const string& portname, bool keep) const
768 Glib::Mutex::Lock lm (_process_lock);
772 fatal << _("get_port_by_name() called before engine was started") << endmsg;
779 boost::shared_ptr<Ports> pr = ports.reader();
781 for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
782 if (portname == (*i)->name()) {
791 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
795 fatal << _("get_ports called before engine was started") << endmsg;
801 return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
805 AudioEngine::halted (void *arg)
807 AudioEngine* ae = static_cast<AudioEngine *> (arg);
809 ae->_running = false;
810 ae->_buffer_size = 0;
814 ae->Halted(); /* EMIT SIGNAL */
818 AudioEngine::n_physical_outputs () const
827 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
832 for (i = 0; ports[i]; ++i);
839 AudioEngine::n_physical_inputs () const
848 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
853 for (i = 0; ports[i]; ++i);
860 AudioEngine::get_physical_inputs (vector<string>& ins)
869 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
874 for (i = 0; ports[i]; ++i) {
875 ins.push_back (ports[i]);
882 AudioEngine::get_physical_outputs (vector<string>& outs)
891 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
896 for (i = 0; ports[i]; ++i) {
897 outs.push_back (ports[i]);
904 AudioEngine::get_nth_physical (DataType type, uint32_t n, int flag)
910 assert(type != DataType::NIL);
912 if (!_running || !_jack) {
914 fatal << _("get_nth_physical called before engine was started") << endmsg;
921 ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|flag);
927 for (i = 0; i < n && ports[i]; ++i);
933 free ((char *) ports);
939 AudioEngine::get_port_total_latency (const Port& port)
941 return port.total_latency ();
945 AudioEngine::update_total_latency (const Port& port)
948 fatal << _("update_total_latency() called with no JACK client connection") << endmsg;
954 fatal << _("update_total_latency() called before engine was started") << endmsg;
959 port.recompute_total_latency ();
963 AudioEngine::transport_stop ()
965 // cerr << "tell JACK to stop\n";
967 jack_transport_stop (_jack);
972 AudioEngine::transport_start ()
974 // cerr << "tell JACK to start\n";
976 jack_transport_start (_jack);
981 AudioEngine::transport_locate (nframes_t where)
983 // cerr << "tell JACK to locate to " << where << endl;
985 jack_transport_locate (_jack, where);
989 AudioEngine::TransportState
990 AudioEngine::transport_state ()
994 return (TransportState) jack_transport_query (_jack, &pos);
996 return (TransportState) JackTransportStopped;
1001 AudioEngine::reset_timebase ()
1004 if (Config->get_jack_time_master()) {
1005 return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1007 return jack_release_timebase (_jack);
1015 AudioEngine::freewheel (bool onoff)
1020 _freewheel_thread_registered = false;
1023 return jack_set_freewheel (_jack, onoff);
1031 AudioEngine::remove_all_ports ()
1033 /* process lock MUST be held */
1036 RCUWriter<Ports> writer (ports);
1037 boost::shared_ptr<Ports> ps = writer.get_copy ();
1041 port_connections.clear ();
1045 AudioEngine::remove_connections_for (Port& port)
1047 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ) {
1048 PortConnections::iterator tmp;
1053 if ((*i).first == port.name()) {
1054 port_connections.erase (i);
1061 #ifdef HAVE_JACK_CLIENT_OPEN
1064 AudioEngine::connect_to_jack (string client_name)
1066 jack_options_t options = JackNullOption;
1067 jack_status_t status;
1068 const char *server_name = NULL;
1070 jack_client_name = client_name; /* might be reset below */
1072 _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
1074 if (_jack == NULL) {
1076 if (status & JackServerFailed) {
1077 error << _("Unable to connect to JACK server") << endmsg;
1080 // error message is not useful here
1084 if (status & JackServerStarted) {
1085 info << _("JACK server started") << endmsg;
1088 if (status & JackNameNotUnique) {
1089 jack_client_name = jack_get_client_name (_jack);
1092 jack_set_error_function (ardour_jack_error);
1100 AudioEngine::connect_to_jack (string client_name)
1102 jack_client_name = client_name;
1104 if ((_jack = jack_client_new (client_name.c_str())) == NULL) {
1111 #endif /* HAVE_JACK_CLIENT_OPEN */
1114 AudioEngine::disconnect_from_jack ()
1120 jack_client_close (_jack);
1127 Stopped(); /* EMIT SIGNAL */
1135 AudioEngine::reconnect_to_jack ()
1138 disconnect_from_jack ();
1139 /* XXX give jackd a chance */
1140 Glib::usleep (250000);
1143 if (connect_to_jack (jack_client_name)) {
1144 error << _("failed to connect to JACK") << endmsg;
1150 boost::shared_ptr<Ports> p = ports.reader ();
1152 for (i = p->begin(); i != p->end(); ++i) {
1154 if ((*i)->reestablish ()) {
1159 if (i != p->end()) {
1161 remove_all_ports ();
1167 session->reset_jack_connection (_jack);
1168 nframes_t blocksize = jack_get_buffer_size (_jack);
1169 session->set_block_size (blocksize);
1170 session->set_frame_rate (jack_get_sample_rate (_jack));
1173 last_monitor_check = 0;
1175 jack_on_shutdown (_jack, halted, this);
1176 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
1177 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1178 jack_set_process_callback (_jack, _process_callback, this);
1179 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1180 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1181 jack_set_xrun_callback (_jack, _xrun_callback, this);
1182 jack_set_sync_callback (_jack, _jack_sync_callback, this);
1183 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1185 if (Config->get_jack_time_master()) {
1186 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1189 if (jack_activate (_jack) == 0) {
1196 /* re-establish connections */
1198 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ++i) {
1202 if ((err = jack_connect (_jack, (*i).first.c_str(), (*i).second.c_str())) != 0) {
1203 if (err != EEXIST) {
1204 error << string_compose (_("could not reconnect %1 and %2 (err = %3)"),
1205 (*i).first, (*i).second, err)
1211 Running (); /* EMIT SIGNAL*/
1217 AudioEngine::request_buffer_size (nframes_t nframes)
1221 if (nframes == jack_get_buffer_size (_jack)) {
1225 return jack_set_buffer_size (_jack, nframes);
1233 AudioEngine::update_total_latencies ()
1235 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1236 jack_recompute_total_latencies (_jack);
1241 AudioEngine::make_port_name_relative (string portname)
1243 string::size_type len;
1244 string::size_type n;
1246 len = portname.length();
1248 for (n = 0; n < len; ++n) {
1249 if (portname[n] == ':') {
1254 if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1255 return portname.substr (n+1);
1262 AudioEngine::make_port_name_non_relative (string portname)
1266 if (portname.find_first_of (':') != string::npos) {
1270 str = jack_client_name;
1278 AudioEngine::is_realtime () const
1281 return jack_is_realtime (_jack);