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>
27 #include <pbd/stacktrace.h>
29 #include <ardour/audioengine.h>
30 #include <ardour/buffer.h>
31 #include <ardour/port.h>
32 #include <ardour/session.h>
33 #include <ardour/cycle_timer.h>
34 #include <ardour/utils.h>
39 #include <ardour/timestamps.h>
44 using namespace ARDOUR;
47 gint AudioEngine::m_meter_exit;
50 ardour_jack_error (const char* msg)
52 error << "JACK: " << msg << endmsg;
55 AudioEngine::AudioEngine (string client_name)
59 session_remove_pending = false;
62 last_monitor_check = 0;
63 monitor_check_interval = max_frames;
64 _processed_frames = 0;
65 _freewheeling = false;
70 _freewheeling = false;
71 _freewheel_thread_registered = false;
74 g_atomic_int_set (&m_meter_exit, 0);
76 if (connect_to_jack (client_name)) {
77 throw NoBackendAvailable ();
80 start_metering_thread();
84 AudioEngine::~AudioEngine ()
87 Glib::Mutex::Lock tm (_process_lock);
88 session_removed.signal ();
91 jack_client_close (_jack);
94 stop_metering_thread ();
99 _thread_init_callback (void *arg)
101 /* make sure that anybody who needs to know about this thread
105 PBD::ThreadCreatedWithRequestSize (pthread_self(), X_("Audioengine"), 4096);
109 AudioEngine::start ()
114 nframes_t blocksize = jack_get_buffer_size (_jack);
116 session->set_block_size (blocksize);
117 session->set_frame_rate (jack_get_sample_rate (_jack));
119 /* page in as much of the session process code as we
120 can before we really start running.
123 session->process (blocksize);
124 session->process (blocksize);
125 session->process (blocksize);
126 session->process (blocksize);
127 session->process (blocksize);
128 session->process (blocksize);
129 session->process (blocksize);
130 session->process (blocksize);
133 _processed_frames = 0;
134 last_monitor_check = 0;
136 jack_on_shutdown (_jack, halted, this);
137 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
138 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
139 jack_set_process_callback (_jack, _process_callback, this);
140 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
141 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
142 jack_set_xrun_callback (_jack, _xrun_callback, this);
143 jack_set_sync_callback (_jack, _jack_sync_callback, this);
144 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
146 if (Config->get_jack_time_master()) {
147 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
150 if (jack_activate (_jack) == 0) {
153 Running(); /* EMIT SIGNAL */
155 error << _("cannot activate JACK client") << endmsg;
159 return _running ? 0 : -1;
163 AudioEngine::stop (bool forever)
168 jack_client_t* foo = _jack;
170 jack_client_close (foo);
171 stop_metering_thread ();
173 jack_deactivate (_jack);
175 Stopped(); /* EMIT SIGNAL */
178 return _running ? -1 : 0;
183 AudioEngine::get_sync_offset (nframes_t& offset) const
186 #ifdef HAVE_JACK_VIDEO_SUPPORT
190 (void) jack_transport_query (_jack, &pos);
192 if (pos.valid & JackVideoFrameOffset) {
193 offset = pos.video_offset;
203 AudioEngine::_jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
204 jack_position_t* pos, int new_position, void *arg)
206 static_cast<AudioEngine*> (arg)->jack_timebase_callback (state, nframes, pos, new_position);
210 AudioEngine::jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
211 jack_position_t* pos, int new_position)
213 if (_jack && session && session->synced_to_jack()) {
214 session->jack_timebase_callback (state, nframes, pos, new_position);
219 AudioEngine::_jack_sync_callback (jack_transport_state_t state, jack_position_t* pos, void* arg)
221 return static_cast<AudioEngine*> (arg)->jack_sync_callback (state, pos);
225 AudioEngine::jack_sync_callback (jack_transport_state_t state, jack_position_t* pos)
227 if (_jack && session) {
228 return session->jack_sync_callback (state, pos);
235 AudioEngine::_xrun_callback (void *arg)
237 AudioEngine* ae = static_cast<AudioEngine*> (arg);
239 ae->Xrun (); /* EMIT SIGNAL */
245 AudioEngine::_graph_order_callback (void *arg)
247 AudioEngine* ae = static_cast<AudioEngine*> (arg);
249 ae->GraphReordered (); /* EMIT SIGNAL */
255 AudioEngine::_process_callback (nframes_t nframes, void *arg)
257 return static_cast<AudioEngine *> (arg)->process_callback (nframes);
261 AudioEngine::_freewheel_callback (int onoff, void *arg)
263 static_cast<AudioEngine*>(arg)->_freewheeling = onoff;
267 AudioEngine::process_callback (nframes_t nframes)
269 // CycleTimer ct ("AudioEngine::process");
270 Glib::Mutex::Lock tm (_process_lock, Glib::TRY_LOCK);
271 nframes_t next_processed_frames;
273 /* handle wrap around of total frames counter */
275 if (max_frames - _processed_frames < nframes) {
276 next_processed_frames = nframes - (max_frames - _processed_frames);
278 next_processed_frames = _processed_frames + nframes;
281 if (!tm.locked() || session == 0) {
282 _processed_frames = next_processed_frames;
286 if (session_remove_pending) {
288 session_remove_pending = false;
289 session_removed.signal();
290 _processed_frames = next_processed_frames;
295 if (Freewheel (nframes)) {
296 cerr << "Freewheeling returned non-zero!\n";
297 _freewheeling = false;
298 jack_set_freewheel (_jack, false);
303 session->process (nframes);
306 /* we were zombified, maybe because a ladspa plugin took
307 too long, or jackd exited, or something like that.
310 _processed_frames = next_processed_frames;
314 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
316 boost::shared_ptr<Ports> p = ports.reader();
318 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
323 if (port->_last_monitor != (x = port->monitoring_input ())) {
324 port->_last_monitor = x;
325 /* XXX I think this is dangerous, due to
326 a likely mutex in the signal handlers ...
328 port->MonitorInputChanged (x); /* EMIT SIGNAL */
331 last_monitor_check = next_processed_frames;
334 _processed_frames = next_processed_frames;
339 AudioEngine::_sample_rate_callback (nframes_t nframes, void *arg)
341 return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
345 AudioEngine::jack_sample_rate_callback (nframes_t nframes)
347 _frame_rate = nframes;
348 _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
350 /* check for monitor input change every 1/10th of second */
352 monitor_check_interval = nframes / 10;
353 last_monitor_check = 0;
356 session->set_frame_rate (nframes);
359 SampleRateChanged (nframes); /* EMIT SIGNAL */
365 AudioEngine::_bufsize_callback (nframes_t nframes, void *arg)
367 return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
371 AudioEngine::jack_bufsize_callback (nframes_t nframes)
373 _buffer_size = nframes;
374 _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
375 last_monitor_check = 0;
377 boost::shared_ptr<Ports> p = ports.reader();
379 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
384 session->set_block_size (_buffer_size);
391 AudioEngine::stop_metering_thread ()
393 if (m_meter_thread) {
394 g_atomic_int_set (&m_meter_exit, 1);
395 m_meter_thread->join ();
401 AudioEngine::start_metering_thread ()
403 if (m_meter_thread == 0) {
404 m_meter_thread = Glib::Thread::create (sigc::mem_fun(this, &AudioEngine::meter_thread),
405 500000, true, true, Glib::THREAD_PRIORITY_NORMAL);
410 AudioEngine::meter_thread ()
413 Glib::usleep (10000); /* 1/100th sec interval */
414 if (g_atomic_int_get(&m_meter_exit)) {
417 IO::update_meters ();
422 AudioEngine::set_session (Session *s)
424 Glib::Mutex::Lock pl (_process_lock);
430 nframes_t blocksize = jack_get_buffer_size (_jack);
432 /* page in as much of the session process code as we
433 can before we really start running.
436 session->process (blocksize);
437 session->process (blocksize);
438 session->process (blocksize);
439 session->process (blocksize);
440 session->process (blocksize);
441 session->process (blocksize);
442 session->process (blocksize);
443 session->process (blocksize);
448 AudioEngine::remove_session ()
450 Glib::Mutex::Lock lm (_process_lock);
455 session_remove_pending = true;
456 session_removed.wait(_process_lock);
467 AudioEngine::register_input_port (DataType type, const string& portname)
471 fatal << _("register input port called before engine was started") << endmsg;
478 jack_port_t *p = jack_port_register (_jack, portname.c_str(), type.to_jack_type(), JackPortIsInput, 0);
484 if ((newport = new Port (p)) != 0) {
485 RCUWriter<Ports> writer (ports);
486 boost::shared_ptr<Ports> ps = writer.get_copy ();
487 ps->insert (ps->begin(), newport);
488 /* writer goes out of scope, forces update */
494 throw PortRegistrationFailure();
501 AudioEngine::register_output_port (DataType type, const string& portname)
505 fatal << _("register output port called before engine was started") << endmsg;
514 if ((p = jack_port_register (_jack, portname.c_str(),
515 type.to_jack_type(), JackPortIsOutput, 0)) != 0) {
520 RCUWriter<Ports> writer (ports);
521 boost::shared_ptr<Ports> ps = writer.get_copy ();
523 newport = new Port (p);
524 ps->insert (ps->begin(), newport);
526 /* writer goes out of scope, forces update */
532 throw PortRegistrationFailure ();
540 AudioEngine::unregister_port (Port *port)
543 /* probably happening when the engine has been halted by JACK,
544 in which case, there is nothing we can do here.
551 int ret = jack_port_unregister (_jack, port->_port);
557 RCUWriter<Ports> writer (ports);
558 boost::shared_ptr<Ports> ps = writer.get_copy ();
560 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
567 /* writer goes out of scope, forces update */
570 remove_connections_for (port);
581 AudioEngine::connect (const string& source, const string& destination)
585 fatal << _("connect called before engine was started") << endmsg;
592 string s = make_port_name_non_relative (source);
593 string d = make_port_name_non_relative (destination);
595 int ret = jack_connect (_jack, s.c_str(), d.c_str());
598 pair<string,string> c (s, d);
599 port_connections.push_back (c);
600 } else if (ret == EEXIST) {
601 error << string_compose(_("AudioEngine: connection already exists: %1 (%2) to %3 (%4)"),
602 source, s, destination, d)
605 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
606 source, s, destination, d)
614 AudioEngine::disconnect (const string& source, const string& destination)
618 fatal << _("disconnect 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 int ret = jack_disconnect (_jack, s.c_str(), d.c_str());
631 pair<string,string> c (s, d);
632 PortConnections::iterator i;
634 if ((i = find (port_connections.begin(), port_connections.end(), c)) != port_connections.end()) {
635 port_connections.erase (i);
643 AudioEngine::disconnect (Port *port)
647 fatal << _("disconnect called before engine was started") << endmsg;
654 int ret = jack_port_disconnect (_jack, port->_port);
657 remove_connections_for (port);
665 AudioEngine::frame_rate ()
668 if (_frame_rate == 0) {
669 return (_frame_rate = jack_get_sample_rate (_jack));
674 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
682 AudioEngine::frames_per_cycle ()
685 if (_buffer_size == 0) {
686 return (_buffer_size = jack_get_buffer_size (_jack));
691 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
699 AudioEngine::get_port_by_name (const string& portname, bool keep)
701 Glib::Mutex::Lock lm (_process_lock);
705 fatal << _("get_port_by_name() called before engine was started") << endmsg;
712 /* check to see if we have a Port for this name already */
714 boost::shared_ptr<Ports> pr = ports.reader();
716 for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
717 if (portname == (*i)->name()) {
724 if ((p = jack_port_by_name (_jack, portname.c_str())) != 0) {
725 Port *newport = new Port (p);
728 if (keep && newport->is_mine (_jack)) {
729 RCUWriter<Ports> writer (ports);
730 boost::shared_ptr<Ports> ps = writer.get_copy ();
731 ps->insert (newport);
732 /* writer goes out of scope, forces update */
745 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
749 fatal << _("get_ports called before engine was started") << endmsg;
755 return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
759 AudioEngine::halted (void *arg)
761 AudioEngine* ae = static_cast<AudioEngine *> (arg);
763 ae->_running = false;
764 ae->_buffer_size = 0;
767 ae->Halted(); /* EMIT SIGNAL */
771 AudioEngine::n_physical_outputs () const
780 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
785 for (i = 0; ports[i]; ++i);
792 AudioEngine::n_physical_inputs () const
801 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
806 for (i = 0; ports[i]; ++i);
813 AudioEngine::get_physical_inputs (vector<string>& ins)
822 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
827 for (i = 0; ports[i]; ++i) {
828 ins.push_back (ports[i]);
835 AudioEngine::get_physical_outputs (vector<string>& outs)
844 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
849 for (i = 0; ports[i]; ++i) {
850 outs.push_back (ports[i]);
857 AudioEngine::get_nth_physical (uint32_t n, int flag)
863 if (!_running || !_jack) {
865 fatal << _("get_nth_physical called before engine was started") << endmsg;
872 ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|flag);
878 for (i = 0; i < n && ports[i]; ++i);
884 free ((char *) ports);
890 AudioEngine::get_port_total_latency (const Port& port)
893 fatal << _("get_port_total_latency() called with no JACK client connection") << endmsg;
899 fatal << _("get_port_total_latency() called before engine was started") << endmsg;
904 return jack_port_get_total_latency (_jack, port._port);
908 AudioEngine::transport_stop ()
910 // cerr << "tell JACK to stop\n";
912 jack_transport_stop (_jack);
917 AudioEngine::transport_start ()
919 // cerr << "tell JACK to start\n";
921 jack_transport_start (_jack);
926 AudioEngine::transport_locate (nframes_t where)
928 // cerr << "tell JACK to locate to " << where << endl;
930 jack_transport_locate (_jack, where);
934 AudioEngine::TransportState
935 AudioEngine::transport_state ()
939 return (TransportState) jack_transport_query (_jack, &pos);
941 return (TransportState) JackTransportStopped;
946 AudioEngine::reset_timebase ()
949 if (Config->get_jack_time_master()) {
950 return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
952 return jack_release_timebase (_jack);
960 AudioEngine::freewheel (bool onoff)
965 _freewheel_thread_registered = false;
972 return jack_set_freewheel (_jack, onoff);
980 AudioEngine::remove_all_ports ()
982 /* process lock MUST be held */
985 boost::shared_ptr<Ports> p = ports.reader();
987 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
988 jack_port_unregister (_jack, (*i)->_port);
993 RCUWriter<Ports> writer (ports);
994 boost::shared_ptr<Ports> ps = writer.get_copy ();
998 port_connections.clear ();
1002 AudioEngine::remove_connections_for (Port* port)
1004 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ) {
1005 PortConnections::iterator tmp;
1010 if ((*i).first == port->name()) {
1011 port_connections.erase (i);
1018 #ifdef HAVE_JACK_CLIENT_OPEN
1021 AudioEngine::connect_to_jack (string client_name)
1023 jack_options_t options = JackNullOption;
1024 jack_status_t status;
1025 const char *server_name = NULL;
1027 jack_client_name = client_name; /* might be reset below */
1029 _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
1031 if (_jack == NULL) {
1033 if (status & JackServerFailed) {
1034 error << _("Unable to connect to JACK server") << endmsg;
1037 error << string_compose (_("Could not connect to JACK server as \"%1\""), jack_client_name) << endmsg;
1041 if (status & JackServerStarted) {
1042 info << _("JACK server started") << endmsg;
1045 if (status & JackNameNotUnique) {
1046 jack_client_name = jack_get_client_name (_jack);
1049 jack_set_error_function (ardour_jack_error);
1057 AudioEngine::connect_to_jack (string client_name)
1059 jack_client_name = client_name;
1061 if ((_jack = jack_client_new (client_name.c_str())) == NULL) {
1068 #endif /* HAVE_JACK_CLIENT_OPEN */
1071 AudioEngine::disconnect_from_jack ()
1077 jack_client_close (_jack);
1084 Stopped(); /* EMIT SIGNAL */
1092 AudioEngine::reconnect_to_jack ()
1095 disconnect_from_jack ();
1096 /* XXX give jackd a chance */
1097 Glib::usleep (250000);
1100 if (connect_to_jack (jack_client_name)) {
1101 error << _("failed to connect to JACK") << endmsg;
1107 boost::shared_ptr<Ports> p = ports.reader ();
1109 for (i = p->begin(); i != p->end(); ++i) {
1111 /* XXX hack hack hack */
1113 string long_name = (*i)->name();
1116 short_name = long_name.substr (long_name.find_last_of (':') + 1);
1118 if (((*i)->_port = jack_port_register (_jack, short_name.c_str(), (*i)->type(), (*i)->flags(), 0)) == 0) {
1119 error << string_compose (_("could not reregister %1"), (*i)->name()) << endmsg;
1126 if ((*i)->flags() & JackPortIsOutput) {
1127 (*i)->silence (jack_get_buffer_size (_jack), 0);
1131 if (i != p->end()) {
1133 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
1134 jack_port_unregister (_jack, (*i)->_port);
1141 nframes_t blocksize = jack_get_buffer_size (_jack);
1142 session->set_block_size (blocksize);
1143 session->set_frame_rate (jack_get_sample_rate (_jack));
1146 last_monitor_check = 0;
1148 jack_on_shutdown (_jack, halted, this);
1149 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
1150 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1151 jack_set_process_callback (_jack, _process_callback, this);
1152 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1153 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1154 jack_set_xrun_callback (_jack, _xrun_callback, this);
1155 jack_set_sync_callback (_jack, _jack_sync_callback, this);
1156 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1158 if (Config->get_jack_time_master()) {
1159 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1162 if (jack_activate (_jack) == 0) {
1169 /* re-establish connections */
1171 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ++i) {
1175 if ((err = jack_connect (_jack, (*i).first.c_str(), (*i).second.c_str())) != 0) {
1176 if (err != EEXIST) {
1177 error << string_compose (_("could not reconnect %1 and %2 (err = %3)"),
1178 (*i).first, (*i).second, err)
1184 Running (); /* EMIT SIGNAL*/
1190 AudioEngine::request_buffer_size (nframes_t nframes)
1194 if (nframes == jack_get_buffer_size (_jack)) {
1198 return jack_set_buffer_size (_jack, nframes);
1206 AudioEngine::update_total_latencies ()
1208 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1209 jack_recompute_total_latencies (_jack);
1214 AudioEngine::make_port_name_relative (string portname)
1216 string::size_type len;
1217 string::size_type n;
1219 len = portname.length();
1221 for (n = 0; n < len; ++n) {
1222 if (portname[n] == ':') {
1227 if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1228 return portname.substr (n+1);
1235 AudioEngine::make_port_name_non_relative (string portname)
1239 if (portname.find_first_of (':') != string::npos) {
1243 str = jack_client_name;
1251 AudioEngine::is_realtime () const
1254 return jack_is_realtime (_jack);