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/audio_port.h>
32 #include <ardour/midi_port.h>
33 #include <ardour/session.h>
34 #include <ardour/cycle_timer.h>
35 #include <ardour/utils.h>
40 #include <ardour/timestamps.h>
45 using namespace ARDOUR;
48 AudioEngine::AudioEngine (string client_name)
51 session_remove_pending = false;
54 last_monitor_check = 0;
55 monitor_check_interval = max_frames;
56 _processed_frames = 0;
57 _freewheeling = false;
62 _freewheeling = false;
63 _freewheel_thread_registered = false;
68 start_metering_thread();
70 if (connect_to_jack (client_name)) {
71 throw NoBackendAvailable ();
76 AudioEngine::~AudioEngine ()
79 jack_client_close (_jack);
83 g_atomic_int_inc(&m_meter_exit);
88 _thread_init_callback (void *arg)
90 /* make sure that anybody who needs to know about this thread
94 PBD::ThreadCreatedWithRequestSize (pthread_self(), X_("Audioengine"), 4096);
103 jack_nframes_t blocksize = jack_get_buffer_size (_jack);
105 session->set_block_size (blocksize);
106 session->set_frame_rate (jack_get_sample_rate (_jack));
108 /* page in as much of the session process code as we
109 can before we really start running.
112 session->process (blocksize);
113 session->process (blocksize);
114 session->process (blocksize);
115 session->process (blocksize);
116 session->process (blocksize);
117 session->process (blocksize);
118 session->process (blocksize);
119 session->process (blocksize);
122 _processed_frames = 0;
123 last_monitor_check = 0;
125 jack_on_shutdown (_jack, halted, this);
126 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
127 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
128 jack_set_process_callback (_jack, _process_callback, this);
129 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
130 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
131 jack_set_xrun_callback (_jack, _xrun_callback, this);
132 jack_set_sync_callback (_jack, _jack_sync_callback, this);
133 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
135 if (Config->get_jack_time_master()) {
136 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
139 if (jack_activate (_jack) == 0) {
142 Running(); /* EMIT SIGNAL */
144 error << _("cannot activate JACK client") << endmsg;
148 return _running ? 0 : -1;
156 jack_deactivate (_jack);
157 Stopped(); /* EMIT SIGNAL */
160 return _running ? -1 : 0;
165 AudioEngine::_jack_timebase_callback (jack_transport_state_t state, jack_nframes_t nframes,
167 jack_position_t* pos, int new_position, void *arg)
169 static_cast<AudioEngine*> (arg)->jack_timebase_callback (state, nframes, pos, new_position);
173 AudioEngine::jack_timebase_callback (jack_transport_state_t state, jack_nframes_t nframes,
175 jack_position_t* pos, int new_position)
177 if (session && session->synced_to_jack()) {
178 session->jack_timebase_callback (state, nframes, pos, new_position);
183 AudioEngine::_jack_sync_callback (jack_transport_state_t state, jack_position_t* pos, void* arg)
185 return static_cast<AudioEngine*> (arg)->jack_sync_callback (state, pos);
189 AudioEngine::jack_sync_callback (jack_transport_state_t state, jack_position_t* pos)
192 return session->jack_sync_callback (state, pos);
199 AudioEngine::_xrun_callback (void *arg)
201 static_cast<AudioEngine *>(arg)->Xrun (); /* EMIT SIGNAL */
206 AudioEngine::_graph_order_callback (void *arg)
208 static_cast<AudioEngine *>(arg)->GraphReordered (); /* EMIT SIGNAL */
213 AudioEngine::_process_callback (jack_nframes_t nframes, void *arg)
215 return static_cast<AudioEngine *> (arg)->process_callback (nframes);
219 AudioEngine::_freewheel_callback (int onoff, void *arg)
221 static_cast<AudioEngine*>(arg)->_freewheeling = onoff;
225 AudioEngine::process_callback (jack_nframes_t nframes)
227 // CycleTimer ct ("AudioEngine::process");
228 Glib::Mutex::Lock tm (_process_lock, Glib::TRY_LOCK);
229 jack_nframes_t next_processed_frames;
231 /* handle wrap around of total frames counter */
233 if (max_frames - _processed_frames < nframes) {
234 next_processed_frames = nframes - (max_frames - _processed_frames);
236 next_processed_frames = _processed_frames + nframes;
239 if (!tm.locked() || session == 0) {
240 _processed_frames = next_processed_frames;
244 if (session_remove_pending) {
246 session_remove_pending = false;
247 session_removed.signal();
248 _processed_frames = next_processed_frames;
253 if (Freewheel (nframes)) {
254 _freewheeling = false;
255 jack_set_freewheel (_jack, false);
260 // Prepare ports (ie read data if necessary)
261 for (Ports::iterator i = ports.begin(); i != ports.end(); ++i)
262 (*i)->cycle_start(nframes);
264 session->process (nframes);
267 /* we were zombified, maybe because a ladspa plugin took
268 too long, or jackd exited, or something like that.
271 _processed_frames = next_processed_frames;
275 // Finalize ports (ie write data if necessary)
276 for (Ports::iterator i = ports.begin(); i != ports.end(); ++i)
279 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
280 for (Ports::iterator i = ports.begin(); i != ports.end(); ++i) {
285 if (port->_last_monitor != (x = port->monitoring_input ())) {
286 port->_last_monitor = x;
287 /* XXX I think this is dangerous, due to
288 a likely mutex in the signal handlers ...
290 port->MonitorInputChanged (x); /* EMIT SIGNAL */
293 last_monitor_check = next_processed_frames;
296 _processed_frames = next_processed_frames;
301 AudioEngine::_sample_rate_callback (jack_nframes_t nframes, void *arg)
303 return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
307 AudioEngine::jack_sample_rate_callback (jack_nframes_t nframes)
309 _frame_rate = nframes;
310 _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
312 /* check for monitor input change every 1/10th of second */
314 monitor_check_interval = nframes / 10;
315 last_monitor_check = 0;
318 session->set_frame_rate (nframes);
321 SampleRateChanged (nframes); /* EMIT SIGNAL */
327 AudioEngine::_bufsize_callback (jack_nframes_t nframes, void *arg)
329 return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
333 AudioEngine::jack_bufsize_callback (jack_nframes_t nframes)
335 _buffer_size = nframes;
336 _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
337 last_monitor_check = 0;
339 for (Ports::iterator i = ports.begin(); i != ports.end(); ++i) {
344 session->set_block_size (_buffer_size);
351 AudioEngine::start_metering_thread ()
353 if(m_meter_thread == 0) {
354 m_meter_thread = Glib::Thread::create (sigc::mem_fun(this, &AudioEngine::meter_thread), false);
359 AudioEngine::meter_thread ()
361 while (g_atomic_int_get(&m_meter_exit) != true) {
362 Glib::usleep (10000); /* 1/100th sec interval */
363 IO::update_meters ();
369 AudioEngine::set_session (Session *s)
377 AudioEngine::remove_session ()
379 Glib::Mutex::Lock lm (_process_lock);
384 session_remove_pending = true;
385 session_removed.wait(_process_lock);
399 AudioEngine::register_input_port (DataType type, const string& portname)
403 fatal << _("register input port called before engine was started") << endmsg;
410 jack_port_t *p = jack_port_register (_jack, portname.c_str(),
411 type.to_jack_type(), JackPortIsInput, 0);
417 if (type == DataType::AUDIO)
418 newport = new AudioPort (p);
419 else if (type == DataType::MIDI)
420 newport = new MidiPort (p);
423 ports.insert (ports.begin(), newport);
429 _process_lock.unlock();
430 throw PortRegistrationFailure();
437 AudioEngine::register_output_port (DataType type, const string& portname)
441 fatal << _("register output port called before engine was started") << endmsg;
450 if ((p = jack_port_register (_jack, portname.c_str(),
451 type.to_jack_type(), JackPortIsOutput, 0)) != 0) {
452 Port *newport = NULL;
454 if (type == DataType::AUDIO)
455 newport = new AudioPort (p);
456 else if (type == DataType::MIDI)
457 newport = new MidiPort (p);
460 ports.insert (ports.begin(), newport);
466 _process_lock.unlock();
467 throw PortRegistrationFailure ();
475 AudioEngine::unregister_port (Port *port)
478 /* probably happening when the engine has been halted by JACK,
479 in which case, there is nothing we can do here.
486 int ret = jack_port_unregister (_jack, port->_port);
490 for (Ports::iterator i = ports.begin(); i != ports.end(); ++i) {
497 remove_connections_for (port);
508 AudioEngine::connect (const string& source, const string& destination)
512 fatal << _("connect called before engine was started") << endmsg;
519 string s = make_port_name_non_relative (source);
520 string d = make_port_name_non_relative (destination);
522 int ret = jack_connect (_jack, s.c_str(), d.c_str());
525 pair<string,string> c (s, d);
526 port_connections.push_back (c);
528 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
529 source, s, destination, d)
537 AudioEngine::disconnect (const string& source, const string& destination)
541 fatal << _("disconnect called before engine was started") << endmsg;
548 string s = make_port_name_non_relative (source);
549 string d = make_port_name_non_relative (destination);
551 int ret = jack_disconnect (_jack, s.c_str(), d.c_str());
554 pair<string,string> c (s, d);
555 PortConnections::iterator i;
557 if ((i = find (port_connections.begin(), port_connections.end(), c)) != port_connections.end()) {
558 port_connections.erase (i);
566 AudioEngine::disconnect (Port *port)
570 fatal << _("disconnect called before engine was started") << endmsg;
577 int ret = jack_port_disconnect (_jack, port->_port);
580 remove_connections_for (port);
588 AudioEngine::frame_rate ()
591 if (_frame_rate == 0) {
592 return (_frame_rate = jack_get_sample_rate (_jack));
597 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
605 AudioEngine::frames_per_cycle ()
608 if (_buffer_size == 0) {
609 return (_buffer_size = jack_get_buffer_size (_jack));
614 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
621 /** Get a port by name.
622 * Note this can return NULL, it will NOT create a port if it is not found (any more).
625 AudioEngine::get_port_by_name (const string& portname, bool keep)
627 Glib::Mutex::Lock lm (_process_lock);
631 fatal << _("get_port_by_name() called before engine was started") << endmsg;
638 for (Ports::iterator i = ports.begin(); i != ports.end(); ++i) {
639 if (portname == (*i)->name()) {
648 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
652 fatal << _("get_ports called before engine was started") << endmsg;
658 return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
662 AudioEngine::halted (void *arg)
664 AudioEngine *ae = reinterpret_cast<AudioEngine *> (arg);
666 ae->_running = false;
669 ae->_buffer_size = 0;
672 ae->Halted(); /* EMIT SIGNAL */
676 AudioEngine::n_physical_outputs () const
685 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
690 for (i = 0; ports[i]; ++i);
697 AudioEngine::n_physical_inputs () const
706 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
711 for (i = 0; ports[i]; ++i);
718 AudioEngine::get_nth_physical (DataType type, uint32_t n, int flag)
724 assert(type != DataType::NIL);
726 if (!_running || !_jack) {
728 fatal << _("get_nth_physical called before engine was started") << endmsg;
735 ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|flag);
741 for (i = 0; i < n && ports[i]; ++i);
747 free ((char *) ports);
753 AudioEngine::get_port_total_latency (const Port& port)
756 fatal << _("get_port_total_latency() called with no JACK client connection") << endmsg;
762 fatal << _("get_port_total_latency() called before engine was started") << endmsg;
767 return jack_port_get_total_latency (_jack, port._port);
771 AudioEngine::transport_stop ()
773 // cerr << "tell JACK to stop\n";
775 jack_transport_stop (_jack);
780 AudioEngine::transport_start ()
782 // cerr << "tell JACK to start\n";
784 jack_transport_start (_jack);
789 AudioEngine::transport_locate (jack_nframes_t where)
791 // cerr << "tell JACK to locate to " << where << endl;
793 jack_transport_locate (_jack, where);
797 AudioEngine::TransportState
798 AudioEngine::transport_state ()
802 return (TransportState) jack_transport_query (_jack, &pos);
804 return (TransportState) JackTransportStopped;
809 AudioEngine::reset_timebase ()
812 if (Config->get_jack_time_master()) {
813 return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
815 return jack_release_timebase (_jack);
823 AudioEngine::freewheel (bool onoff)
828 _freewheel_thread_registered = false;
831 return jack_set_freewheel (_jack, onoff);
839 AudioEngine::remove_all_ports ()
841 /* process lock MUST be held */
844 for (Ports::iterator i = ports.begin(); i != ports.end(); ++i) {
845 jack_port_unregister (_jack, (*i)->_port);
850 port_connections.clear ();
854 AudioEngine::remove_connections_for (Port* port)
856 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ) {
857 PortConnections::iterator tmp;
862 if ((*i).first == port->name()) {
863 port_connections.erase (i);
870 #ifdef HAVE_JACK_CLIENT_OPEN
873 AudioEngine::connect_to_jack (string client_name)
875 jack_options_t options = JackNullOption;
876 jack_status_t status;
877 const char *server_name = NULL;
879 jack_client_name = client_name; /* might be reset below */
881 _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
885 if (status & JackServerFailed) {
886 error << _("Unable to connect to JACK server") << endmsg;
889 error << string_compose (_("Could not connect to JACK server as \"%1\""), jack_client_name) << endmsg;
893 if (status & JackServerStarted) {
894 info << _("JACK server started") << endmsg;
897 if (status & JackNameNotUnique) {
898 jack_client_name = jack_get_client_name (_jack);
907 AudioEngine::connect_to_jack (string client_name)
909 jack_client_name = client_name;
911 if ((_jack = jack_client_new (client_name.c_str())) == NULL) {
918 #endif /* HAVE_JACK_CLIENT_OPEN */
921 AudioEngine::disconnect_from_jack ()
927 if (jack_client_close (_jack)) {
928 error << _("cannot shutdown connection to JACK") << endmsg;
936 Stopped(); /* EMIT SIGNAL */
944 AudioEngine::reconnect_to_jack ()
947 disconnect_from_jack ();
948 /* XXX give jackd a chance */
949 Glib::usleep (250000);
952 if (connect_to_jack (jack_client_name)) {
953 error << _("failed to connect to JACK") << endmsg;
959 for (i = ports.begin(); i != ports.end(); ++i) {
961 /* XXX hack hack hack */
963 string long_name = (*i)->name();
966 short_name = long_name.substr (long_name.find_last_of (':') + 1);
968 if (((*i)->_port = jack_port_register (_jack, short_name.c_str(), (*i)->type().to_jack_type(), (*i)->flags(), 0)) == 0) {
969 error << string_compose (_("could not reregister %1"), (*i)->name()) << endmsg;
976 if ((*i)->flags() & JackPortIsOutput) {
977 (*i)->silence (jack_get_buffer_size (_jack), 0);
981 if (i != ports.end()) {
982 for (Ports::iterator i = ports.begin(); i != ports.end(); ++i) {
983 jack_port_unregister (_jack, (*i)->_port);
990 jack_nframes_t blocksize = jack_get_buffer_size (_jack);
991 session->set_block_size (blocksize);
992 session->set_frame_rate (jack_get_sample_rate (_jack));
995 last_monitor_check = 0;
997 jack_on_shutdown (_jack, halted, this);
998 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
999 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1000 jack_set_process_callback (_jack, _process_callback, this);
1001 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1002 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1003 jack_set_xrun_callback (_jack, _xrun_callback, this);
1004 jack_set_sync_callback (_jack, _jack_sync_callback, this);
1005 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1007 if (Config->get_jack_time_master()) {
1008 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1011 if (jack_activate (_jack) == 0) {
1018 /* re-establish connections */
1020 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ++i) {
1024 if ((err = jack_connect (_jack, (*i).first.c_str(), (*i).second.c_str())) != 0) {
1025 if (err != EEXIST) {
1026 error << string_compose (_("could not reconnect %1 and %2 (err = %3)"),
1027 (*i).first, (*i).second, err)
1033 Running (); /* EMIT SIGNAL*/
1039 AudioEngine::request_buffer_size (jack_nframes_t nframes)
1042 int ret = jack_set_buffer_size (_jack, nframes);
1050 AudioEngine::update_total_latencies ()
1052 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1053 jack_recompute_total_latencies (_jack);
1058 AudioEngine::make_port_name_relative (string portname)
1060 string::size_type len;
1061 string::size_type n;
1063 len = portname.length();
1065 for (n = 0; n < len; ++n) {
1066 if (portname[n] == ':') {
1071 if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1072 return portname.substr (n+1);
1079 AudioEngine::make_port_name_non_relative (string portname)
1083 if (portname.find_first_of (':') != string::npos) {
1087 str = jack_client_name;