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>
27 #include <pbd/unknown_type.h>
29 #include <ardour/audioengine.h>
30 #include <ardour/buffer.h>
31 #include <ardour/port.h>
32 #include <ardour/audio_port.h>
33 #include <ardour/midi_port.h>
34 #include <ardour/session.h>
35 #include <ardour/cycle_timer.h>
36 #include <ardour/utils.h>
41 #include <ardour/timestamps.h>
46 using namespace ARDOUR;
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 boost::shared_ptr<Ports> p = ports.reader();
278 // Prepare ports (ie read data if necessary)
279 for (Ports::iterator i = p->begin(); i != p->end(); ++i)
280 (*i)->cycle_start(nframes);
282 session->process (nframes);
285 /* we were zombified, maybe because a ladspa plugin took
286 too long, or jackd exited, or something like that.
289 _processed_frames = next_processed_frames;
293 // Finalize ports (ie write data if necessary)
294 for (Ports::iterator i = p->begin(); i != p->end(); ++i)
297 if (last_monitor_check + monitor_check_interval < next_processed_frames) {
299 boost::shared_ptr<Ports> p = ports.reader();
301 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
306 if (port->_last_monitor != (x = port->monitoring_input ())) {
307 port->_last_monitor = x;
308 /* XXX I think this is dangerous, due to
309 a likely mutex in the signal handlers ...
311 port->MonitorInputChanged (x); /* EMIT SIGNAL */
314 last_monitor_check = next_processed_frames;
317 _processed_frames = next_processed_frames;
322 AudioEngine::_sample_rate_callback (jack_nframes_t nframes, void *arg)
324 return static_cast<AudioEngine *> (arg)->jack_sample_rate_callback (nframes);
328 AudioEngine::jack_sample_rate_callback (jack_nframes_t nframes)
330 _frame_rate = nframes;
331 _usecs_per_cycle = (int) floor ((((double) frames_per_cycle() / nframes)) * 1000000.0);
333 /* check for monitor input change every 1/10th of second */
335 monitor_check_interval = nframes / 10;
336 last_monitor_check = 0;
339 session->set_frame_rate (nframes);
342 SampleRateChanged (nframes); /* EMIT SIGNAL */
348 AudioEngine::_bufsize_callback (jack_nframes_t nframes, void *arg)
350 return static_cast<AudioEngine *> (arg)->jack_bufsize_callback (nframes);
354 AudioEngine::jack_bufsize_callback (jack_nframes_t nframes)
356 _buffer_size = nframes;
357 _usecs_per_cycle = (int) floor ((((double) nframes / frame_rate())) * 1000000.0);
358 last_monitor_check = 0;
360 boost::shared_ptr<Ports> p = ports.reader();
362 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
367 session->set_block_size (_buffer_size);
374 AudioEngine::start_metering_thread ()
376 if(m_meter_thread == 0) {
377 m_meter_thread = Glib::Thread::create (sigc::mem_fun(this, &AudioEngine::meter_thread), false);
382 AudioEngine::meter_thread ()
384 while (g_atomic_int_get(&m_meter_exit) != true) {
385 Glib::usleep (10000); /* 1/100th sec interval */
386 IO::update_meters ();
392 AudioEngine::set_session (Session *s)
400 AudioEngine::remove_session ()
402 Glib::Mutex::Lock lm (_process_lock);
407 session_remove_pending = true;
408 session_removed.wait(_process_lock);
422 AudioEngine::register_input_port (DataType type, const string& portname)
426 fatal << _("register input port called before engine was started") << endmsg;
433 jack_port_t *p = jack_port_register (_jack, portname.c_str(), type.to_jack_type(), JackPortIsInput, 0);
439 if (type == DataType::AUDIO)
440 newport = new AudioPort (p);
441 else if (type == DataType::MIDI)
442 newport = new MidiPort (p);
444 throw unknown_type();
447 RCUWriter<Ports> writer (ports);
448 boost::shared_ptr<Ports> ps = writer.get_copy ();
449 ps->insert (ps->begin(), newport);
450 /* writer goes out of scope, forces update */
457 _process_lock.unlock();
458 throw PortRegistrationFailure();
465 AudioEngine::register_output_port (DataType type, const string& portname)
469 fatal << _("register output port called before engine was started") << endmsg;
478 if ((p = jack_port_register (_jack, portname.c_str(),
479 type.to_jack_type(), JackPortIsOutput, 0)) != 0) {
483 if (type == DataType::AUDIO)
484 newport = new AudioPort (p);
485 else if (type == DataType::MIDI)
486 newport = new MidiPort (p);
488 throw unknown_type ();
491 RCUWriter<Ports> writer (ports);
492 boost::shared_ptr<Ports> ps = writer.get_copy ();
493 ps->insert (ps->begin(), newport);
494 /* writer goes out of scope, forces update */
501 _process_lock.unlock();
502 throw PortRegistrationFailure ();
510 AudioEngine::unregister_port (Port& port)
513 /* probably happening when the engine has been halted by JACK,
514 in which case, there is nothing we can do here.
519 int ret = jack_port_unregister (_jack, port._port);
525 RCUWriter<Ports> writer (ports);
526 boost::shared_ptr<Ports> ps = writer.get_copy ();
528 for (Ports::iterator i = ps->begin(); i != ps->end(); ++i) {
535 /* writer goes out of scope, forces update */
538 remove_connections_for (port);
545 AudioEngine::connect (const string& source, const string& destination)
549 fatal << _("connect 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_connect (_jack, s.c_str(), d.c_str());
562 pair<string,string> c (s, d);
563 port_connections.push_back (c);
565 error << string_compose(_("AudioEngine: cannot connect %1 (%2) to %3 (%4)"),
566 source, s, destination, d)
574 AudioEngine::disconnect (const string& source, const string& destination)
578 fatal << _("disconnect called before engine was started") << endmsg;
585 string s = make_port_name_non_relative (source);
586 string d = make_port_name_non_relative (destination);
588 int ret = jack_disconnect (_jack, s.c_str(), d.c_str());
591 pair<string,string> c (s, d);
592 PortConnections::iterator i;
594 if ((i = find (port_connections.begin(), port_connections.end(), c)) != port_connections.end()) {
595 port_connections.erase (i);
603 AudioEngine::disconnect (Port& port)
607 fatal << _("disconnect called before engine was started") << endmsg;
614 int ret = jack_port_disconnect (_jack, port._port);
617 remove_connections_for (port);
625 AudioEngine::frame_rate ()
628 if (_frame_rate == 0) {
629 return (_frame_rate = jack_get_sample_rate (_jack));
634 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
642 AudioEngine::frames_per_cycle ()
645 if (_buffer_size == 0) {
646 return (_buffer_size = jack_get_buffer_size (_jack));
651 fatal << X_("programming error: AudioEngine::frame_rate() called while disconnected from JACK")
658 /** Get a port by name.
659 * Note this can return NULL, it will NOT create a port if it is not found (any more).
662 AudioEngine::get_port_by_name (const string& portname, bool keep)
664 Glib::Mutex::Lock lm (_process_lock);
668 fatal << _("get_port_by_name() called before engine was started") << endmsg;
675 boost::shared_ptr<Ports> pr = ports.reader();
677 for (Ports::iterator i = pr->begin(); i != pr->end(); ++i) {
678 if (portname == (*i)->name()) {
687 AudioEngine::get_ports (const string& port_name_pattern, const string& type_name_pattern, uint32_t flags)
691 fatal << _("get_ports called before engine was started") << endmsg;
697 return jack_get_ports (_jack, port_name_pattern.c_str(), type_name_pattern.c_str(), flags);
701 AudioEngine::halted (void *arg)
703 AudioEngine *ae = reinterpret_cast<AudioEngine *> (arg);
705 ae->_running = false;
708 ae->_buffer_size = 0;
711 ae->Halted(); /* EMIT SIGNAL */
715 AudioEngine::n_physical_outputs () const
724 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
729 for (i = 0; ports[i]; ++i);
736 AudioEngine::n_physical_inputs () const
745 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
750 for (i = 0; ports[i]; ++i);
757 AudioEngine::get_physical_inputs (vector<string>& ins)
766 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == 0) {
771 for (i = 0; ports[i]; ++i) {
772 ins.push_back (ports[i]);
779 AudioEngine::get_physical_outputs (vector<string>& outs)
788 if ((ports = jack_get_ports (_jack, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == 0) {
793 for (i = 0; ports[i]; ++i) {
794 outs.push_back (ports[i]);
801 AudioEngine::get_nth_physical (DataType type, uint32_t n, int flag)
807 assert(type != DataType::NIL);
809 if (!_running || !_jack) {
811 fatal << _("get_nth_physical called before engine was started") << endmsg;
818 ports = jack_get_ports (_jack, NULL, type.to_jack_type(), JackPortIsPhysical|flag);
824 for (i = 0; i < n && ports[i]; ++i);
830 free ((char *) ports);
836 AudioEngine::get_port_total_latency (const Port& port)
839 fatal << _("get_port_total_latency() called with no JACK client connection") << endmsg;
845 fatal << _("get_port_total_latency() called before engine was started") << endmsg;
850 return jack_port_get_total_latency (_jack, port._port);
854 AudioEngine::transport_stop ()
856 // cerr << "tell JACK to stop\n";
858 jack_transport_stop (_jack);
863 AudioEngine::transport_start ()
865 // cerr << "tell JACK to start\n";
867 jack_transport_start (_jack);
872 AudioEngine::transport_locate (jack_nframes_t where)
874 // cerr << "tell JACK to locate to " << where << endl;
876 jack_transport_locate (_jack, where);
880 AudioEngine::TransportState
881 AudioEngine::transport_state ()
885 return (TransportState) jack_transport_query (_jack, &pos);
887 return (TransportState) JackTransportStopped;
892 AudioEngine::reset_timebase ()
895 if (Config->get_jack_time_master()) {
896 return jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
898 return jack_release_timebase (_jack);
906 AudioEngine::freewheel (bool onoff)
911 _freewheel_thread_registered = false;
914 return jack_set_freewheel (_jack, onoff);
922 AudioEngine::remove_all_ports ()
924 /* process lock MUST be held */
927 boost::shared_ptr<Ports> p = ports.reader();
929 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
930 jack_port_unregister (_jack, (*i)->_port);
935 RCUWriter<Ports> writer (ports);
936 boost::shared_ptr<Ports> ps = writer.get_copy ();
940 port_connections.clear ();
944 AudioEngine::remove_connections_for (Port& port)
946 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ) {
947 PortConnections::iterator tmp;
952 if ((*i).first == port.name()) {
953 port_connections.erase (i);
960 #ifdef HAVE_JACK_CLIENT_OPEN
963 AudioEngine::connect_to_jack (string client_name)
965 jack_options_t options = JackNullOption;
966 jack_status_t status;
967 const char *server_name = NULL;
969 jack_client_name = client_name; /* might be reset below */
971 _jack = jack_client_open (jack_client_name.c_str(), options, &status, server_name);
975 if (status & JackServerFailed) {
976 error << _("Unable to connect to JACK server") << endmsg;
979 error << string_compose (_("Could not connect to JACK server as \"%1\""), jack_client_name) << endmsg;
983 if (status & JackServerStarted) {
984 info << _("JACK server started") << endmsg;
987 if (status & JackNameNotUnique) {
988 jack_client_name = jack_get_client_name (_jack);
997 AudioEngine::connect_to_jack (string client_name)
999 jack_client_name = client_name;
1001 if ((_jack = jack_client_new (client_name.c_str())) == NULL) {
1008 #endif /* HAVE_JACK_CLIENT_OPEN */
1011 AudioEngine::disconnect_from_jack ()
1017 if (jack_client_close (_jack)) {
1018 error << _("cannot shutdown connection to JACK") << endmsg;
1026 Stopped(); /* EMIT SIGNAL */
1034 AudioEngine::reconnect_to_jack ()
1037 disconnect_from_jack ();
1038 /* XXX give jackd a chance */
1039 Glib::usleep (250000);
1042 if (connect_to_jack (jack_client_name)) {
1043 error << _("failed to connect to JACK") << endmsg;
1049 boost::shared_ptr<Ports> p = ports.reader ();
1051 for (i = p->begin(); i != p->end(); ++i) {
1053 /* XXX hack hack hack */
1055 string long_name = (*i)->name();
1058 short_name = long_name.substr (long_name.find_last_of (':') + 1);
1060 if (((*i)->_port = jack_port_register (_jack, short_name.c_str(), (*i)->type().to_jack_type(), (*i)->flags(), 0)) == 0) {
1061 error << string_compose (_("could not reregister %1"), (*i)->name()) << endmsg;
1068 if ((*i)->flags() & JackPortIsOutput) {
1069 (*i)->silence (jack_get_buffer_size (_jack), 0);
1073 if (i != p->end()) {
1075 for (Ports::iterator i = p->begin(); i != p->end(); ++i) {
1076 jack_port_unregister (_jack, (*i)->_port);
1083 jack_nframes_t blocksize = jack_get_buffer_size (_jack);
1084 session->set_block_size (blocksize);
1085 session->set_frame_rate (jack_get_sample_rate (_jack));
1088 last_monitor_check = 0;
1090 jack_on_shutdown (_jack, halted, this);
1091 jack_set_graph_order_callback (_jack, _graph_order_callback, this);
1092 jack_set_thread_init_callback (_jack, _thread_init_callback, this);
1093 jack_set_process_callback (_jack, _process_callback, this);
1094 jack_set_sample_rate_callback (_jack, _sample_rate_callback, this);
1095 jack_set_buffer_size_callback (_jack, _bufsize_callback, this);
1096 jack_set_xrun_callback (_jack, _xrun_callback, this);
1097 jack_set_sync_callback (_jack, _jack_sync_callback, this);
1098 jack_set_freewheel_callback (_jack, _freewheel_callback, this);
1100 if (Config->get_jack_time_master()) {
1101 jack_set_timebase_callback (_jack, 0, _jack_timebase_callback, this);
1104 if (jack_activate (_jack) == 0) {
1111 /* re-establish connections */
1113 for (PortConnections::iterator i = port_connections.begin(); i != port_connections.end(); ++i) {
1117 if ((err = jack_connect (_jack, (*i).first.c_str(), (*i).second.c_str())) != 0) {
1118 if (err != EEXIST) {
1119 error << string_compose (_("could not reconnect %1 and %2 (err = %3)"),
1120 (*i).first, (*i).second, err)
1126 Running (); /* EMIT SIGNAL*/
1132 AudioEngine::request_buffer_size (jack_nframes_t nframes)
1135 int ret = jack_set_buffer_size (_jack, nframes);
1143 AudioEngine::update_total_latencies ()
1145 #ifdef HAVE_JACK_RECOMPUTE_LATENCIES
1146 jack_recompute_total_latencies (_jack);
1151 AudioEngine::make_port_name_relative (string portname)
1153 string::size_type len;
1154 string::size_type n;
1156 len = portname.length();
1158 for (n = 0; n < len; ++n) {
1159 if (portname[n] == ':') {
1164 if ((n != len) && (portname.substr (0, n) == jack_client_name)) {
1165 return portname.substr (n+1);
1172 AudioEngine::make_port_name_non_relative (string portname)
1176 if (portname.find_first_of (':') != string::npos) {
1180 str = jack_client_name;