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.
24 #include <glibmm/timer.h>
25 #include <pbd/pthread_utils.h>
26 #include <pbd/stacktrace.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;
49 ardour_jack_error (const char* msg)
51 error << "JACK: " << msg << endmsg;
54 AudioEngine::AudioEngine (string client_name)
58 session_remove_pending = false;
61 last_monitor_check = 0;
62 monitor_check_interval = max_frames;
63 _processed_frames = 0;
64 _freewheeling = false;
69 _freewheeling = false;
70 _freewheel_thread_registered = false;
73 g_atomic_int_set (&m_meter_exit, 0);
75 if (connect_to_jack (client_name)) {
76 throw NoBackendAvailable ();
79 start_metering_thread();
83 AudioEngine::~AudioEngine ()
86 Glib::Mutex::Lock tm (_process_lock);
87 session_removed.signal ();
90 jack_client_close (_jack);
93 stop_metering_thread ();
98 _thread_init_callback (void *arg)
100 /* make sure that anybody who needs to know about this thread
104 PBD::ThreadCreatedWithRequestSize (pthread_self(), X_("Audioengine"), 4096);
108 AudioEngine::start ()
113 nframes_t blocksize = jack_get_buffer_size (_jack);
115 session->set_block_size (blocksize);
116 session->set_frame_rate (jack_get_sample_rate (_jack));
118 /* page in as much of the session process code as we
119 can before we really start running.
122 session->process (blocksize);
123 session->process (blocksize);
124 session->process (blocksize);
125 session->process (blocksize);
126 session->process (blocksize);
127 session->process (blocksize);
128 session->process (blocksize);
129 session->process (blocksize);
132 _processed_frames = 0;
133 last_monitor_check = 0;
135 jack_on_shutdown (_jack, halted, this);
136 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
137 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
138 jack_set_process_callback (_jack, _process_callback, this);
139 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
140 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
141 jack_set_xrun_callback (_jack, _xrun_callback, this);
142 jack_set_sync_callback (_jack, _jack_sync_callback, this);
143 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
145 if (Config->get_jack_time_master()) {
146 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
149 if (jack_activate (_jack) == 0) {
152 Running(); /* EMIT SIGNAL */
154 error << _("cannot activate JACK client") << endmsg;
158 return _running ? 0 : -1;
162 AudioEngine::stop (bool forever)
167 jack_client_t* foo = _jack;
169 jack_client_close (foo);
170 stop_metering_thread ();
172 jack_deactivate (_jack);
174 Stopped(); /* EMIT SIGNAL */
177 return _running ? -1 : 0;
182 AudioEngine::get_sync_offset (nframes_t& offset) const
185 #ifdef HAVE_JACK_VIDEO_SUPPORT
189 (void) jack_transport_query (_jack, &pos);
191 if (pos.valid & JackVideoFrameOffset) {
192 offset = pos.video_offset;
202 AudioEngine::_jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
203 jack_position_t* pos, int new_position, void *arg)
205 static_cast<AudioEngine*> (arg)->jack_timebase_callback (state, nframes, pos, new_position);
209 AudioEngine::jack_timebase_callback (jack_transport_state_t state, nframes_t nframes,
210 jack_position_t* pos, int new_position)
212 if (_jack && session && session->synced_to_jack()) {
213 session->jack_timebase_callback (state, nframes, pos, new_position);
218 AudioEngine::_jack_sync_callback (jack_transport_state_t state, jack_position_t* pos, void* arg)
220 return static_cast<AudioEngine*> (arg)->jack_sync_callback (state, pos);
224 AudioEngine::jack_sync_callback (jack_transport_state_t state, jack_position_t* pos)
226 if (_jack && session) {
227 return session->jack_sync_callback (state, pos);
234 AudioEngine::_xrun_callback (void *arg)
236 AudioEngine* ae = static_cast<AudioEngine*> (arg);
238 ae->Xrun (); /* EMIT SIGNAL */
244 AudioEngine::_graph_order_callback (void *arg)
246 AudioEngine* ae = static_cast<AudioEngine*> (arg);
248 ae->GraphReordered (); /* EMIT SIGNAL */
254 AudioEngine::_process_callback (nframes_t nframes, void *arg)
256 return static_cast<AudioEngine *> (arg)->process_callback (nframes);
260 AudioEngine::_freewheel_callback (int onoff, void *arg)
262 static_cast<AudioEngine*>(arg)->_freewheeling = onoff;
266 AudioEngine::process_callback (nframes_t nframes)
268 // CycleTimer ct ("AudioEngine::process");
269 Glib::Mutex::Lock tm (_process_lock, Glib::TRY_LOCK);
270 nframes_t next_processed_frames;
272 /* handle wrap around of total frames counter */
274 if (max_frames - _processed_frames < nframes) {
275 next_processed_frames = nframes - (max_frames - _processed_frames);
277 next_processed_frames = _processed_frames + nframes;
280 if (!tm.locked() || session == 0) {
281 _processed_frames = next_processed_frames;
285 if (session_remove_pending) {
287 session_remove_pending = false;
288 session_removed.signal();
289 _processed_frames = next_processed_frames;
294 if (Freewheel (nframes)) {
295 cerr << "Freewheeling returned non-zero!\n";
296 _freewheeling = false;
297 jack_set_freewheel (_jack, false);
302 session->process (nframes);
305 /* we were zombified, maybe because a ladspa plugin took
306 too long, or jackd exited, or something like that.
309 _processed_frames = next_processed_frames;
313 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
315 boost::shared_ptr<Ports> p = ports.reader();
317 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
322 if (port->_last_monitor != (x = port->monitoring_input ())) {
323 port->_last_monitor = x;
324 /* XXX I think this is dangerous, due to
325 a likely mutex in the signal handlers ...
327 port->MonitorInputChanged (x); /* EMIT SIGNAL */
330 last_monitor_check = next_processed_frames;
333 _processed_frames = next_processed_frames;
338 AudioEngine::_sample_rate_callback (nframes_t nframes, void *arg)
340 return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
344 AudioEngine::jack_sample_rate_callback (nframes_t nframes)
346 _frame_rate = nframes;
347 _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
349 /* check for monitor input change every 1/10th of second */
351 monitor_check_interval = nframes / 10;
352 last_monitor_check = 0;
355 session->set_frame_rate (nframes);
358 SampleRateChanged (nframes); /* EMIT SIGNAL */
364 AudioEngine::_bufsize_callback (nframes_t nframes, void *arg)
366 return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
370 AudioEngine::jack_bufsize_callback (nframes_t nframes)
372 _buffer_size = nframes;
373 _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
374 last_monitor_check = 0;
376 boost::shared_ptr<Ports> p = ports.reader();
378 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
383 session->set_block_size (_buffer_size);
390 AudioEngine::stop_metering_thread ()
392 if (m_meter_thread) {
393 g_atomic_int_set (&m_meter_exit, 1);
394 m_meter_thread->join ();
400 AudioEngine::start_metering_thread ()
402 if (m_meter_thread == 0) {
403 m_meter_thread = Glib::Thread::create (sigc::mem_fun(this, &AudioEngine::meter_thread),
404 500000, true, true, Glib::THREAD_PRIORITY_NORMAL);
409 AudioEngine::meter_thread ()
412 Glib::usleep (10000); /* 1/100th sec interval */
413 if (g_atomic_int_get(&m_meter_exit)) {
416 IO::update_meters ();
421 AudioEngine::set_session (Session *s)
423 Glib::Mutex::Lock pl (_process_lock);
429 nframes_t blocksize = jack_get_buffer_size (_jack);
431 /* page in as much of the session process code as we
432 can before we really start running.
435 session->process (blocksize);
436 session->process (blocksize);
437 session->process (blocksize);
438 session->process (blocksize);
439 session->process (blocksize);
440 session->process (blocksize);
441 session->process (blocksize);
442 session->process (blocksize);
447 AudioEngine::remove_session ()
449 Glib::Mutex::Lock lm (_process_lock);
454 session_remove_pending = true;
455 session_removed.wait(_process_lock);
466 AudioEngine::register_input_port (DataType type, const string& portname)
470 fatal << _("register input port called before engine was started") << endmsg;
477 jack_port_t *p = jack_port_register (_jack, portname.c_str(), type.to_jack_type(), JackPortIsInput, 0);
483 if ((newport = new Port (p)) != 0) {
484 RCUWriter<Ports> writer (ports);
485 boost::shared_ptr<Ports> ps = writer.get_copy ();
486 ps->insert (ps->begin(), newport);
487 /* writer goes out of scope, forces update */
493 throw PortRegistrationFailure();
500 AudioEngine::register_output_port (DataType type, const string& portname)
504 fatal << _("register output port called before engine was started") << endmsg;
513 if ((p = jack_port_register (_jack, portname.c_str(),
514 type.to_jack_type(), JackPortIsOutput, 0)) != 0) {
519 RCUWriter<Ports> writer (ports);
520 boost::shared_ptr<Ports> ps = writer.get_copy ();
522 newport = new Port (p);
523 ps->insert (ps->begin(), newport);
525 /* writer goes out of scope, forces update */
531 throw PortRegistrationFailure ();
539 AudioEngine::unregister_port (Port *port)
542 /* probably happening when the engine has been halted by JACK,
543 in which case, there is nothing we can do here.
550 int ret = jack_port_unregister (_jack, port->_port);
556 RCUWriter<Ports> writer (ports);
557 boost::shared_ptr<Ports> ps = writer.get_copy ();
559 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
566 /* writer goes out of scope, forces update */
569 remove_connections_for (port);
580 AudioEngine::connect (const string& source, const string& destination)
584 fatal << _("connect called before engine was started") << endmsg;
591 string s = make_port_name_non_relative (source);
592 string d = make_port_name_non_relative (destination);
594 int ret = jack_connect (_jack, s.c_str(), d.c_str());
597 pair<string,string> c (s, d);
598 port_connections.push_back (c);
599 } else if (ret == EEXIST) {
600 error << string_compose(_("AudioEngine: connection already exists: %1 (%2) to %3 (%4)"),
601 source, s, destination, d)
604 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
605 source, s, destination, d)
613 AudioEngine::disconnect (const string& source, const string& destination)
617 fatal << _("disconnect called before engine was started") << endmsg;
624 string s = make_port_name_non_relative (source);
625 string d = make_port_name_non_relative (destination);
627 int ret = jack_disconnect (_jack, s.c_str(), d.c_str());
630 pair<string,string> c (s, d);
631 PortConnections::iterator i;
633 if ((i = find (port_connections.begin(), port_connections.end(), c)) != port_connections.end()) {
634 port_connections.erase (i);
642 AudioEngine::disconnect (Port *port)
646 fatal << _("disconnect called before engine was started") << endmsg;
653 int ret = jack_port_disconnect (_jack, port->_port);
656 remove_connections_for (port);
664 AudioEngine::frame_rate ()
667 if (_frame_rate == 0) {
668 return (_frame_rate = jack_get_sample_rate (_jack));
673 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
681 AudioEngine::frames_per_cycle ()
684 if (_buffer_size == 0) {
685 return (_buffer_size = jack_get_buffer_size (_jack));
690 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
698 AudioEngine::get_port_by_name (const string& portname, bool keep)
700 Glib::Mutex::Lock lm (_process_lock);
704 fatal << _("get_port_by_name() called before engine was started") << endmsg;
711 /* check to see if we have a Port for this name already */
713 boost::shared_ptr<Ports> pr = ports.reader();
715 for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
716 if (portname == (*i)->name()) {
723 if ((p = jack_port_by_name (_jack, portname.c_str())) != 0) {
724 Port *newport = new Port (p);
727 if (keep && newport->is_mine (_jack)) {
728 RCUWriter<Ports> writer (ports);
729 boost::shared_ptr<Ports> ps = writer.get_copy ();
730 ps->insert (newport);
731 /* writer goes out of scope, forces update */
744 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
748 fatal << _("get_ports called before engine was started") << endmsg;
754 return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
758 AudioEngine::halted (void *arg)
760 AudioEngine* ae = static_cast<AudioEngine *> (arg);
762 ae->_running = false;
763 ae->_buffer_size = 0;
766 ae->Halted(); /* EMIT SIGNAL */
770 AudioEngine::n_physical_outputs () const
779 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
784 for (i = 0; ports[i]; ++i);
791 AudioEngine::n_physical_inputs () const
800 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
805 for (i = 0; ports[i]; ++i);
812 AudioEngine::get_physical_inputs (vector<string>& ins)
821 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
826 for (i = 0; ports[i]; ++i) {
827 ins.push_back (ports[i]);
834 AudioEngine::get_physical_outputs (vector<string>& outs)
843 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
848 for (i = 0; ports[i]; ++i) {
849 outs.push_back (ports[i]);
856 AudioEngine::get_nth_physical (uint32_t n, int flag)
862 if (!_running || !_jack) {
864 fatal << _("get_nth_physical called before engine was started") << endmsg;
871 ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|flag);
877 for (i = 0; i < n && ports[i]; ++i);
883 free ((char *) ports);
889 AudioEngine::get_port_total_latency (const Port& port)
892 fatal << _("get_port_total_latency() called with no JACK client connection") << endmsg;
898 fatal << _("get_port_total_latency() called before engine was started") << endmsg;
903 return jack_port_get_total_latency (_jack, port._port);
907 AudioEngine::transport_stop ()
909 // cerr << "tell JACK to stop\n";
911 jack_transport_stop (_jack);
916 AudioEngine::transport_start ()
918 // cerr << "tell JACK to start\n";
920 jack_transport_start (_jack);
925 AudioEngine::transport_locate (nframes_t where)
927 // cerr << "tell JACK to locate to " << where << endl;
929 jack_transport_locate (_jack, where);
933 AudioEngine::TransportState
934 AudioEngine::transport_state ()
938 return (TransportState) jack_transport_query (_jack, &pos);
940 return (TransportState) JackTransportStopped;
945 AudioEngine::reset_timebase ()
948 if (Config->get_jack_time_master()) {
949 return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
951 return jack_release_timebase (_jack);
959 AudioEngine::freewheel (bool onoff)
964 _freewheel_thread_registered = false;
967 return jack_set_freewheel (_jack, onoff);
975 AudioEngine::remove_all_ports ()
977 /* process lock MUST be held */
980 boost::shared_ptr<Ports> p = ports.reader();
982 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
983 jack_port_unregister (_jack, (*i)->_port);
988 RCUWriter<Ports> writer (ports);
989 boost::shared_ptr<Ports> ps = writer.get_copy ();
993 port_connections.clear ();
997 AudioEngine::remove_connections_for (Port* port)
999 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ) {
1000 PortConnections::iterator tmp;
1005 if ((*i).first == port->name()) {
1006 port_connections.erase (i);
1013 #ifdef HAVE_JACK_CLIENT_OPEN
1016 AudioEngine::connect_to_jack (string client_name)
1018 jack_options_t options = JackNullOption;
1019 jack_status_t status;
1020 const char *server_name = NULL;
1022 jack_client_name = client_name; /* might be reset below */
1024 _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
1026 if (_jack == NULL) {
1028 if (status & JackServerFailed) {
1029 error << _("Unable to connect to JACK server") << endmsg;
1032 error << string_compose (_("Could not connect to JACK server as \"%1\""), jack_client_name) << endmsg;
1036 if (status & JackServerStarted) {
1037 info << _("JACK server started") << endmsg;
1040 if (status & JackNameNotUnique) {
1041 jack_client_name = jack_get_client_name (_jack);
1044 jack_set_error_function (ardour_jack_error);
1052 AudioEngine::connect_to_jack (string client_name)
1054 jack_client_name = client_name;
1056 if ((_jack = jack_client_new (client_name.c_str())) == NULL) {
1063 #endif /* HAVE_JACK_CLIENT_OPEN */
1066 AudioEngine::disconnect_from_jack ()
1072 jack_client_close (_jack);
1079 Stopped(); /* EMIT SIGNAL */
1087 AudioEngine::reconnect_to_jack ()
1090 disconnect_from_jack ();
1091 /* XXX give jackd a chance */
1092 Glib::usleep (250000);
1095 if (connect_to_jack (jack_client_name)) {
1096 error << _("failed to connect to JACK") << endmsg;
1102 boost::shared_ptr<Ports> p = ports.reader ();
1104 for (i = p->begin(); i != p->end(); ++i) {
1106 /* XXX hack hack hack */
1108 string long_name = (*i)->name();
1111 short_name = long_name.substr (long_name.find_last_of (':') + 1);
1113 if (((*i)->_port = jack_port_register (_jack, short_name.c_str(), (*i)->type(), (*i)->flags(), 0)) == 0) {
1114 error << string_compose (_("could not reregister %1"), (*i)->name()) << endmsg;
1121 if ((*i)->flags() & JackPortIsOutput) {
1122 (*i)->silence (jack_get_buffer_size (_jack), 0);
1126 if (i != p->end()) {
1128 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
1129 jack_port_unregister (_jack, (*i)->_port);
1136 nframes_t blocksize = jack_get_buffer_size (_jack);
1137 session->set_block_size (blocksize);
1138 session->set_frame_rate (jack_get_sample_rate (_jack));
1141 last_monitor_check = 0;
1143 jack_on_shutdown (_jack, halted, this);
1144 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
1145 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1146 jack_set_process_callback (_jack, _process_callback, this);
1147 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1148 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1149 jack_set_xrun_callback (_jack, _xrun_callback, this);
1150 jack_set_sync_callback (_jack, _jack_sync_callback, this);
1151 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1153 if (Config->get_jack_time_master()) {
1154 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1157 if (jack_activate (_jack) == 0) {
1164 /* re-establish connections */
1166 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ++i) {
1170 if ((err = jack_connect (_jack, (*i).first.c_str(), (*i).second.c_str())) != 0) {
1171 if (err != EEXIST) {
1172 error << string_compose (_("could not reconnect %1 and %2 (err = %3)"),
1173 (*i).first, (*i).second, err)
1179 Running (); /* EMIT SIGNAL*/
1185 AudioEngine::request_buffer_size (nframes_t nframes)
1189 if (nframes == jack_get_buffer_size (_jack)) {
1193 return jack_set_buffer_size (_jack, nframes);
1201 AudioEngine::update_total_latencies ()
1203 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1204 jack_recompute_total_latencies (_jack);
1209 AudioEngine::make_port_name_relative (string portname)
1211 string::size_type len;
1212 string::size_type n;
1214 len = portname.length();
1216 for (n = 0; n < len; ++n) {
1217 if (portname[n] == ':') {
1222 if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1223 return portname.substr (n+1);
1230 AudioEngine::make_port_name_non_relative (string portname)
1234 if (portname.find_first_of (':') != string::npos) {
1238 str = jack_client_name;
1246 AudioEngine::is_realtime () const
1249 return jack_is_realtime (_jack);