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;
167 AudioEngine::_jack_timebase_callback (jack_transport_state_t state, jack_nframes_t nframes,
169 jack_position_t* pos, int new_position, void *arg)
171 static_cast<AudioEngine*> (arg)->jack_timebase_callback (state, nframes, pos, new_position);
175 AudioEngine::jack_timebase_callback (jack_transport_state_t state, jack_nframes_t nframes,
177 jack_position_t* pos, int new_position)
179 if (session && session->synced_to_jack()) {
180 session->jack_timebase_callback (state, nframes, pos, new_position);
185 AudioEngine::_jack_sync_callback (jack_transport_state_t state, jack_position_t* pos, void* arg)
187 return static_cast<AudioEngine*> (arg)->jack_sync_callback (state, pos);
191 AudioEngine::jack_sync_callback (jack_transport_state_t state, jack_position_t* pos)
194 return session->jack_sync_callback (state, pos);
201 AudioEngine::_xrun_callback (void *arg)
203 static_cast<AudioEngine *>(arg)->Xrun (); /* EMIT SIGNAL */
208 AudioEngine::_graph_order_callback (void *arg)
210 static_cast<AudioEngine *>(arg)->GraphReordered (); /* EMIT SIGNAL */
215 AudioEngine::_process_callback (jack_nframes_t nframes, void *arg)
217 return static_cast<AudioEngine *> (arg)->process_callback (nframes);
221 AudioEngine::_freewheel_callback (int onoff, void *arg)
223 static_cast<AudioEngine*>(arg)->_freewheeling = onoff;
227 AudioEngine::process_callback (jack_nframes_t nframes)
229 // CycleTimer ct ("AudioEngine::process");
230 Glib::Mutex::Lock tm (_process_lock, Glib::TRY_LOCK);
231 jack_nframes_t next_processed_frames;
233 /* handle wrap around of total frames counter */
235 if (max_frames - _processed_frames < nframes) {
236 next_processed_frames = nframes - (max_frames - _processed_frames);
238 next_processed_frames = _processed_frames + nframes;
241 if (!tm.locked() || session == 0) {
242 _processed_frames = next_processed_frames;
246 if (session_remove_pending) {
248 session_remove_pending = false;
249 session_removed.signal();
250 _processed_frames = next_processed_frames;
255 if (Freewheel (nframes)) {
256 _freewheeling = false;
257 jack_set_freewheel (_jack, false);
262 session->process (nframes);
265 /* we were zombified, maybe because a ladspa plugin took
266 too long, or jackd exited, or something like that.
269 _processed_frames = next_processed_frames;
273 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
275 boost::shared_ptr<Ports> p = ports.reader();
277 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
282 if (port->_last_monitor != (x = port->monitoring_input ())) {
283 port->_last_monitor = x;
284 /* XXX I think this is dangerous, due to
285 a likely mutex in the signal handlers ...
287 port->MonitorInputChanged (x); /* EMIT SIGNAL */
290 last_monitor_check = next_processed_frames;
293 _processed_frames = next_processed_frames;
298 AudioEngine::_sample_rate_callback (jack_nframes_t nframes, void *arg)
300 return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
304 AudioEngine::jack_sample_rate_callback (jack_nframes_t nframes)
306 _frame_rate = nframes;
307 _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
309 /* check for monitor input change every 1/10th of second */
311 monitor_check_interval = nframes / 10;
312 last_monitor_check = 0;
315 session->set_frame_rate (nframes);
318 SampleRateChanged (nframes); /* EMIT SIGNAL */
324 AudioEngine::_bufsize_callback (jack_nframes_t nframes, void *arg)
326 return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
330 AudioEngine::jack_bufsize_callback (jack_nframes_t nframes)
332 _buffer_size = nframes;
333 _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
334 last_monitor_check = 0;
336 boost::shared_ptr<Ports> p = ports.reader();
338 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
343 session->set_block_size (_buffer_size);
350 AudioEngine::start_metering_thread ()
352 if(m_meter_thread == 0) {
353 m_meter_thread = Glib::Thread::create (sigc::mem_fun(this, &AudioEngine::meter_thread), false);
358 AudioEngine::meter_thread ()
360 while (g_atomic_int_get(&m_meter_exit) != true) {
361 Glib::usleep (10000); /* 1/100th sec interval */
362 IO::update_meters ();
368 AudioEngine::set_session (Session *s)
376 AudioEngine::remove_session ()
378 Glib::Mutex::Lock lm (_process_lock);
383 session_remove_pending = true;
384 session_removed.wait(_process_lock);
398 AudioEngine::register_input_port (DataType type, const string& portname)
402 fatal << _("register input port called before engine was started") << endmsg;
409 jack_port_t *p = jack_port_register (_jack, portname.c_str(), type.to_jack_type(), JackPortIsInput, 0);
415 if ((newport = new Port (p)) != 0) {
416 RCUWriter<Ports> writer (ports);
417 boost::shared_ptr<Ports> ps = writer.get_copy ();
418 ps->insert (ps->begin(), newport);
419 /* writer goes out of scope, forces update */
426 _process_lock.unlock();
427 throw PortRegistrationFailure();
434 AudioEngine::register_output_port (DataType type, const string& portname)
438 fatal << _("register output port called before engine was started") << endmsg;
447 if ((p = jack_port_register (_jack, portname.c_str(),
448 type.to_jack_type(), JackPortIsOutput, 0)) != 0) {
453 RCUWriter<Ports> writer (ports);
454 boost::shared_ptr<Ports> ps = writer.get_copy ();
456 newport = new Port (p);
457 ps->insert (ps->begin(), newport);
459 /* writer goes out of scope, forces update */
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);
492 RCUWriter<Ports> writer (ports);
493 boost::shared_ptr<Ports> ps = writer.get_copy ();
495 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
502 /* writer goes out of scope, forces update */
505 remove_connections_for (port);
516 AudioEngine::connect (const string& source, const string& destination)
520 fatal << _("connect called before engine was started") << endmsg;
527 string s = make_port_name_non_relative (source);
528 string d = make_port_name_non_relative (destination);
530 int ret = jack_connect (_jack, s.c_str(), d.c_str());
533 pair<string,string> c (s, d);
534 port_connections.push_back (c);
536 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
537 source, s, destination, d)
545 AudioEngine::disconnect (const string& source, const string& destination)
549 fatal << _("disconnect called before engine was started") << endmsg;
556 string s = make_port_name_non_relative (source);
557 string d = make_port_name_non_relative (destination);
559 int ret = jack_disconnect (_jack, s.c_str(), d.c_str());
562 pair<string,string> c (s, d);
563 PortConnections::iterator i;
565 if ((i = find (port_connections.begin(), port_connections.end(), c)) != port_connections.end()) {
566 port_connections.erase (i);
574 AudioEngine::disconnect (Port *port)
578 fatal << _("disconnect called before engine was started") << endmsg;
585 int ret = jack_port_disconnect (_jack, port->_port);
588 remove_connections_for (port);
596 AudioEngine::frame_rate ()
599 if (_frame_rate == 0) {
600 return (_frame_rate = jack_get_sample_rate (_jack));
605 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
613 AudioEngine::frames_per_cycle ()
616 if (_buffer_size == 0) {
617 return (_buffer_size = jack_get_buffer_size (_jack));
622 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
630 AudioEngine::get_port_by_name (const string& portname, bool keep)
632 Glib::Mutex::Lock lm (_process_lock);
636 fatal << _("get_port_by_name() called before engine was started") << endmsg;
643 /* check to see if we have a Port for this name already */
645 boost::shared_ptr<Ports> pr = ports.reader();
647 for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
648 if (portname == (*i)->name()) {
655 if ((p = jack_port_by_name (_jack, portname.c_str())) != 0) {
656 Port *newport = new Port (p);
659 if (keep && newport->is_mine (_jack)) {
660 RCUWriter<Ports> writer (ports);
661 boost::shared_ptr<Ports> ps = writer.get_copy ();
662 ps->insert (newport);
663 /* writer goes out of scope, forces update */
676 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
680 fatal << _("get_ports called before engine was started") << endmsg;
686 return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
690 AudioEngine::halted (void *arg)
692 AudioEngine *ae = reinterpret_cast<AudioEngine *> (arg);
694 ae->_running = false;
697 ae->_buffer_size = 0;
700 ae->Halted(); /* EMIT SIGNAL */
704 AudioEngine::n_physical_outputs () const
713 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
718 for (i = 0; ports[i]; ++i);
725 AudioEngine::n_physical_inputs () const
734 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
739 for (i = 0; ports[i]; ++i);
746 AudioEngine::get_physical_inputs (vector<string>& ins)
755 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
760 for (i = 0; ports[i]; ++i) {
761 ins.push_back (ports[i]);
768 AudioEngine::get_physical_outputs (vector<string>& outs)
777 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
782 for (i = 0; ports[i]; ++i) {
783 outs.push_back (ports[i]);
790 AudioEngine::get_nth_physical (uint32_t n, int flag)
796 if (!_running || !_jack) {
798 fatal << _("get_nth_physical called before engine was started") << endmsg;
805 ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|flag);
811 for (i = 0; i < n && ports[i]; ++i);
817 free ((char *) ports);
823 AudioEngine::get_port_total_latency (const Port& port)
826 fatal << _("get_port_total_latency() called with no JACK client connection") << endmsg;
832 fatal << _("get_port_total_latency() called before engine was started") << endmsg;
837 return jack_port_get_total_latency (_jack, port._port);
841 AudioEngine::transport_stop ()
843 // cerr << "tell JACK to stop\n";
845 jack_transport_stop (_jack);
850 AudioEngine::transport_start ()
852 // cerr << "tell JACK to start\n";
854 jack_transport_start (_jack);
859 AudioEngine::transport_locate (jack_nframes_t where)
861 // cerr << "tell JACK to locate to " << where << endl;
863 jack_transport_locate (_jack, where);
867 AudioEngine::TransportState
868 AudioEngine::transport_state ()
872 return (TransportState) jack_transport_query (_jack, &pos);
874 return (TransportState) JackTransportStopped;
879 AudioEngine::reset_timebase ()
882 if (Config->get_jack_time_master()) {
883 return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
885 return jack_release_timebase (_jack);
893 AudioEngine::freewheel (bool onoff)
898 _freewheel_thread_registered = false;
901 return jack_set_freewheel (_jack, onoff);
909 AudioEngine::remove_all_ports ()
911 /* process lock MUST be held */
914 boost::shared_ptr<Ports> p = ports.reader();
916 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
917 jack_port_unregister (_jack, (*i)->_port);
922 RCUWriter<Ports> writer (ports);
923 boost::shared_ptr<Ports> ps = writer.get_copy ();
927 port_connections.clear ();
931 AudioEngine::remove_connections_for (Port* port)
933 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ) {
934 PortConnections::iterator tmp;
939 if ((*i).first == port->name()) {
940 port_connections.erase (i);
947 #ifdef HAVE_JACK_CLIENT_OPEN
950 AudioEngine::connect_to_jack (string client_name)
952 jack_options_t options = JackNullOption;
953 jack_status_t status;
954 const char *server_name = NULL;
956 jack_client_name = client_name; /* might be reset below */
958 _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
962 if (status & JackServerFailed) {
963 error << _("Unable to connect to JACK server") << endmsg;
966 error << string_compose (_("Could not connect to JACK server as \"%1\""), jack_client_name) << endmsg;
970 if (status & JackServerStarted) {
971 info << _("JACK server started") << endmsg;
974 if (status & JackNameNotUnique) {
975 jack_client_name = jack_get_client_name (_jack);
984 AudioEngine::connect_to_jack (string client_name)
986 jack_client_name = client_name;
988 if ((_jack = jack_client_new (client_name.c_str())) == NULL) {
995 #endif /* HAVE_JACK_CLIENT_OPEN */
998 AudioEngine::disconnect_from_jack ()
1004 if (jack_client_close (_jack)) {
1005 error << _("cannot shutdown connection to JACK") << endmsg;
1013 Stopped(); /* EMIT SIGNAL */
1021 AudioEngine::reconnect_to_jack ()
1024 disconnect_from_jack ();
1025 /* XXX give jackd a chance */
1026 Glib::usleep (250000);
1029 if (connect_to_jack (jack_client_name)) {
1030 error << _("failed to connect to JACK") << endmsg;
1036 boost::shared_ptr<Ports> p = ports.reader ();
1038 for (i = p->begin(); i != p->end(); ++i) {
1040 /* XXX hack hack hack */
1042 string long_name = (*i)->name();
1045 short_name = long_name.substr (long_name.find_last_of (':') + 1);
1047 if (((*i)->_port = jack_port_register (_jack, short_name.c_str(), (*i)->type(), (*i)->flags(), 0)) == 0) {
1048 error << string_compose (_("could not reregister %1"), (*i)->name()) << endmsg;
1055 if ((*i)->flags() & JackPortIsOutput) {
1056 (*i)->silence (jack_get_buffer_size (_jack), 0);
1060 if (i != p->end()) {
1062 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
1063 jack_port_unregister (_jack, (*i)->_port);
1070 jack_nframes_t blocksize = jack_get_buffer_size (_jack);
1071 session->set_block_size (blocksize);
1072 session->set_frame_rate (jack_get_sample_rate (_jack));
1075 last_monitor_check = 0;
1077 jack_on_shutdown (_jack, halted, this);
1078 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
1079 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1080 jack_set_process_callback (_jack, _process_callback, this);
1081 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1082 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1083 jack_set_xrun_callback (_jack, _xrun_callback, this);
1084 jack_set_sync_callback (_jack, _jack_sync_callback, this);
1085 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1087 if (Config->get_jack_time_master()) {
1088 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1091 if (jack_activate (_jack) == 0) {
1098 /* re-establish connections */
1100 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ++i) {
1104 if ((err = jack_connect (_jack, (*i).first.c_str(), (*i).second.c_str())) != 0) {
1105 if (err != EEXIST) {
1106 error << string_compose (_("could not reconnect %1 and %2 (err = %3)"),
1107 (*i).first, (*i).second, err)
1113 Running (); /* EMIT SIGNAL*/
1119 AudioEngine::request_buffer_size (jack_nframes_t nframes)
1122 int ret = jack_set_buffer_size (_jack, nframes);
1130 AudioEngine::update_total_latencies ()
1132 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1133 jack_recompute_total_latencies (_jack);
1138 AudioEngine::make_port_name_relative (string portname)
1140 string::size_type len;
1141 string::size_type n;
1143 len = portname.length();
1145 for (n = 0; n < len; ++n) {
1146 if (portname[n] == ':') {
1151 if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1152 return portname.substr (n+1);
1159 AudioEngine::make_port_name_non_relative (string portname)
1163 if (portname.find_first_of (':') != string::npos) {
1167 str = jack_client_name;