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 gint AudioEngine::m_meter_exit;
48 AudioEngine::AudioEngine (string client_name)
52 session_remove_pending = false;
55 last_monitor_check = 0;
56 monitor_check_interval = max_frames;
57 _processed_frames = 0;
58 _freewheeling = false;
63 _freewheeling = false;
64 _freewheel_thread_registered = false;
67 g_atomic_int_set (&m_meter_exit, 0);
69 if (connect_to_jack (client_name)) {
70 throw NoBackendAvailable ();
73 start_metering_thread();
77 AudioEngine::~AudioEngine ()
80 jack_client_close (_jack);
83 stop_metering_thread ();
87 _thread_init_callback (void *arg)
89 /* make sure that anybody who needs to know about this thread
93 PBD::ThreadCreatedWithRequestSize (pthread_self(), X_("Audioengine"), 4096);
102 nframes_t blocksize = jack_get_buffer_size (_jack);
104 session->set_block_size (blocksize);
105 session->set_frame_rate (jack_get_sample_rate (_jack));
107 /* page in as much of the session process code as we
108 can before we really start running.
111 session->process (blocksize);
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);
121 _processed_frames = 0;
122 last_monitor_check = 0;
124 jack_on_shutdown (_jack, halted, this);
125 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
126 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
127 jack_set_process_callback (_jack, _process_callback, this);
128 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
129 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
130 jack_set_xrun_callback (_jack, _xrun_callback, this);
131 jack_set_sync_callback (_jack, _jack_sync_callback, this);
132 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
134 if (Config->get_jack_time_master()) {
135 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
138 if (jack_activate (_jack) == 0) {
141 Running(); /* EMIT SIGNAL */
143 error << _("cannot activate JACK client") << endmsg;
147 return _running ? 0 : -1;
151 AudioEngine::stop (bool forever)
156 jack_client_t* foo = _jack;
158 jack_client_close (foo);
159 stop_metering_thread ();
161 jack_deactivate (_jack);
163 Stopped(); /* EMIT SIGNAL */
166 return _running ? -1 : 0;
171 AudioEngine::get_sync_offset (nframes_t& offset) const
174 #ifdef HAVE_JACK_VIDEO_SUPPORT
178 (void) jack_transport_query (_jack, &pos);
180 if (pos.valid & JackVideoFrameOffset) {
181 offset = pos.video_offset;
191 AudioEngine::_jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
192 jack_position_t* pos, int new_position, void *arg)
194 static_cast<AudioEngine*> (arg)->jack_timebase_callback (state, nframes, pos, new_position);
198 AudioEngine::jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
199 jack_position_t* pos, int new_position)
201 if (_jack && session && session->synced_to_jack()) {
202 session->jack_timebase_callback (state, nframes, pos, new_position);
207 AudioEngine::_jack_sync_callback (jack_transport_state_t state, jack_position_t* pos, void* arg)
209 return static_cast<AudioEngine*> (arg)->jack_sync_callback (state, pos);
213 AudioEngine::jack_sync_callback (jack_transport_state_t state, jack_position_t* pos)
215 if (_jack && session) {
216 return session->jack_sync_callback (state, pos);
223 AudioEngine::_xrun_callback (void *arg)
225 AudioEngine* ae = static_cast<AudioEngine*> (arg);
227 ae->Xrun (); /* EMIT SIGNAL */
233 AudioEngine::_graph_order_callback (void *arg)
235 AudioEngine* ae = static_cast<AudioEngine*> (arg);
237 ae->GraphReordered (); /* EMIT SIGNAL */
243 AudioEngine::_process_callback (nframes_t nframes, void *arg)
245 return static_cast<AudioEngine *> (arg)->process_callback (nframes);
249 AudioEngine::_freewheel_callback (int onoff, void *arg)
251 static_cast<AudioEngine*>(arg)->_freewheeling = onoff;
255 AudioEngine::process_callback (nframes_t nframes)
257 // CycleTimer ct ("AudioEngine::process");
258 Glib::Mutex::Lock tm (_process_lock, Glib::TRY_LOCK);
259 nframes_t next_processed_frames;
261 /* handle wrap around of total frames counter */
263 if (max_frames - _processed_frames < nframes) {
264 next_processed_frames = nframes - (max_frames - _processed_frames);
266 next_processed_frames = _processed_frames + nframes;
269 if (!tm.locked() || session == 0) {
270 _processed_frames = next_processed_frames;
274 if (session_remove_pending) {
276 session_remove_pending = false;
277 session_removed.signal();
278 _processed_frames = next_processed_frames;
283 if (Freewheel (nframes)) {
284 _freewheeling = false;
285 jack_set_freewheel (_jack, false);
290 session->process (nframes);
293 /* we were zombified, maybe because a ladspa plugin took
294 too long, or jackd exited, or something like that.
297 _processed_frames = next_processed_frames;
301 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
303 boost::shared_ptr<Ports> p = ports.reader();
305 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
310 if (port->_last_monitor != (x = port->monitoring_input ())) {
311 port->_last_monitor = x;
312 /* XXX I think this is dangerous, due to
313 a likely mutex in the signal handlers ...
315 port->MonitorInputChanged (x); /* EMIT SIGNAL */
318 last_monitor_check = next_processed_frames;
321 _processed_frames = next_processed_frames;
326 AudioEngine::_sample_rate_callback (nframes_t nframes, void *arg)
328 return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
332 AudioEngine::jack_sample_rate_callback (nframes_t nframes)
334 _frame_rate = nframes;
335 _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
337 /* check for monitor input change every 1/10th of second */
339 monitor_check_interval = nframes / 10;
340 last_monitor_check = 0;
343 session->set_frame_rate (nframes);
346 SampleRateChanged (nframes); /* EMIT SIGNAL */
352 AudioEngine::_bufsize_callback (nframes_t nframes, void *arg)
354 return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
358 AudioEngine::jack_bufsize_callback (nframes_t nframes)
360 _buffer_size = nframes;
361 _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
362 last_monitor_check = 0;
364 boost::shared_ptr<Ports> p = ports.reader();
366 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
371 session->set_block_size (_buffer_size);
378 AudioEngine::stop_metering_thread ()
380 if (m_meter_thread) {
381 g_atomic_int_set (&m_meter_exit, 1);
382 m_meter_thread->join ();
388 AudioEngine::start_metering_thread ()
390 if (m_meter_thread == 0) {
391 m_meter_thread = Glib::Thread::create (sigc::mem_fun(this, &AudioEngine::meter_thread), true);
396 AudioEngine::meter_thread ()
399 Glib::usleep (10000); /* 1/100th sec interval */
400 if (g_atomic_int_get(&m_meter_exit)) {
403 IO::update_meters ();
408 AudioEngine::set_session (Session *s)
416 AudioEngine::remove_session ()
418 Glib::Mutex::Lock lm (_process_lock);
423 session_remove_pending = true;
424 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 ((newport = new Port (p)) != 0) {
455 RCUWriter<Ports> writer (ports);
456 boost::shared_ptr<Ports> ps = writer.get_copy ();
457 ps->insert (ps->begin(), newport);
458 /* writer goes out of scope, forces update */
465 _process_lock.unlock();
466 throw PortRegistrationFailure();
473 AudioEngine::register_output_port (DataType type, const string& portname)
477 fatal << _("register output port called before engine was started") << endmsg;
486 if ((p = jack_port_register (_jack, portname.c_str(),
487 type.to_jack_type(), JackPortIsOutput, 0)) != 0) {
492 RCUWriter<Ports> writer (ports);
493 boost::shared_ptr<Ports> ps = writer.get_copy ();
495 newport = new Port (p);
496 ps->insert (ps->begin(), newport);
498 /* writer goes out of scope, forces update */
505 _process_lock.unlock();
506 throw PortRegistrationFailure ();
514 AudioEngine::unregister_port (Port *port)
517 /* probably happening when the engine has been halted by JACK,
518 in which case, there is nothing we can do here.
525 int ret = jack_port_unregister (_jack, port->_port);
531 RCUWriter<Ports> writer (ports);
532 boost::shared_ptr<Ports> ps = writer.get_copy ();
534 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
541 /* writer goes out of scope, forces update */
544 remove_connections_for (port);
555 AudioEngine::connect (const string& source, const string& destination)
559 fatal << _("connect called before engine was started") << endmsg;
566 string s = make_port_name_non_relative (source);
567 string d = make_port_name_non_relative (destination);
569 int ret = jack_connect (_jack, s.c_str(), d.c_str());
572 pair<string,string> c (s, d);
573 port_connections.push_back (c);
574 } else if (ret == EEXIST) {
575 error << string_compose(_("AudioEngine: connection already exists: %1 (%2) to %3 (%4)"),
576 source, s, destination, d)
579 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
580 source, s, destination, d)
588 AudioEngine::disconnect (const string& source, const string& destination)
592 fatal << _("disconnect called before engine was started") << endmsg;
599 string s = make_port_name_non_relative (source);
600 string d = make_port_name_non_relative (destination);
602 int ret = jack_disconnect (_jack, s.c_str(), d.c_str());
605 pair<string,string> c (s, d);
606 PortConnections::iterator i;
608 if ((i = find (port_connections.begin(), port_connections.end(), c)) != port_connections.end()) {
609 port_connections.erase (i);
617 AudioEngine::disconnect (Port *port)
621 fatal << _("disconnect called before engine was started") << endmsg;
628 int ret = jack_port_disconnect (_jack, port->_port);
631 remove_connections_for (port);
639 AudioEngine::frame_rate ()
642 if (_frame_rate == 0) {
643 return (_frame_rate = jack_get_sample_rate (_jack));
648 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
656 AudioEngine::frames_per_cycle ()
659 if (_buffer_size == 0) {
660 return (_buffer_size = jack_get_buffer_size (_jack));
665 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
673 AudioEngine::get_port_by_name (const string& portname, bool keep)
675 Glib::Mutex::Lock lm (_process_lock);
679 fatal << _("get_port_by_name() called before engine was started") << endmsg;
686 /* check to see if we have a Port for this name already */
688 boost::shared_ptr<Ports> pr = ports.reader();
690 for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
691 if (portname == (*i)->name()) {
698 if ((p = jack_port_by_name (_jack, portname.c_str())) != 0) {
699 Port *newport = new Port (p);
702 if (keep && newport->is_mine (_jack)) {
703 RCUWriter<Ports> writer (ports);
704 boost::shared_ptr<Ports> ps = writer.get_copy ();
705 ps->insert (newport);
706 /* writer goes out of scope, forces update */
719 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
723 fatal << _("get_ports called before engine was started") << endmsg;
729 return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
733 AudioEngine::halted (void *arg)
735 AudioEngine* ae = static_cast<AudioEngine *> (arg);
737 ae->_running = false;
738 ae->_buffer_size = 0;
741 ae->Halted(); /* EMIT SIGNAL */
745 AudioEngine::n_physical_outputs () const
754 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
759 for (i = 0; ports[i]; ++i);
766 AudioEngine::n_physical_inputs () const
775 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
780 for (i = 0; ports[i]; ++i);
787 AudioEngine::get_physical_inputs (vector<string>& ins)
796 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
801 for (i = 0; ports[i]; ++i) {
802 ins.push_back (ports[i]);
809 AudioEngine::get_physical_outputs (vector<string>& outs)
818 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
823 for (i = 0; ports[i]; ++i) {
824 outs.push_back (ports[i]);
831 AudioEngine::get_nth_physical (uint32_t n, int flag)
837 if (!_running || !_jack) {
839 fatal << _("get_nth_physical called before engine was started") << endmsg;
846 ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|flag);
852 for (i = 0; i < n && ports[i]; ++i);
858 free ((char *) ports);
864 AudioEngine::get_port_total_latency (const Port& port)
867 fatal << _("get_port_total_latency() called with no JACK client connection") << endmsg;
873 fatal << _("get_port_total_latency() called before engine was started") << endmsg;
878 return jack_port_get_total_latency (_jack, port._port);
882 AudioEngine::transport_stop ()
884 // cerr << "tell JACK to stop\n";
886 jack_transport_stop (_jack);
891 AudioEngine::transport_start ()
893 // cerr << "tell JACK to start\n";
895 jack_transport_start (_jack);
900 AudioEngine::transport_locate (nframes_t where)
902 // cerr << "tell JACK to locate to " << where << endl;
904 jack_transport_locate (_jack, where);
908 AudioEngine::TransportState
909 AudioEngine::transport_state ()
913 return (TransportState) jack_transport_query (_jack, &pos);
915 return (TransportState) JackTransportStopped;
920 AudioEngine::reset_timebase ()
923 if (Config->get_jack_time_master()) {
924 return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
926 return jack_release_timebase (_jack);
934 AudioEngine::freewheel (bool onoff)
939 _freewheel_thread_registered = false;
942 return jack_set_freewheel (_jack, onoff);
950 AudioEngine::remove_all_ports ()
952 /* process lock MUST be held */
955 boost::shared_ptr<Ports> p = ports.reader();
957 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
958 jack_port_unregister (_jack, (*i)->_port);
963 RCUWriter<Ports> writer (ports);
964 boost::shared_ptr<Ports> ps = writer.get_copy ();
968 port_connections.clear ();
972 AudioEngine::remove_connections_for (Port* port)
974 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ) {
975 PortConnections::iterator tmp;
980 if ((*i).first == port->name()) {
981 port_connections.erase (i);
988 #ifdef HAVE_JACK_CLIENT_OPEN
991 AudioEngine::connect_to_jack (string client_name)
993 jack_options_t options = JackNullOption;
994 jack_status_t status;
995 const char *server_name = NULL;
997 jack_client_name = client_name; /* might be reset below */
999 _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
1001 if (_jack == NULL) {
1003 if (status & JackServerFailed) {
1004 error << _("Unable to connect to JACK server") << endmsg;
1007 error << string_compose (_("Could not connect to JACK server as \"%1\""), jack_client_name) << endmsg;
1011 if (status & JackServerStarted) {
1012 info << _("JACK server started") << endmsg;
1015 if (status & JackNameNotUnique) {
1016 jack_client_name = jack_get_client_name (_jack);
1025 AudioEngine::connect_to_jack (string client_name)
1027 jack_client_name = client_name;
1029 if ((_jack = jack_client_new (client_name.c_str())) == NULL) {
1036 #endif /* HAVE_JACK_CLIENT_OPEN */
1039 AudioEngine::disconnect_from_jack ()
1045 jack_client_close (_jack);
1052 Stopped(); /* EMIT SIGNAL */
1060 AudioEngine::reconnect_to_jack ()
1063 disconnect_from_jack ();
1064 /* XXX give jackd a chance */
1065 Glib::usleep (250000);
1068 if (connect_to_jack (jack_client_name)) {
1069 error << _("failed to connect to JACK") << endmsg;
1075 boost::shared_ptr<Ports> p = ports.reader ();
1077 for (i = p->begin(); i != p->end(); ++i) {
1079 /* XXX hack hack hack */
1081 string long_name = (*i)->name();
1084 short_name = long_name.substr (long_name.find_last_of (':') + 1);
1086 if (((*i)->_port = jack_port_register (_jack, short_name.c_str(), (*i)->type(), (*i)->flags(), 0)) == 0) {
1087 error << string_compose (_("could not reregister %1"), (*i)->name()) << endmsg;
1094 if ((*i)->flags() & JackPortIsOutput) {
1095 (*i)->silence (jack_get_buffer_size (_jack), 0);
1099 if (i != p->end()) {
1101 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
1102 jack_port_unregister (_jack, (*i)->_port);
1109 nframes_t blocksize = jack_get_buffer_size (_jack);
1110 session->set_block_size (blocksize);
1111 session->set_frame_rate (jack_get_sample_rate (_jack));
1114 last_monitor_check = 0;
1116 jack_on_shutdown (_jack, halted, this);
1117 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
1118 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1119 jack_set_process_callback (_jack, _process_callback, this);
1120 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1121 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1122 jack_set_xrun_callback (_jack, _xrun_callback, this);
1123 jack_set_sync_callback (_jack, _jack_sync_callback, this);
1124 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1126 if (Config->get_jack_time_master()) {
1127 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1130 if (jack_activate (_jack) == 0) {
1137 /* re-establish connections */
1139 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ++i) {
1143 if ((err = jack_connect (_jack, (*i).first.c_str(), (*i).second.c_str())) != 0) {
1144 if (err != EEXIST) {
1145 error << string_compose (_("could not reconnect %1 and %2 (err = %3)"),
1146 (*i).first, (*i).second, err)
1152 Running (); /* EMIT SIGNAL*/
1158 AudioEngine::request_buffer_size (nframes_t nframes)
1161 int ret = jack_set_buffer_size (_jack, nframes);
1169 AudioEngine::update_total_latencies ()
1171 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1172 jack_recompute_total_latencies (_jack);
1177 AudioEngine::make_port_name_relative (string portname)
1179 string::size_type len;
1180 string::size_type n;
1182 len = portname.length();
1184 for (n = 0; n < len; ++n) {
1185 if (portname[n] == ':') {
1190 if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1191 return portname.substr (n+1);
1198 AudioEngine::make_port_name_non_relative (string portname)
1202 if (portname.find_first_of (':') != string::npos) {
1206 str = jack_client_name;