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/unknown_type.h>
30 #include <ardour/audioengine.h>
31 #include <ardour/buffer.h>
32 #include <ardour/port.h>
33 #include <ardour/audio_port.h>
34 #include <ardour/midi_port.h>
35 #include <ardour/session.h>
36 #include <ardour/cycle_timer.h>
37 #include <ardour/utils.h>
42 #include <ardour/timestamps.h>
47 using namespace ARDOUR;
50 gint AudioEngine::m_meter_exit;
52 AudioEngine::AudioEngine (string client_name)
56 session_remove_pending = false;
59 last_monitor_check = 0;
60 monitor_check_interval = max_frames;
61 _processed_frames = 0;
62 _freewheeling = false;
67 _freewheeling = false;
68 _freewheel_thread_registered = false;
71 g_atomic_int_set (&m_meter_exit, 0);
73 if (connect_to_jack (client_name)) {
74 throw NoBackendAvailable ();
77 start_metering_thread();
81 AudioEngine::~AudioEngine ()
84 jack_client_close (_jack);
87 stop_metering_thread ();
91 _thread_init_callback (void *arg)
93 /* make sure that anybody who needs to know about this thread
97 PBD::ThreadCreatedWithRequestSize (pthread_self(), X_("Audioengine"), 4096);
101 AudioEngine::start ()
106 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;
169 AudioEngine::get_sync_offset (nframes_t& offset) const
172 #ifdef HAVE_JACK_VIDEO_SUPPORT
176 (void) jack_transport_query (_jack, &pos);
178 if (pos.valid & JackVideoFrameOffset) {
179 offset = pos.video_offset;
189 AudioEngine::_jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
190 jack_position_t* pos, int new_position, void *arg)
192 static_cast<AudioEngine*> (arg)->jack_timebase_callback (state, nframes, pos, new_position);
196 AudioEngine::jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
197 jack_position_t* pos, int new_position)
199 if (session && session->synced_to_jack()) {
200 session->jack_timebase_callback (state, nframes, pos, new_position);
205 AudioEngine::_jack_sync_callback (jack_transport_state_t state, jack_position_t* pos, void* arg)
207 return static_cast<AudioEngine*> (arg)->jack_sync_callback (state, pos);
211 AudioEngine::jack_sync_callback (jack_transport_state_t state, jack_position_t* pos)
214 return session->jack_sync_callback (state, pos);
221 AudioEngine::_xrun_callback (void *arg)
223 static_cast<AudioEngine *>(arg)->Xrun (); /* EMIT SIGNAL */
228 AudioEngine::_graph_order_callback (void *arg)
230 static_cast<AudioEngine *>(arg)->GraphReordered (); /* EMIT SIGNAL */
235 AudioEngine::_process_callback (nframes_t nframes, void *arg)
237 return static_cast<AudioEngine *> (arg)->process_callback (nframes);
241 AudioEngine::_freewheel_callback (int onoff, void *arg)
243 static_cast<AudioEngine*>(arg)->_freewheeling = onoff;
247 AudioEngine::process_callback (nframes_t nframes)
249 // CycleTimer ct ("AudioEngine::process");
250 Glib::Mutex::Lock tm (_process_lock, Glib::TRY_LOCK);
251 nframes_t next_processed_frames;
253 /* handle wrap around of total frames counter */
255 if (max_frames - _processed_frames < nframes) {
256 next_processed_frames = nframes - (max_frames - _processed_frames);
258 next_processed_frames = _processed_frames + nframes;
261 if (!tm.locked() || session == 0) {
262 _processed_frames = next_processed_frames;
266 if (session_remove_pending) {
268 session_remove_pending = false;
269 session_removed.signal();
270 _processed_frames = next_processed_frames;
275 if (Freewheel (nframes)) {
276 _freewheeling = false;
277 jack_set_freewheel (_jack, false);
282 boost::shared_ptr<Ports> p = ports.reader();
284 // Prepare ports (ie read data if necessary)
285 for (Ports::iterator i = p->begin(); i != p->end(); ++i)
286 (*i)->cycle_start(nframes);
288 session->process (nframes);
291 /* we were zombified, maybe because a ladspa plugin took
292 too long, or jackd exited, or something like that.
295 _processed_frames = next_processed_frames;
299 // Finalize ports (ie write data if necessary)
300 for (Ports::iterator i = p->begin(); i != p->end(); ++i)
303 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
305 boost::shared_ptr<Ports> p = ports.reader();
307 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
312 if (port->_last_monitor != (x = port->monitoring_input ())) {
313 port->_last_monitor = x;
314 /* XXX I think this is dangerous, due to
315 a likely mutex in the signal handlers ...
317 port->MonitorInputChanged (x); /* EMIT SIGNAL */
320 last_monitor_check = next_processed_frames;
323 _processed_frames = next_processed_frames;
328 AudioEngine::_sample_rate_callback (nframes_t nframes, void *arg)
330 return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
334 AudioEngine::jack_sample_rate_callback (nframes_t nframes)
336 _frame_rate = nframes;
337 _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
339 /* check for monitor input change every 1/10th of second */
341 monitor_check_interval = nframes / 10;
342 last_monitor_check = 0;
345 session->set_frame_rate (nframes);
348 SampleRateChanged (nframes); /* EMIT SIGNAL */
354 AudioEngine::_bufsize_callback (nframes_t nframes, void *arg)
356 return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
360 AudioEngine::jack_bufsize_callback (nframes_t nframes)
362 _buffer_size = nframes;
363 _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
364 last_monitor_check = 0;
366 boost::shared_ptr<Ports> p = ports.reader();
368 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
373 session->set_block_size (_buffer_size);
380 AudioEngine::stop_metering_thread ()
382 if (m_meter_thread) {
383 g_atomic_int_set (&m_meter_exit, 1);
385 m_meter_thread->join ();
390 AudioEngine::start_metering_thread ()
392 if (m_meter_thread == 0) {
393 m_meter_thread = Glib::Thread::create (sigc::mem_fun(this, &AudioEngine::meter_thread), true);
398 AudioEngine::meter_thread ()
400 while (g_atomic_int_get(&m_meter_exit) != true) {
401 Glib::usleep (10000); /* 1/100th sec interval */
402 IO::update_meters ();
407 AudioEngine::set_session (Session *s)
415 AudioEngine::remove_session ()
417 Glib::Mutex::Lock lm (_process_lock);
422 session_remove_pending = true;
423 session_removed.wait(_process_lock);
437 AudioEngine::register_input_port (DataType type, const string& portname)
441 fatal << _("register input port called before engine was started") << endmsg;
448 jack_port_t *p = jack_port_register (_jack, portname.c_str(), type.to_jack_type(), JackPortIsInput, 0);
454 if (type == DataType::AUDIO)
455 newport = new AudioPort (p);
456 else if (type == DataType::MIDI)
457 newport = new MidiPort (p);
459 throw unknown_type();
462 RCUWriter<Ports> writer (ports);
463 boost::shared_ptr<Ports> ps = writer.get_copy ();
464 ps->insert (ps->begin(), newport);
465 /* writer goes out of scope, forces update */
472 _process_lock.unlock();
473 throw PortRegistrationFailure();
480 AudioEngine::register_output_port (DataType type, const string& portname)
484 fatal << _("register output port called before engine was started") << endmsg;
493 if ((p = jack_port_register (_jack, portname.c_str(),
494 type.to_jack_type(), JackPortIsOutput, 0)) != 0) {
498 if (type == DataType::AUDIO)
499 newport = new AudioPort (p);
500 else if (type == DataType::MIDI)
501 newport = new MidiPort (p);
503 throw unknown_type ();
506 RCUWriter<Ports> writer (ports);
507 boost::shared_ptr<Ports> ps = writer.get_copy ();
508 ps->insert (ps->begin(), newport);
509 /* writer goes out of scope, forces update */
516 _process_lock.unlock();
517 throw PortRegistrationFailure ();
525 AudioEngine::unregister_port (Port& port)
528 /* probably happening when the engine has been halted by JACK,
529 in which case, there is nothing we can do here.
534 int ret = jack_port_unregister (_jack, port._port);
540 RCUWriter<Ports> writer (ports);
541 boost::shared_ptr<Ports> ps = writer.get_copy ();
543 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
550 /* writer goes out of scope, forces update */
553 remove_connections_for (port);
560 AudioEngine::connect (const string& source, const string& destination)
564 fatal << _("connect called before engine was started") << endmsg;
571 string s = make_port_name_non_relative (source);
572 string d = make_port_name_non_relative (destination);
574 int ret = jack_connect (_jack, s.c_str(), d.c_str());
577 pair<string,string> c (s, d);
578 port_connections.push_back (c);
579 } else if (ret == EEXIST) {
580 error << string_compose(_("AudioEngine: connection already exists: %1 (%2) to %3 (%4)"),
581 source, s, destination, d)
584 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
585 source, s, destination, d)
593 AudioEngine::disconnect (const string& source, const string& destination)
597 fatal << _("disconnect called before engine was started") << endmsg;
604 string s = make_port_name_non_relative (source);
605 string d = make_port_name_non_relative (destination);
607 int ret = jack_disconnect (_jack, s.c_str(), d.c_str());
610 pair<string,string> c (s, d);
611 PortConnections::iterator i;
613 if ((i = find (port_connections.begin(), port_connections.end(), c)) != port_connections.end()) {
614 port_connections.erase (i);
622 AudioEngine::disconnect (Port& port)
626 fatal << _("disconnect called before engine was started") << endmsg;
633 int ret = jack_port_disconnect (_jack, port._port);
636 remove_connections_for (port);
644 AudioEngine::frame_rate ()
647 if (_frame_rate == 0) {
648 return (_frame_rate = jack_get_sample_rate (_jack));
653 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
661 AudioEngine::frames_per_cycle ()
664 if (_buffer_size == 0) {
665 return (_buffer_size = jack_get_buffer_size (_jack));
670 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
677 /** Get a port by name.
678 * Note this can return NULL, it will NOT create a port if it is not found (any more).
681 AudioEngine::get_port_by_name (const string& portname, bool keep)
683 Glib::Mutex::Lock lm (_process_lock);
687 fatal << _("get_port_by_name() called before engine was started") << endmsg;
694 boost::shared_ptr<Ports> pr = ports.reader();
696 for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
697 if (portname == (*i)->name()) {
706 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
710 fatal << _("get_ports called before engine was started") << endmsg;
716 return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
720 AudioEngine::halted (void *arg)
722 AudioEngine *ae = reinterpret_cast<AudioEngine *> (arg);
724 ae->_running = false;
727 ae->_buffer_size = 0;
730 ae->Halted(); /* EMIT SIGNAL */
734 AudioEngine::n_physical_outputs () const
743 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
748 for (i = 0; ports[i]; ++i);
755 AudioEngine::n_physical_inputs () const
764 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
769 for (i = 0; ports[i]; ++i);
776 AudioEngine::get_physical_inputs (vector<string>& ins)
785 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
790 for (i = 0; ports[i]; ++i) {
791 ins.push_back (ports[i]);
798 AudioEngine::get_physical_outputs (vector<string>& outs)
807 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
812 for (i = 0; ports[i]; ++i) {
813 outs.push_back (ports[i]);
820 AudioEngine::get_nth_physical (DataType type, uint32_t n, int flag)
826 assert(type != DataType::NIL);
828 if (!_running || !_jack) {
830 fatal << _("get_nth_physical called before engine was started") << endmsg;
837 ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|flag);
843 for (i = 0; i < n && ports[i]; ++i);
849 free ((char *) ports);
855 AudioEngine::get_port_total_latency (const Port& port)
858 fatal << _("get_port_total_latency() called with no JACK client connection") << endmsg;
864 fatal << _("get_port_total_latency() called before engine was started") << endmsg;
869 return jack_port_get_total_latency (_jack, port._port);
873 AudioEngine::transport_stop ()
875 // cerr << "tell JACK to stop\n";
877 jack_transport_stop (_jack);
882 AudioEngine::transport_start ()
884 // cerr << "tell JACK to start\n";
886 jack_transport_start (_jack);
891 AudioEngine::transport_locate (nframes_t where)
893 // cerr << "tell JACK to locate to " << where << endl;
895 jack_transport_locate (_jack, where);
899 AudioEngine::TransportState
900 AudioEngine::transport_state ()
904 return (TransportState) jack_transport_query (_jack, &pos);
906 return (TransportState) JackTransportStopped;
911 AudioEngine::reset_timebase ()
914 if (Config->get_jack_time_master()) {
915 return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
917 return jack_release_timebase (_jack);
925 AudioEngine::freewheel (bool onoff)
930 _freewheel_thread_registered = false;
933 return jack_set_freewheel (_jack, onoff);
941 AudioEngine::remove_all_ports ()
943 /* process lock MUST be held */
946 boost::shared_ptr<Ports> p = ports.reader();
948 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
949 jack_port_unregister (_jack, (*i)->_port);
954 RCUWriter<Ports> writer (ports);
955 boost::shared_ptr<Ports> ps = writer.get_copy ();
959 port_connections.clear ();
963 AudioEngine::remove_connections_for (Port& port)
965 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ) {
966 PortConnections::iterator tmp;
971 if ((*i).first == port.name()) {
972 port_connections.erase (i);
979 #ifdef HAVE_JACK_CLIENT_OPEN
982 AudioEngine::connect_to_jack (string client_name)
984 jack_options_t options = JackNullOption;
985 jack_status_t status;
986 const char *server_name = NULL;
988 jack_client_name = client_name; /* might be reset below */
990 _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
994 if (status & JackServerFailed) {
995 error << _("Unable to connect to JACK server") << endmsg;
998 error << string_compose (_("Could not connect to JACK server as \"%1\""), jack_client_name) << endmsg;
1002 if (status & JackServerStarted) {
1003 info << _("JACK server started") << endmsg;
1006 if (status & JackNameNotUnique) {
1007 jack_client_name = jack_get_client_name (_jack);
1016 AudioEngine::connect_to_jack (string client_name)
1018 jack_client_name = client_name;
1020 if ((_jack = jack_client_new (client_name.c_str())) == NULL) {
1027 #endif /* HAVE_JACK_CLIENT_OPEN */
1030 AudioEngine::disconnect_from_jack ()
1036 if (jack_client_close (_jack)) {
1037 error << _("cannot shutdown connection to JACK") << endmsg;
1045 Stopped(); /* EMIT SIGNAL */
1053 AudioEngine::reconnect_to_jack ()
1056 disconnect_from_jack ();
1057 /* XXX give jackd a chance */
1058 Glib::usleep (250000);
1061 if (connect_to_jack (jack_client_name)) {
1062 error << _("failed to connect to JACK") << endmsg;
1068 boost::shared_ptr<Ports> p = ports.reader ();
1070 for (i = p->begin(); i != p->end(); ++i) {
1072 /* XXX hack hack hack */
1074 string long_name = (*i)->name();
1077 short_name = long_name.substr (long_name.find_last_of (':') + 1);
1079 if (((*i)->_port = jack_port_register (_jack, short_name.c_str(), (*i)->type().to_jack_type(), (*i)->flags(), 0)) == 0) {
1080 error << string_compose (_("could not reregister %1"), (*i)->name()) << endmsg;
1087 if ((*i)->flags() & JackPortIsOutput) {
1088 (*i)->get_buffer().silence (jack_get_buffer_size (_jack), 0);
1092 if (i != p->end()) {
1094 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
1095 jack_port_unregister (_jack, (*i)->_port);
1102 nframes_t blocksize = jack_get_buffer_size (_jack);
1103 session->set_block_size (blocksize);
1104 session->set_frame_rate (jack_get_sample_rate (_jack));
1107 last_monitor_check = 0;
1109 jack_on_shutdown (_jack, halted, this);
1110 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
1111 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1112 jack_set_process_callback (_jack, _process_callback, this);
1113 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1114 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1115 jack_set_xrun_callback (_jack, _xrun_callback, this);
1116 jack_set_sync_callback (_jack, _jack_sync_callback, this);
1117 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1119 if (Config->get_jack_time_master()) {
1120 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1123 if (jack_activate (_jack) == 0) {
1130 /* re-establish connections */
1132 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ++i) {
1136 if ((err = jack_connect (_jack, (*i).first.c_str(), (*i).second.c_str())) != 0) {
1137 if (err != EEXIST) {
1138 error << string_compose (_("could not reconnect %1 and %2 (err = %3)"),
1139 (*i).first, (*i).second, err)
1145 Running (); /* EMIT SIGNAL*/
1151 AudioEngine::request_buffer_size (nframes_t nframes)
1154 int ret = jack_set_buffer_size (_jack, nframes);
1162 AudioEngine::update_total_latencies ()
1164 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1165 jack_recompute_total_latencies (_jack);
1170 AudioEngine::make_port_name_relative (string portname)
1172 string::size_type len;
1173 string::size_type n;
1175 len = portname.length();
1177 for (n = 0; n < len; ++n) {
1178 if (portname[n] == ':') {
1183 if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1184 return portname.substr (n+1);
1191 AudioEngine::make_port_name_non_relative (string portname)
1195 if (portname.find_first_of (':') != string::npos) {
1199 str = jack_client_name;