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 jack_nframes_t Port::_short_over_length = 2;
47 jack_nframes_t Port::_long_over_length = 10;
49 AudioEngine::AudioEngine (string client_name)
53 session_remove_pending = false;
56 last_monitor_check = 0;
57 monitor_check_interval = max_frames;
58 _processed_frames = 0;
59 _freewheeling = false;
64 _freewheeling = false;
65 _freewheel_thread_registered = false;
70 if (connect_to_jack (client_name)) {
71 throw NoBackendAvailable ();
74 start_metering_thread();
78 AudioEngine::~AudioEngine ()
81 jack_client_close (_jack);
85 g_atomic_int_inc(&m_meter_exit);
90 _thread_init_callback (void *arg)
92 /* make sure that anybody who needs to know about this thread
96 PBD::ThreadCreatedWithRequestSize (pthread_self(), X_("Audioengine"), 4096);
100 AudioEngine::start ()
105 jack_nframes_t blocksize = jack_get_buffer_size (_jack);
107 session->set_block_size (blocksize);
108 session->set_frame_rate (jack_get_sample_rate (_jack));
110 /* page in as much of the session process code as we
111 can before we really start running.
114 session->process (blocksize);
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);
124 _processed_frames = 0;
125 last_monitor_check = 0;
127 jack_on_shutdown (_jack, halted, this);
128 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
129 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
130 jack_set_process_callback (_jack, _process_callback, this);
131 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
132 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
133 jack_set_xrun_callback (_jack, _xrun_callback, this);
134 jack_set_sync_callback (_jack, _jack_sync_callback, this);
135 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
137 if (Config->get_jack_time_master()) {
138 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
141 if (jack_activate (_jack) == 0) {
144 Running(); /* EMIT SIGNAL */
146 error << _("cannot activate JACK client") << endmsg;
150 return _running ? 0 : -1;
158 jack_deactivate (_jack);
159 Stopped(); /* EMIT SIGNAL */
162 return _running ? -1 : 0;
168 AudioEngine::get_sync_offset (jack_nframes_t& offset) const
172 (void) jack_transport_query (_jack, &pos);
174 if (pos.valid & JackVideoFrameOffset) {
175 offset = pos.video_offset;
183 AudioEngine::_jack_timebase_callback (jack_transport_state_t state, jack_nframes_t nframes,
184 jack_position_t* pos, int new_position, void *arg)
186 static_cast<AudioEngine*> (arg)->jack_timebase_callback (state, nframes, pos, new_position);
190 AudioEngine::jack_timebase_callback (jack_transport_state_t state, jack_nframes_t nframes,
191 jack_position_t* pos, int new_position)
193 if (session && session->synced_to_jack()) {
194 session->jack_timebase_callback (state, nframes, pos, new_position);
199 AudioEngine::_jack_sync_callback (jack_transport_state_t state, jack_position_t* pos, void* arg)
201 return static_cast<AudioEngine*> (arg)->jack_sync_callback (state, pos);
205 AudioEngine::jack_sync_callback (jack_transport_state_t state, jack_position_t* pos)
208 return session->jack_sync_callback (state, pos);
215 AudioEngine::_xrun_callback (void *arg)
217 static_cast<AudioEngine *>(arg)->Xrun (); /* EMIT SIGNAL */
222 AudioEngine::_graph_order_callback (void *arg)
224 static_cast<AudioEngine *>(arg)->GraphReordered (); /* EMIT SIGNAL */
229 AudioEngine::_process_callback (jack_nframes_t nframes, void *arg)
231 return static_cast<AudioEngine *> (arg)->process_callback (nframes);
235 AudioEngine::_freewheel_callback (int onoff, void *arg)
237 static_cast<AudioEngine*>(arg)->_freewheeling = onoff;
241 AudioEngine::process_callback (jack_nframes_t nframes)
243 // CycleTimer ct ("AudioEngine::process");
244 Glib::Mutex::Lock tm (_process_lock, Glib::TRY_LOCK);
245 jack_nframes_t next_processed_frames;
247 /* handle wrap around of total frames counter */
249 if (max_frames - _processed_frames < nframes) {
250 next_processed_frames = nframes - (max_frames - _processed_frames);
252 next_processed_frames = _processed_frames + nframes;
255 if (!tm.locked() || session == 0) {
256 _processed_frames = next_processed_frames;
260 if (session_remove_pending) {
262 session_remove_pending = false;
263 session_removed.signal();
264 _processed_frames = next_processed_frames;
269 if (Freewheel (nframes)) {
270 _freewheeling = false;
271 jack_set_freewheel (_jack, false);
276 session->process (nframes);
279 /* we were zombified, maybe because a ladspa plugin took
280 too long, or jackd exited, or something like that.
283 _processed_frames = next_processed_frames;
287 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
289 boost::shared_ptr<Ports> p = ports.reader();
291 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
296 if (port->_last_monitor != (x = port->monitoring_input ())) {
297 port->_last_monitor = x;
298 /* XXX I think this is dangerous, due to
299 a likely mutex in the signal handlers ...
301 port->MonitorInputChanged (x); /* EMIT SIGNAL */
304 last_monitor_check = next_processed_frames;
307 _processed_frames = next_processed_frames;
312 AudioEngine::_sample_rate_callback (jack_nframes_t nframes, void *arg)
314 return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
318 AudioEngine::jack_sample_rate_callback (jack_nframes_t nframes)
320 _frame_rate = nframes;
321 _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
323 /* check for monitor input change every 1/10th of second */
325 monitor_check_interval = nframes / 10;
326 last_monitor_check = 0;
329 session->set_frame_rate (nframes);
332 SampleRateChanged (nframes); /* EMIT SIGNAL */
338 AudioEngine::_bufsize_callback (jack_nframes_t nframes, void *arg)
340 return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
344 AudioEngine::jack_bufsize_callback (jack_nframes_t nframes)
346 _buffer_size = nframes;
347 _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
348 last_monitor_check = 0;
350 boost::shared_ptr<Ports> p = ports.reader();
352 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
357 session->set_block_size (_buffer_size);
364 AudioEngine::start_metering_thread ()
366 if(m_meter_thread == 0) {
367 m_meter_thread = Glib::Thread::create (sigc::mem_fun(this, &AudioEngine::meter_thread), false);
372 AudioEngine::meter_thread ()
374 while (g_atomic_int_get(&m_meter_exit) != true) {
375 Glib::usleep (10000); /* 1/100th sec interval */
376 IO::update_meters ();
382 AudioEngine::set_session (Session *s)
390 AudioEngine::remove_session ()
392 Glib::Mutex::Lock lm (_process_lock);
397 session_remove_pending = true;
398 session_removed.wait(_process_lock);
412 AudioEngine::register_input_port (DataType type, const string& portname)
416 fatal << _("register input port called before engine was started") << endmsg;
423 jack_port_t *p = jack_port_register (_jack, portname.c_str(), type.to_jack_type(), JackPortIsInput, 0);
429 if ((newport = new Port (p)) != 0) {
430 RCUWriter<Ports> writer (ports);
431 boost::shared_ptr<Ports> ps = writer.get_copy ();
432 ps->insert (ps->begin(), newport);
433 /* writer goes out of scope, forces update */
440 _process_lock.unlock();
441 throw PortRegistrationFailure();
448 AudioEngine::register_output_port (DataType type, const string& portname)
452 fatal << _("register output port called before engine was started") << endmsg;
461 if ((p = jack_port_register (_jack, portname.c_str(),
462 type.to_jack_type(), JackPortIsOutput, 0)) != 0) {
467 RCUWriter<Ports> writer (ports);
468 boost::shared_ptr<Ports> ps = writer.get_copy ();
470 newport = new Port (p);
471 ps->insert (ps->begin(), newport);
473 /* writer goes out of scope, forces update */
480 _process_lock.unlock();
481 throw PortRegistrationFailure ();
489 AudioEngine::unregister_port (Port *port)
492 /* probably happening when the engine has been halted by JACK,
493 in which case, there is nothing we can do here.
500 int ret = jack_port_unregister (_jack, port->_port);
506 RCUWriter<Ports> writer (ports);
507 boost::shared_ptr<Ports> ps = writer.get_copy ();
509 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
516 /* writer goes out of scope, forces update */
519 remove_connections_for (port);
530 AudioEngine::connect (const string& source, const string& destination)
534 fatal << _("connect called before engine was started") << endmsg;
541 string s = make_port_name_non_relative (source);
542 string d = make_port_name_non_relative (destination);
544 int ret = jack_connect (_jack, s.c_str(), d.c_str());
547 pair<string,string> c (s, d);
548 port_connections.push_back (c);
550 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
551 source, s, destination, d)
559 AudioEngine::disconnect (const string& source, const string& destination)
563 fatal << _("disconnect called before engine was started") << endmsg;
570 string s = make_port_name_non_relative (source);
571 string d = make_port_name_non_relative (destination);
573 int ret = jack_disconnect (_jack, s.c_str(), d.c_str());
576 pair<string,string> c (s, d);
577 PortConnections::iterator i;
579 if ((i = find (port_connections.begin(), port_connections.end(), c)) != port_connections.end()) {
580 port_connections.erase (i);
588 AudioEngine::disconnect (Port *port)
592 fatal << _("disconnect called before engine was started") << endmsg;
599 int ret = jack_port_disconnect (_jack, port->_port);
602 remove_connections_for (port);
610 AudioEngine::frame_rate ()
613 if (_frame_rate == 0) {
614 return (_frame_rate = jack_get_sample_rate (_jack));
619 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
627 AudioEngine::frames_per_cycle ()
630 if (_buffer_size == 0) {
631 return (_buffer_size = jack_get_buffer_size (_jack));
636 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
644 AudioEngine::get_port_by_name (const string& portname, bool keep)
646 Glib::Mutex::Lock lm (_process_lock);
650 fatal << _("get_port_by_name() called before engine was started") << endmsg;
657 /* check to see if we have a Port for this name already */
659 boost::shared_ptr<Ports> pr = ports.reader();
661 for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
662 if (portname == (*i)->name()) {
669 if ((p = jack_port_by_name (_jack, portname.c_str())) != 0) {
670 Port *newport = new Port (p);
673 if (keep && newport->is_mine (_jack)) {
674 RCUWriter<Ports> writer (ports);
675 boost::shared_ptr<Ports> ps = writer.get_copy ();
676 ps->insert (newport);
677 /* writer goes out of scope, forces update */
690 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
694 fatal << _("get_ports called before engine was started") << endmsg;
700 return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
704 AudioEngine::halted (void *arg)
706 AudioEngine *ae = reinterpret_cast<AudioEngine *> (arg);
708 ae->_running = false;
711 ae->_buffer_size = 0;
714 ae->Halted(); /* EMIT SIGNAL */
718 AudioEngine::n_physical_outputs () const
727 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
732 for (i = 0; ports[i]; ++i);
739 AudioEngine::n_physical_inputs () const
748 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
753 for (i = 0; ports[i]; ++i);
760 AudioEngine::get_physical_inputs (vector<string>& ins)
769 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
774 for (i = 0; ports[i]; ++i) {
775 ins.push_back (ports[i]);
782 AudioEngine::get_physical_outputs (vector<string>& outs)
791 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
796 for (i = 0; ports[i]; ++i) {
797 outs.push_back (ports[i]);
804 AudioEngine::get_nth_physical (uint32_t n, int flag)
810 if (!_running || !_jack) {
812 fatal << _("get_nth_physical called before engine was started") << endmsg;
819 ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|flag);
825 for (i = 0; i < n && ports[i]; ++i);
831 free ((char *) ports);
837 AudioEngine::get_port_total_latency (const Port& port)
840 fatal << _("get_port_total_latency() called with no JACK client connection") << endmsg;
846 fatal << _("get_port_total_latency() called before engine was started") << endmsg;
851 return jack_port_get_total_latency (_jack, port._port);
855 AudioEngine::transport_stop ()
857 // cerr << "tell JACK to stop\n";
859 jack_transport_stop (_jack);
864 AudioEngine::transport_start ()
866 // cerr << "tell JACK to start\n";
868 jack_transport_start (_jack);
873 AudioEngine::transport_locate (jack_nframes_t where)
875 // cerr << "tell JACK to locate to " << where << endl;
877 jack_transport_locate (_jack, where);
881 AudioEngine::TransportState
882 AudioEngine::transport_state ()
886 return (TransportState) jack_transport_query (_jack, &pos);
888 return (TransportState) JackTransportStopped;
893 AudioEngine::reset_timebase ()
896 if (Config->get_jack_time_master()) {
897 return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
899 return jack_release_timebase (_jack);
907 AudioEngine::freewheel (bool onoff)
912 _freewheel_thread_registered = false;
915 return jack_set_freewheel (_jack, onoff);
923 AudioEngine::remove_all_ports ()
925 /* process lock MUST be held */
928 boost::shared_ptr<Ports> p = ports.reader();
930 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
931 jack_port_unregister (_jack, (*i)->_port);
936 RCUWriter<Ports> writer (ports);
937 boost::shared_ptr<Ports> ps = writer.get_copy ();
941 port_connections.clear ();
945 AudioEngine::remove_connections_for (Port* port)
947 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ) {
948 PortConnections::iterator tmp;
953 if ((*i).first == port->name()) {
954 port_connections.erase (i);
961 #ifdef HAVE_JACK_CLIENT_OPEN
964 AudioEngine::connect_to_jack (string client_name)
966 jack_options_t options = JackNullOption;
967 jack_status_t status;
968 const char *server_name = NULL;
970 jack_client_name = client_name; /* might be reset below */
972 _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
976 if (status & JackServerFailed) {
977 error << _("Unable to connect to JACK server") << endmsg;
980 error << string_compose (_("Could not connect to JACK server as \"%1\""), jack_client_name) << endmsg;
984 if (status & JackServerStarted) {
985 info << _("JACK server started") << endmsg;
988 if (status & JackNameNotUnique) {
989 jack_client_name = jack_get_client_name (_jack);
998 AudioEngine::connect_to_jack (string client_name)
1000 jack_client_name = client_name;
1002 if ((_jack = jack_client_new (client_name.c_str())) == NULL) {
1009 #endif /* HAVE_JACK_CLIENT_OPEN */
1012 AudioEngine::disconnect_from_jack ()
1018 if (jack_client_close (_jack)) {
1019 error << _("cannot shutdown connection to JACK") << endmsg;
1027 Stopped(); /* EMIT SIGNAL */
1035 AudioEngine::reconnect_to_jack ()
1038 disconnect_from_jack ();
1039 /* XXX give jackd a chance */
1040 Glib::usleep (250000);
1043 if (connect_to_jack (jack_client_name)) {
1044 error << _("failed to connect to JACK") << endmsg;
1050 boost::shared_ptr<Ports> p = ports.reader ();
1052 for (i = p->begin(); i != p->end(); ++i) {
1054 /* XXX hack hack hack */
1056 string long_name = (*i)->name();
1059 short_name = long_name.substr (long_name.find_last_of (':') + 1);
1061 if (((*i)->_port = jack_port_register (_jack, short_name.c_str(), (*i)->type(), (*i)->flags(), 0)) == 0) {
1062 error << string_compose (_("could not reregister %1"), (*i)->name()) << endmsg;
1069 if ((*i)->flags() & JackPortIsOutput) {
1070 (*i)->silence (jack_get_buffer_size (_jack), 0);
1074 if (i != p->end()) {
1076 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
1077 jack_port_unregister (_jack, (*i)->_port);
1084 jack_nframes_t blocksize = jack_get_buffer_size (_jack);
1085 session->set_block_size (blocksize);
1086 session->set_frame_rate (jack_get_sample_rate (_jack));
1089 last_monitor_check = 0;
1091 jack_on_shutdown (_jack, halted, this);
1092 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
1093 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1094 jack_set_process_callback (_jack, _process_callback, this);
1095 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1096 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1097 jack_set_xrun_callback (_jack, _xrun_callback, this);
1098 jack_set_sync_callback (_jack, _jack_sync_callback, this);
1099 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1101 if (Config->get_jack_time_master()) {
1102 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1105 if (jack_activate (_jack) == 0) {
1112 /* re-establish connections */
1114 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ++i) {
1118 if ((err = jack_connect (_jack, (*i).first.c_str(), (*i).second.c_str())) != 0) {
1119 if (err != EEXIST) {
1120 error << string_compose (_("could not reconnect %1 and %2 (err = %3)"),
1121 (*i).first, (*i).second, err)
1127 Running (); /* EMIT SIGNAL*/
1133 AudioEngine::request_buffer_size (jack_nframes_t nframes)
1136 int ret = jack_set_buffer_size (_jack, nframes);
1144 AudioEngine::update_total_latencies ()
1146 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1147 jack_recompute_total_latencies (_jack);
1152 AudioEngine::make_port_name_relative (string portname)
1154 string::size_type len;
1155 string::size_type n;
1157 len = portname.length();
1159 for (n = 0; n < len; ++n) {
1160 if (portname[n] == ':') {
1165 if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1166 return portname.substr (n+1);
1173 AudioEngine::make_port_name_non_relative (string portname)
1177 if (portname.find_first_of (':') != string::npos) {
1181 str = jack_client_name;