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.
25 #include <glibmm/timer.h>
26 #include <pbd/pthread_utils.h>
28 #include <ardour/audioengine.h>
29 #include <ardour/buffer.h>
30 #include <ardour/port.h>
31 #include <ardour/session.h>
32 #include <ardour/cycle_timer.h>
33 #include <ardour/utils.h>
38 #include <ardour/timestamps.h>
43 using namespace ARDOUR;
46 nframes_t Port::_short_over_length = 2;
47 nframes_t Port::_long_over_length = 10;
49 AudioEngine::AudioEngine (string client_name)
53 session_remove_pending = false;
56 last_monitor_check = 0;
57 monitor_check_interval = max_frames;
58 _processed_frames = 0;
59 _freewheeling = false;
64 _freewheeling = false;
65 _freewheel_thread_registered = false;
70 if (connect_to_jack (client_name)) {
71 throw NoBackendAvailable ();
74 start_metering_thread();
78 AudioEngine::~AudioEngine ()
81 jack_client_close (_jack);
85 g_atomic_int_inc(&m_meter_exit);
90 _thread_init_callback (void *arg)
92 /* make sure that anybody who needs to know about this thread
96 PBD::ThreadCreatedWithRequestSize (pthread_self(), X_("Audioengine"), 4096);
100 AudioEngine::start ()
105 nframes_t blocksize = jack_get_buffer_size (_jack);
107 session->set_block_size (blocksize);
108 session->set_frame_rate (jack_get_sample_rate (_jack));
110 /* page in as much of the session process code as we
111 can before we really start running.
114 session->process (blocksize);
115 session->process (blocksize);
116 session->process (blocksize);
117 session->process (blocksize);
118 session->process (blocksize);
119 session->process (blocksize);
120 session->process (blocksize);
121 session->process (blocksize);
124 _processed_frames = 0;
125 last_monitor_check = 0;
127 jack_on_shutdown (_jack, halted, this);
128 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
129 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
130 jack_set_process_callback (_jack, _process_callback, this);
131 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
132 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
133 jack_set_xrun_callback (_jack, _xrun_callback, this);
134 jack_set_sync_callback (_jack, _jack_sync_callback, this);
135 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
137 if (Config->get_jack_time_master()) {
138 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
141 if (jack_activate (_jack) == 0) {
144 Running(); /* EMIT SIGNAL */
146 error << _("cannot activate JACK client") << endmsg;
150 return _running ? 0 : -1;
158 jack_deactivate (_jack);
159 Stopped(); /* EMIT SIGNAL */
162 return _running ? -1 : 0;
168 AudioEngine::get_sync_offset (nframes_t& offset) const
171 #ifdef HAVE_JACK_VIDEO_SUPPORT
175 (void) jack_transport_query (_jack, &pos);
177 if (pos.valid & JackVideoFrameOffset) {
178 offset = pos.video_offset;
188 AudioEngine::_jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
189 jack_position_t* pos, int new_position, void *arg)
191 static_cast<AudioEngine*> (arg)->jack_timebase_callback (state, nframes, pos, new_position);
195 AudioEngine::jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
196 jack_position_t* pos, int new_position)
198 if (session && session->synced_to_jack()) {
199 session->jack_timebase_callback (state, nframes, pos, new_position);
204 AudioEngine::_jack_sync_callback (jack_transport_state_t state, jack_position_t* pos, void* arg)
206 return static_cast<AudioEngine*> (arg)->jack_sync_callback (state, pos);
210 AudioEngine::jack_sync_callback (jack_transport_state_t state, jack_position_t* pos)
213 return session->jack_sync_callback (state, pos);
220 AudioEngine::_xrun_callback (void *arg)
222 static_cast<AudioEngine *>(arg)->Xrun (); /* EMIT SIGNAL */
227 AudioEngine::_graph_order_callback (void *arg)
229 static_cast<AudioEngine *>(arg)->GraphReordered (); /* EMIT SIGNAL */
234 AudioEngine::_process_callback (nframes_t nframes, void *arg)
236 return static_cast<AudioEngine *> (arg)->process_callback (nframes);
240 AudioEngine::_freewheel_callback (int onoff, void *arg)
242 static_cast<AudioEngine*>(arg)->_freewheeling = onoff;
246 AudioEngine::process_callback (nframes_t nframes)
248 // CycleTimer ct ("AudioEngine::process");
249 Glib::Mutex::Lock tm (_process_lock, Glib::TRY_LOCK);
250 nframes_t next_processed_frames;
252 /* handle wrap around of total frames counter */
254 if (max_frames - _processed_frames < nframes) {
255 next_processed_frames = nframes - (max_frames - _processed_frames);
257 next_processed_frames = _processed_frames + nframes;
260 if (!tm.locked() || session == 0) {
261 _processed_frames = next_processed_frames;
265 if (session_remove_pending) {
267 session_remove_pending = false;
268 session_removed.signal();
269 _processed_frames = next_processed_frames;
274 if (Freewheel (nframes)) {
275 _freewheeling = false;
276 jack_set_freewheel (_jack, false);
281 session->process (nframes);
284 /* we were zombified, maybe because a ladspa plugin took
285 too long, or jackd exited, or something like that.
288 _processed_frames = next_processed_frames;
292 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
294 boost::shared_ptr<Ports> p = ports.reader();
296 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
301 if (port->_last_monitor != (x = port->monitoring_input ())) {
302 port->_last_monitor = x;
303 /* XXX I think this is dangerous, due to
304 a likely mutex in the signal handlers ...
306 port->MonitorInputChanged (x); /* EMIT SIGNAL */
309 last_monitor_check = next_processed_frames;
312 _processed_frames = next_processed_frames;
317 AudioEngine::_sample_rate_callback (nframes_t nframes, void *arg)
319 return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
323 AudioEngine::jack_sample_rate_callback (nframes_t nframes)
325 _frame_rate = nframes;
326 _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
328 /* check for monitor input change every 1/10th of second */
330 monitor_check_interval = nframes / 10;
331 last_monitor_check = 0;
334 session->set_frame_rate (nframes);
337 SampleRateChanged (nframes); /* EMIT SIGNAL */
343 AudioEngine::_bufsize_callback (nframes_t nframes, void *arg)
345 return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
349 AudioEngine::jack_bufsize_callback (nframes_t nframes)
351 _buffer_size = nframes;
352 _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
353 last_monitor_check = 0;
355 boost::shared_ptr<Ports> p = ports.reader();
357 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
362 session->set_block_size (_buffer_size);
369 AudioEngine::start_metering_thread ()
371 if(m_meter_thread == 0) {
372 m_meter_thread = Glib::Thread::create (sigc::mem_fun(this, &AudioEngine::meter_thread), false);
377 AudioEngine::meter_thread ()
379 while (g_atomic_int_get(&m_meter_exit) != true) {
380 Glib::usleep (10000); /* 1/100th sec interval */
381 IO::update_meters ();
387 AudioEngine::set_session (Session *s)
395 AudioEngine::remove_session ()
397 Glib::Mutex::Lock lm (_process_lock);
402 session_remove_pending = true;
403 session_removed.wait(_process_lock);
417 AudioEngine::register_input_port (DataType type, const string& portname)
421 fatal << _("register input port called before engine was started") << endmsg;
428 jack_port_t *p = jack_port_register (_jack, portname.c_str(), type.to_jack_type(), JackPortIsInput, 0);
434 if ((newport = new Port (p)) != 0) {
435 RCUWriter<Ports> writer (ports);
436 boost::shared_ptr<Ports> ps = writer.get_copy ();
437 ps->insert (ps->begin(), newport);
438 /* writer goes out of scope, forces update */
445 _process_lock.unlock();
446 throw PortRegistrationFailure();
453 AudioEngine::register_output_port (DataType type, const string& portname)
457 fatal << _("register output port called before engine was started") << endmsg;
466 if ((p = jack_port_register (_jack, portname.c_str(),
467 type.to_jack_type(), JackPortIsOutput, 0)) != 0) {
472 RCUWriter<Ports> writer (ports);
473 boost::shared_ptr<Ports> ps = writer.get_copy ();
475 newport = new Port (p);
476 ps->insert (ps->begin(), newport);
478 /* writer goes out of scope, forces update */
485 _process_lock.unlock();
486 throw PortRegistrationFailure ();
494 AudioEngine::unregister_port (Port *port)
497 /* probably happening when the engine has been halted by JACK,
498 in which case, there is nothing we can do here.
505 int ret = jack_port_unregister (_jack, port->_port);
511 RCUWriter<Ports> writer (ports);
512 boost::shared_ptr<Ports> ps = writer.get_copy ();
514 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
521 /* writer goes out of scope, forces update */
524 remove_connections_for (port);
535 AudioEngine::connect (const string& source, const string& destination)
539 fatal << _("connect called before engine was started") << endmsg;
546 string s = make_port_name_non_relative (source);
547 string d = make_port_name_non_relative (destination);
549 int ret = jack_connect (_jack, s.c_str(), d.c_str());
552 pair<string,string> c (s, d);
553 port_connections.push_back (c);
555 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
556 source, s, destination, d)
564 AudioEngine::disconnect (const string& source, const string& destination)
568 fatal << _("disconnect called before engine was started") << endmsg;
575 string s = make_port_name_non_relative (source);
576 string d = make_port_name_non_relative (destination);
578 int ret = jack_disconnect (_jack, s.c_str(), d.c_str());
581 pair<string,string> c (s, d);
582 PortConnections::iterator i;
584 if ((i = find (port_connections.begin(), port_connections.end(), c)) != port_connections.end()) {
585 port_connections.erase (i);
593 AudioEngine::disconnect (Port *port)
597 fatal << _("disconnect called before engine was started") << endmsg;
604 int ret = jack_port_disconnect (_jack, port->_port);
607 remove_connections_for (port);
615 AudioEngine::frame_rate ()
618 if (_frame_rate == 0) {
619 return (_frame_rate = jack_get_sample_rate (_jack));
624 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
632 AudioEngine::frames_per_cycle ()
635 if (_buffer_size == 0) {
636 return (_buffer_size = jack_get_buffer_size (_jack));
641 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
649 AudioEngine::get_port_by_name (const string& portname, bool keep)
651 Glib::Mutex::Lock lm (_process_lock);
655 fatal << _("get_port_by_name() called before engine was started") << endmsg;
662 /* check to see if we have a Port for this name already */
664 boost::shared_ptr<Ports> pr = ports.reader();
666 for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
667 if (portname == (*i)->name()) {
674 if ((p = jack_port_by_name (_jack, portname.c_str())) != 0) {
675 Port *newport = new Port (p);
678 if (keep && newport->is_mine (_jack)) {
679 RCUWriter<Ports> writer (ports);
680 boost::shared_ptr<Ports> ps = writer.get_copy ();
681 ps->insert (newport);
682 /* writer goes out of scope, forces update */
695 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
699 fatal << _("get_ports called before engine was started") << endmsg;
705 return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
709 AudioEngine::halted (void *arg)
711 AudioEngine *ae = reinterpret_cast<AudioEngine *> (arg);
713 ae->_running = false;
716 ae->_buffer_size = 0;
719 ae->Halted(); /* EMIT SIGNAL */
723 AudioEngine::n_physical_outputs () const
732 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
737 for (i = 0; ports[i]; ++i);
744 AudioEngine::n_physical_inputs () const
753 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
758 for (i = 0; ports[i]; ++i);
765 AudioEngine::get_physical_inputs (vector<string>& ins)
774 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
779 for (i = 0; ports[i]; ++i) {
780 ins.push_back (ports[i]);
787 AudioEngine::get_physical_outputs (vector<string>& outs)
796 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
801 for (i = 0; ports[i]; ++i) {
802 outs.push_back (ports[i]);
809 AudioEngine::get_nth_physical (uint32_t n, int flag)
815 if (!_running || !_jack) {
817 fatal << _("get_nth_physical called before engine was started") << endmsg;
824 ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|flag);
830 for (i = 0; i < n && ports[i]; ++i);
836 free ((char *) ports);
842 AudioEngine::get_port_total_latency (const Port& port)
845 fatal << _("get_port_total_latency() called with no JACK client connection") << endmsg;
851 fatal << _("get_port_total_latency() called before engine was started") << endmsg;
856 return jack_port_get_total_latency (_jack, port._port);
860 AudioEngine::transport_stop ()
862 // cerr << "tell JACK to stop\n";
864 jack_transport_stop (_jack);
869 AudioEngine::transport_start ()
871 // cerr << "tell JACK to start\n";
873 jack_transport_start (_jack);
878 AudioEngine::transport_locate (nframes_t where)
880 // cerr << "tell JACK to locate to " << where << endl;
882 jack_transport_locate (_jack, where);
886 AudioEngine::TransportState
887 AudioEngine::transport_state ()
891 return (TransportState) jack_transport_query (_jack, &pos);
893 return (TransportState) JackTransportStopped;
898 AudioEngine::reset_timebase ()
901 if (Config->get_jack_time_master()) {
902 return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
904 return jack_release_timebase (_jack);
912 AudioEngine::freewheel (bool onoff)
917 _freewheel_thread_registered = false;
920 return jack_set_freewheel (_jack, onoff);
928 AudioEngine::remove_all_ports ()
930 /* process lock MUST be held */
933 boost::shared_ptr<Ports> p = ports.reader();
935 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
936 jack_port_unregister (_jack, (*i)->_port);
941 RCUWriter<Ports> writer (ports);
942 boost::shared_ptr<Ports> ps = writer.get_copy ();
946 port_connections.clear ();
950 AudioEngine::remove_connections_for (Port* port)
952 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ) {
953 PortConnections::iterator tmp;
958 if ((*i).first == port->name()) {
959 port_connections.erase (i);
966 #ifdef HAVE_JACK_CLIENT_OPEN
969 AudioEngine::connect_to_jack (string client_name)
971 jack_options_t options = JackNullOption;
972 jack_status_t status;
973 const char *server_name = NULL;
975 jack_client_name = client_name; /* might be reset below */
977 _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
981 if (status & JackServerFailed) {
982 error << _("Unable to connect to JACK server") << endmsg;
985 error << string_compose (_("Could not connect to JACK server as \"%1\""), jack_client_name) << endmsg;
989 if (status & JackServerStarted) {
990 info << _("JACK server started") << endmsg;
993 if (status & JackNameNotUnique) {
994 jack_client_name = jack_get_client_name (_jack);
1003 AudioEngine::connect_to_jack (string client_name)
1005 jack_client_name = client_name;
1007 if ((_jack = jack_client_new (client_name.c_str())) == NULL) {
1014 #endif /* HAVE_JACK_CLIENT_OPEN */
1017 AudioEngine::disconnect_from_jack ()
1023 if (jack_client_close (_jack)) {
1024 error << _("cannot shutdown connection to JACK") << endmsg;
1032 Stopped(); /* EMIT SIGNAL */
1040 AudioEngine::reconnect_to_jack ()
1043 disconnect_from_jack ();
1044 /* XXX give jackd a chance */
1045 Glib::usleep (250000);
1048 if (connect_to_jack (jack_client_name)) {
1049 error << _("failed to connect to JACK") << endmsg;
1055 boost::shared_ptr<Ports> p = ports.reader ();
1057 for (i = p->begin(); i != p->end(); ++i) {
1059 /* XXX hack hack hack */
1061 string long_name = (*i)->name();
1064 short_name = long_name.substr (long_name.find_last_of (':') + 1);
1066 if (((*i)->_port = jack_port_register (_jack, short_name.c_str(), (*i)->type(), (*i)->flags(), 0)) == 0) {
1067 error << string_compose (_("could not reregister %1"), (*i)->name()) << endmsg;
1074 if ((*i)->flags() & JackPortIsOutput) {
1075 (*i)->silence (jack_get_buffer_size (_jack), 0);
1079 if (i != p->end()) {
1081 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
1082 jack_port_unregister (_jack, (*i)->_port);
1089 nframes_t blocksize = jack_get_buffer_size (_jack);
1090 session->set_block_size (blocksize);
1091 session->set_frame_rate (jack_get_sample_rate (_jack));
1094 last_monitor_check = 0;
1096 jack_on_shutdown (_jack, halted, this);
1097 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
1098 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1099 jack_set_process_callback (_jack, _process_callback, this);
1100 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1101 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1102 jack_set_xrun_callback (_jack, _xrun_callback, this);
1103 jack_set_sync_callback (_jack, _jack_sync_callback, this);
1104 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1106 if (Config->get_jack_time_master()) {
1107 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1110 if (jack_activate (_jack) == 0) {
1117 /* re-establish connections */
1119 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ++i) {
1123 if ((err = jack_connect (_jack, (*i).first.c_str(), (*i).second.c_str())) != 0) {
1124 if (err != EEXIST) {
1125 error << string_compose (_("could not reconnect %1 and %2 (err = %3)"),
1126 (*i).first, (*i).second, err)
1132 Running (); /* EMIT SIGNAL*/
1138 AudioEngine::request_buffer_size (nframes_t nframes)
1141 int ret = jack_set_buffer_size (_jack, nframes);
1149 AudioEngine::update_total_latencies ()
1151 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1152 jack_recompute_total_latencies (_jack);
1157 AudioEngine::make_port_name_relative (string portname)
1159 string::size_type len;
1160 string::size_type n;
1162 len = portname.length();
1164 for (n = 0; n < len; ++n) {
1165 if (portname[n] == ':') {
1170 if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1171 return portname.substr (n+1);
1178 AudioEngine::make_port_name_non_relative (string portname)
1182 if (portname.find_first_of (':') != string::npos) {
1186 str = jack_client_name;