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 <pbd/pthread_utils.h>
27 #include <ardour/audioengine.h>
28 #include <ardour/port.h>
29 #include <ardour/session.h>
30 #include <ardour/cycle_timer.h>
31 #include <ardour/utils.h>
36 #include <ardour/timestamps.h>
41 using namespace ARDOUR;
43 jack_nframes_t Port::short_over_length = 2;
44 jack_nframes_t Port::long_over_length = 10;
46 AudioEngine::AudioEngine (string client_name)
48 pthread_cond_init (&session_removed, 0);
50 session_remove_pending = false;
53 last_monitor_check = 0;
54 monitor_check_interval = max_frames;
55 _processed_frames = 0;
56 _freewheeling = false;
61 _freewheeling = false;
62 _freewheel_thread_registered = false;
65 meter_thread_id = (pthread_t) 0;
67 if (connect_to_jack (client_name)) {
68 throw NoBackendAvailable ();
73 AudioEngine::~AudioEngine ()
76 jack_client_close (_jack);
79 if (meter_thread_id != (pthread_t) 0) {
80 pthread_cancel (meter_thread_id);
85 _thread_init_callback (void *arg)
87 /* make sure that anybody who needs to know about this thread
91 PBD::ThreadCreatedWithRequestSize (pthread_self(), X_("Audioengine"), 4096);
94 if (Config->get_use_vst()) {
101 AudioEngine::start ()
106 jack_nframes_t blocksize = jack_get_buffer_size (_jack);
108 session->set_block_size (blocksize);
109 session->set_frame_rate (jack_get_sample_rate (_jack));
111 /* page in as much of the session process code as we
112 can before we really start running.
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);
122 session->process (blocksize);
125 _processed_frames = 0;
126 last_monitor_check = 0;
128 jack_on_shutdown (_jack, halted, this);
129 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
130 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
131 jack_set_process_callback (_jack, _process_callback, this);
132 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
133 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
134 jack_set_xrun_callback (_jack, _xrun_callback, this);
135 jack_set_sync_callback (_jack, _jack_sync_callback, this);
136 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
138 if (Config->get_jack_time_master()) {
139 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
142 if (jack_activate (_jack) == 0) {
145 Running(); /* EMIT SIGNAL */
147 error << _("cannot activate JACK client") << endmsg;
151 return _running ? 0 : -1;
159 jack_deactivate (_jack);
160 Stopped(); /* EMIT SIGNAL */
163 return _running ? -1 : 0;
168 AudioEngine::_jack_timebase_callback (jack_transport_state_t state, jack_nframes_t nframes,
170 jack_position_t* pos, int new_position, void *arg)
172 static_cast<AudioEngine*> (arg)->jack_timebase_callback (state, nframes, pos, new_position);
176 AudioEngine::jack_timebase_callback (jack_transport_state_t state, jack_nframes_t nframes,
178 jack_position_t* pos, int new_position)
180 if (session && session->synced_to_jack()) {
181 session->jack_timebase_callback (state, nframes, pos, new_position);
186 AudioEngine::_jack_sync_callback (jack_transport_state_t state, jack_position_t* pos, void* arg)
188 return static_cast<AudioEngine*> (arg)->jack_sync_callback (state, pos);
192 AudioEngine::jack_sync_callback (jack_transport_state_t state, jack_position_t* pos)
195 return session->jack_sync_callback (state, pos);
202 AudioEngine::_xrun_callback (void *arg)
204 static_cast<AudioEngine *>(arg)->Xrun (); /* EMIT SIGNAL */
209 AudioEngine::_graph_order_callback (void *arg)
211 static_cast<AudioEngine *>(arg)->GraphReordered (); /* EMIT SIGNAL */
216 AudioEngine::_process_callback (jack_nframes_t nframes, void *arg)
218 return static_cast<AudioEngine *> (arg)->process_callback (nframes);
222 AudioEngine::_freewheel_callback (int onoff, void *arg)
224 static_cast<AudioEngine*>(arg)->_freewheeling = onoff;
228 AudioEngine::process_callback (jack_nframes_t nframes)
230 TentativeLockMonitor tm (_process_lock, __LINE__, __FILE__);
231 jack_nframes_t next_processed_frames;
233 /* handle wrap around of total frames counter */
235 if (max_frames - _processed_frames < nframes) {
236 next_processed_frames = nframes - (max_frames - _processed_frames);
238 next_processed_frames = _processed_frames + nframes;
241 if (!tm.locked() || session == 0) {
242 _processed_frames = next_processed_frames;
246 if (session_remove_pending) {
248 session_remove_pending = false;
249 pthread_cond_signal (&session_removed);
250 _processed_frames = next_processed_frames;
255 if (Freewheel (nframes)) {
256 _freewheeling = false;
257 jack_set_freewheel (_jack, false);
262 session->process (nframes);
265 /* we were zombified, maybe because a ladspa plugin took
266 too long, or jackd exited, or something like that.
269 _processed_frames = next_processed_frames;
275 if ((meter_interval > _buffer_size) && (last_meter_point + meter_interval < next_processed_frames)) {
277 last_meter_point = next_processed_frames;
280 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
281 for (Ports::iterator i = ports.begin(); i != ports.end(); ++i) {
286 if (port->last_monitor != (x = port->monitoring_input ())) {
287 port->last_monitor = x;
288 /* XXX I think this is dangerous, due to
289 a likely mutex in the signal handlers ...
291 port->MonitorInputChanged (x); /* EMIT SIGNAL */
294 last_monitor_check = next_processed_frames;
297 _processed_frames = next_processed_frames;
302 AudioEngine::_sample_rate_callback (jack_nframes_t nframes, void *arg)
304 return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
308 AudioEngine::jack_sample_rate_callback (jack_nframes_t nframes)
310 _frame_rate = nframes;
311 _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
313 /* check for monitor input change every 1/10th of second */
315 monitor_check_interval = nframes / 10;
316 last_monitor_check = 0;
318 meter_interval = nframes / 100;
319 last_meter_point = 0;
321 maybe_start_metering_thread ();
324 session->set_frame_rate (nframes);
327 SampleRateChanged (nframes); /* EMIT SIGNAL */
333 AudioEngine::_bufsize_callback (jack_nframes_t nframes, void *arg)
335 return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
339 AudioEngine::jack_bufsize_callback (jack_nframes_t nframes)
341 _buffer_size = nframes;
342 _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
343 last_monitor_check = 0;
345 for (Ports::iterator i = ports.begin(); i != ports.end(); ++i) {
350 session->set_block_size (_buffer_size);
353 maybe_start_metering_thread ();
359 AudioEngine::maybe_start_metering_thread ()
361 if (meter_interval == 0) {
365 if (_buffer_size == 0) {
369 if (meter_interval < _buffer_size) {
370 if (meter_thread_id != (pthread_t) 0) {
371 pthread_cancel (meter_thread_id);
373 pthread_create (&meter_thread_id, 0, _meter_thread, this);
378 AudioEngine::_meter_thread (void *arg)
380 return static_cast<AudioEngine*>(arg)->meter_thread ();
384 AudioEngine::meter_thread ()
386 PBD::ThreadCreated (pthread_self(), "Metering");
389 usleep (10000); /* 1/100th sec interval */
390 pthread_testcancel();
398 AudioEngine::set_session (Session *s)
406 AudioEngine::remove_session ()
408 LockMonitor lm (_process_lock, __LINE__, __FILE__);
413 session_remove_pending = true;
414 pthread_cond_wait (&session_removed, _process_lock.mutex());
428 AudioEngine::register_audio_input_port (const string& portname)
432 fatal << _("register audio input port called before engine was started") << endmsg;
439 jack_port_t *p = jack_port_register (_jack, portname.c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
444 if ((newport = new Port (p)) != 0) {
445 ports.insert (ports.begin(), newport);
451 pthread_mutex_unlock (_process_lock.mutex());
452 throw PortRegistrationFailure();
459 AudioEngine::register_audio_output_port (const string& portname)
463 fatal << _("register audio output port called before engine was started") << endmsg;
472 if ((p = jack_port_register (_jack, portname.c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0)) != 0) {
473 Port *newport = new Port (p);
474 ports.insert (ports.begin(), newport);
479 pthread_mutex_unlock (_process_lock.mutex());
480 throw PortRegistrationFailure ();
487 AudioEngine::unregister_port (Port *port)
490 /* probably happening when the engine has been halted by JACK,
491 in which case, there is nothing we can do here.
498 int ret = jack_port_unregister (_jack, port->port);
502 for (Ports::iterator i = ports.begin(); i != ports.end(); ++i) {
509 remove_connections_for (port);
520 AudioEngine::connect (const string& source, const string& destination)
524 fatal << _("connect called before engine was started") << endmsg;
531 string s = make_port_name_non_relative (source);
532 string d = make_port_name_non_relative (destination);
534 int ret = jack_connect (_jack, s.c_str(), d.c_str());
537 pair<string,string> c (s, d);
538 port_connections.push_back (c);
540 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
541 source, s, destination, d)
549 AudioEngine::disconnect (const string& source, const string& destination)
553 fatal << _("disconnect called before engine was started") << endmsg;
560 string s = make_port_name_non_relative (source);
561 string d = make_port_name_non_relative (destination);
563 int ret = jack_disconnect (_jack, s.c_str(), d.c_str());
566 pair<string,string> c (s, d);
567 PortConnections::iterator i;
569 if ((i = find (port_connections.begin(), port_connections.end(), c)) != port_connections.end()) {
570 port_connections.erase (i);
578 AudioEngine::disconnect (Port *port)
582 fatal << _("disconnect called before engine was started") << endmsg;
589 int ret = jack_port_disconnect (_jack, port->port);
592 remove_connections_for (port);
600 AudioEngine::frame_rate ()
603 if (_frame_rate == 0) {
604 return (_frame_rate = jack_get_sample_rate (_jack));
609 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
617 AudioEngine::frames_per_cycle ()
620 if (_buffer_size == 0) {
621 return (_buffer_size = jack_get_buffer_size (_jack));
626 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
634 AudioEngine::get_port_by_name (const string& portname, bool keep)
636 LockMonitor lm (_process_lock, __LINE__, __FILE__);
640 fatal << _("get_port_by_name() called before engine was started") << endmsg;
647 /* check to see if we have a Port for this name already */
649 for (Ports::iterator i = ports.begin(); i != ports.end(); ++i) {
650 if (portname == (*i)->name()) {
657 if ((p = jack_port_by_name (_jack, portname.c_str())) != 0) {
658 Port *newport = new Port (p);
659 if (keep && newport->is_mine (_jack)) {
660 ports.insert (newport);
669 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
673 fatal << _("get_ports called before engine was started") << endmsg;
679 return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
683 AudioEngine::halted (void *arg)
685 AudioEngine *ae = reinterpret_cast<AudioEngine *> (arg);
687 ae->_running = false;
690 ae->_buffer_size = 0;
693 ae->Halted(); /* EMIT SIGNAL */
697 AudioEngine::n_physical_outputs () const
706 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
711 for (i = 0; ports[i]; ++i);
718 AudioEngine::n_physical_inputs () const
727 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
732 for (i = 0; ports[i]; ++i);
740 AudioEngine::get_nth_physical (uint32_t n, int flag)
746 if (!_running || !_jack) {
748 fatal << _("get_nth_physical called before engine was started") << endmsg;
755 ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|flag);
761 for (i = 0; i < n && ports[i]; ++i);
767 free ((char *) ports);
773 AudioEngine::get_port_total_latency (const Port& port)
776 fatal << _("get_port_total_latency() called with no JACK client connection") << endmsg;
782 fatal << _("get_port_total_latency() called before engine was started") << endmsg;
787 return jack_port_get_total_latency (_jack, port.port);
791 AudioEngine::transport_stop ()
793 // cerr << "tell JACK to stop\n";
795 jack_transport_stop (_jack);
800 AudioEngine::transport_start ()
802 // cerr << "tell JACK to start\n";
804 jack_transport_start (_jack);
809 AudioEngine::transport_locate (jack_nframes_t where)
811 // cerr << "tell JACK to locate to " << where << endl;
813 jack_transport_locate (_jack, where);
817 AudioEngine::TransportState
818 AudioEngine::transport_state ()
822 return (TransportState) jack_transport_query (_jack, &pos);
824 return (TransportState) JackTransportStopped;
829 AudioEngine::reset_timebase ()
832 if (Config->get_jack_time_master()) {
833 return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
835 return jack_release_timebase (_jack);
843 AudioEngine::freewheel (bool onoff)
848 _freewheel_thread_registered = false;
851 return jack_set_freewheel (_jack, onoff);
859 AudioEngine::remove_all_ports ()
861 /* process lock MUST be held */
864 for (Ports::iterator i = ports.begin(); i != ports.end(); ++i) {
865 jack_port_unregister (_jack, (*i)->port);
870 port_connections.clear ();
874 AudioEngine::remove_connections_for (Port* port)
876 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ) {
877 PortConnections::iterator tmp;
882 if ((*i).first == port->name()) {
883 port_connections.erase (i);
890 #ifdef HAVE_JACK_CLIENT_OPEN
893 AudioEngine::connect_to_jack (string client_name)
895 jack_options_t options = JackNullOption;
896 jack_status_t status;
897 const char *server_name = NULL;
899 jack_client_name = client_name; /* might be reset below */
901 _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
905 if (status & JackServerFailed) {
906 error << _("Unable to connect to JACK server") << endmsg;
909 error << string_compose (_("Could not connect to JACK server as \"%1\""), jack_client_name) << endmsg;
913 if (status & JackServerStarted) {
914 info << _("JACK server started") << endmsg;
917 if (status & JackNameNotUnique) {
918 jack_client_name = jack_get_client_name (_jack);
927 AudioEngine::connect_to_jack (string client_name)
929 jack_client_name = client_name;
931 if ((_jack = jack_client_new (client_name.c_str())) == NULL) {
938 #endif /* HAVE_JACK_CLIENT_OPEN */
941 AudioEngine::disconnect_from_jack ()
947 if (jack_client_close (_jack)) {
948 error << _("cannot shutdown connection to JACK") << endmsg;
956 Stopped(); /* EMIT SIGNAL */
964 AudioEngine::reconnect_to_jack ()
967 disconnect_from_jack ();
968 /* XXX give jackd a chance */
972 if (connect_to_jack (jack_client_name)) {
973 error << _("failed to connect to JACK") << endmsg;
979 for (i = ports.begin(); i != ports.end(); ++i) {
981 /* XXX hack hack hack */
983 string long_name = (*i)->name();
986 short_name = long_name.substr (long_name.find_last_of (':') + 1);
988 if (((*i)->port = jack_port_register (_jack, short_name.c_str(), (*i)->type(), (*i)->flags(), 0)) == 0) {
989 error << string_compose (_("could not reregister %1"), (*i)->name()) << endmsg;
996 if ((*i)->flags() & JackPortIsOutput) {
997 (*i)->silence (jack_get_buffer_size (_jack), 0);
1001 if (i != ports.end()) {
1002 for (Ports::iterator i = ports.begin(); i != ports.end(); ++i) {
1003 jack_port_unregister (_jack, (*i)->port);
1010 jack_nframes_t blocksize = jack_get_buffer_size (_jack);
1011 session->set_block_size (blocksize);
1012 session->set_frame_rate (jack_get_sample_rate (_jack));
1015 last_monitor_check = 0;
1017 jack_on_shutdown (_jack, halted, this);
1018 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
1019 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1020 jack_set_process_callback (_jack, _process_callback, this);
1021 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1022 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1023 jack_set_xrun_callback (_jack, _xrun_callback, this);
1024 jack_set_sync_callback (_jack, _jack_sync_callback, this);
1025 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1027 if (Config->get_jack_time_master()) {
1028 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1031 if (jack_activate (_jack) == 0) {
1038 /* re-establish connections */
1040 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ++i) {
1044 if ((err = jack_connect (_jack, (*i).first.c_str(), (*i).second.c_str())) != 0) {
1045 if (err != EEXIST) {
1046 error << string_compose (_("could not reconnect %1 and %2 (err = %3)"),
1047 (*i).first, (*i).second, err)
1053 Running (); /* EMIT SIGNAL*/
1059 AudioEngine::request_buffer_size (jack_nframes_t nframes)
1062 int ret = jack_set_buffer_size (_jack, nframes);
1070 AudioEngine::update_total_latencies ()
1072 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1073 jack_recompute_total_latencies (_jack);
1078 AudioEngine::make_port_name_relative (string portname)
1080 string::size_type len;
1081 string::size_type n;
1083 len = portname.length();
1085 for (n = 0; n < len; ++n) {
1086 if (portname[n] == ':') {
1091 if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1092 return portname.substr (n+1);
1099 AudioEngine::make_port_name_non_relative (string portname)
1103 if (portname.find_first_of (':') != string::npos) {
1107 str = jack_client_name;